Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL
// SPDX-License-Identifier: MIT

using System;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Opc.Ua.Server
{
/// <summary>
/// Counts the <see cref="IConfigurationNodeManager.DefaultPermissionsChanged"/>
/// notifications of one configuration node manager.
/// </summary>
/// <remarks>
/// Monitored nodes and sampling groups fold <see cref="Value"/> into the stamps of their
/// cached permission verdicts instead of subscribing to the event each. One subscription
/// per configuration node manager keeps adding and removing a monitored item O(1): a
/// per-node subscription rebuilds the multicast invocation list, an array as long as all
/// monitored nodes of the server, on every first add and last remove.
/// </remarks>
internal sealed class DefaultPermissionsVersion
{
private DefaultPermissionsVersion(IConfigurationNodeManager owner)
{
Owner = owner;
// every counter starts in its own range, so a verdict stamped with the counter of
// a replaced configuration node manager never matches the counter of the new one.
m_value = Interlocked.Add(ref s_nextBase, 1L << 32);
}

/// <summary>
/// The configuration node manager whose notifications are counted.
/// </summary>
public IConfigurationNodeManager Owner { get; }

/// <summary>
/// Moves on every notification. A value read before a verdict was computed that still
/// matches afterwards means no notification was raised in between.
/// </summary>
public long Value => Interlocked.Read(ref m_value);

/// <summary>
/// Returns the counter of the server's current configuration node manager, reusing
/// <paramref name="cached"/> while it still belongs to it.
/// </summary>
/// <returns><c>null</c> when the server has no configuration node manager.</returns>
public static DefaultPermissionsVersion? Get(
IServerInternal server,
ref DefaultPermissionsVersion? cached)
{
IConfigurationNodeManager? owner = server.ConfigurationNodeManager;
if (owner == null)
{
return null;
}
DefaultPermissionsVersion? current = Volatile.Read(ref cached);
if (current == null || !ReferenceEquals(current.Owner, owner))
{
current = s_versions.GetValue(owner, static value => new DefaultPermissionsVersion(value));
current.EnsureSubscribed();
Volatile.Write(ref cached, current);
}
return current;
}

/// <summary>
/// Subscribes once and returns only after the handler is attached, so no caller can
/// stamp a verdict with <see cref="Value"/> while a notification could still be missed.
/// The factory of <see cref="ConditionalWeakTable{TKey, TValue}"/> may run more than once
/// under a race, so only the published instance subscribes.
/// </summary>
private void EnsureSubscribed()
{
if (Volatile.Read(ref m_subscribed))
{
return;
}
lock (m_subscribeLock)
{
if (!m_subscribed)
{
Owner.DefaultPermissionsChanged += OnDefaultPermissionsChanged;
Volatile.Write(ref m_subscribed, true);
}
}
}

private void OnDefaultPermissionsChanged(object? sender, EventArgs e)
{
Interlocked.Increment(ref m_value);
}

private static readonly ConditionalWeakTable<IConfigurationNodeManager, DefaultPermissionsVersion>
s_versions = new();
private static long s_nextBase;
private readonly Lock m_subscribeLock = new();
private long m_value;
private bool m_subscribed;
}
}
50 changes: 15 additions & 35 deletions src/Opc.Ua.Server/NodeManager/MonitoredItem/MonitoredNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,17 +348,10 @@ public void Add(IDataChangeMonitoredItem2 datachangeItem)
{
throw new ObjectDisposedException(nameof(MonitoredNode2));
}
bool wasEmpty = !HasMonitoredItems;
m_dataChangeMonitoredItems.TryAdd(datachangeItem.Id, datachangeItem);
m_dataChangeItems = null;

Node.OnStateChangedAsync = OnMonitoredNodeChangedAsync;

// Subscribe to namespace default permission changes when the first item is added.
if (wasEmpty && m_server.ConfigurationNodeManager != null)
{
m_server.ConfigurationNodeManager.DefaultPermissionsChanged += OnDefaultPermissionsChanged;
}
}
}

Expand All @@ -380,12 +373,6 @@ public void Remove(IDataChangeMonitoredItem2 datachangeItem)
if (m_dataChangeMonitoredItems.IsEmpty)
{
Node.OnStateChangedAsync = null;

// Unsubscribe from namespace default permission changes when the last item is removed.
if (m_eventMonitoredItems.IsEmpty)
{
m_server.ConfigurationNodeManager?.DefaultPermissionsChanged -= OnDefaultPermissionsChanged;
}
}
}
}
Expand Down Expand Up @@ -440,15 +427,10 @@ public void Add(IEventMonitoredItem eventItem)
{
throw new ObjectDisposedException(nameof(MonitoredNode2));
}
bool wasEmpty = !HasMonitoredItems;
m_eventMonitoredItems.TryAdd(eventItem.Id, eventItem);
m_eventItems = null;

Node.OnReportEventAsync = OnReportEventAsync;
if (wasEmpty && m_server.ConfigurationNodeManager != null)
{
m_server.ConfigurationNodeManager.DefaultPermissionsChanged += OnDefaultPermissionsChanged;
}
}
}

Expand All @@ -470,10 +452,6 @@ public void Remove(IEventMonitoredItem eventItem)
if (m_eventMonitoredItems.IsEmpty)
{
Node.OnReportEventAsync = null;
if (m_dataChangeMonitoredItems.IsEmpty)
{
m_server.ConfigurationNodeManager?.DefaultPermissionsChanged -= OnDefaultPermissionsChanged;
}
}
}
}
Expand Down Expand Up @@ -1838,7 +1816,7 @@ source.Node is not { } sourceNode ||
EndpointDescription? endpoint = MonitoredReadAuthorization.GetEndpoint(context.Session);
if (!TryGetEventRestrictionVerdict(
endpoint,
Volatile.Read(ref m_permissionGeneration),
PermissionGeneration,
NamespaceDefaultPermissionReader.Generation,
Node.AccessRestrictions,
out _,
Expand Down Expand Up @@ -1990,7 +1968,7 @@ private async ValueTask<ServiceResult> ValidateEventRestrictionsAsync(
{
ISession? session = monitoredItem.Session;
EndpointDescription? endpoint = MonitoredReadAuthorization.GetEndpoint(session);
long generation = Volatile.Read(ref m_permissionGeneration);
long generation = PermissionGeneration;
long defaultsGeneration = NamespaceDefaultPermissionReader.Generation;
AccessRestrictionType? restrictions = Node.AccessRestrictions;
if (TryGetEventRestrictionVerdict(
Expand All @@ -2010,7 +1988,7 @@ private async ValueTask<ServiceResult> ValidateEventRestrictionsAsync(
if (slot != null &&
ServiceResult.IsGood(result) &&
ReferenceEquals(context.ChannelContext?.EndpointDescription, endpoint) &&
generation == Volatile.Read(ref m_permissionGeneration) &&
generation == PermissionGeneration &&
defaultsGeneration == NamespaceDefaultPermissionReader.Generation &&
restrictions == Node.AccessRestrictions &&
NamespaceDefaultPermissionReader.AreDefaultsStatic(defaults))
Expand Down Expand Up @@ -2048,7 +2026,7 @@ private bool TryGetEventRestrictionVerdict(
EventRestrictionVerdict? verdict = Volatile.Read(ref slot.Current);
return verdict != null &&
verdict.Matches(generation, defaultsGeneration, defaults, endpoint, restrictions) &&
generation == Volatile.Read(ref m_permissionGeneration) &&
generation == PermissionGeneration &&
defaultsGeneration == NamespaceDefaultPermissionReader.Generation &&
restrictions == Node.AccessRestrictions;
}
Expand All @@ -2060,7 +2038,7 @@ private MonitoredItemPermissionContext CapturePermissionContext(IMonitoredItem m
{
ISession? session = monitoredItem.Session;
return new MonitoredItemPermissionContext(
Volatile.Read(ref m_permissionGeneration),
PermissionGeneration,
NodeState.RolePermissionsVersion,
Node,
Node.PermissionVersion,
Expand Down Expand Up @@ -2674,14 +2652,16 @@ public void InvalidatePermissionCacheForSession(NodeId sessionId)
}

/// <summary>
/// Called when the namespace default permissions (<c>DefaultRolePermissions</c> or
/// <c>DefaultUserRolePermissions</c>) change. Invalidates the entire permission cache
/// so that all entries are re-validated on the next value change.
/// The stamp of every cached permission verdict of the node. It moves when the node
/// invalidates its caches and when the namespace default permissions
/// (<c>DefaultRolePermissions</c>, <c>DefaultUserRolePermissions</c> or
/// <c>DefaultAccessRestrictions</c>) change, so every verdict is validated again on its
/// next use. The defaults are observed through one server-wide counter instead of a
/// subscription per node, which keeps adding and removing items O(1).
/// </summary>
private void OnDefaultPermissionsChanged(object? sender, EventArgs e)
{
InvalidatePermissionCaches();
}
private long PermissionGeneration =>
Volatile.Read(ref m_permissionGeneration) +
(DefaultPermissionsVersion.Get(m_server, ref m_defaultPermissionsVersion)?.Value ?? 0);

/// <summary>
/// Invalidates an item only while the deleted source still owns its binding.
Expand Down Expand Up @@ -2816,6 +2796,7 @@ private ConditionalWeakTable<EndpointDescription, EventRestrictionVerdictSlot>?
m_eventRestrictionVerdicts;

private long m_permissionGeneration;
private DefaultPermissionsVersion? m_defaultPermissionsVersion;


/// <summary>
Expand Down Expand Up @@ -3149,7 +3130,6 @@ protected virtual void Dispose(bool disposing)
m_draining = true;
if (disposing)
{
m_server.ConfigurationNodeManager?.DefaultPermissionsChanged -= OnDefaultPermissionsChanged;
if (Node.OnStateChangedAsync == OnMonitoredNodeChangedAsync)
{
Node.OnStateChangedAsync = null;
Expand Down
47 changes: 7 additions & 40 deletions src/Opc.Ua.Server/NodeManager/MonitoredItem/SamplingGroup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ protected virtual void Dispose(bool disposing)
lock (m_lock)
{
(samplingCts, samplingTask) = DetachSamplingLoop();
UnsubscribePermissionChanges();
}

CancelSamplingLoop(samplingCts, samplingTask);
Expand All @@ -142,7 +141,6 @@ public void Startup()
m_samplingCts = samplingCts;
CancellationToken token = samplingCts.Token;
double samplingInterval = m_samplingInterval;
SubscribePermissionChanges();
m_samplingTask = Task.Run(
() => SampleMonitoredItemsAsync(samplingInterval, samplingCts, token).AsTask(),
CancellationToken.None);
Expand All @@ -157,50 +155,20 @@ public void Shutdown()
lock (m_lock)
{
StopSamplingLoop();
UnsubscribePermissionChanges();
m_items.Clear();
m_itemSnapshot = null;
}
}

/// <summary>
/// Invalidates the cached role permission verdicts of the sampled items when the
/// default permissions of a namespace change. Must be called while holding the lock.
/// </summary>
private void SubscribePermissionChanges()
{
if (m_configurationNodeManager != null)
{
return;
}

IConfigurationNodeManager? configurationNodeManager = m_server.ConfigurationNodeManager;
if (configurationNodeManager != null)
{
configurationNodeManager.DefaultPermissionsChanged += OnDefaultPermissionsChanged;
m_configurationNodeManager = configurationNodeManager;
}
}

/// <summary>
/// Stops observing namespace default permission changes. Must be called while holding the lock.
/// </summary>
private void UnsubscribePermissionChanges()
{
m_configurationNodeManager?.DefaultPermissionsChanged -= OnDefaultPermissionsChanged;
m_configurationNodeManager = null;
}

private void OnDefaultPermissionsChanged(object? sender, EventArgs e)
{
Interlocked.Increment(ref m_permissionEpoch);
}

/// <summary>
/// Changes whenever a cached role permission verdict of an item may be stale: the role
/// permissions of a node or the default permissions of a namespace changed.
/// permissions of a node or the default permissions of a namespace changed. The defaults
/// are observed through the server-wide <see cref="DefaultPermissionsVersion"/>, not a
/// subscription per group.
/// </summary>
private long PermissionEpoch => Interlocked.Read(ref m_permissionEpoch) + NodeState.RolePermissionsVersion;
private long PermissionEpoch =>
(DefaultPermissionsVersion.Get(m_server, ref m_defaultPermissionsVersion)?.Value ?? 0) +
NodeState.RolePermissionsVersion;

/// <summary>
/// Stops the running sampling loop. Must be called while holding the lock.
Expand Down Expand Up @@ -1275,8 +1243,7 @@ private readonly record struct PermissionVerdict(
private readonly Dictionary<uint, ISampledDataChangeMonitoredItem> m_items;
private readonly List<SamplingRateGroup> m_samplingRates;
private ISampledDataChangeMonitoredItem[]? m_itemSnapshot;
private IConfigurationNodeManager? m_configurationNodeManager;
private long m_permissionEpoch;
private DefaultPermissionsVersion? m_defaultPermissionsVersion;
private Task? m_samplingTask;
// Dispose detaches the source and CancelSamplingLoop disposes it once the loop completes.
// TODO: Remove the pragma when CA2213 recognizes deferred ownership transfer.
Expand Down
Loading
Loading