feat(opcua): A3 ProjectedConditionRegistry — mapped/conditions namespace, lazy symmetric notifier wiring, gated marked delivery, publish-time re-gating, refresh replay
This commit is contained in:
@@ -120,8 +120,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// <see cref="V3NodeIds.UnsNamespaceUri"/> SECOND ([1]); <see cref="NamespaceIndexForRealm"/> maps a realm
|
||||
/// to its index. Which realm a node belongs to travels with each sink call as an
|
||||
/// <see cref="AddressSpaceRealm"/> — the namespace is never parsed back out of the id string.</summary>
|
||||
// A3 (§5.2 N4): the imported-condition namespace is registered FIFTH ([4]). It has no realm — every classifier dispatches
|
||||
// IsImportedConditionId BEFORE RealmOf (which folds every index other than 0/2 into Uns).
|
||||
private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri,
|
||||
ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri };
|
||||
ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri, Core.Abstractions.DataConnections.ImportedConditionIds.NamespaceUri };
|
||||
|
||||
/// <summary>Transitional alias kept so the pre-v3 single-namespace integration tests
|
||||
/// (<c>SubscriptionSurvivalTests</c>) still resolve a namespace index. It points at
|
||||
@@ -286,6 +288,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// ones this manager mints into).</summary>
|
||||
/// <param name="nodeId">The resolved SDK node id.</param>
|
||||
/// <returns>The realm the node belongs to.</returns>
|
||||
/// <remarks>⚠️ A3: an imported-condition id (<see cref="IsImportedConditionId"/>) has NO realm and must be dispatched before
|
||||
/// this is asked; every classifier does (the authorizer intercepts the namespace before using the realm it is handed).</remarks>
|
||||
private AddressSpaceRealm RealmOf(NodeId nodeId) =>
|
||||
nodeId.NamespaceIndex == NamespaceIndexes[0] || nodeId.NamespaceIndex == NamespaceIndexes[2] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
|
||||
|
||||
@@ -821,6 +825,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
value.UnsSubjectResolver = ResolveUnsAclSubject;
|
||||
value.MappedSubjectResolver = _mappedSubjectResolver;
|
||||
value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant;
|
||||
value.ImportedConditionClassifier = ClassifyImportedCondition; // A3: before RealmOf, always
|
||||
}
|
||||
_authorizer = value;
|
||||
}
|
||||
@@ -1931,6 +1936,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// </summary>
|
||||
private void QueueToItem(IEventMonitoredItem item, IFilterTarget e)
|
||||
{
|
||||
if (ImportedOf(e) is { } imported)
|
||||
{
|
||||
QueueImportedToItem(item, e, imported);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e is ConditionEventSnapshot snapshot)
|
||||
{
|
||||
if (snapshot.DeliveryCache.Queue(Server, item, e, UseProjectedEventDelivery)) Interlocked.Increment(ref _projectedDeliveries);
|
||||
@@ -2030,7 +2041,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// legitimate notifier of it, and its visibility scopes — is resolved ONCE per hop, not per item (it is what
|
||||
// IsNotifierEventVisibleTo resolves for an item attached here). Only the grant check and the SDK's role check
|
||||
// remain per item.
|
||||
var enforced = AclEnforced;
|
||||
// A3 (§5.4): an imported condition reaches a projected folder's items only while the registry wires it there, and
|
||||
// each item passes the mapping gate — ACLs on or off.
|
||||
var imported = ImportedOf(e);
|
||||
if (imported is not null && !_importedConditions.IsWiredTo(imported, monitored.Node)) return;
|
||||
var enforced = AclEnforced && imported is null;
|
||||
List<NodeId>? scopes = null;
|
||||
if (enforced)
|
||||
{
|
||||
@@ -2053,6 +2068,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (IsAuditEvent(e) && !IsAuditDeliverableTo(item)) continue;
|
||||
if (!RoleAllows(item, e)) continue;
|
||||
if (scopes is not null && !IsConditionVisibleTo(item, scopes, visibleByIdentity!)) continue;
|
||||
if (imported is not null && !ImportedVisibleTo(item, imported)) continue;
|
||||
QueueConditionEventToItem(item, e, deferred, DeferredFolderDeliveryProbe);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -2075,7 +2091,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
|
||||
/// <summary>Whether <paramref name="condition"/> is the instance the address space currently holds for its NodeId.</summary>
|
||||
private bool IsLiveCondition(NodeState condition) =>
|
||||
_alarmConditions.TryGetValue(MapKey(condition.NodeId), out var live) && ReferenceEquals(live, condition);
|
||||
IsImportedConditionId(condition.NodeId)
|
||||
? _importedConditions.IsLive(condition)
|
||||
: _alarmConditions.TryGetValue(MapKey(condition.NodeId), out var live) && ReferenceEquals(live, condition);
|
||||
|
||||
/// <summary>Adjusts the deferred depth and logs episode entry/exit. Under the gate.</summary>
|
||||
private void CountDeferred(int delta, AlarmConditionState condition)
|
||||
@@ -4318,6 +4336,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
parent.AddChild(folder); AddPredefinedNode(SystemContext, folder);
|
||||
_projectedAnchors[id] = (definition, folder);
|
||||
_projectedNodeCharges.Add(id, charge); _projectedNodeBytes += charge;
|
||||
OnProjectedFolderMaterialised(folder, definition.MappingId, definition.LocalSubject); // A3 N7
|
||||
nodeId = id; return true;
|
||||
}
|
||||
}
|
||||
@@ -4346,12 +4365,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
if (_projectedVariables.Remove(id, out var child))
|
||||
{
|
||||
OnProjectedFolderRemoving(id); // A3 N7: a removed mapping unwires even a pinned folder
|
||||
if (_projectedDefinitions.Remove(id, out var definition)) RetireProjectedCharge(id, definition.Lifetime);
|
||||
RemoveProjectedSample(id);
|
||||
TombstoneMonitoredNode(id, UtcNow);
|
||||
child.Node.Parent?.RemoveChild(child.Node); PredefinedNodes?.Remove(id);
|
||||
}
|
||||
}
|
||||
OnProjectedFolderRemoving(nodeId);
|
||||
_projectedAnchors.TryRemove(nodeId, out _);
|
||||
_projectedRootLeaves.TryRemove(nodeId, out _);
|
||||
RetireProjectedCharge(nodeId, anchor.Definition.Lifetime);
|
||||
@@ -4439,9 +4460,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
|
||||
foreach (var pair in _projectedDefinitions.ToArray())
|
||||
{
|
||||
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() ||
|
||||
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
|
||||
_projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
|
||||
if (!_projectedVariables.Remove(pair.Key, out var entry)) continue;
|
||||
OnProjectedFolderRemoving(pair.Key);
|
||||
_projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
|
||||
RemoveCommittedProjectedDefinition(pair.Key);
|
||||
if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes;
|
||||
@@ -4450,9 +4472,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
}
|
||||
foreach (var pair in _projectedAnchors.ToArray())
|
||||
{
|
||||
if (pair.Value.Definition.AuthorityIsCurrent() ||
|
||||
if (pair.Value.Definition.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
|
||||
_projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
|
||||
if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue;
|
||||
OnProjectedFolderRemoving(pair.Key);
|
||||
if (_projectedRootLeaves.TryRemove(pair.Key, out _))
|
||||
{
|
||||
_projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
|
||||
@@ -4826,6 +4849,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var id in added)
|
||||
{
|
||||
if (!_projectedVariables.Remove(id, out var entry)) continue;
|
||||
OnProjectedFolderRemoving(id);
|
||||
RemoveProjectedSample(id);
|
||||
_projectedDefinitions.Remove(id);
|
||||
if (_projectedNodeCharges.Remove(id, out var charge)) _projectedNodeBytes -= charge;
|
||||
@@ -4936,7 +4960,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
lock (Lock)
|
||||
{
|
||||
if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) ||
|
||||
IsPinnedEventFolder(nodeId) || // A3 N7: a folder holding an admitted event item is not retired
|
||||
_projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
|
||||
OnProjectedFolderRemoving(nodeId);
|
||||
_projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime);
|
||||
TombstoneMonitoredNode(nodeId, UtcNow);
|
||||
entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(nodeId);
|
||||
@@ -5003,6 +5029,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
_projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent));
|
||||
_projectedDefinitions.Add(candidate, definition);
|
||||
_projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge;
|
||||
if (node is FolderState projectedFolder && definition.Metadata.View.MappingId is { } folderMapping)
|
||||
OnProjectedFolderMaterialised(projectedFolder, folderMapping, definition.Metadata.View.Subject); // A3 N7
|
||||
if (!stage) CommitProjectedDefinition(candidate, definition);
|
||||
nodeId = candidate; return true;
|
||||
}
|
||||
@@ -6046,6 +6074,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
|
||||
{
|
||||
if (!OwnsNamespace(nodeId)) return true;
|
||||
// A3 (§5.2): the imported-condition namespace has no realm — classified BEFORE RealmOf, ACLs on or off.
|
||||
if (IsImportedConditionId(nodeId)) return AuthorizeImportedCondition(identity, operation, nodeId);
|
||||
var realm = RealmOf(nodeId);
|
||||
if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse)
|
||||
{
|
||||
@@ -6525,7 +6555,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
//
|
||||
// Only creation is gated. Refusing an UNSUBSCRIBE would strand the item on a node the session can
|
||||
// no longer reach — the client could never detach it, and the server would keep delivering.
|
||||
if (SecurityFilteringActive && !unsubscribe
|
||||
// A3 (§5.4): an event item on a projected notifier (a folder wired for imported conditions) is admitted through the
|
||||
// verified path — Browse on the folder at subscribe time, the mapping gate per event at delivery and again at
|
||||
// publish — instead of the mapped blanket deny that still applies to data items.
|
||||
var projectedNotifier = !unsubscribe && IsHandleInNamespace(sourceId) is { } candidate && IsProjectedEventNotifier(candidate.NodeId)
|
||||
? candidate.NodeId : (NodeId?)null;
|
||||
if (projectedNotifier is { } notifierId)
|
||||
{
|
||||
if (!Permits(IdentityOf(context), OpcUaOperation.Browse, notifierId)) return StatusCodes.BadUserAccessDenied;
|
||||
}
|
||||
else if (SecurityFilteringActive && !unsubscribe
|
||||
&& IsHandleInNamespace(sourceId) is { } source
|
||||
&& !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, source.NodeId))
|
||||
{
|
||||
@@ -6557,11 +6596,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
}
|
||||
}
|
||||
|
||||
TrackImportedDemand(monitoredItem, unsubscribe: true);
|
||||
return base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe);
|
||||
}
|
||||
|
||||
var result = base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe);
|
||||
TrackLiveEventItem(sourceId, monitoredItem);
|
||||
if (projectedNotifier is not null && ServiceResult.IsGood(result)) TrackImportedDemand(monitoredItem, unsubscribe: false);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -7089,6 +7130,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
ReconcileAllEventsMonitoring();
|
||||
}
|
||||
|
||||
// A3 (§5.5): a Server-object event item could see imported conditions — it opens (or releases) per-connection demand.
|
||||
// Off Lock: the access never blocks, but it is not ours to call under Lock.
|
||||
TrackImportedDemand(monitoredItem, unsubscribe);
|
||||
|
||||
return ServiceResult.Good;
|
||||
}
|
||||
|
||||
@@ -7257,10 +7302,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// through its OLD equipment folder (#808).
|
||||
if (!IsLiveCondition(node)) return;
|
||||
|
||||
// A3 (§5.4): an imported condition is gated per item by the mapping gate, ACLs on or off.
|
||||
var imported = _importedConditions.Find(node);
|
||||
List<NodeId>? scopes;
|
||||
try
|
||||
{
|
||||
scopes = AclEnforced ? ConditionVisibilityScopes(node) : null;
|
||||
scopes = imported is null && AclEnforced ? ConditionVisibilityScopes(node) : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -7279,6 +7326,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
if (e is AuditEventState && !IsAuditDeliverableTo(item)) continue;
|
||||
if (scopes is not null && !IsConditionVisibleTo(item, scopes, visibleByIdentity!)) continue;
|
||||
if (imported is not null && !ImportedVisibleTo(item, imported)) continue;
|
||||
if (!RoleAllows(item, e)) continue;
|
||||
if (reportingSession is { IsNull: false } reportingId
|
||||
&& item.Session?.Id is { } own
|
||||
@@ -7875,6 +7923,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (direct.Count > 0) RefreshDirectItems(systemContext, direct, enforced);
|
||||
|
||||
if (serverItems.Count > 0) RefreshServerObjectItems(systemContext, serverItems, enforced);
|
||||
// A3 (§5.4): imported conditions are replayed through the gated, marked path, ACLs on or off.
|
||||
ReplayImportedConditions(serverItems, direct);
|
||||
return ServiceResult.Good;
|
||||
}
|
||||
finally
|
||||
@@ -7980,7 +8030,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var (e, _, scopes) in replay)
|
||||
{
|
||||
// #855 review 3: never replay a condition a deploy removed or replaced since the walk collected it.
|
||||
if (ConditionOf(e) is AlarmConditionState walked && !IsLiveCondition(walked)) continue;
|
||||
if (ConditionOf(e) is AlarmConditionState walked && (IsImportedConditionId(walked.NodeId) || !IsLiveCondition(walked))) continue;
|
||||
if (scopes is not null && !IsConditionVisibleTo(item, scopes)) continue;
|
||||
if (ServiceResult.IsBad(ValidateEventRolePermissions(item, e))) continue;
|
||||
item.QueueEvent(e);
|
||||
@@ -8265,7 +8315,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var e in events)
|
||||
{
|
||||
// #855 review 3: never replay a condition a deploy removed or replaced since the walk collected it.
|
||||
if (ConditionOf(e) is AlarmConditionState walked && !IsLiveCondition(walked)) continue;
|
||||
if (ConditionOf(e) is AlarmConditionState walked && (IsImportedConditionId(walked.NodeId) || !IsLiveCondition(walked))) continue;
|
||||
if (!IsDirectRefreshEventAllowed(item, e, enforced)) continue;
|
||||
item.QueueEvent(e);
|
||||
}
|
||||
@@ -8374,6 +8424,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var target in live)
|
||||
{
|
||||
if (target is not BaseInstanceState instance) continue;
|
||||
if (IsImportedConditionId(instance.NodeId)) continue; // A3: replayed through the marked path only
|
||||
// A condition materialised since the verdicts were taken is decided here (rare).
|
||||
if (!allowed.Contains((item, instance)))
|
||||
{
|
||||
|
||||
@@ -743,7 +743,7 @@ public sealed class OtOpcUaSdkServer : StandardServer
|
||||
var response = await base.PublishAsync(secureChannelContext, requestHeader, subscriptionAcknowledgements, requestLifetime)
|
||||
.ConfigureAwait(false);
|
||||
if (response?.NotificationMessage is { } projectedMessage)
|
||||
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false);
|
||||
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false, ImportedGateFor(requestHeader));
|
||||
if (_standby.Delivery is not { } record || response?.NotificationMessage is not { } message) return response!;
|
||||
|
||||
if (message.NotificationData.Count > 0)
|
||||
@@ -765,12 +765,29 @@ public sealed class OtOpcUaSdkServer : StandardServer
|
||||
var response = await base.RepublishAsync(secureChannelContext, requestHeader, subscriptionId, retransmitSequenceNumber,
|
||||
requestLifetime).ConfigureAwait(false);
|
||||
if (response?.NotificationMessage is { } projectedMessage)
|
||||
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true);
|
||||
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true, ImportedGateFor(requestHeader));
|
||||
if (_standby.Delivery is { } record && response?.NotificationMessage is { NotificationData.Count: > 0 } message)
|
||||
response.NotificationMessage = Decide(record, subscriptionId, message);
|
||||
return response!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.4): the publishing session's gate for UNMARKED imported-condition event lists (a select-clause modify rebuilt
|
||||
/// them). Null when no imported condition exists (v1 path, nothing to judge).
|
||||
/// </summary>
|
||||
private Func<EventFieldList, bool?>? ImportedGateFor(RequestHeader? requestHeader)
|
||||
{
|
||||
if (NodeManager is not { HasImportedConditions: true } nm) return null;
|
||||
object? identity = null;
|
||||
try
|
||||
{
|
||||
if (requestHeader?.AuthenticationToken is { IsNull: false } token)
|
||||
identity = ServerInternal?.SessionManager?.GetSession(token)?.EffectiveIdentity;
|
||||
}
|
||||
catch (Exception) { identity = null; }
|
||||
return list => nm.ReevaluateImportedEvent(list, identity);
|
||||
}
|
||||
|
||||
/// <summary>The recorded (or, first time, current) decision for one delivery, applied to the SDK's fresh clone.</summary>
|
||||
private NotificationMessage Decide(FirstDeliveryRecord record, uint subscriptionId, NotificationMessage message)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
using ReferenceEqualityComparer = System.Collections.Generic.ReferenceEqualityComparer;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// A3 (plan §5.3): one imported condition — its node, identity (connection, condition_key), current placements and the
|
||||
/// projected folders it is wired into right now. Mutated only under the node manager's <c>Lock</c>.
|
||||
/// </summary>
|
||||
internal sealed class ImportedCondition(AlarmConditionState alarm, string connectionId, string conditionKey)
|
||||
{
|
||||
public AlarmConditionState Alarm { get; } = alarm;
|
||||
public string ConnectionId { get; } = connectionId;
|
||||
public string ConditionKey { get; } = conditionKey;
|
||||
public IReadOnlyList<ImportedConditionPlacement> Placements { get; set; } = [];
|
||||
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
|
||||
/// <summary>The last origin record applied (state known), re-applied with another Quality on staleness.</summary>
|
||||
public AlarmConditionSnapshot? Last { get; set; }
|
||||
public DataActivationMarker? Activation { get; set; }
|
||||
/// <summary>N6: consumer-minted EventIds of this condition's recent events → the activation marker each described.</summary>
|
||||
public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new();
|
||||
/// <summary>Bumped on every placement change (verdict caches key on it).</summary>
|
||||
public long PlacementVersion { get; set; }
|
||||
/// <summary>Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path.</summary>
|
||||
public bool IsNative { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3: what a consumer-minted EventId of an imported condition resolves to — the seam remote condition methods (A3b, §5.6)
|
||||
/// dispatch through: the connection, the origin's opaque key, the PRIMARY placement (the address the origin resolves), and
|
||||
/// the activation marker of the event the client saw.
|
||||
/// </summary>
|
||||
public sealed record ImportedConditionBinding(string ConnectionId, string ConditionKey, ImportedConditionPlacement Primary,
|
||||
IReadOnlyList<ImportedConditionPlacement> Placements, DataActivationMarker? Activation, bool IsNative);
|
||||
|
||||
/// <summary>
|
||||
/// A3 (plan §5.3, N7): the consumer's imported-condition registry, keyed by FULL NodeId in the
|
||||
/// <c>https://zb.com/otopcua/mapped/conditions</c> namespace. Imported conditions never enter the realm-keyed maps
|
||||
/// (<c>_alarmConditions</c> and friends). Mutated only under the node manager's <c>Lock</c>; <see cref="IsLive"/> and
|
||||
/// <see cref="Find"/> are lock-free reads.
|
||||
/// </summary>
|
||||
internal sealed class ProjectedConditionRegistry
|
||||
{
|
||||
/// <summary>Recent EventIds kept per condition for N6 re-binding.</summary>
|
||||
internal const int RecentEventIds = 32;
|
||||
|
||||
private readonly ConcurrentDictionary<NodeId, ImportedCondition> _byNode = new();
|
||||
private readonly ConcurrentDictionary<AlarmConditionState, ImportedCondition> _byInstance = new(ReferenceEqualityComparer.Instance);
|
||||
/// <summary>(mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise).</summary>
|
||||
internal readonly Dictionary<(string Mapping, string Subject), HashSet<NodeId>> ByFolderKey = new();
|
||||
/// <summary>Projected folder node → conditions wired into it.</summary>
|
||||
internal readonly Dictionary<NodeId, HashSet<NodeId>> WiredByFolder = new();
|
||||
private readonly object _verdictGate = new();
|
||||
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed)> _verdicts = new();
|
||||
|
||||
public int Count => _byNode.Count;
|
||||
public IEnumerable<ImportedCondition> All => _byNode.Values;
|
||||
public bool IsLive(NodeState node) => node is AlarmConditionState alarm && _byInstance.ContainsKey(alarm);
|
||||
public ImportedCondition? Find(NodeState? node) =>
|
||||
node is AlarmConditionState alarm && _byInstance.TryGetValue(alarm, out var c) ? c : null;
|
||||
public ImportedCondition? Find(NodeId id) => _byNode.TryGetValue(id, out var c) ? c : null;
|
||||
public bool IsWiredTo(ImportedCondition condition, NodeState notifier) =>
|
||||
notifier is FolderState folder && condition.Folders.Contains(folder) && _byInstance.ContainsKey(condition.Alarm);
|
||||
|
||||
public void Add(ImportedCondition condition)
|
||||
{
|
||||
_byNode[condition.Alarm.NodeId] = condition;
|
||||
_byInstance[condition.Alarm] = condition;
|
||||
}
|
||||
|
||||
public void Remove(ImportedCondition condition)
|
||||
{
|
||||
_byNode.TryRemove(condition.Alarm.NodeId, out _);
|
||||
_byInstance.TryRemove(condition.Alarm, out _);
|
||||
foreach (var key in condition.Placements.Select(FolderKey).Distinct())
|
||||
if (ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) ByFolderKey.Remove(key);
|
||||
lock (_verdictGate)
|
||||
foreach (var stale in _verdicts.Keys.Where(k => k.Condition == condition.Alarm.NodeId).ToList()) _verdicts.Remove(stale);
|
||||
}
|
||||
|
||||
public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject);
|
||||
|
||||
/// <summary>The §5.4 verdict, cached per (identity, condition, authority generation, placement version).</summary>
|
||||
public bool Verdict(object identity, ImportedCondition condition, long generation, Func<bool> compute)
|
||||
{
|
||||
var key = (identity, condition.Alarm.NodeId);
|
||||
lock (_verdictGate)
|
||||
{
|
||||
if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion)
|
||||
return cached.Allowed;
|
||||
}
|
||||
var allowed = compute();
|
||||
lock (_verdictGate)
|
||||
{
|
||||
if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
|
||||
_verdicts[key] = (generation, condition.PlacementVersion, allowed);
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
|
||||
{
|
||||
/// <summary>Most imported updates applied per <c>Lock</c> hold (bounded Lock holds, A1 lessons).</summary>
|
||||
internal const int ImportedApplyChunk = 128;
|
||||
|
||||
private readonly ProjectedConditionRegistry _importedConditions = new();
|
||||
private readonly ConcurrentDictionary<IEventMonitoredItem, IDisposable> _importedEventDemand = new();
|
||||
private long _importedEventsReported, _importedRefreshRequired;
|
||||
|
||||
/// <summary>A3: the consumer's condition gate + demand (null on a node with no data connections).</summary>
|
||||
public IProjectedConditionAccess? ProjectedConditionAccess { get; set; }
|
||||
|
||||
/// <summary>Whether any imported condition is materialised (the publish rewriter's fast exit).</summary>
|
||||
internal bool HasImportedConditions => _importedConditions.Count > 0;
|
||||
|
||||
/// <summary>Imported conditions currently materialised (test/diagnostic observation).</summary>
|
||||
internal int ImportedConditionCount => _importedConditions.Count;
|
||||
|
||||
/// <summary>Imported condition events reported (one per genuine origin transition).</summary>
|
||||
internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported);
|
||||
|
||||
/// <summary>RefreshRequired events queued for imported conditions.</summary>
|
||||
internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired);
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.2 N4): whether <paramref name="nodeId"/> is in the imported-condition namespace. Every NodeId classifier
|
||||
/// (authorizer, read, history, call) asks this BEFORE <see cref="RealmOf"/>, which would fold it into Uns.
|
||||
/// </summary>
|
||||
internal bool IsImportedConditionId(NodeId nodeId) =>
|
||||
NamespaceIndexes.Count > 4 && nodeId.NamespaceIndex == NamespaceIndexes[4];
|
||||
|
||||
/// <summary>The imported-condition NodeId for (connection, condition_key) — never the mapping or placement (N4).</summary>
|
||||
internal NodeId ImportedConditionNodeId(string connectionId, string conditionKey) =>
|
||||
new(ImportedConditionIds.Identifier(connectionId, conditionKey), NamespaceIndexes[4]);
|
||||
|
||||
/// <summary>The imported condition an event is about (its snapshot handle, or an audit's SourceNode), or null.</summary>
|
||||
private ImportedCondition? ImportedOf(IFilterTarget e)
|
||||
{
|
||||
if (_importedConditions.Count == 0) return null;
|
||||
var node = ConditionOf(e);
|
||||
if (_importedConditions.Find(node) is { } c) return c;
|
||||
return node is BaseEventState { SourceNode.Value: { IsNull: false } source } && IsImportedConditionId(source)
|
||||
? _importedConditions.Find(source)
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.4): the mapping gate (<c>CreateMonitoredItems</c> on ANY current placement mapping) for an item's identity,
|
||||
/// REGARDLESS of <c>Security:Acl:Enabled</c>. No access wired / no role-carrying identity ⇒ false.
|
||||
/// </summary>
|
||||
private bool ImportedVisibleTo(IEventMonitoredItem item, ImportedCondition condition) =>
|
||||
ImportedVisibleTo(item.EffectiveIdentity, condition);
|
||||
|
||||
private bool ImportedVisibleTo(object? identity, ImportedCondition condition)
|
||||
{
|
||||
if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false;
|
||||
var generation = access.AuthorityGeneration;
|
||||
var placements = condition.Placements;
|
||||
return _importedConditions.Verdict(caller, condition, generation, () => access.CanSee(caller, placements));
|
||||
}
|
||||
|
||||
/// <summary>The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4).</summary>
|
||||
private ProjectedEventMarker ImportedMarker(IEventMonitoredItem item, ImportedCondition condition)
|
||||
{
|
||||
var identity = item.EffectiveIdentity;
|
||||
var generation = ProjectedConditionAccess?.AuthorityGeneration ?? 0;
|
||||
return new ProjectedEventMarker(identity, condition.Alarm.NodeId, generation,
|
||||
() => _importedConditions.IsLive(condition.Alarm) && ImportedVisibleTo(identity, condition));
|
||||
}
|
||||
|
||||
/// <summary>Imported-condition events always take the marked path, whatever <see cref="UseProjectedEventDelivery"/> says.</summary>
|
||||
private void QueueImportedToItem(IEventMonitoredItem item, IFilterTarget e, ImportedCondition condition)
|
||||
{
|
||||
var cache = e is ConditionEventSnapshot snapshot ? snapshot.DeliveryCache : new EventDeliveryCache();
|
||||
if (cache.QueueMarked(Server, item, e, i => ImportedMarker(i, condition))) Interlocked.Increment(ref _projectedDeliveries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §5.4: the publish-time gate for an UNMARKED list (a select-clause modify rebuilt it). Null when the list is not an
|
||||
/// imported-condition event; otherwise the gate re-evaluated for the publishing session.
|
||||
/// </summary>
|
||||
internal bool? ReevaluateImportedEvent(EventFieldList list, object? identity)
|
||||
{
|
||||
if (list.Handle is not InstanceStateSnapshot { Handle: ConditionState condition } || !IsImportedConditionId(condition.NodeId))
|
||||
return null;
|
||||
return _importedConditions.Find(condition.NodeId) is { } live && ReferenceEquals(live.Alarm, condition)
|
||||
&& ImportedVisibleTo(identity, live);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.4): the authorizer's classifier for an imported-condition id (or a child of one): Browse / Read /
|
||||
/// CreateMonitoredItems are allowed when the caller passes the mapping gate on any placement; everything else
|
||||
/// (Call — A3b, HistoryRead, writes) is refused here.
|
||||
/// </summary>
|
||||
internal bool AuthorizeImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
|
||||
{
|
||||
if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.CreateMonitoredItems)) return false;
|
||||
if (!nodeId.TryGetValue(out string identifier)
|
||||
|| !ImportedConditionIds.TryParse(identifier, out var conditionIdentifier, out _, out _, out _)) return false;
|
||||
var condition = _importedConditions.Find(new NodeId(conditionIdentifier, nodeId.NamespaceIndex));
|
||||
return condition is not null && ImportedVisibleTo(identity, condition);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3b seam (§5.6, N6): resolves an imported condition NodeId and a consumer-minted EventId to its connection, origin
|
||||
/// key, primary placement and the activation marker the event described. False for an unknown condition or EventId.
|
||||
/// </summary>
|
||||
public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding)
|
||||
{
|
||||
binding = null;
|
||||
lock (Lock)
|
||||
{
|
||||
if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false;
|
||||
foreach (var (id, activation) in c.RecentEvents)
|
||||
{
|
||||
if (id != eventId) continue;
|
||||
binding = new(c.ConnectionId, c.ConditionKey, c.Placements[0], c.Placements, activation, c.IsNative);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// IProjectedConditionSink
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <inheritdoc />
|
||||
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(updates);
|
||||
EnsureAddressSpaceCreated();
|
||||
for (var start = 0; start < updates.Count; start += ImportedApplyChunk)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
if (_disposing) return;
|
||||
var index = ProjectedFolderIndex();
|
||||
for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++)
|
||||
{
|
||||
try { ApplyImported(updates[i], index); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException)
|
||||
{
|
||||
_logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})",
|
||||
updates[i].ConnectionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys)
|
||||
{
|
||||
var keys = conditionKeys.ToArray();
|
||||
for (var start = 0; start < keys.Length; start += ImportedApplyChunk)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
foreach (var key in keys.Skip(start).Take(ImportedApplyChunk))
|
||||
{
|
||||
if (!ImportedConditionIds.IsWellFormedConditionKey(key)) continue;
|
||||
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) RemoveImported(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConnectionStale(string connectionId)
|
||||
{
|
||||
List<ImportedCondition> targets;
|
||||
lock (Lock) targets = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
for (var start = 0; start < targets.Count; start += ImportedApplyChunk)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
foreach (var c in targets.Skip(start).Take(ImportedApplyChunk))
|
||||
{
|
||||
if (!_importedConditions.IsLive(c.Alarm)) continue;
|
||||
var stale = (c.Last ?? CurrentSnapshot(c.Alarm)) with { StatusCode = StatusCodes.BadNoCommunication.Code };
|
||||
if (ApplyConditionState(c.Alarm, stale, UtcNow)) ReportImported(c, UtcNow);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RequireRefresh(string connectionId)
|
||||
{
|
||||
List<(IEventMonitoredItem Item, bool Allowed)> targets = [];
|
||||
lock (Lock)
|
||||
{
|
||||
var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
if (conditions.Count == 0) return;
|
||||
var items = new HashSet<IEventMonitoredItem>(_allEventsItems.Keys, ReferenceEqualityComparer.Instance);
|
||||
foreach (var folder in conditions.SelectMany(c => c.Folders).Distinct())
|
||||
if (MonitoredNodes.TryGetValue(folder.NodeId, out var monitored) && monitored.EventMonitoredItems is { } attached)
|
||||
foreach (var item in attached.Values) if (item is not null) items.Add(item);
|
||||
foreach (var item in items) targets.Add((item, conditions.Any(c => ImportedVisibleTo(item, c))));
|
||||
}
|
||||
foreach (var (item, allowed) in targets)
|
||||
{
|
||||
if (!allowed) continue;
|
||||
var e = new RefreshRequiredEventState(null);
|
||||
e.Initialize(SystemContext, null, EventSeverity.Low, new LocalizedText("RefreshRequired"));
|
||||
e.SetChildValue(SystemContext, BrowseNames.SourceNode, ObjectIds.Server, false);
|
||||
e.SetChildValue(SystemContext, BrowseNames.SourceName, "Server", false);
|
||||
item.QueueEvent(e);
|
||||
Interlocked.Increment(ref _importedRefreshRequired);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// Materialise / apply / remove (under Lock)
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
private void ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders)
|
||||
{
|
||||
var state = update.State;
|
||||
if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update));
|
||||
var id = ImportedConditionNodeId(update.ConnectionId, state.ConditionKey);
|
||||
if (state.Removed)
|
||||
{
|
||||
if (_importedConditions.Find(id) is { } gone) RemoveImported(gone);
|
||||
return;
|
||||
}
|
||||
|
||||
var condition = _importedConditions.Find(id);
|
||||
if (condition is null)
|
||||
{
|
||||
var info = update.Info;
|
||||
var name = string.IsNullOrWhiteSpace(info?.ConditionName) ? state.ConditionKey : info!.ConditionName;
|
||||
var native = info?.SourceKind == DataConditionSourceKind.Native;
|
||||
var type = info?.ConditionType is { } t && t.Contains("OffNormalAlarm", StringComparison.Ordinal) ? "OffNormalAlarm"
|
||||
: info?.ConditionType is { } d && d.Contains("DiscreteAlarm", StringComparison.Ordinal) ? "DiscreteAlarm" : "AlarmCondition";
|
||||
var alarm = CreateConditionNode(type, null, id, name, update.SourceName, (int)Math.Clamp(state.Severity, 1u, 1000u), native);
|
||||
// A3a: no local apply of a remote method. Remote dispatch (claim / base.Call / await) is A3b (§5.6); until then
|
||||
// every Part 9 method on an imported condition is refused before the SDK touches its state.
|
||||
alarm.OnAcknowledge = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||||
alarm.OnConfirm = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||||
alarm.OnAddComment = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||||
alarm.OnShelve = (_, _, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||||
alarm.OnTimedUnshelve = (_, _) => ServiceResult.Good;
|
||||
alarm.OnEnableDisable = (_, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
|
||||
alarm.OnReportEvent = OnConditionReportEvent;
|
||||
AddPredefinedNode(SystemContext, alarm);
|
||||
condition = new ImportedCondition(alarm, update.ConnectionId, state.ConditionKey) { IsNative = native };
|
||||
if (!state.StateKnown && alarm.Quality is not null)
|
||||
{
|
||||
// §5.1 T2: unknown at first sight ⇒ Uncertain, never "known inactive".
|
||||
alarm.Quality.Value = StatusCodes.UncertainInitialValue;
|
||||
}
|
||||
_importedConditions.Add(condition);
|
||||
}
|
||||
|
||||
UpdatePlacements(condition, update.Placements, folders);
|
||||
if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event
|
||||
|
||||
// §5.1 T2: a record with state_known = false never changes the consumer's last state.
|
||||
if (!state.StateKnown) return;
|
||||
var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled,
|
||||
Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved,
|
||||
(ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality,
|
||||
state.UnshelveAtUtc?.UtcDateTime,
|
||||
Enum.IsDefined(typeof(AlarmConditionClass), state.ConditionClass) ? (AlarmConditionClass)state.ConditionClass : null);
|
||||
var ts = state.TimeUtc?.UtcDateTime ?? UtcNow;
|
||||
if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment);
|
||||
if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId;
|
||||
condition.Activation = state.Activation;
|
||||
condition.Last = snapshot;
|
||||
if (ApplyConditionState(condition.Alarm, snapshot, ts)) ReportImported(condition, ts);
|
||||
}
|
||||
|
||||
/// <summary>Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter.</summary>
|
||||
private void ReportImported(ImportedCondition condition, DateTime ts)
|
||||
{
|
||||
ReportConditionEvent(condition.Alarm, ts);
|
||||
Interlocked.Increment(ref _importedEventsReported);
|
||||
if (condition.Alarm.EventId?.Value is { } eventId)
|
||||
{
|
||||
condition.RecentEvents.AddFirst((eventId, condition.Activation));
|
||||
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveImported(ImportedCondition condition)
|
||||
{
|
||||
foreach (var folder in condition.Folders.ToList()) UnwireImportedFolder(condition, folder);
|
||||
_importedConditions.Remove(condition);
|
||||
TombstoneMonitoredSubtree(condition.Alarm, UtcNow);
|
||||
ForgetPredefinedSubtree(condition.Alarm);
|
||||
}
|
||||
|
||||
/// <summary>A snapshot of a node's current state (staleness before any known record arrived).</summary>
|
||||
private static AlarmConditionSnapshot CurrentSnapshot(AlarmConditionState alarm) => new(
|
||||
alarm.ActiveState?.Id?.Value == true, alarm.AckedState?.Id?.Value != false, alarm.ConfirmedState?.Id?.Value != false,
|
||||
alarm.EnabledState?.Id?.Value != false, AlarmShelvingKind.Unshelved, (ushort)Math.Clamp((int)(alarm.Severity?.Value ?? 1), 1, 1000),
|
||||
alarm.Message?.Value.Text ?? "", alarm.Quality?.Value.Code ?? StatusCodes.Good.Code);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// Notifier wiring (N7): lazy, symmetric
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>(mapping, local subject) → materialised projected folder (anchors included). One scan per apply batch.</summary>
|
||||
private Dictionary<(string, string), FolderState> ProjectedFolderIndex()
|
||||
{
|
||||
var index = new Dictionary<(string, string), FolderState>();
|
||||
if (_importedConditions.ByFolderKey.Count == 0 && _projectedVariables.Count + _projectedAnchors.Count == 0) return index;
|
||||
foreach (var anchor in _projectedAnchors.Values)
|
||||
if (anchor.Node is FolderState folder) index.TryAdd((anchor.Definition.MappingId, anchor.Definition.LocalSubject), folder);
|
||||
foreach (var entry in _projectedVariables.Values)
|
||||
if (entry.Node is FolderState folder && entry.Metadata.View.MappingId is { } mapping)
|
||||
index.TryAdd((mapping, entry.Metadata.View.Subject), folder);
|
||||
return index;
|
||||
}
|
||||
|
||||
private void UpdatePlacements(ImportedCondition condition, IReadOnlyList<ImportedConditionPlacement> placements,
|
||||
Dictionary<(string, string), FolderState> folders)
|
||||
{
|
||||
var before = condition.Placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
|
||||
var after = placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
|
||||
if (!condition.Placements.SequenceEqual(placements)) condition.PlacementVersion++;
|
||||
condition.Placements = placements;
|
||||
foreach (var key in before.Except(after))
|
||||
if (_importedConditions.ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0)
|
||||
_importedConditions.ByFolderKey.Remove(key);
|
||||
foreach (var key in after)
|
||||
{
|
||||
if (!_importedConditions.ByFolderKey.TryGetValue(key, out var set)) _importedConditions.ByFolderKey[key] = set = [];
|
||||
set.Add(condition.Alarm.NodeId);
|
||||
}
|
||||
var desired = new HashSet<FolderState>(ReferenceEqualityComparer.Instance);
|
||||
foreach (var key in after) if (folders.TryGetValue(key, out var f)) desired.Add(f);
|
||||
foreach (var folder in condition.Folders.Where(f => !desired.Contains(f)).ToList()) UnwireImportedFolder(condition, folder);
|
||||
foreach (var folder in desired) WireImportedFolder(condition, folder);
|
||||
}
|
||||
|
||||
private void WireImportedFolder(ImportedCondition condition, FolderState folder)
|
||||
{
|
||||
if (!condition.Folders.Add(folder)) return;
|
||||
condition.Alarm.AddNotifier(SystemContext, NodeId.Null, isInverse: true, folder);
|
||||
folder.AddNotifier(SystemContext, NodeId.Null, isInverse: false, condition.Alarm);
|
||||
if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired))
|
||||
{
|
||||
_importedConditions.WiredByFolder[folder.NodeId] = wired = [];
|
||||
// Projected folders are created with EventNotifier = None (NM projected page sink); promoted only while wired.
|
||||
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
|
||||
AddRootNotifier(folder);
|
||||
folder.ClearChangeMasks(SystemContext, includeChildren: false);
|
||||
}
|
||||
wired.Add(condition.Alarm.NodeId);
|
||||
condition.PlacementVersion++;
|
||||
}
|
||||
|
||||
private void UnwireImportedFolder(ImportedCondition condition, FolderState folder)
|
||||
{
|
||||
if (!condition.Folders.Remove(folder)) return;
|
||||
condition.Alarm.RemoveNotifier(SystemContext, folder, bidirectional: true);
|
||||
condition.PlacementVersion++;
|
||||
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired) && wired.Remove(condition.Alarm.NodeId) && wired.Count == 0)
|
||||
{
|
||||
_importedConditions.WiredByFolder.Remove(folder.NodeId);
|
||||
RemoveRootNotifier(folder);
|
||||
folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents);
|
||||
folder.ClearChangeMasks(SystemContext, includeChildren: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A projected folder (or anchor) materialised: wire every imported condition placed there (N7). Under Lock.</summary>
|
||||
private void OnProjectedFolderMaterialised(FolderState folder, string mappingId, string localSubject)
|
||||
{
|
||||
if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return;
|
||||
foreach (var id in set.ToList())
|
||||
if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder);
|
||||
}
|
||||
|
||||
/// <summary>A projected folder is being removed: unwire it symmetrically first (N7). Under Lock.</summary>
|
||||
private void OnProjectedFolderRemoving(NodeId folderId)
|
||||
{
|
||||
if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var wired)) return;
|
||||
foreach (var id in wired.ToList())
|
||||
{
|
||||
if (_importedConditions.Find(id) is not { } c) continue;
|
||||
var folder = c.Folders.FirstOrDefault(f => f.NodeId == folderId);
|
||||
if (folder is not null) UnwireImportedFolder(c, folder);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// N7: a projected folder holding an admitted event item is pinned — capacity eviction and page removal skip it (a
|
||||
/// mapping removal still removes it, unwiring first). Under Lock.
|
||||
/// </summary>
|
||||
private bool IsPinnedEventFolder(NodeId nodeId) =>
|
||||
_importedConditions.WiredByFolder.ContainsKey(nodeId)
|
||||
&& MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 };
|
||||
|
||||
/// <summary>A projected folder currently wired as a notifier of an imported condition (event items there are admitted, §5.4).</summary>
|
||||
private bool IsProjectedEventNotifier(NodeId nodeId)
|
||||
{
|
||||
if (_importedConditions.Count == 0) return false;
|
||||
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise
|
||||
/// the imported verdict.
|
||||
/// </summary>
|
||||
internal bool? ClassifyImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) =>
|
||||
IsImportedConditionId(nodeId) ? AuthorizeImportedCondition(identity, operation, nodeId) : null;
|
||||
|
||||
/// <summary>Test observation: whether a projected folder is currently wired as a notifier of some imported condition.</summary>
|
||||
internal bool IsImportedNotifierWired(NodeId folderId)
|
||||
{
|
||||
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(folderId);
|
||||
}
|
||||
|
||||
/// <summary>Test observation: the imported condition node for (connection, key), or null.</summary>
|
||||
internal AlarmConditionState? FindImportedCondition(string connectionId, string conditionKey) =>
|
||||
_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey))?.Alarm;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// Demand + ConditionRefresh
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>An admitted event item (Server object or projected notifier) opens condition demand; its removal releases it.</summary>
|
||||
private void TrackImportedDemand(IEventMonitoredItem item, bool unsubscribe)
|
||||
{
|
||||
if (unsubscribe)
|
||||
{
|
||||
if (_importedEventDemand.TryRemove(item, out var lease)) lease.Dispose();
|
||||
return;
|
||||
}
|
||||
if (ProjectedConditionAccess is not { } access || _importedEventDemand.ContainsKey(item)) return;
|
||||
IDisposable? acquired;
|
||||
try { acquired = access.AcquireEventDemand(item.EffectiveIdentity as RoleCarryingUserIdentity); }
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition demand failed"); return; }
|
||||
if (acquired is not null && !_importedEventDemand.TryAdd(item, acquired)) acquired.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ConditionRefresh for imported conditions: every retained one the item may see, through the marked path. Server-object
|
||||
/// items see all; a direct item only those wired to its notifier. One Lock hold (consistent with synchronous events).
|
||||
/// </summary>
|
||||
private void ReplayImportedConditions(List<IEventMonitoredItem> serverItems, List<IEventMonitoredItem> directItems)
|
||||
{
|
||||
if (_importedConditions.Count == 0) return;
|
||||
lock (Lock)
|
||||
{
|
||||
var retained = _importedConditions.All.Where(c => c.Alarm.Retain?.Value == true).ToList();
|
||||
if (retained.Count == 0) return;
|
||||
var snapshots = new Dictionary<ImportedCondition, InstanceStateSnapshot>(ReferenceEqualityComparer.Instance);
|
||||
InstanceStateSnapshot SnapshotOf(ImportedCondition c)
|
||||
{
|
||||
if (snapshots.TryGetValue(c, out var s)) return s;
|
||||
s = new InstanceStateSnapshot();
|
||||
s.Initialize(SystemContext, c.Alarm);
|
||||
return snapshots[c] = s;
|
||||
}
|
||||
foreach (var item in serverItems)
|
||||
foreach (var c in retained)
|
||||
if (ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm)))
|
||||
new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c));
|
||||
foreach (var item in directItems)
|
||||
{
|
||||
if (!MonitoredItems.ContainsKey(item.Id) || (item.ManagerHandle as NodeHandle)?.Node is not FolderState notifier) continue;
|
||||
foreach (var c in retained)
|
||||
if (c.Folders.Contains(notifier) && ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm)))
|
||||
new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,24 @@ internal sealed class EventDeliveryCache
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.4): queues an imported-condition event ALWAYS through the projected path with a
|
||||
/// <see cref="ProjectedEventFieldList"/> marker, whatever the node manager's <c>UseProjectedEventDelivery</c> switch
|
||||
/// says. An item of a shape the projected path cannot serve gets nothing (fail closed, counted) — never the SDK's
|
||||
/// unmarked <c>QueueEvent(IFilterTarget)</c>.
|
||||
/// </summary>
|
||||
/// <returns>True when queued (or decided not to queue exactly as the SDK would).</returns>
|
||||
public bool QueueMarked(IServerInternal server, IEventMonitoredItem item, IFilterTarget e, Func<IEventMonitoredItem, ProjectedEventMarker> marker)
|
||||
{
|
||||
if (item.GetType() == typeof(SdkMonitoredItem)
|
||||
&& e is InstanceStateSnapshot { Handle: ConditionState condition }
|
||||
&& condition.SupportsFilteredRetain?.Value != true
|
||||
&& ProjectedEventDelivery.TryQueue(server, (SdkMonitoredItem)item, e, this, marker))
|
||||
return true;
|
||||
Interlocked.Increment(ref ProjectedEventFieldList.s_unservable);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Marks the item as queued for this report; false when it already was (the SDK's duplicate check).</summary>
|
||||
internal bool TryMarkQueued(IEventMonitoredItem item)
|
||||
{
|
||||
@@ -216,7 +234,8 @@ internal static class ProjectedEventDelivery
|
||||
/// The SDK's <c>QueueEvent(instance, bypassFilter: false)</c> for one condition snapshot, with the projection taken
|
||||
/// from <paramref name="cache"/>. Returns false (nothing done) when the item is not in a shape this reproduces.
|
||||
/// </summary>
|
||||
internal static bool TryQueue(IServerInternal server, SdkMonitoredItem item, IFilterTarget e, EventDeliveryCache cache)
|
||||
internal static bool TryQueue(IServerInternal server, SdkMonitoredItem item, IFilterTarget e, EventDeliveryCache cache,
|
||||
Func<IEventMonitoredItem, ProjectedEventMarker>? marker = null)
|
||||
{
|
||||
if (!Available || (item.MonitoredItemType & 2) == 0) return false;
|
||||
|
||||
@@ -237,12 +256,20 @@ internal static class ProjectedEventDelivery
|
||||
if (!projection.Passes || handler.SetQueueOverflowIfFull()) return true;
|
||||
|
||||
Interlocked.Increment(ref s_projectedQueued);
|
||||
item.QueueEvent(new EventFieldList
|
||||
{
|
||||
ClientHandle = item.ClientHandle,
|
||||
Handle = e,
|
||||
EventFields = projection.Fields, // shared, read-only (see Projection)
|
||||
});
|
||||
// A3 (§5.4): an imported condition's list carries its publish-time re-check (ProjectedNotificationRewriter).
|
||||
item.QueueEvent(marker is null
|
||||
? new EventFieldList
|
||||
{
|
||||
ClientHandle = item.ClientHandle,
|
||||
Handle = e,
|
||||
EventFields = projection.Fields, // shared, read-only (see Projection)
|
||||
}
|
||||
: new ProjectedEventFieldList(marker(item))
|
||||
{
|
||||
ClientHandle = item.ClientHandle,
|
||||
Handle = e,
|
||||
EventFields = projection.Fields,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -412,3 +439,40 @@ internal static class ProjectedEventDelivery
|
||||
return property.GetMethod.CreateDelegate<Func<SdkMonitoredItem, T?>>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.4): the captured authority of one queued imported-condition event — the caller, the condition, the authority
|
||||
/// generation it was admitted under and a re-check, like <c>ProjectedNotificationMarker</c> for data.
|
||||
/// </summary>
|
||||
internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId, long Generation, Func<bool> Recheck)
|
||||
{
|
||||
/// <summary>Re-evaluates the gate; any failure denies.</summary>
|
||||
public bool Permits()
|
||||
{
|
||||
try { return Recheck(); }
|
||||
catch { return false; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A3 (§5.4): an <see cref="EventFieldList"/> carrying its <see cref="ProjectedEventMarker"/>. The SDK never clones a
|
||||
/// queued list on its way to the wire (SDK 2.0.1: <c>QueueEvent(EventFieldList)</c> enqueues the instance,
|
||||
/// <c>Publish</c> dequeues it, <c>ConstructMessage</c> places it, Republish returns the stored message), so
|
||||
/// <c>ProjectedNotificationRewriter</c> sees this instance on every Publish and Republish and drops it when the re-check
|
||||
/// fails.
|
||||
/// </summary>
|
||||
internal sealed class ProjectedEventFieldList(ProjectedEventMarker marker) : EventFieldList
|
||||
{
|
||||
internal static long s_unservable, s_droppedOnPublish, s_droppedUnmarked, s_keptUnmarked;
|
||||
|
||||
public ProjectedEventMarker Marker { get; } = marker;
|
||||
|
||||
/// <summary>Imported events an item could not receive through the marked path (fail closed).</summary>
|
||||
internal static long Unservable => Interlocked.Read(ref s_unservable);
|
||||
/// <summary>Marked events dropped at Publish/Republish because the re-check failed.</summary>
|
||||
internal static long DroppedOnPublish => Interlocked.Read(ref s_droppedOnPublish);
|
||||
/// <summary>Unmarked imported events (rebuilt by a select-clause modify) dropped because the gate denied.</summary>
|
||||
internal static long DroppedUnmarked => Interlocked.Read(ref s_droppedUnmarked);
|
||||
/// <summary>Unmarked imported events kept after the gate re-evaluated them for the publishing session.</summary>
|
||||
internal static long KeptUnmarked => Interlocked.Read(ref s_keptUnmarked);
|
||||
}
|
||||
|
||||
@@ -141,6 +141,12 @@ public sealed class DataPlaneAuthorizer
|
||||
/// <summary>Live catalog classification owned by the node manager, consulted before either local path resolver.</summary>
|
||||
public Func<AddressSpaceRealm, string, MappedNodeResolution>? MappedSubjectResolver { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A3: the node manager's imported-condition classifier — null for an id outside the imported-condition namespace,
|
||||
/// otherwise the verdict (Browse/Read/CreateMonitoredItems via the condition's mapping gate; anything else refused).
|
||||
/// </summary>
|
||||
public Func<RoleCarryingUserIdentity?, OpcUaOperation, NodeId, bool?>? ImportedConditionClassifier { get; set; }
|
||||
|
||||
/// <summary>Optional actual-namespace filter for projected subject classification.</summary>
|
||||
public Func<NodeId, bool>? MappedNamespacePredicate { get; set; }
|
||||
|
||||
@@ -162,6 +168,20 @@ public sealed class DataPlaneAuthorizer
|
||||
public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
|
||||
NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto)
|
||||
{
|
||||
// A3 (§5.2 N4): the imported-condition namespace has NO realm; it is classified before anything reads `realm` (which a
|
||||
// caller computed with the node manager's RealmOf, folding it into Uns). Every entry point (Authorize, AuthorizeIfRequired,
|
||||
// IsAllowedCached, TryAuthorizeMapped) reaches this first, ACLs on or off.
|
||||
if (ImportedConditionClassifier is { } imported)
|
||||
{
|
||||
bool? verdict;
|
||||
try { verdict = imported(identity, operation, nodeId); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogWarning(ex, "Imported condition classification failed");
|
||||
verdict = false;
|
||||
}
|
||||
if (verdict is { } decided) { veto = decided ? null : DeniedResult; return true; }
|
||||
}
|
||||
var resolver = MappedSubjectResolver;
|
||||
if (MappedNamespacePredicate is { } predicate && !predicate(nodeId)) { veto = null; return false; }
|
||||
if (resolver is null) { veto = null; return false; }
|
||||
|
||||
@@ -916,12 +916,48 @@ internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredI
|
||||
/// <summary>Rechecks captured projected notification authority for every delivery and retransmission.</summary>
|
||||
internal static class ProjectedNotificationRewriter
|
||||
{
|
||||
public static NotificationMessage Project(NotificationMessage message, bool republish)
|
||||
public static NotificationMessage Project(NotificationMessage message, bool republish) => Project(message, republish, null);
|
||||
|
||||
/// <param name="message">The message about to be sent (Publish) or re-sent (Republish).</param>
|
||||
/// <param name="republish">Whether this is a Republish.</param>
|
||||
/// <param name="importedGate">
|
||||
/// A3 (§5.4): for an UNMARKED event list whose <c>Handle</c> is an imported-condition snapshot (a select-clause
|
||||
/// <c>ModifyMonitoredItems</c> rebuilt it through <c>GetEventFields</c>), re-evaluates the gate for the publishing
|
||||
/// session: true keeps it, false drops it; null = not an imported condition (kept, v1 behaviour).
|
||||
/// </param>
|
||||
public static NotificationMessage Project(NotificationMessage message, bool republish, Func<EventFieldList, bool?>? importedGate)
|
||||
{
|
||||
var changed = false;
|
||||
var payloads = new List<ExtensionObject>(message.NotificationData.Count);
|
||||
foreach (var payload in message.NotificationData)
|
||||
{
|
||||
if (payload.TryGetValue<EventNotificationList>(out var events) && events is not null)
|
||||
{
|
||||
var kept = new List<EventFieldList>(events.Events.Count);
|
||||
foreach (var list in events.Events)
|
||||
{
|
||||
if (list is ProjectedEventFieldList marked)
|
||||
{
|
||||
if (marked.Marker.Permits()) kept.Add(list);
|
||||
else Interlocked.Increment(ref ProjectedEventFieldList.s_droppedOnPublish);
|
||||
continue;
|
||||
}
|
||||
bool? verdict;
|
||||
try { verdict = importedGate?.Invoke(list); }
|
||||
catch { verdict = false; }
|
||||
if (verdict == false) { Interlocked.Increment(ref ProjectedEventFieldList.s_droppedUnmarked); continue; }
|
||||
if (verdict == true) Interlocked.Increment(ref ProjectedEventFieldList.s_keptUnmarked);
|
||||
kept.Add(list);
|
||||
}
|
||||
if (kept.Count == events.Events.Count) payloads.Add(payload);
|
||||
else
|
||||
{
|
||||
changed = true;
|
||||
// Events have no Bad-value form: a denied event is dropped; an emptied list leaves the payload out.
|
||||
if (kept.Count > 0) payloads.Add(new ExtensionObject(new EventNotificationList { Events = kept }));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!payload.TryGetValue<DataChangeNotification>(out var change) || change is null)
|
||||
{ payloads.Add(payload); continue; }
|
||||
var items = new List<MonitoredItemNotification>(change.MonitoredItems.Count);
|
||||
|
||||
Reference in New Issue
Block a user