diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
index 1d9f36dd1..c1271a36a 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
@@ -120,8 +120,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// SECOND ([1]); maps a realm
/// to its index. Which realm a node belongs to travels with each sink call as an
/// — the namespace is never parsed back out of the id string.
+ // 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 };
/// Transitional alias kept so the pre-v3 single-namespace integration tests
/// (SubscriptionSurvivalTests) still resolve a namespace index. It points at
@@ -286,6 +288,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// ones this manager mints into).
/// The resolved SDK node id.
/// The realm the node belongs to.
+ /// ⚠️ A3: an imported-condition id () 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).
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
///
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? 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
/// Whether is the instance the address space currently holds for its NodeId.
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);
/// Adjusts the deferred depth and logs episode entry/exit. Under the gate.
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? 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)))
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
index d8bf1cd39..e7a72a311 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
@@ -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!;
}
+ ///
+ /// 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).
+ ///
+ private Func? 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);
+ }
+
/// The recorded (or, first time, current) decision for one delivery, applied to the SDK's fresh clone.
private NotificationMessage Decide(FirstDeliveryRecord record, uint subscriptionId, NotificationMessage message)
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs
new file mode 100644
index 000000000..56d13ddce
--- /dev/null
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs
@@ -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;
+
+///
+/// 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 Lock.
+///
+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 Placements { get; set; } = [];
+ public HashSet Folders { get; } = new(ReferenceEqualityComparer.Instance);
+ /// The last origin record applied (state known), re-applied with another Quality on staleness.
+ public AlarmConditionSnapshot? Last { get; set; }
+ public DataActivationMarker? Activation { get; set; }
+ /// N6: consumer-minted EventIds of this condition's recent events → the activation marker each described.
+ public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new();
+ /// Bumped on every placement change (verdict caches key on it).
+ public long PlacementVersion { get; set; }
+ /// Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path.
+ public bool IsNative { get; init; }
+}
+
+///
+/// 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.
+///
+public sealed record ImportedConditionBinding(string ConnectionId, string ConditionKey, ImportedConditionPlacement Primary,
+ IReadOnlyList Placements, DataActivationMarker? Activation, bool IsNative);
+
+///
+/// A3 (plan §5.3, N7): the consumer's imported-condition registry, keyed by FULL NodeId in the
+/// https://zb.com/otopcua/mapped/conditions namespace. Imported conditions never enter the realm-keyed maps
+/// (_alarmConditions and friends). Mutated only under the node manager's Lock; and
+/// are lock-free reads.
+///
+internal sealed class ProjectedConditionRegistry
+{
+ /// Recent EventIds kept per condition for N6 re-binding.
+ internal const int RecentEventIds = 32;
+
+ private readonly ConcurrentDictionary _byNode = new();
+ private readonly ConcurrentDictionary _byInstance = new(ReferenceEqualityComparer.Instance);
+ /// (mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise).
+ internal readonly Dictionary<(string Mapping, string Subject), HashSet> ByFolderKey = new();
+ /// Projected folder node → conditions wired into it.
+ internal readonly Dictionary> 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 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);
+
+ /// The §5.4 verdict, cached per (identity, condition, authority generation, placement version).
+ public bool Verdict(object identity, ImportedCondition condition, long generation, Func 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
+{
+ /// Most imported updates applied per Lock hold (bounded Lock holds, A1 lessons).
+ internal const int ImportedApplyChunk = 128;
+
+ private readonly ProjectedConditionRegistry _importedConditions = new();
+ private readonly ConcurrentDictionary _importedEventDemand = new();
+ private long _importedEventsReported, _importedRefreshRequired;
+
+ /// A3: the consumer's condition gate + demand (null on a node with no data connections).
+ public IProjectedConditionAccess? ProjectedConditionAccess { get; set; }
+
+ /// Whether any imported condition is materialised (the publish rewriter's fast exit).
+ internal bool HasImportedConditions => _importedConditions.Count > 0;
+
+ /// Imported conditions currently materialised (test/diagnostic observation).
+ internal int ImportedConditionCount => _importedConditions.Count;
+
+ /// Imported condition events reported (one per genuine origin transition).
+ internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported);
+
+ /// RefreshRequired events queued for imported conditions.
+ internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired);
+
+ ///
+ /// A3 (§5.2 N4): whether is in the imported-condition namespace. Every NodeId classifier
+ /// (authorizer, read, history, call) asks this BEFORE , which would fold it into Uns.
+ ///
+ internal bool IsImportedConditionId(NodeId nodeId) =>
+ NamespaceIndexes.Count > 4 && nodeId.NamespaceIndex == NamespaceIndexes[4];
+
+ /// The imported-condition NodeId for (connection, condition_key) — never the mapping or placement (N4).
+ internal NodeId ImportedConditionNodeId(string connectionId, string conditionKey) =>
+ new(ImportedConditionIds.Identifier(connectionId, conditionKey), NamespaceIndexes[4]);
+
+ /// The imported condition an event is about (its snapshot handle, or an audit's SourceNode), or null.
+ 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;
+ }
+
+ ///
+ /// A3 (§5.4): the mapping gate (CreateMonitoredItems on ANY current placement mapping) for an item's identity,
+ /// REGARDLESS of Security:Acl:Enabled. No access wired / no role-carrying identity ⇒ false.
+ ///
+ 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));
+ }
+
+ /// The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4).
+ 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));
+ }
+
+ /// Imported-condition events always take the marked path, whatever says.
+ 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);
+ }
+
+ ///
+ /// §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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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
+ // ---------------------------------------------------------------------------------------------------------------------
+
+ ///
+ public void ApplyConditions(IReadOnlyList 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);
+ }
+ }
+ }
+ }
+ }
+
+ ///
+ public void RemoveConditions(string connectionId, IReadOnlyCollection 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);
+ }
+ }
+ }
+ }
+
+ ///
+ public void MarkConnectionStale(string connectionId)
+ {
+ List 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);
+ }
+ }
+ }
+ }
+
+ ///
+ 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(_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);
+ }
+
+ /// Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter.
+ 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);
+ }
+
+ /// A snapshot of a node's current state (staleness before any known record arrived).
+ 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
+ // ---------------------------------------------------------------------------------------------------------------------
+
+ /// (mapping, local subject) → materialised projected folder (anchors included). One scan per apply batch.
+ 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 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(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);
+ }
+ }
+
+ /// A projected folder (or anchor) materialised: wire every imported condition placed there (N7). Under Lock.
+ 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);
+ }
+
+ /// A projected folder is being removed: unwire it symmetrically first (N7). Under Lock.
+ 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);
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ private bool IsPinnedEventFolder(NodeId nodeId) =>
+ _importedConditions.WiredByFolder.ContainsKey(nodeId)
+ && MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 };
+
+ /// A projected folder currently wired as a notifier of an imported condition (event items there are admitted, §5.4).
+ private bool IsProjectedEventNotifier(NodeId nodeId)
+ {
+ if (_importedConditions.Count == 0) return false;
+ lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId);
+ }
+
+ ///
+ /// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise
+ /// the imported verdict.
+ ///
+ internal bool? ClassifyImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) =>
+ IsImportedConditionId(nodeId) ? AuthorizeImportedCondition(identity, operation, nodeId) : null;
+
+ /// Test observation: whether a projected folder is currently wired as a notifier of some imported condition.
+ internal bool IsImportedNotifierWired(NodeId folderId)
+ {
+ lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(folderId);
+ }
+
+ /// Test observation: the imported condition node for (connection, key), or null.
+ internal AlarmConditionState? FindImportedCondition(string connectionId, string conditionKey) =>
+ _importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey))?.Alarm;
+
+ // ---------------------------------------------------------------------------------------------------------------------
+ // Demand + ConditionRefresh
+ // ---------------------------------------------------------------------------------------------------------------------
+
+ /// An admitted event item (Server object or projected notifier) opens condition demand; its removal releases it.
+ 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();
+ }
+
+ ///
+ /// 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).
+ ///
+ private void ReplayImportedConditions(List serverItems, List 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(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));
+ }
+ }
+ }
+}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs
index 0f1aa859d..17cacc98a 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs
@@ -101,6 +101,24 @@ internal sealed class EventDeliveryCache
return false;
}
+ ///
+ /// A3 (§5.4): queues an imported-condition event ALWAYS through the projected path with a
+ /// marker, whatever the node manager's UseProjectedEventDelivery switch
+ /// says. An item of a shape the projected path cannot serve gets nothing (fail closed, counted) — never the SDK's
+ /// unmarked QueueEvent(IFilterTarget).
+ ///
+ /// True when queued (or decided not to queue exactly as the SDK would).
+ public bool QueueMarked(IServerInternal server, IEventMonitoredItem item, IFilterTarget e, Func 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;
+ }
+
/// Marks the item as queued for this report; false when it already was (the SDK's duplicate check).
internal bool TryMarkQueued(IEventMonitoredItem item)
{
@@ -216,7 +234,8 @@ internal static class ProjectedEventDelivery
/// The SDK's QueueEvent(instance, bypassFilter: false) for one condition snapshot, with the projection taken
/// from . Returns false (nothing done) when the item is not in a shape this reproduces.
///
- 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? 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>();
}
}
+
+///
+/// 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 ProjectedNotificationMarker for data.
+///
+internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId, long Generation, Func Recheck)
+{
+ /// Re-evaluates the gate; any failure denies.
+ public bool Permits()
+ {
+ try { return Recheck(); }
+ catch { return false; }
+ }
+}
+
+///
+/// A3 (§5.4): an carrying its . The SDK never clones a
+/// queued list on its way to the wire (SDK 2.0.1: QueueEvent(EventFieldList) enqueues the instance,
+/// Publish dequeues it, ConstructMessage places it, Republish returns the stored message), so
+/// ProjectedNotificationRewriter sees this instance on every Publish and Republish and drops it when the re-check
+/// fails.
+///
+internal sealed class ProjectedEventFieldList(ProjectedEventMarker marker) : EventFieldList
+{
+ internal static long s_unservable, s_droppedOnPublish, s_droppedUnmarked, s_keptUnmarked;
+
+ public ProjectedEventMarker Marker { get; } = marker;
+
+ /// Imported events an item could not receive through the marked path (fail closed).
+ internal static long Unservable => Interlocked.Read(ref s_unservable);
+ /// Marked events dropped at Publish/Republish because the re-check failed.
+ internal static long DroppedOnPublish => Interlocked.Read(ref s_droppedOnPublish);
+ /// Unmarked imported events (rebuilt by a select-clause modify) dropped because the gate denied.
+ internal static long DroppedUnmarked => Interlocked.Read(ref s_droppedUnmarked);
+ /// Unmarked imported events kept after the gate re-evaluated them for the publishing session.
+ internal static long KeptUnmarked => Interlocked.Read(ref s_keptUnmarked);
+}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs
index f3bfdce2a..663f5b457 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs
@@ -141,6 +141,12 @@ public sealed class DataPlaneAuthorizer
/// Live catalog classification owned by the node manager, consulted before either local path resolver.
public Func? MappedSubjectResolver { get; set; }
+ ///
+ /// 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).
+ ///
+ public Func? ImportedConditionClassifier { get; set; }
+
/// Optional actual-namespace filter for projected subject classification.
public Func? 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; }
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs
index 38fcb2eb2..68786bb82 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs
@@ -916,12 +916,48 @@ internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredI
/// Rechecks captured projected notification authority for every delivery and retransmission.
internal static class ProjectedNotificationRewriter
{
- public static NotificationMessage Project(NotificationMessage message, bool republish)
+ public static NotificationMessage Project(NotificationMessage message, bool republish) => Project(message, republish, null);
+
+ /// The message about to be sent (Publish) or re-sent (Republish).
+ /// Whether this is a Republish.
+ ///
+ /// A3 (§5.4): for an UNMARKED event list whose Handle is an imported-condition snapshot (a select-clause
+ /// ModifyMonitoredItems rebuilt it through GetEventFields), re-evaluates the gate for the publishing
+ /// session: true keeps it, false drops it; null = not an imported condition (kept, v1 behaviour).
+ ///
+ public static NotificationMessage Project(NotificationMessage message, bool republish, Func? importedGate)
{
var changed = false;
var payloads = new List(message.NotificationData.Count);
foreach (var payload in message.NotificationData)
{
+ if (payload.TryGetValue(out var events) && events is not null)
+ {
+ var kept = new List(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(out var change) || change is null)
{ payloads.Add(payload); continue; }
var items = new List(change.MonitoredItems.Count);