Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,13 @@ namespace Opc.Ua.Server
public partial class ConfigurationNodeManager :
INamespaceMetadataHost,
INamespaceMetadataSnapshot,
INamespaceMetadataSource
INamespaceMetadataSource,
INamespaceDefaultPermissionCacheProvider
{
/// <inheritdoc/>
NamespaceDefaultPermissionCache INamespaceDefaultPermissionCacheProvider.DefaultPermissionCache
=> m_namespaceMetadata.DefaultPermissionCache;

/// <inheritdoc/>
public event EventHandler? DefaultPermissionsChanged
{
Expand Down
445 changes: 445 additions & 0 deletions src/Opc.Ua.Server/Configuration/NamespaceDefaultPermissionCache.cs

Large diffs are not rendered by default.

78 changes: 68 additions & 10 deletions src/Opc.Ua.Server/Configuration/NamespaceDefaultPermissionReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,14 @@ public static async ValueTask<NamespaceDefaultPermissions> ReadAsync(
}

OperationContext? operationContext = callerContext.OperationContext;
if (operationContext != null &&
operationContext.TryGetDefaultPermissions(namespaceIndex, out NamespaceDefaultPermissions cached))
IConfigurationNodeManager? configuration = server.NodeManager?.ConfigurationNodeManager;
if (TryGetCached(operationContext, configuration, namespaceIndex, out NamespaceDefaultPermissions cached))
{
return cached;
}

long generation = Generation;
NamespaceMetadataNode? state = null;
IConfigurationNodeManager? configuration = server.NodeManager?.ConfigurationNodeManager;
if (configuration != null)
{
try
Expand All @@ -130,9 +129,7 @@ public static async ValueTask<NamespaceDefaultPermissions> ReadAsync(
}
}

NamespaceDefaultPermissions result = Decode(callerContext, state, namespaceIndex, generation);
operationContext?.SetDefaultPermissions(result);
return result;
return DecodeAndRemember(callerContext, operationContext, configuration, state, namespaceIndex, generation);
}

/// <summary>
Expand All @@ -156,15 +153,14 @@ public static NamespaceDefaultPermissions Read(
}

OperationContext? operationContext = callerContext.OperationContext;
if (operationContext != null &&
operationContext.TryGetDefaultPermissions(namespaceIndex, out NamespaceDefaultPermissions cached))
IConfigurationNodeManager? configuration = server.NodeManager?.ConfigurationNodeManager;
if (TryGetCached(operationContext, configuration, namespaceIndex, out NamespaceDefaultPermissions cached))
{
return cached;
}

long generation = Generation;
NamespaceMetadataNode? state = null;
IConfigurationNodeManager? configuration = server.NodeManager?.ConfigurationNodeManager;
if (configuration != null)
{
if (configuration is not INamespaceMetadataSnapshot snapshot)
Expand All @@ -185,7 +181,69 @@ public static NamespaceDefaultPermissions Read(
}
}

return DecodeAndRemember(callerContext, operationContext, configuration, state, namespaceIndex, generation);
}

/// <summary>
/// Looks the defaults up in the request cache of <paramref name="operationContext"/>, then
/// in the server-wide cache of <paramref name="configuration"/>.
/// </summary>
private static bool TryGetCached(
OperationContext? operationContext,
IConfigurationNodeManager? configuration,
ushort namespaceIndex,
out NamespaceDefaultPermissions permissions)
{
if (operationContext != null &&
operationContext.TryGetDefaultPermissions(namespaceIndex, out permissions))
{
return true;
}

if (configuration is INamespaceDefaultPermissionCacheProvider provider &&
provider.DefaultPermissionCache.TryGet(namespaceIndex, out permissions))
{
// the hit is a private copy: share it with the rest of this request only.
operationContext?.SetDefaultPermissions(permissions);
return true;
}

permissions = default;
return false;
}

/// <summary>
/// Decodes the defaults, remembers them server-wide when they are static and for the
/// rest of the service request of <paramref name="operationContext"/>.
/// </summary>
private static NamespaceDefaultPermissions DecodeAndRemember(
ServerSystemContext callerContext,
OperationContext? operationContext,
IConfigurationNodeManager? configuration,
NamespaceMetadataNode? state,
ushort namespaceIndex,
long generation)
{
// capture the properties before reading them: a typed state reads its slots live.
BaseVariableState? accessRestrictions = state?.DefaultAccessRestrictions;
BaseVariableState? rolePermissions = state?.DefaultRolePermissions;
BaseVariableState? userRolePermissions = state?.DefaultUserRolePermissions;
// a callback that removes itself while it runs must not make its result look static.
bool staticBeforeDecode = IsStatic(accessRestrictions) &&
IsStatic(rolePermissions) &&
IsStatic(userRolePermissions);
// any assignment from here on, reported or not, makes the entry stale at once.
DefaultPropertyVersions versions = DefaultPropertyVersions.Capture(
accessRestrictions, rolePermissions, userRolePermissions);
NamespaceDefaultPermissions result = Decode(callerContext, state, namespaceIndex, generation);
if (configuration is INamespaceDefaultPermissionCacheProvider provider)
{
provider.DefaultPermissionCache.TryAdd(
state, accessRestrictions, rolePermissions, userRolePermissions, result,
staticBeforeDecode,
versions);
}

operationContext?.SetDefaultPermissions(result);
return result;
}
Expand Down Expand Up @@ -391,7 +449,7 @@ internal static bool AreDefaultsStatic(NamespaceMetadataNode? state)
IsStatic(state.DefaultUserRolePermissions));
}

private static bool IsStatic(BaseVariableState? property)
internal static bool IsStatic(BaseVariableState? property)
{
return property == null ||
(IsWithoutReadCallbacks(property) &&
Expand Down
31 changes: 31 additions & 0 deletions src/Opc.Ua.Server/Configuration/NamespaceMetadataRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,29 @@ public NamespaceMetadataRegistry(INamespaceMetadataHost host, ILogger logger)
{
m_host = host ?? throw new ArgumentNullException(nameof(host));
m_logger = logger ?? throw new ArgumentNullException(nameof(logger));
DefaultPermissionCache = new NamespaceDefaultPermissionCache(AreDefaultPropertiesTracked);
}

/// <summary>
/// Returns <c>true</c> when this registry is subscribed to the value changes of each of
/// the given default properties of <paramref name="metadata"/>. Only then does a reported
/// change of one of them move <see cref="NamespaceDefaultPermissionReader.Generation"/>,
/// so only then may its decoded defaults be cached. A property replaced in a typed state
/// is subscribed once the change of the node's children is reported.
/// </summary>
internal bool AreDefaultPropertiesTracked(
NamespaceMetadataNode metadata,
BaseVariableState? accessRestrictions,
BaseVariableState? rolePermissions,
BaseVariableState? userRolePermissions)
{
lock (m_lock)
{
return m_trackedProperties.TryGetValue(metadata.Node, out HashSet<BaseVariableState>? tracked) &&
(accessRestrictions == null || tracked.Contains(accessRestrictions)) &&
(rolePermissions == null || tracked.Contains(rolePermissions)) &&
(userRolePermissions == null || tracked.Contains(userRolePermissions));
}
}

/// <summary>
Expand All @@ -86,6 +109,13 @@ public NamespaceMetadataRegistry(INamespaceMetadataHost host, ILogger logger)
/// </summary>
public event EventHandler? DefaultPermissionsChanged;

/// <summary>
/// The server-wide cache of decoded static namespace defaults. Its entries are retired
/// by every move of <see cref="NamespaceDefaultPermissionReader.Generation"/> this
/// registry makes, and dropped by <see cref="Detach"/>.
/// </summary>
public NamespaceDefaultPermissionCache DefaultPermissionCache { get; }

/// <summary>
/// Gets the <see cref="NamespaceMetadataState"/> for
/// <paramref name="namespaceUri"/>, or <c>null</c> when none exists or
Expand Down Expand Up @@ -889,6 +919,7 @@ public void Detach()
}

NamespaceDefaultPermissionReader.Invalidate();
DefaultPermissionCache.Clear();
}

/// <summary>
Expand Down
111 changes: 86 additions & 25 deletions src/Opc.Ua.Server/Server/OperationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: MIT

using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading;

Expand Down Expand Up @@ -1089,36 +1090,49 @@ private sealed class SystemContextCache
/// <remarks>
/// Permission checks read the DefaultAccessRestrictions, DefaultRolePermissions
/// and DefaultUserRolePermissions of the node's namespace for every node of a
/// request, which took two server-wide locks and deep-copied the role permission
/// array per node. One read per namespace and request is enough. Contexts that
/// are not a service request (monitored item and session contexts, which can be
/// kept for a long time) remember nothing, so a changed default applies to them
/// at once.
/// request. Static defaults are remembered server-wide by
/// <see cref="NamespaceDefaultPermissionCache"/>; this cache keeps the defaults
/// that depend on the caller (read callbacks) for one service request. Contexts
/// that are not a service request (monitored item and session contexts, which can
/// be kept for a long time) remember nothing here, so a changed dynamic default
/// applies to them at once. Entries are indexed by namespace index: a slot array
/// for the first <see cref="kDefaultPermissionSlots"/> namespaces, sized to the highest
/// index seen, and a concurrent dictionary beyond it.
/// </remarks>
internal bool TryGetDefaultPermissions(
ushort namespaceIndex,
out NamespaceDefaultPermissions permissions)
{
NamespaceDefaultPermissions[]? entries = m_defaultPermissions;
if (entries != null)
StrongBox<NamespaceDefaultPermissions>? entry = null;
if (namespaceIndex < kDefaultPermissionSlots)
{
long generation = NamespaceDefaultPermissionReader.Generation;
foreach (NamespaceDefaultPermissions entry in entries)
StrongBox<NamespaceDefaultPermissions>?[]? slots = Volatile.Read(ref m_defaultPermissionSlots);
if (slots != null && namespaceIndex < slots.Length)
{
if (entry.NamespaceIndex == namespaceIndex && entry.Generation == generation)
{
permissions = entry;
return true;
}
entry = Volatile.Read(ref slots[namespaceIndex]);
}
}
else
{
ConcurrentDictionary<ushort, StrongBox<NamespaceDefaultPermissions>>? overflow =
Volatile.Read(ref m_defaultPermissionOverflow);
overflow?.TryGetValue(namespaceIndex, out entry);
}

if (entry != null && entry.Value.Generation == NamespaceDefaultPermissionReader.Generation)
{
permissions = entry.Value;
return true;
}

permissions = default;
return false;
}

/// <summary>
/// Remembers the namespace default permissions for the rest of this service request.
/// Node managers can validate nodes of one request concurrently: each slot is replaced
/// as a whole, and a lost update only costs a second read.
/// </summary>
internal void SetDefaultPermissions(NamespaceDefaultPermissions permissions)
{
Expand All @@ -1130,19 +1144,63 @@ internal void SetDefaultPermissions(NamespaceDefaultPermissions permissions)
return;
}

// copy on write: node managers can validate nodes of one request concurrently,
// and a lost update only costs a second read.
NamespaceDefaultPermissions[]? entries = m_defaultPermissions;
if (entries == null)
var entry = new StrongBox<NamespaceDefaultPermissions>(permissions);
ushort namespaceIndex = permissions.NamespaceIndex;
if (namespaceIndex < kDefaultPermissionSlots)
{
m_defaultPermissions = [permissions];
StrongBox<NamespaceDefaultPermissions>?[] slots = GetDefaultPermissionSlots(namespaceIndex);

Volatile.Write(ref slots[namespaceIndex], entry);
return;
}

var updated = new NamespaceDefaultPermissions[entries.Length + 1];
Array.Copy(entries, updated, entries.Length);
updated[entries.Length] = permissions;
m_defaultPermissions = updated;
ConcurrentDictionary<ushort, StrongBox<NamespaceDefaultPermissions>>? overflow =
Volatile.Read(ref m_defaultPermissionOverflow);
if (overflow == null)
{
overflow = new ConcurrentDictionary<ushort, StrongBox<NamespaceDefaultPermissions>>();
overflow = Interlocked.CompareExchange(ref m_defaultPermissionOverflow, overflow, null) ?? overflow;
}

overflow[namespaceIndex] = entry;
}

/// <summary>
/// Returns a slot array that holds <paramref name="namespaceIndex"/>, sized to the
/// highest index seen so a request over a few low namespaces allocates little. A
/// store into an array that a concurrent grow just replaced is lost; that only costs
/// a second read.
/// </summary>
private StrongBox<NamespaceDefaultPermissions>?[] GetDefaultPermissionSlots(ushort namespaceIndex)
{
while (true)
{
StrongBox<NamespaceDefaultPermissions>?[]? slots = Volatile.Read(ref m_defaultPermissionSlots);
if (slots != null && namespaceIndex < slots.Length)
{
return slots;
}

int length = slots?.Length ?? 4;
while (length <= namespaceIndex)
{
length *= 2;
}

var grown = new StrongBox<NamespaceDefaultPermissions>?[Math.Min(length, kDefaultPermissionSlots)];
if (slots != null)
{
for (int ii = 0; ii < slots.Length; ii++)
{
grown[ii] = Volatile.Read(ref slots[ii]);
}
}

if (ReferenceEquals(Interlocked.CompareExchange(ref m_defaultPermissionSlots, grown, slots), slots))
{
return grown;
}
}
}

/// <summary>
Expand All @@ -1153,7 +1211,8 @@ internal void SetDefaultPermissions(NamespaceDefaultPermissions permissions)
internal void DisableDefaultPermissionCache()
{
m_defaultPermissionCacheDisabled = true;
m_defaultPermissions = null;
Volatile.Write(ref m_defaultPermissionSlots, null);
Volatile.Write(ref m_defaultPermissionOverflow, null);
}

/// <summary>
Expand Down Expand Up @@ -1365,7 +1424,9 @@ public void Dispose()
private readonly Action? m_beforeRoutingBootstrap;

private SystemContextCache? m_systemContextCache;
private NamespaceDefaultPermissions[]? m_defaultPermissions;
private StrongBox<NamespaceDefaultPermissions>?[]? m_defaultPermissionSlots;
private ConcurrentDictionary<ushort, StrongBox<NamespaceDefaultPermissions>>? m_defaultPermissionOverflow;
private const int kDefaultPermissionSlots = 64;
private bool m_defaultPermissionCacheDisabled;
private static uint s_lastRequestId;
private const int kRoutingPinUnclaimed = 0;
Expand Down
Loading
Loading