From c4df7673d740b97e79943186ea8967c09a7904b5 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sun, 29 Nov 2026 17:50:21 +0100 Subject: [PATCH 1/2] Server: observe namespace default permission changes through one counter (N14) Every MonitoredNode2 subscribed to the server-wide IConfigurationNodeManager.DefaultPermissionsChanged event on its first item and unsubscribed on its last, and every SamplingGroup did the same on startup. Each += / -= rebuilds the multicast invocation list, an array as long as all subscribers, so adding or removing a monitored item cost O(monitored nodes on the server) and a reload of a manager with many monitored nodes was quadratic. DefaultPermissionsVersion now subscribes once per configuration node manager and counts the notifications. Monitored nodes fold the counter into the generation that stamps their cached data-change, event and event-restriction verdicts; sampling groups fold it into their permission epoch. A notification still invalidates every verdict before its next use, as before, but adding and removing items no longer touches the event. Co-Authored-By: Claude Opus 5.5 --- .../DefaultPermissionsVersion.cs | 90 ++++++++++ .../MonitoredItem/MonitoredNode.cs | 50 ++---- .../MonitoredItem/SamplingGroup.cs | 47 +---- .../MonitoredNode2Tests.cs | 161 +++++++++++++++++- 4 files changed, 271 insertions(+), 77 deletions(-) create mode 100644 src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs diff --git a/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs b/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs new file mode 100644 index 0000000000..52b438cdd8 --- /dev/null +++ b/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs @@ -0,0 +1,90 @@ +// 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 +{ + /// + /// Counts the + /// notifications of one configuration node manager. + /// + /// + /// Monitored nodes and sampling groups fold 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. + /// + 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); + } + + /// + /// The configuration node manager whose notifications are counted. + /// + public IConfigurationNodeManager Owner { get; } + + /// + /// Moves on every notification. A value read before a verdict was computed that still + /// matches afterwards means no notification was raised in between. + /// + public long Value => Interlocked.Read(ref m_value); + + /// + /// Returns the counter of the server's current configuration node manager, reusing + /// while it still belongs to it. + /// + /// null when the server has no configuration node manager. + 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; + } + + /// + /// Subscribes once. The factory of may + /// run more than once under a race, so the losing instance must not subscribe. + /// + private void EnsureSubscribed() + { + if (Volatile.Read(ref m_subscribed) == 0 && + Interlocked.CompareExchange(ref m_subscribed, 1, 0) == 0) + { + Owner.DefaultPermissionsChanged += OnDefaultPermissionsChanged; + } + } + + private void OnDefaultPermissionsChanged(object? sender, EventArgs e) + { + Interlocked.Increment(ref m_value); + } + + private static readonly ConditionalWeakTable + s_versions = new(); + private static long s_nextBase; + private long m_value; + private int m_subscribed; + } +} diff --git a/src/Opc.Ua.Server/NodeManager/MonitoredItem/MonitoredNode.cs b/src/Opc.Ua.Server/NodeManager/MonitoredItem/MonitoredNode.cs index ae79a3cb23..1764abfee0 100644 --- a/src/Opc.Ua.Server/NodeManager/MonitoredItem/MonitoredNode.cs +++ b/src/Opc.Ua.Server/NodeManager/MonitoredItem/MonitoredNode.cs @@ -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; - } } } @@ -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; - } } } } @@ -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; - } } } @@ -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; - } } } } @@ -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 _, @@ -1990,7 +1968,7 @@ private async ValueTask 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( @@ -2010,7 +1988,7 @@ private async ValueTask 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)) @@ -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; } @@ -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, @@ -2674,14 +2652,16 @@ public void InvalidatePermissionCacheForSession(NodeId sessionId) } /// - /// Called when the namespace default permissions (DefaultRolePermissions or - /// DefaultUserRolePermissions) 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 + /// (DefaultRolePermissions, DefaultUserRolePermissions or + /// DefaultAccessRestrictions) 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). /// - 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); /// /// Invalidates an item only while the deleted source still owns its binding. @@ -2816,6 +2796,7 @@ private ConditionalWeakTable? m_eventRestrictionVerdicts; private long m_permissionGeneration; + private DefaultPermissionsVersion? m_defaultPermissionsVersion; /// @@ -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; diff --git a/src/Opc.Ua.Server/NodeManager/MonitoredItem/SamplingGroup.cs b/src/Opc.Ua.Server/NodeManager/MonitoredItem/SamplingGroup.cs index 6a9ff6b7ac..45c4644e9f 100644 --- a/src/Opc.Ua.Server/NodeManager/MonitoredItem/SamplingGroup.cs +++ b/src/Opc.Ua.Server/NodeManager/MonitoredItem/SamplingGroup.cs @@ -118,7 +118,6 @@ protected virtual void Dispose(bool disposing) lock (m_lock) { (samplingCts, samplingTask) = DetachSamplingLoop(); - UnsubscribePermissionChanges(); } CancelSamplingLoop(samplingCts, samplingTask); @@ -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); @@ -157,50 +155,20 @@ public void Shutdown() lock (m_lock) { StopSamplingLoop(); - UnsubscribePermissionChanges(); m_items.Clear(); m_itemSnapshot = null; } } - /// - /// 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. - /// - private void SubscribePermissionChanges() - { - if (m_configurationNodeManager != null) - { - return; - } - - IConfigurationNodeManager? configurationNodeManager = m_server.ConfigurationNodeManager; - if (configurationNodeManager != null) - { - configurationNodeManager.DefaultPermissionsChanged += OnDefaultPermissionsChanged; - m_configurationNodeManager = configurationNodeManager; - } - } - - /// - /// Stops observing namespace default permission changes. Must be called while holding the lock. - /// - private void UnsubscribePermissionChanges() - { - m_configurationNodeManager?.DefaultPermissionsChanged -= OnDefaultPermissionsChanged; - m_configurationNodeManager = null; - } - - private void OnDefaultPermissionsChanged(object? sender, EventArgs e) - { - Interlocked.Increment(ref m_permissionEpoch); - } - /// /// 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 , not a + /// subscription per group. /// - private long PermissionEpoch => Interlocked.Read(ref m_permissionEpoch) + NodeState.RolePermissionsVersion; + private long PermissionEpoch => + (DefaultPermissionsVersion.Get(m_server, ref m_defaultPermissionsVersion)?.Value ?? 0) + + NodeState.RolePermissionsVersion; /// /// Stops the running sampling loop. Must be called while holding the lock. @@ -1275,8 +1243,7 @@ private readonly record struct PermissionVerdict( private readonly Dictionary m_items; private readonly List 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. diff --git a/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs b/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs index f9058bc47c..c7759524d6 100644 --- a/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs +++ b/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs @@ -254,13 +254,170 @@ public void DisposedMonitoredNodeReleasesPermissionNotificationsAndNodeCallbacks monitored.Dispose(); monitored.Dispose(); - configuration.VerifyAdd(value => value.DefaultPermissionsChanged += It.IsAny(), Times.Once); + // adding and removing items never subscribes the node itself: the defaults are + // observed through one server-wide counter. + configuration.VerifyAdd( + value => value.DefaultPermissionsChanged += It.IsAny(), Times.Never); configuration.VerifyRemove( - value => value.DefaultPermissionsChanged -= It.IsAny(), Times.Once); + value => value.DefaultPermissionsChanged -= It.IsAny(), Times.Never); Assert.That(node.OnStateChangedAsync, Is.Null); Assert.That(node.OnReportEventAsync, Is.Null); } +#if NET + /// + /// Adding and removing an item allocates the same, however many monitored nodes the + /// server has. A subscription per node to the server-wide default permission event + /// copied an invocation list as long as all monitored nodes on every first add and + /// last remove. + /// + [Test] + public void AddAndRemoveItemAllocationIsIndependentOfMonitoredNodeCount() + { + const int kRounds = 200; + EventHandler? handlers = null; + var configuration = new Mock(); + configuration.SetupAdd(value => value.DefaultPermissionsChanged += It.IsAny()) + .Callback(handler => handlers += handler); + configuration.SetupRemove(value => value.DefaultPermissionsChanged -= It.IsAny()) + .Callback(handler => handlers -= handler); + var server = new Mock(); + server.SetupGet(value => value.ConfigurationNodeManager).Returns(configuration.Object); + IAsyncNodeManager nodeManager = Mock.Of(); + IDataChangeMonitoredItem2 probe = CreateDataChangeMonitoredItemMock(uint.MaxValue, Attributes.Value).Object; + var monitoredNodes = new List(); + try + { + long MeasurePerPair() + { + var target = new MonitoredNode2( + nodeManager, server.Object, new BaseObjectState(null) { NodeId = new NodeId(0u, 2) }); + monitoredNodes.Add(target); + // warm up the dictionaries and the mock interception. + target.Add(probe); + target.Remove(probe); + configuration.Invocations.Clear(); + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int ii = 0; ii < kRounds; ii++) + { + target.Add(probe); + target.Remove(probe); + } + long bytes = (GC.GetAllocatedBytesForCurrentThread() - before) / kRounds; + configuration.Invocations.Clear(); + return bytes; + } + + void AddMonitoredNodes(int count) + { + for (int ii = 0; ii < count; ii++) + { + var node = new MonitoredNode2( + nodeManager, + server.Object, + new BaseObjectState(null) { NodeId = new NodeId((uint)monitoredNodes.Count + 1, 3) }); + node.Add(CreateDataChangeMonitoredItemMock((uint)monitoredNodes.Count + 1, Attributes.Value).Object); + monitoredNodes.Add(node); + } + configuration.Invocations.Clear(); + } + + AddMonitoredNodes(10); + long small = MeasurePerPair(); + AddMonitoredNodes(5000); + long large = MeasurePerPair(); + TestContext.Out.WriteLine( + $"add+remove: {small} B at 10 monitored nodes, {large} B at 5,010 monitored nodes"); + Assert.That(large - small, Is.LessThan(1024), + "Adding and removing an item must not allocate in proportion to the monitored nodes."); + } + finally + { + foreach (MonitoredNode2 monitored in monitoredNodes) + { + monitored.Dispose(); + } + } + } +#endif + + [Test] + public async Task MonitoredNodesShareOneDefaultPermissionsSubscriptionAsync() + { + Mock server = DeterministicServerMock.Create(out MonitoredItemQueueFactory queues); + using (queues) + { + var configuration = new Mock(); + server.SetupGet(value => value.ConfigurationNodeManager).Returns(configuration.Object); + int calls = 0; + var nodeManager = new Mock(); + nodeManager.Setup(value => value.ValidateRolePermissionsAsync( + It.IsAny(), It.IsAny(), PermissionType.Read, + It.IsAny())) + .Returns(() => + { + Interlocked.Increment(ref calls); + return new ValueTask(ServiceResult.Good); + }); + var monitoredNodes = new List<(MonitoredNode2 Monitored, BaseDataVariableState Node)>(); + try + { + for (uint ii = 1; ii <= 3; ii++) + { + var node = new BaseDataVariableState(null) + { + NodeId = new NodeId(ii, 1), + DataType = DataTypeIds.Int32, + Value = 42, + AccessLevel = AccessLevels.CurrentRead, + UserAccessLevel = AccessLevels.CurrentRead + }; + var monitored = new MonitoredNode2(nodeManager.Object, server.Object, node); + monitoredNodes.Add((monitored, node)); + monitored.Add(CreateDataChangeMonitoredItemMockWithSession( + ii, Attributes.Value, new NodeId(2, 1)).Object); + } + + async Task ChangeAllAsync() + { + foreach ((MonitoredNode2 monitored, BaseDataVariableState node) in monitoredNodes) + { + await monitored.OnMonitoredNodeChangedAsync( + server.Object.DefaultSystemContext, node, NodeStateChangeMasks.Value) + .ConfigureAwait(false); + await monitored.WaitForPendingNotificationsAsync(CancellationToken.None) + .ConfigureAwait(false); + } + } + + await ChangeAllAsync().ConfigureAwait(false); + int validated = Volatile.Read(ref calls); + Assert.That(validated, Is.EqualTo(3)); + + // cached verdicts are reused while the defaults are unchanged. + await ChangeAllAsync().ConfigureAwait(false); + Assert.That(Volatile.Read(ref calls), Is.EqualTo(validated)); + + // one notification invalidates the verdicts of every node. + configuration.Raise(value => value.DefaultPermissionsChanged += null, EventArgs.Empty); + await ChangeAllAsync().ConfigureAwait(false); + Assert.That(Volatile.Read(ref calls), Is.EqualTo(validated + 3)); + } + finally + { + foreach ((MonitoredNode2 monitored, _) in monitoredNodes) + { + await monitored.DisposeAsync().ConfigureAwait(false); + } + } + + configuration.VerifyAdd( + value => value.DefaultPermissionsChanged += It.IsAny(), Times.Once); + configuration.VerifyRemove( + value => value.DefaultPermissionsChanged -= It.IsAny(), Times.Never); + } + } + [TestCase(false)] [TestCase(true)] public async Task InFlightDataPermissionCannotReviveInvalidatedGrantAsync(bool defaultsChanged) From 692b239e47b025b54b85968b1b3a5c7660f3c620 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Mon, 30 Nov 2026 05:55:55 +0100 Subject: [PATCH 2/2] Server: publish the default-permissions subscription only after += (N14) A concurrent first caller could see the subscribed flag before the handler was attached and stamp a verdict with a counter that could still miss a notification. Subscribe under a lock and publish the flag after the handler is attached; a regression test gates the event add accessor with two concurrent callers. Co-Authored-By: Claude Opus 5.5 --- .../DefaultPermissionsVersion.cs | 22 ++++++--- .../MonitoredNode2Tests.cs | 45 +++++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs b/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs index 52b438cdd8..3685f8a025 100644 --- a/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs +++ b/src/Opc.Ua.Server/NodeManager/MonitoredItem/DefaultPermissionsVersion.cs @@ -64,15 +64,24 @@ private DefaultPermissionsVersion(IConfigurationNodeManager owner) } /// - /// Subscribes once. The factory of may - /// run more than once under a race, so the losing instance must not subscribe. + /// Subscribes once and returns only after the handler is attached, so no caller can + /// stamp a verdict with while a notification could still be missed. + /// The factory of may run more than once + /// under a race, so only the published instance subscribes. /// private void EnsureSubscribed() { - if (Volatile.Read(ref m_subscribed) == 0 && - Interlocked.CompareExchange(ref m_subscribed, 1, 0) == 0) + if (Volatile.Read(ref m_subscribed)) { - Owner.DefaultPermissionsChanged += OnDefaultPermissionsChanged; + return; + } + lock (m_subscribeLock) + { + if (!m_subscribed) + { + Owner.DefaultPermissionsChanged += OnDefaultPermissionsChanged; + Volatile.Write(ref m_subscribed, true); + } } } @@ -84,7 +93,8 @@ private void OnDefaultPermissionsChanged(object? sender, EventArgs e) private static readonly ConditionalWeakTable s_versions = new(); private static long s_nextBase; + private readonly Lock m_subscribeLock = new(); private long m_value; - private int m_subscribed; + private bool m_subscribed; } } diff --git a/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs b/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs index c7759524d6..a4a4fa88ce 100644 --- a/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs +++ b/tests/Opc.Ua.Server.Tests/MonitoredNode2Tests.cs @@ -341,6 +341,51 @@ void AddMonitoredNodes(int count) } #endif + [Test] + public async Task DefaultPermissionsVersionReturnsOnlyAfterTheHandlerIsAttachedAsync() + { + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + EventHandler? handlers = null; + var configuration = new Mock(); + configuration.SetupAdd(value => value.DefaultPermissionsChanged += It.IsAny()) + .Callback(handler => + { + entered.Set(); + release.Wait(TimeSpan.FromSeconds(10)); + handlers += handler; + }); + var server = new Mock(); + server.SetupGet(value => value.ConfigurationNodeManager).Returns(configuration.Object); + DefaultPermissionsVersion? firstCache = null; + DefaultPermissionsVersion? secondCache = null; + try + { + Task first = Task.Run( + () => DefaultPermissionsVersion.Get(server.Object, ref firstCache)); + Assert.That(entered.Wait(TimeSpan.FromSeconds(10)), Is.True); + Task second = Task.Run( + () => DefaultPermissionsVersion.Get(server.Object, ref secondCache)!.Value); + + // a stamp taken while the handler is not attached could miss a notification. + Task completed = await Task.WhenAny(second, Task.Delay(200)).ConfigureAwait(false); + Assert.That(completed, Is.Not.SameAs(second), + "A concurrent caller must wait until the handler is attached."); + + release.Set(); + long stamp = await second.ConfigureAwait(false); + handlers!.Invoke(configuration.Object, EventArgs.Empty); + DefaultPermissionsVersion? version = await first.ConfigureAwait(false); + Assert.That(version!.Value, Is.Not.EqualTo(stamp)); + configuration.VerifyAdd( + value => value.DefaultPermissionsChanged += It.IsAny(), Times.Once); + } + finally + { + release.Set(); + } + } + [Test] public async Task MonitoredNodesShareOneDefaultPermissionsSubscriptionAsync() {