mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-29 15:11:53 +08:00
Removes per-request allocations on the server's single-value Read path
with small, internal changes. No wire-format change, no public API
change, no change of the execution model (the receive loop is
untouched). Exactly-once semantics of the isolation leases,
cancellation, timeouts, diagnostics and auditing are unchanged.
## Effect
Allocated bytes per single-value Read (perf harness, `native-read`, 10
clients x 100 in flight, `AsyncCustomNodeManager`, Server GC;
deterministic):
| | 1 core | 4 cores |
|---|---|---|
| master 4ae2395f3 | 2929 | 2753 |
| this PR | 2320 (-21 %) | 2326 (-16 %) |
Per commit (4 cores): T1 -120 B, T2 -64 B, receive chunk list ~-70 B,
closure -17 B, pool floor -74 B, routing capture ~-100 B.
CPU per request is unchanged within the noise of a shared machine
(paired, alternating A/B rounds, 4 pinned cores: async node manager -1.8
%, encrypted -4.7 %, sync node manager +2.5 %, all ranges overlapping).
Read with 1/100 nodes and 20/200 sessions, Browse and subscriptions show
no regression and 1-14 % fewer bytes.
## Changes (one commit each)
1. **Isolation stages held as reservations.** `FairRequestQueue`
acquired three to four `Lease` objects per request. The default provider
now also admits by value through an internal
`IResourceIsolationReservations`; the queue entry keeps one compact hold
per stage and releases it exactly once with an atomic exchange. Other
providers keep using leases. `TryAcquire` and its lease are unchanged.
2. **Validation scopes reused.** Disposed `RequestValidationScope`s are
kept in per-processor spare slots and reused under a new id. Ids stay
unique, so a drain that read a scope before its reuse can only wait for
the newer validation, never miss one.
3. **Receive chunk list reused.** The server channel keeps the
`BufferCollection` of a dispatched request (released after the handler;
the decoder copied the request) to assemble the next single-chunk
message.
4. **No closure per service call.** The rejection counter lambda in the
catch block of 28 service methods made the async method allocate its
closure on every call. It moved into `CountRejectedServiceRequest`.
5. **Pool floor.** The request continuation and response source pools
retained 4 objects per processor; with many requests in flight, bursts
of completions overflowed them. They now retain at least 256.
6. **Routing snapshot captured without a restore.** #4759 captures the
routing snapshot per service call in an `AsyncLocal` through a
`ReadScope`; the capture, the scope object and the restore on dispose
cost about 190 B per Read. The dispatcher's service methods capture
until they return, and an async method's execution-context changes end
when it returns, so these sites use the new internal
`CaptureUntilReturn` (no scope, no restore, no write when already
captured). Captures that end inside a method keep the scope. The capture
itself (~90 B) remains.
Not included: pooling `FairRequestQueue.Entry` (an entry is also the
node of the lock-free FIFO and stays referenced after dispatch) and
caching a `NodeHandle` per node (the shared, publicly mutable handle
would reach overridable node manager code).
## Tests
- New: queue tests run against a reservation-capable provider and assert
every stage is released exactly once (a deliberately broken release
fails 6 of them); validation scope reuse with drains; routing capture
ends when the async method returns (sync and async completion).
- Locally on net10.0: Opc.Ua.Core.Tests, Opc.Ua.Server.Tests,
Opc.Ua.Client.Tests, Opc.Ua.Sessions.Tests and Opc.Ua.Stress.Tests
(Contract, Integration) pass; net48 test projects compile.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
851 lines
36 KiB
C#
851 lines
36 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
|
|
namespace Opc.Ua.Server.Tests.NodeManager
|
|
{
|
|
[TestFixture]
|
|
[Category("NodeManagerLifecycle")]
|
|
[Parallelizable(ParallelScope.All)]
|
|
public sealed partial class NodeManagerRoutingTableTests
|
|
{
|
|
private static readonly int[] AddNamespaceIndexes = [2, 2, 3];
|
|
private static readonly int[] ReplaceNamespaceIndexes = [3, 4];
|
|
private static readonly int[] InitialNamespaceIndexes = [2, 3];
|
|
private static readonly int[] ConcurrentNamespaceIndexes = [9];
|
|
private static readonly int[] BatchNamespaceIndexes = [2];
|
|
|
|
[TestCase(false)]
|
|
[TestCase(true)]
|
|
public void PreparedBatchRevealsOnlyItsCandidatesInThePublishedImage(bool replace)
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
IAsyncNodeManager original = CreateManager();
|
|
if (replace)
|
|
{
|
|
table.Add(original, BatchNamespaceIndexes);
|
|
}
|
|
IAsyncNodeManager candidate = CreateManager();
|
|
IAsyncNodeManager unrelated = CreateManager();
|
|
table.RegisterNamespace(2, candidate, visible: false);
|
|
table.RegisterNamespace(3, unrelated, visible: false);
|
|
var prepared = new PreparedNodeManager(candidate, [])
|
|
{
|
|
Staged = true,
|
|
ReplacedNodeManager = replace ? original : null
|
|
};
|
|
using NodeManagerRoutingTable.PreparedRoutes routes = table.PrepareBatch(
|
|
[prepared], [], table.Revision, _ => BatchNamespaceIndexes,
|
|
new TypeTable(new NamespaceTable()), (EncodeableFactory)EncodeableFactory.Create());
|
|
using (table.Capture())
|
|
{
|
|
routes.Reserve();
|
|
routes.Publish();
|
|
Assert.That(table.Any(manager => ReferenceEquals(manager, candidate)), Is.False,
|
|
"An in-flight request must retain the unpublished routing image.");
|
|
}
|
|
using (Assert.EnterMultipleScope())
|
|
{
|
|
Assert.That(table.IsVisible(candidate), Is.True);
|
|
Assert.That(table.IsVisible(unrelated), Is.False);
|
|
Assert.That(table.NamespaceManagers.ContainsKey(3), Is.False);
|
|
Assert.That(table.Revision.HiddenNodeManagers, Is.EquivalentTo(new[] { unrelated }));
|
|
AssertSingleManagerRoute(table.NamespaceManagers, 2, candidate);
|
|
if (replace)
|
|
{
|
|
Assert.That(table.IsVisible(original), Is.False);
|
|
}
|
|
}
|
|
}
|
|
|
|
[TestCase(false)]
|
|
[TestCase(true)]
|
|
public async Task CaptureUntilReturnEndsWhenTheAsyncMethodReturnsAsync(bool completeAsynchronously)
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
IAsyncNodeManager lifecycleManager = CreateManager();
|
|
|
|
async ValueTask CaptureAndPublishAsync()
|
|
{
|
|
table.CaptureUntilReturn();
|
|
NodeManagerRoutingTable.RoutingSnapshot captured = table.CapturedRevision;
|
|
table.Add(lifecycleManager, AddNamespaceIndexes);
|
|
if (completeAsynchronously)
|
|
{
|
|
await Task.Yield();
|
|
}
|
|
Assert.That(table.CapturedRevision, Is.SameAs(captured),
|
|
"The rest of the method must keep the captured routing image.");
|
|
Assert.That(table.Any(manager => ReferenceEquals(manager, lifecycleManager)), Is.False);
|
|
}
|
|
|
|
await CaptureAndPublishAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(table.CapturedRevision, Is.SameAs(table.Revision),
|
|
"The caller must read the live routing once the method returned.");
|
|
Assert.That(table.Any(manager => ReferenceEquals(manager, lifecycleManager)), Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public void AddPublishesManagerAndNamespaceRoutesWithoutMutatingCapturedSnapshots()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
IAsyncNodeManager lifecycleManager = CreateManager();
|
|
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>>
|
|
namespaceRouteSnapshot = table.NamespaceManagers;
|
|
|
|
table.Add(lifecycleManager, AddNamespaceIndexes);
|
|
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> currentRoutes =
|
|
table.NamespaceManagers;
|
|
Assert.That(table, Has.Count.EqualTo(3));
|
|
Assert.That(table[0], Is.SameAs(firstPermanent));
|
|
Assert.That(table[1], Is.SameAs(secondPermanent));
|
|
Assert.That(table[2], Is.SameAs(lifecycleManager));
|
|
Assert.That(currentRoutes, Is.Not.SameAs(namespaceRouteSnapshot));
|
|
Assert.That(currentRoutes, Has.Count.EqualTo(2));
|
|
Assert.That(currentRoutes.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
|
|
AssertSingleManagerRoute(currentRoutes, 2, lifecycleManager);
|
|
AssertSingleManagerRoute(currentRoutes, 3, lifecycleManager);
|
|
|
|
AssertManagerSnapshot(
|
|
managerSnapshot,
|
|
firstPermanent,
|
|
secondPermanent);
|
|
Assert.That(namespaceRouteSnapshot, Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public void ReplacePublishesReplacementRoutesWithoutMutatingCapturedSnapshots()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
IAsyncNodeManager original = CreateManager();
|
|
IAsyncNodeManager replacement = CreateManager();
|
|
table.Add(original, InitialNamespaceIndexes);
|
|
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>>
|
|
namespaceRouteSnapshot = table.NamespaceManagers;
|
|
IReadOnlyList<IAsyncNodeManager> namespaceTwoSnapshot =
|
|
namespaceRouteSnapshot[2];
|
|
IReadOnlyList<IAsyncNodeManager> namespaceThreeSnapshot =
|
|
namespaceRouteSnapshot[3];
|
|
|
|
table.Replace(original, replacement, ReplaceNamespaceIndexes);
|
|
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> currentRoutes =
|
|
table.NamespaceManagers;
|
|
Assert.That(table, Has.Count.EqualTo(3));
|
|
Assert.That(table[0], Is.SameAs(firstPermanent));
|
|
Assert.That(table[1], Is.SameAs(secondPermanent));
|
|
Assert.That(table[2], Is.SameAs(replacement));
|
|
Assert.That(table[2], Is.Not.SameAs(original));
|
|
Assert.That(currentRoutes, Is.Not.SameAs(namespaceRouteSnapshot));
|
|
Assert.That(currentRoutes, Has.Count.EqualTo(2));
|
|
Assert.That(currentRoutes.Keys, Is.EquivalentTo(ReplaceNamespaceIndexes));
|
|
Assert.That(currentRoutes.ContainsKey(2), Is.False);
|
|
AssertSingleManagerRoute(currentRoutes, 3, replacement);
|
|
AssertSingleManagerRoute(currentRoutes, 4, replacement);
|
|
Assert.That(currentRoutes[3][0], Is.Not.SameAs(original));
|
|
Assert.That(currentRoutes[4][0], Is.Not.SameAs(original));
|
|
|
|
AssertManagerSnapshot(
|
|
managerSnapshot,
|
|
firstPermanent,
|
|
secondPermanent,
|
|
original);
|
|
Assert.That(namespaceRouteSnapshot, Has.Count.EqualTo(2));
|
|
Assert.That(namespaceRouteSnapshot.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
|
|
Assert.That(namespaceRouteSnapshot[2], Is.SameAs(namespaceTwoSnapshot));
|
|
Assert.That(namespaceRouteSnapshot[3], Is.SameAs(namespaceThreeSnapshot));
|
|
AssertSingleManagerRoute(namespaceRouteSnapshot, 2, original);
|
|
AssertSingleManagerRoute(namespaceRouteSnapshot, 3, original);
|
|
}
|
|
|
|
[Test]
|
|
public void RestoreReplacementRecoversDroppedRoutePositions()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
IAsyncNodeManager original = CreateManager();
|
|
IAsyncNodeManager peer = CreateManager();
|
|
IAsyncNodeManager replacement = CreateManager();
|
|
table.Add(original, InitialNamespaceIndexes);
|
|
table.Add(peer, InitialNamespaceIndexes);
|
|
|
|
NodeManagerRoutingTable.NodeManagerRoutingPosition position =
|
|
table.Replace(
|
|
original,
|
|
replacement,
|
|
ReplaceNamespaceIndexes);
|
|
table.RestoreReplacement(
|
|
replacement,
|
|
original,
|
|
position,
|
|
visible: true);
|
|
|
|
Assert.That(table[2], Is.SameAs(original));
|
|
Assert.That(table[3], Is.SameAs(peer));
|
|
Assert.That(table.NamespaceManagers.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
|
|
Assert.That(table.NamespaceManagers[2][0], Is.SameAs(original));
|
|
Assert.That(table.NamespaceManagers[2][1], Is.SameAs(peer));
|
|
Assert.That(table.NamespaceManagers[3][0], Is.SameAs(original));
|
|
Assert.That(table.NamespaceManagers[3][1], Is.SameAs(peer));
|
|
}
|
|
|
|
[Test]
|
|
public void RemoveUnpublishesManagerWithoutMutatingCapturedSnapshots()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
IAsyncNodeManager lifecycleManager = CreateManager();
|
|
table.Add(lifecycleManager, InitialNamespaceIndexes);
|
|
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>>
|
|
namespaceRouteSnapshot = table.NamespaceManagers;
|
|
IReadOnlyList<IAsyncNodeManager> namespaceTwoSnapshot =
|
|
namespaceRouteSnapshot[2];
|
|
IReadOnlyList<IAsyncNodeManager> namespaceThreeSnapshot =
|
|
namespaceRouteSnapshot[3];
|
|
|
|
table.Remove(lifecycleManager);
|
|
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> currentRoutes =
|
|
table.NamespaceManagers;
|
|
Assert.That(table, Has.Count.EqualTo(2));
|
|
Assert.That(table[0], Is.SameAs(firstPermanent));
|
|
Assert.That(table[1], Is.SameAs(secondPermanent));
|
|
Assert.That(currentRoutes, Is.Not.SameAs(namespaceRouteSnapshot));
|
|
Assert.That(currentRoutes, Is.Empty);
|
|
|
|
AssertManagerSnapshot(
|
|
managerSnapshot,
|
|
firstPermanent,
|
|
secondPermanent,
|
|
lifecycleManager);
|
|
Assert.That(namespaceRouteSnapshot, Has.Count.EqualTo(2));
|
|
Assert.That(namespaceRouteSnapshot.Keys, Is.EquivalentTo(InitialNamespaceIndexes));
|
|
Assert.That(namespaceRouteSnapshot[2], Is.SameAs(namespaceTwoSnapshot));
|
|
Assert.That(namespaceRouteSnapshot[3], Is.SameAs(namespaceThreeSnapshot));
|
|
AssertSingleManagerRoute(namespaceRouteSnapshot, 2, lifecycleManager);
|
|
AssertSingleManagerRoute(namespaceRouteSnapshot, 3, lifecycleManager);
|
|
}
|
|
|
|
[Test]
|
|
public void RestoreReturnsManagerToCapturedGlobalAndNamespacePositions()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
IAsyncNodeManager earlier = CreateManager();
|
|
IAsyncNodeManager first = CreateManager();
|
|
IAsyncNodeManager second = CreateManager();
|
|
table.Add(earlier, InitialNamespaceIndexes);
|
|
table.Add(first, InitialNamespaceIndexes);
|
|
table.Add(second, InitialNamespaceIndexes);
|
|
|
|
NodeManagerRoutingTable.NodeManagerRoutingPosition position =
|
|
table.RemoveAndCapturePosition(first);
|
|
table.Remove(earlier);
|
|
table.Restore(first, position);
|
|
|
|
Assert.That(table[2], Is.SameAs(first));
|
|
Assert.That(table[3], Is.SameAs(second));
|
|
Assert.That(table.NamespaceManagers[2][0], Is.SameAs(first));
|
|
Assert.That(table.NamespaceManagers[2][1], Is.SameAs(second));
|
|
Assert.That(table.NamespaceManagers[3][0], Is.SameAs(first));
|
|
Assert.That(table.NamespaceManagers[3][1], Is.SameAs(second));
|
|
}
|
|
|
|
[Test]
|
|
public void RoutingMutationsMatchAdaptersBySynchronousManagerIdentity()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
INodeManager syncManager = new Mock<INodeManager>().Object;
|
|
IAsyncNodeManager registeredAdapter =
|
|
CreateManagerWithSync(syncManager);
|
|
IAsyncNodeManager lookupAdapter =
|
|
CreateManagerWithSync(syncManager);
|
|
table.Add(registeredAdapter, [2]);
|
|
|
|
table.RegisterNamespace(3, lookupAdapter);
|
|
|
|
Assert.That(table.NamespaceManagers[3], Has.Count.EqualTo(1));
|
|
Assert.That(
|
|
table.NamespaceManagers[3][0],
|
|
Is.SameAs(registeredAdapter));
|
|
|
|
table.Remove(lookupAdapter);
|
|
|
|
Assert.That(table, Has.Count.EqualTo(2));
|
|
Assert.That(table.NamespaceManagers, Is.Empty);
|
|
}
|
|
|
|
/// <summary>
|
|
/// While one writer alternates replacing the single lifecycle-managed slot between
|
|
/// two manager instances (~200 times) and several readers loop concurrently, every
|
|
/// individually captured manager-list snapshot (via <see cref="NodeManagerRoutingTable.GetEnumerator"/>)
|
|
/// must remain structurally complete - three managers, the first two always the
|
|
/// same permanent instances, and the third always exactly one of the two lifecycle
|
|
/// generations, never anything else - and every individually captured
|
|
/// <see cref="NodeManagerRoutingTable.NamespaceManagers"/> snapshot must show exactly
|
|
/// one non-null route to the same namespace index, pointing at exactly one valid
|
|
/// lifecycle generation. The manager list and the namespace-route dictionary are
|
|
/// each read via a single, separate, atomic snapshot access; a legitimate concurrent
|
|
/// write can therefore be interleaved between the two reads, so the two are
|
|
/// deliberately never cross-correlated against each other.
|
|
/// </summary>
|
|
[Test]
|
|
public async Task ConcurrentReadersObserveOnlyCompleteRoutingSnapshotsAsync()
|
|
{
|
|
const int ReaderIterations = 100;
|
|
const int ReaderCount = 4;
|
|
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
IAsyncNodeManager generationA = CreateManager();
|
|
IAsyncNodeManager generationB = CreateManager();
|
|
table.Add(generationA, ConcurrentNamespaceIndexes);
|
|
|
|
var managerSnapshotFailures = new ConcurrentBag<string>();
|
|
var namespaceSnapshotFailures = new ConcurrentBag<string>();
|
|
using var startBarrier = new Barrier(ReaderCount + 1);
|
|
using var writerStarted = new ManualResetEventSlim();
|
|
using var readersReadyForConcurrentWrite = new CountdownEvent(ReaderCount);
|
|
using var concurrentWriteCompleted = new ManualResetEventSlim();
|
|
using var stopWriter = new CancellationTokenSource();
|
|
int writerIterations = 0;
|
|
|
|
var writerTask = Task.Run(() =>
|
|
{
|
|
IAsyncNodeManager current = generationA;
|
|
startBarrier.SignalAndWait();
|
|
|
|
ReplaceCurrent();
|
|
writerStarted.Set();
|
|
readersReadyForConcurrentWrite.Wait();
|
|
ReplaceCurrent();
|
|
concurrentWriteCompleted.Set();
|
|
|
|
while (!stopWriter.IsCancellationRequested)
|
|
{
|
|
ReplaceCurrent();
|
|
Thread.Yield();
|
|
}
|
|
|
|
void ReplaceCurrent()
|
|
{
|
|
IAsyncNodeManager next = ReferenceEquals(current, generationA)
|
|
? generationB
|
|
: generationA;
|
|
table.Replace(current, next, ConcurrentNamespaceIndexes);
|
|
current = next;
|
|
Interlocked.Increment(ref writerIterations);
|
|
}
|
|
});
|
|
|
|
Task[] readerTasks = [.. Enumerable.Range(0, ReaderCount).Select(_ => Task.Run(() =>
|
|
{
|
|
startBarrier.SignalAndWait();
|
|
writerStarted.Wait();
|
|
readersReadyForConcurrentWrite.Signal();
|
|
concurrentWriteCompleted.Wait();
|
|
|
|
for (int iteration = 0; iteration < ReaderIterations; iteration++)
|
|
{
|
|
using IEnumerator<IAsyncNodeManager> managerSnapshot = table.GetEnumerator();
|
|
var managers = new List<IAsyncNodeManager>();
|
|
while (managerSnapshot.MoveNext())
|
|
{
|
|
managers.Add(managerSnapshot.Current);
|
|
}
|
|
|
|
if (managers.Count != 3 ||
|
|
!ReferenceEquals(managers[0], firstPermanent) ||
|
|
!ReferenceEquals(managers[1], secondPermanent) ||
|
|
(!ReferenceEquals(managers[2], generationA) &&
|
|
!ReferenceEquals(managers[2], generationB)))
|
|
{
|
|
managerSnapshotFailures.Add(
|
|
$"iteration {iteration}: manager count {managers.Count}");
|
|
}
|
|
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> namespaceRoutes =
|
|
table.NamespaceManagers;
|
|
int namespaceIndex = ConcurrentNamespaceIndexes[0];
|
|
bool hasRoute = namespaceRoutes.TryGetValue(
|
|
namespaceIndex,
|
|
out IReadOnlyList<IAsyncNodeManager>? route);
|
|
if (!hasRoute ||
|
|
route!.Count != 1 ||
|
|
(!ReferenceEquals(route[0], generationA) &&
|
|
!ReferenceEquals(route[0], generationB)))
|
|
{
|
|
namespaceSnapshotFailures.Add(
|
|
$"iteration {iteration}: hasRoute {hasRoute}, " +
|
|
$"count {(hasRoute ? route!.Count : -1)}");
|
|
}
|
|
|
|
Thread.Yield();
|
|
}
|
|
}))];
|
|
|
|
try
|
|
{
|
|
await Task.WhenAll(readerTasks).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
stopWriter.Cancel();
|
|
await writerTask.ConfigureAwait(false);
|
|
}
|
|
|
|
Assert.That(writerIterations, Is.GreaterThan(2));
|
|
Assert.That(managerSnapshotFailures, Is.Empty);
|
|
Assert.That(namespaceSnapshotFailures, Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public void AddInitialThrowsOnNullNodeManager()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
|
|
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
|
|
() => table.AddInitial(null!))!;
|
|
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
|
|
}
|
|
|
|
[Test]
|
|
public void InitializePublishesNamespaceRoutesFromDictionary()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
IAsyncNodeManager manager = CreateManager();
|
|
|
|
ArgumentNullException nullEx = Assert.Throws<ArgumentNullException>(
|
|
() => table.Initialize(null!))!;
|
|
Assert.That(nullEx.ParamName, Is.EqualTo("namespaceManagers"));
|
|
|
|
table.Initialize(
|
|
new Dictionary<int, List<IAsyncNodeManager>> { [5] = [manager] });
|
|
|
|
AssertSingleManagerRoute(table.NamespaceManagers, 5, manager);
|
|
}
|
|
|
|
[Test]
|
|
public void AddThrowsOnNullNodeManager()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
|
|
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
|
|
() => table.Add(null!, AddNamespaceIndexes))!;
|
|
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
|
|
}
|
|
|
|
[Test]
|
|
public void AddThrowsOnNullNamespaceIndexes()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
|
|
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
|
|
() => table.Add(CreateManager(), null!))!;
|
|
Assert.That(ex.ParamName, Is.EqualTo("namespaceIndexes"));
|
|
}
|
|
|
|
[Test]
|
|
public void AddThrowsWhenNodeManagerAlreadyRegistered()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out IAsyncNodeManager firstPermanent, out _);
|
|
|
|
Assert.Throws<InvalidOperationException>(
|
|
() => table.Add(firstPermanent, AddNamespaceIndexes));
|
|
}
|
|
|
|
[Test]
|
|
public void AddWithVisibleFalseHidesManagerFromEnumerationButNotFromIndexer()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
IAsyncNodeManager hiddenManager = CreateManager();
|
|
|
|
table.Add(hiddenManager, AddNamespaceIndexes, visible: false);
|
|
|
|
Assert.That(table, Has.Count.EqualTo(3));
|
|
Assert.That(table[2], Is.SameAs(hiddenManager));
|
|
Assert.That(table.IsVisible(hiddenManager), Is.False);
|
|
using IEnumerator<IAsyncNodeManager> visibleSnapshot = table.GetEnumerator();
|
|
AssertManagerSnapshot(visibleSnapshot, firstPermanent, secondPermanent);
|
|
}
|
|
|
|
[Test]
|
|
public void ReplaceThrowsOnNullArguments()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
IAsyncNodeManager original = CreateManager();
|
|
table.Add(original, InitialNamespaceIndexes);
|
|
|
|
Assert.That(
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => table.Replace(null!, CreateManager(), ReplaceNamespaceIndexes))!.ParamName,
|
|
Is.EqualTo("current"));
|
|
Assert.That(
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => table.Replace(original, null!, ReplaceNamespaceIndexes))!.ParamName,
|
|
Is.EqualTo("replacement"));
|
|
Assert.That(
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => table.Replace(original, CreateManager(), null!))!.ParamName,
|
|
Is.EqualTo("replacementNamespaceIndexes"));
|
|
}
|
|
|
|
[Test]
|
|
public void ReplaceThrowsWhenCurrentIsNotLifecycleManaged()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out _);
|
|
|
|
Assert.Throws<InvalidOperationException>(
|
|
() => table.Replace(firstPermanent, CreateManager(), ReplaceNamespaceIndexes));
|
|
}
|
|
|
|
[Test]
|
|
public void ReplaceThrowsWhenReplacementAlreadyRegistered()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
IAsyncNodeManager original = CreateManager();
|
|
IAsyncNodeManager other = CreateManager();
|
|
table.Add(original, InitialNamespaceIndexes);
|
|
table.Add(other, ReplaceNamespaceIndexes);
|
|
|
|
Assert.Throws<InvalidOperationException>(
|
|
() => table.Replace(original, other, ReplaceNamespaceIndexes));
|
|
}
|
|
|
|
[Test]
|
|
public void RemoveThrowsOnNullNodeManager()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
|
|
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
|
|
() => table.Remove(null!))!;
|
|
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
|
|
}
|
|
|
|
[Test]
|
|
public void RemoveThrowsWhenNodeManagerIsNotLifecycleManaged()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out IAsyncNodeManager firstPermanent, out _);
|
|
|
|
Assert.Throws<InvalidOperationException>(() => table.Remove(firstPermanent));
|
|
}
|
|
|
|
[Test]
|
|
public void RegisterNamespaceIsIdempotentForTheSameManager()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
IAsyncNodeManager manager = CreateManager();
|
|
|
|
table.RegisterNamespace(7, manager);
|
|
table.RegisterNamespace(7, manager);
|
|
|
|
AssertSingleManagerRoute(table.NamespaceManagers, 7, manager);
|
|
}
|
|
|
|
[Test]
|
|
public void RegisterNamespaceAppendsToExistingRouteForDifferentManager()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
IAsyncNodeManager first = CreateManager();
|
|
IAsyncNodeManager second = CreateManager();
|
|
|
|
table.RegisterNamespace(7, first);
|
|
table.RegisterNamespace(7, second);
|
|
|
|
Assert.That(table.NamespaceManagers[7], Has.Count.EqualTo(2));
|
|
Assert.That(table.NamespaceManagers[7], Does.Contain(first));
|
|
Assert.That(table.NamespaceManagers[7], Does.Contain(second));
|
|
}
|
|
|
|
[Test]
|
|
public void RegisterNamespaceWithVisibleFalseHidesManager()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
IAsyncNodeManager manager = CreateManager();
|
|
table.AddInitial(manager);
|
|
|
|
table.RegisterNamespace(7, manager, visible: false);
|
|
|
|
Assert.That(table.IsVisible(manager), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void UnregisterNamespaceReturnsFalseWhenNamespaceNotFound()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
|
|
Assert.That(table.UnregisterNamespace(1, CreateManager(), null), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void UnregisterNamespaceReturnsFalseWhenManagerNotInRoute()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
table.RegisterNamespace(7, CreateManager());
|
|
|
|
Assert.That(table.UnregisterNamespace(7, CreateManager(), null), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void UnregisterNamespaceRemovesRouteEntryWhenLastManagerRemoved()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
IAsyncNodeManager manager = CreateManager();
|
|
table.RegisterNamespace(7, manager);
|
|
|
|
bool removed = table.UnregisterNamespace(7, manager, null);
|
|
|
|
Assert.That(removed, Is.True);
|
|
Assert.That(table.NamespaceManagers.ContainsKey(7), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void UnregisterNamespaceKeepsRouteWhenOtherManagersRemain()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
IAsyncNodeManager first = CreateManager();
|
|
IAsyncNodeManager second = CreateManager();
|
|
table.RegisterNamespace(7, first);
|
|
table.RegisterNamespace(7, second);
|
|
|
|
bool removed = table.UnregisterNamespace(7, first, null);
|
|
|
|
Assert.That(removed, Is.True);
|
|
AssertSingleManagerRoute(table.NamespaceManagers, 7, second);
|
|
}
|
|
|
|
[Test]
|
|
public void UnregisterNamespaceMatchesBySyncNodeManagerWhenAsyncNodeManagerIsNull()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
INodeManager syncManager = new Mock<INodeManager>().Object;
|
|
IAsyncNodeManager manager = CreateManagerWithSync(syncManager);
|
|
table.RegisterNamespace(7, manager);
|
|
|
|
bool removed = table.UnregisterNamespace(7, null, syncManager);
|
|
|
|
Assert.That(removed, Is.True);
|
|
Assert.That(table.NamespaceManagers.ContainsKey(7), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void RemoveNamespaceManagerThrowsOnNullNodeManager()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
|
|
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
|
|
() => table.RemoveNamespaceManager(null!))!;
|
|
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
|
|
}
|
|
|
|
[Test]
|
|
public void RemoveNamespaceManagerRemovesAcrossAllNamespacesAndMatchesBySyncNodeManager()
|
|
{
|
|
var table = new NodeManagerRoutingTable();
|
|
INodeManager syncManager = new Mock<INodeManager>().Object;
|
|
IAsyncNodeManager registeredManager = CreateManagerWithSync(syncManager);
|
|
IAsyncNodeManager lookupManager = CreateManagerWithSync(syncManager);
|
|
IAsyncNodeManager unrelated = CreateManager();
|
|
table.RegisterNamespace(2, registeredManager);
|
|
table.RegisterNamespace(3, registeredManager);
|
|
table.RegisterNamespace(3, unrelated);
|
|
|
|
table.RemoveNamespaceManager(lookupManager);
|
|
|
|
Assert.That(table.NamespaceManagers.ContainsKey(2), Is.False);
|
|
AssertSingleManagerRoute(table.NamespaceManagers, 3, unrelated);
|
|
}
|
|
|
|
[Test]
|
|
public void IsVisibleReturnsFalseForUnregisteredManager()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
|
|
Assert.That(table.IsVisible(CreateManager()), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public void IsVisibleReturnsTrueForRegisteredVisibleManager()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out IAsyncNodeManager firstPermanent, out _);
|
|
|
|
Assert.That(table.IsVisible(firstPermanent), Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public void SetVisibleThrowsOnNullNodeManager()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
|
|
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(
|
|
() => table.SetVisible(null!, false))!;
|
|
Assert.That(ex.ParamName, Is.EqualTo("nodeManager"));
|
|
}
|
|
|
|
[Test]
|
|
public void SetVisibleThrowsWhenManagerNotRegistered()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
|
|
Assert.Throws<InvalidOperationException>(
|
|
() => table.SetVisible(CreateManager(), false));
|
|
}
|
|
|
|
[Test]
|
|
public void SetVisibleTogglesVisibilityAffectingEnumerationAndIsVisible()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
|
|
table.SetVisible(firstPermanent, false);
|
|
|
|
Assert.That(table.IsVisible(firstPermanent), Is.False);
|
|
using (IEnumerator<IAsyncNodeManager> hiddenSnapshot = table.GetEnumerator())
|
|
{
|
|
AssertManagerSnapshot(hiddenSnapshot, secondPermanent);
|
|
}
|
|
|
|
table.SetVisible(firstPermanent, true);
|
|
|
|
Assert.That(table.IsVisible(firstPermanent), Is.True);
|
|
using IEnumerator<IAsyncNodeManager> restoredSnapshot = table.GetEnumerator();
|
|
AssertManagerSnapshot(restoredSnapshot, firstPermanent, secondPermanent);
|
|
}
|
|
|
|
[Test]
|
|
public void ClearResetsAllState()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(out _, out _);
|
|
table.Add(CreateManager(), InitialNamespaceIndexes);
|
|
|
|
table.Clear();
|
|
|
|
Assert.That(table, Has.Count.EqualTo(0));
|
|
Assert.That(table.NamespaceManagers, Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public void IndexerReturnsManagerAtPosition()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
|
|
Assert.That(table[0], Is.SameAs(firstPermanent));
|
|
Assert.That(table[1], Is.SameAs(secondPermanent));
|
|
}
|
|
|
|
[Test]
|
|
public void ExplicitEnumerableGetEnumeratorReturnsSameManagersAsGenericEnumerator()
|
|
{
|
|
NodeManagerRoutingTable table = CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent);
|
|
|
|
var managers = new List<IAsyncNodeManager>();
|
|
System.Collections.IEnumerable untyped = table;
|
|
System.Collections.IEnumerator enumerator = untyped.GetEnumerator();
|
|
while (enumerator.MoveNext())
|
|
{
|
|
managers.Add((IAsyncNodeManager)enumerator.Current!);
|
|
}
|
|
|
|
Assert.That(managers, Is.EqualTo([firstPermanent, secondPermanent]));
|
|
}
|
|
|
|
private static NodeManagerRoutingTable CreateTable(
|
|
out IAsyncNodeManager firstPermanent,
|
|
out IAsyncNodeManager secondPermanent)
|
|
{
|
|
firstPermanent = CreateManager();
|
|
secondPermanent = CreateManager();
|
|
var table = new NodeManagerRoutingTable();
|
|
table.AddInitial(firstPermanent);
|
|
table.AddInitial(secondPermanent);
|
|
return table;
|
|
}
|
|
|
|
private static IAsyncNodeManager CreateManager()
|
|
{
|
|
return new Mock<IAsyncNodeManager>().Object;
|
|
}
|
|
|
|
private static IAsyncNodeManager CreateManagerWithSync(INodeManager syncNodeManager)
|
|
{
|
|
var manager = new Mock<IAsyncNodeManager>();
|
|
manager.Setup(m => m.SyncNodeManager).Returns(syncNodeManager);
|
|
return manager.Object;
|
|
}
|
|
|
|
private static void AssertManagerSnapshot(
|
|
IEnumerator<IAsyncNodeManager> snapshot,
|
|
params IAsyncNodeManager[] expected)
|
|
{
|
|
foreach (IAsyncNodeManager expectedManager in expected)
|
|
{
|
|
Assert.That(snapshot.MoveNext(), Is.True);
|
|
Assert.That(snapshot.Current, Is.SameAs(expectedManager));
|
|
}
|
|
Assert.That(snapshot.MoveNext(), Is.False);
|
|
}
|
|
|
|
private static void AssertSingleManagerRoute(
|
|
IReadOnlyDictionary<int, IReadOnlyList<IAsyncNodeManager>> routes,
|
|
int namespaceIndex,
|
|
IAsyncNodeManager expected)
|
|
{
|
|
Assert.That(routes.ContainsKey(namespaceIndex), Is.True);
|
|
Assert.That(routes[namespaceIndex], Has.Count.EqualTo(1));
|
|
Assert.That(routes[namespaceIndex][0], Is.SameAs(expected));
|
|
}
|
|
}
|
|
}
|