mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-29 07:07:24 +08:00
Q7 of the request-queue comparison with ASP.NET Core/Kestrel. Stacked on #4917 (Q4 + Q5): review only the last two commits. ## Q7: requests run on concurrency permits instead of queue workers Without an isolation provider (the SharedOnly profile), the request queue used to grow workers one at a time under `m_workerGate`. Workers were never retired before stop. Requests went through a bounded `Channel`, and the "thread" settings were really limits on concurrent requests. Now: - `ScheduleIncomingRequest` takes one of `MaxRequestThreadCount` permits (a counter under the existing gate) and queues the handler on the ThreadPool directly (`IThreadPoolWorkItem` on .NET, `WaitCallback` on net48). A `Queue<QueuedRequest>` holds only the requests that are waiting for a permit. Waiting requests go first, so ordering stays FIFO. - A request that finishes, or parks with `DecoupleHeldPublishRequests`, hands its permit to the oldest waiting request and runs it on the same thread, as a worker loop did. Otherwise it returns the permit. - External behaviour is unchanged: same configuration, `BadServerTooBusy` once `MaxQueuedRequestCount` requests wait, parking releases the permit. `StopCoreAsync` rejects waiting requests with `BadServerHalted` and waits for executing and parked handlers. It also waits for permits whose request has not started yet, so `m_cts` is disposed only after every permit is back. - `FairRequestQueue` and its worker loop are unchanged; `WorkerLoopAsync` now serves only the fair queue. - `InitializeRequestQueue` no longer raises `MaxRequestThreadCount` values below 100 to 100. The value is still raised to `MinRequestThreadCount`, which is at least 1. - The doc comments of `MinRequestThreadCount` and `MaxRequestThreadCount` and `docs/ServerScalability.md` now describe the settings as concurrency limits. I considered `System.Threading.RateLimiting.ConcurrencyLimiter` and did not use it: every `AttemptAcquire` and queued `AcquireAsync` allocates a lease. A plain counter under the gate the queue already takes per request costs nothing extra. ### Release note (behaviour change) > `MaxRequestThreadCount` values below 100 are no longer raised to 100: the configured value is the limit on requests executing at once. With the SharedOnly isolation profile, requests no longer run on retained queue workers; `MinRequestThreadCount` only starts workers for the other isolation profiles. ## Measurements Paired A/B with `perf/ab.sh`: baseline = #4917 head, candidate = this branch. 20 sessions, SharedOnly. The second commit adds `--isolation sharedonly` to the load harness, because `StandardServer`'s default Balanced profile uses the fair queue and never reaches this path. Quiet run (7 paired rounds, medians, server side): | Scenario | req/s | p99 | server B/req | server CPU µs/req | lock contention | |---|---|---|---|---|---| | read 1 value, 10 in flight | 358k → 407k (+14 %, 7/7 rounds) | 6.2 → 2.8 ms | 2253 → 2241 | 23.2 → 24.1 | −94 % | | read 100 values | 47.0k → 47.4k (+1 %, 7/7 rounds) | 1.98 → 1.96 ms | 52550 → 52480 | 229 → 228 | −99 % | | sub 5×100, pub 100 ms | flat | 9.4 → 9.2 ms | 1821 → 1818 | 24.4 → 25.3 | +12 % | A first run (5 rounds, 6 scenarios) overlapped other sessions' builds, so its throughput varied 4x within each side. Its deterministic numbers agree. Server bytes per request: read 1 value 2336 → 2272, write 100 values 71.7k → 71.8k, browse 32.9k → 32.8k, sub 1825 → 1827. Lock contention was −96 % on every read scenario. ## Tests - New `RequestQueueTests`: - the shared queue starts no workers - permits limit concurrency, and waiters are served in FIFO order (with the executing/queued gauges) - a configured limit below 100 is honoured - stop rejects waiting requests and drains executing and parked handlers - a concurrent stop either halts or runs every request - `Opc.Ua.Core.Tests` `Stack.Server`: 1951 passed (net10.0). net48 build compiles. - `Opc.Ua.Stress.Tests` `Category=Contract|Integration` (not in PR CI): 45/45 passed. - To run the permit path under real servers, I temporarily forced the default isolation mode to SharedOnly (local patch, not committed): - Stress Contract/Integration: 45/45 passed. - `Opc.Ua.Sessions.Tests`: 865 passed, 0 failed, 379 skipped. This includes the load tests. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
480 lines
24 KiB
C#
480 lines
24 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.Threading.Tasks;
|
|
using Microsoft.Extensions.Time.Testing;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Bindings;
|
|
using Opc.Ua.Tests;
|
|
|
|
namespace Opc.Ua.Server.Tests
|
|
{
|
|
/// <summary>
|
|
/// Exercises startup diagnostics without opening listeners or replacing host-owned policies.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Parallelizable(ParallelScope.All)]
|
|
public sealed class IsolationConfigurationValidationTests
|
|
{
|
|
[TestCase(-1L)]
|
|
[TestCase(0L)]
|
|
[TestCase(1_200_000_001L)]
|
|
public void RuntimePlanNamesInvalidHandshakeTimeout(long ticks)
|
|
{
|
|
ServerResourceIsolationOptions options = Options();
|
|
options.HandshakeTimeout = TimeSpan.FromTicks(ticks);
|
|
|
|
Assert.That(() => options.CreateRuntimePlan(Configuration(), new ServerRateLimitOptions()),
|
|
Throws.ArgumentException
|
|
.With.Property(nameof(ArgumentException.ParamName))
|
|
.EqualTo(nameof(ServerResourceIsolationOptions.HandshakeTimeout))
|
|
.And.Message.Contains("positive")
|
|
.And.Message.Contains("two minutes"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The execution stage holds no more requests than the request queue has workers,
|
|
/// so reserved classes cannot be crowded out of the workers by ordinary requests.
|
|
/// </summary>
|
|
[Test]
|
|
public void RuntimePlanExecutionCapacityIsMaxRequestThreadCount()
|
|
{
|
|
ResourceIsolationStagePlan execution = Options()
|
|
.CreateRuntimePlan(Configuration(maxRequestThreadCount: 4), new ServerRateLimitOptions())
|
|
.GetStage(ResourceIsolationStage.RequestExecution);
|
|
|
|
Assert.That(execution.Capacity, Is.EqualTo(4));
|
|
Assert.That(execution.SharedCapacity, Is.EqualTo(1));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Too few workers for the reserved requests are named at startup.
|
|
/// </summary>
|
|
[Test]
|
|
public void RuntimePlanRejectsMaxRequestThreadCountBelowReservations()
|
|
{
|
|
Assert.That(
|
|
() => Options().CreateRuntimePlan(Configuration(maxRequestThreadCount: 3), new ServerRateLimitOptions()),
|
|
Throws.ArgumentException.With.Message.Contains("MaxRequestThreadCount (3)"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task StartupRejectsInvalidTimeoutWithoutInstallingOrDisposingProvidersAsync(
|
|
[Values] ServerResourceIsolationMode mode,
|
|
[Values(-1L, 0L, 1_200_000_001L)] long ticks,
|
|
[Values] bool customProvider)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
var isolation = new Mock<IServerResourceIsolationProvider>(MockBehavior.Strict);
|
|
Mock<IDisposable> disposable = isolation.As<IDisposable>();
|
|
var rate = new Mock<IServerRateLimiterProvider>(MockBehavior.Strict);
|
|
ChunkReassemblyBudget? budget = customProvider ? new ChunkReassemblyBudget(100, 0) : null;
|
|
ServerResourceIsolationOptions options = Options();
|
|
options.Mode = mode;
|
|
options.HandshakeTimeout = TimeSpan.FromTicks(ticks);
|
|
|
|
await using (var server = new StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
ResourceIsolationOptions = options,
|
|
ResourceIsolationProvider = customProvider ? isolation.Object : null,
|
|
ChunkReassemblyBudget = budget,
|
|
RateLimiterProvider = rate.Object
|
|
})
|
|
{
|
|
Assert.That(() => server.InitializeResourceIsolation(Configuration(), telemetry),
|
|
Throws.ArgumentException
|
|
.With.Property(nameof(ArgumentException.ParamName))
|
|
.EqualTo(nameof(ServerResourceIsolationOptions.HandshakeTimeout))
|
|
.And.Message.Contains("positive")
|
|
.And.Message.Contains("two minutes"));
|
|
Assert.That(server.ResourceIsolationProvider,
|
|
Is.SameAs(customProvider ? isolation.Object : null));
|
|
Assert.That(server.ChunkReassemblyBudget, Is.SameAs(budget));
|
|
Assert.That(server.RateLimiterProvider, Is.SameAs(rate.Object));
|
|
Assert.That(options.HandshakeTimeout, Is.EqualTo(TimeSpan.FromTicks(ticks)));
|
|
}
|
|
|
|
disposable.Verify(d => d.Dispose(), Times.Never);
|
|
isolation.VerifyNoOtherCalls();
|
|
rate.VerifyNoOtherCalls();
|
|
}
|
|
|
|
[Test]
|
|
public async Task StartupAcceptsExactTimeoutBoundsWithoutValidatingBypassedReservationsAsync(
|
|
[Values] ServerResourceIsolationMode mode,
|
|
[Values(1L, 1_200_000_000L)] long ticks,
|
|
[Values] bool customProvider)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
var isolation = new Mock<IServerResourceIsolationProvider>(MockBehavior.Strict);
|
|
Mock<IDisposable> disposable = isolation.As<IDisposable>();
|
|
bool bypassPlan = customProvider || mode == ServerResourceIsolationMode.SharedOnly;
|
|
ServerResourceIsolationOptions options = Options(
|
|
mode == ServerResourceIsolationMode.TrustedReservations ? 1 : 0);
|
|
options.Mode = mode;
|
|
options.HandshakeTimeout = TimeSpan.FromTicks(ticks);
|
|
ApplicationConfiguration configuration = Configuration();
|
|
ServerConfiguration serverConfiguration = configuration.ServerConfiguration!;
|
|
TransportQuotas quotas = configuration.TransportQuotas!;
|
|
if (bypassPlan)
|
|
{
|
|
serverConfiguration.MaxSessionCount = 0;
|
|
serverConfiguration.MaxChannelCount = 0;
|
|
quotas.MaxMessageSize = 0;
|
|
quotas.MaxBufferSize = 0;
|
|
options.MaxRetainedMessageBytes = 0;
|
|
options.MaxTrackedOwners = 0;
|
|
}
|
|
|
|
await using (var server = new ListenerSettingsServer(telemetry)
|
|
{
|
|
ResourceIsolationOptions = options,
|
|
ResourceIsolationProvider = customProvider ? isolation.Object : null,
|
|
ResourceIsolationClassifier = Mock.Of<IResourceIsolationClassifier>()
|
|
})
|
|
{
|
|
server.InitializeResourceIsolation(configuration, telemetry);
|
|
TransportListenerSettings settings = server.CreateListenerSettings();
|
|
Assert.That(settings.HandshakeTimeout, Is.EqualTo(TimeSpan.FromTicks(ticks)));
|
|
if (bypassPlan)
|
|
{
|
|
Assert.That(server.ResourceIsolationProvider,
|
|
Is.SameAs(customProvider ? isolation.Object : null));
|
|
Assert.That(server.ChunkReassemblyBudget, Is.Null);
|
|
Assert.That(serverConfiguration.MaxSessionCount, Is.Zero);
|
|
Assert.That(serverConfiguration.MaxChannelCount, Is.Zero);
|
|
Assert.That(quotas.MaxMessageSize, Is.Zero);
|
|
Assert.That(quotas.MaxBufferSize, Is.Zero);
|
|
Assert.That(options.MaxRetainedMessageBytes, Is.Zero);
|
|
Assert.That(options.MaxTrackedOwners, Is.Zero);
|
|
}
|
|
else
|
|
{
|
|
Assert.That(server.ResourceIsolationProvider,
|
|
Is.TypeOf<DefaultServerResourceIsolationProvider>());
|
|
var installed = (DefaultServerResourceIsolationProvider)server.ResourceIsolationProvider!;
|
|
Assert.That(installed.Plan.Mode, Is.EqualTo(mode));
|
|
Assert.That(server.ChunkReassemblyBudget, Is.Not.Null);
|
|
}
|
|
}
|
|
|
|
disposable.Verify(d => d.Dispose(), Times.Never);
|
|
isolation.VerifyNoOtherCalls();
|
|
}
|
|
|
|
[Test]
|
|
public async Task InvalidTimeoutPreservesPreviouslyOwnedIsolationAndRateLimiterAsync(
|
|
[Values] ServerResourceIsolationMode nextMode,
|
|
[Values(-1L, 0L, 1_200_000_001L)] long ticks)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
await using var server = new StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
ResourceIsolationOptions = Options(),
|
|
RateLimitOptions = new ServerRateLimitOptions { ConnectionsPerSecond = 3, ConnectionBurst = 3 }
|
|
};
|
|
server.InitializeResourceIsolation(Configuration(), telemetry);
|
|
server.InitializeRateLimiting();
|
|
var previous = (DefaultServerResourceIsolationProvider)server.ResourceIsolationProvider!;
|
|
ChunkReassemblyBudget? budget = server.ChunkReassemblyBudget;
|
|
IServerRateLimiterProvider? rate = server.RateLimiterProvider;
|
|
server.ResourceIsolationOptions.Mode = nextMode;
|
|
server.ResourceIsolationOptions.HandshakeTimeout = TimeSpan.FromTicks(ticks);
|
|
|
|
Assert.That(() => server.InitializeResourceIsolation(Configuration(), telemetry),
|
|
Throws.ArgumentException
|
|
.With.Property(nameof(ArgumentException.ParamName))
|
|
.EqualTo(nameof(ServerResourceIsolationOptions.HandshakeTimeout)));
|
|
Assert.That(server.ResourceIsolationProvider, Is.SameAs(previous));
|
|
Assert.That(server.ChunkReassemblyBudget, Is.SameAs(budget));
|
|
Assert.That(server.RateLimiterProvider, Is.SameAs(rate));
|
|
AssertProviderAdmitsConnection(previous);
|
|
Assert.That(rate!.ConnectionRateLimiter!.TryAdmitConnection(null, out _), Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ListenerSettingsRevalidateTimeoutChangedAfterInitializationAsync()
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
await using var server = new ListenerSettingsServer(telemetry)
|
|
{
|
|
ResourceIsolationOptions = new ServerResourceIsolationOptions
|
|
{
|
|
Mode = ServerResourceIsolationMode.SharedOnly
|
|
}
|
|
};
|
|
server.InitializeResourceIsolation(new ApplicationConfiguration(), telemetry);
|
|
server.ResourceIsolationOptions.HandshakeTimeout = TimeSpan.Zero;
|
|
|
|
Assert.That(server.CreateListenerSettings,
|
|
Throws.ArgumentException
|
|
.With.Property(nameof(ArgumentException.ParamName))
|
|
.EqualTo(nameof(ServerResourceIsolationOptions.HandshakeTimeout)));
|
|
Assert.That(server.ResourceIsolationProvider, Is.Null);
|
|
}
|
|
|
|
[Test]
|
|
public async Task InvalidFinitePlanPreservesPreviouslyOwnedProviderAndBudgetAsync()
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
await using var server = new StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
ResourceIsolationOptions = Options()
|
|
};
|
|
server.InitializeResourceIsolation(Configuration(), telemetry);
|
|
var previous = (DefaultServerResourceIsolationProvider)server.ResourceIsolationProvider!;
|
|
ChunkReassemblyBudget? budget = server.ChunkReassemblyBudget;
|
|
server.ResourceIsolationOptions.MaxTrackedOwners = 0;
|
|
|
|
Assert.That(() => server.InitializeResourceIsolation(Configuration(), telemetry),
|
|
Throws.ArgumentException.With.Message.Contains("Owner table"));
|
|
Assert.That(server.ResourceIsolationProvider, Is.SameAs(previous));
|
|
Assert.That(server.ChunkReassemblyBudget, Is.SameAs(budget));
|
|
AssertProviderAdmitsConnection(previous);
|
|
}
|
|
|
|
[Test]
|
|
public void ProtectedRateLimitsIdentifyOffendingTotal(
|
|
[Values(0, 1, 2)] int trustedOwnerCount,
|
|
[Values] bool invalidBurst,
|
|
[Values] bool defaultProvider)
|
|
{
|
|
using DefaultServerResourceIsolationProvider isolation = CreateProvider(trustedOwnerCount);
|
|
int minimum = 3 + trustedOwnerCount;
|
|
var options = new ServerRateLimitOptions
|
|
{
|
|
ConnectionsPerSecond = invalidBurst ? minimum : minimum - 1,
|
|
ConnectionBurst = invalidBurst ? minimum - 1 : minimum
|
|
};
|
|
string parameterName = invalidBurst ? "burst" : "connectionsPerSecond";
|
|
string optionName = invalidBurst
|
|
? nameof(ServerRateLimitOptions.ConnectionBurst)
|
|
: nameof(ServerRateLimitOptions.ConnectionsPerSecond);
|
|
|
|
Assert.That(() =>
|
|
{
|
|
using IDisposable limiter = defaultProvider
|
|
? new DefaultServerRateLimiterProvider(options, isolation, new FakeTimeProvider())
|
|
: new ResourceIsolationConnectionRateLimiter(
|
|
options.ConnectionsPerSecond, options.ConnectionBurst, isolation, new FakeTimeProvider());
|
|
}, Throws.ArgumentException
|
|
.With.Property(nameof(ArgumentException.ParamName)).EqualTo(parameterName)
|
|
.And.Message.Contains(optionName)
|
|
.And.Message.Contains($"at least {minimum}")
|
|
.And.Message.Contains("at least one shared token"));
|
|
Assert.That(options.ConnectionsPerSecond, Is.EqualTo(invalidBurst ? minimum : minimum - 1));
|
|
Assert.That(options.ConnectionBurst, Is.EqualTo(invalidBurst ? minimum - 1 : minimum));
|
|
AssertProviderAdmitsConnection(isolation);
|
|
}
|
|
|
|
[Test]
|
|
public void MinimumProtectedRateTotalsRetainExactlyOneSharedToken(
|
|
[Values(0, 1, 2)] int trustedOwnerCount)
|
|
{
|
|
using DefaultServerResourceIsolationProvider isolation = CreateProvider(trustedOwnerCount);
|
|
int minimum = 3 + trustedOwnerCount;
|
|
var options = new ServerRateLimitOptions { ConnectionsPerSecond = minimum, ConnectionBurst = minimum };
|
|
var clock = new FakeTimeProvider();
|
|
using var provider = new DefaultServerRateLimiterProvider(options, isolation, clock);
|
|
|
|
Assert.That(provider.ConnectionRateLimiter, Is.TypeOf<ResourceIsolationConnectionRateLimiter>());
|
|
Assert.That(provider.ConnectionRateLimiter!.TryAdmitConnection(null, out _), Is.True);
|
|
Assert.That(provider.ConnectionRateLimiter.TryAdmitConnection(null, out _), Is.False);
|
|
clock.Advance(TimeSpan.FromSeconds(1));
|
|
Assert.That(provider.ConnectionRateLimiter.TryAdmitConnection(null, out _), Is.True);
|
|
Assert.That(provider.ConnectionRateLimiter.TryAdmitConnection(null, out _), Is.False);
|
|
Assert.That(options.ConnectionsPerSecond, Is.EqualTo(minimum));
|
|
Assert.That(options.ConnectionBurst, Is.EqualTo(minimum));
|
|
}
|
|
|
|
[TestCase(false, true)]
|
|
[TestCase(true, false)]
|
|
[TestCase(false, false)]
|
|
public async Task DisabledRateLimitsSkipProtectedMinimumValidationAsync(
|
|
bool enabled,
|
|
bool connectionEnabled)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
await using var server = new StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
ResourceIsolationOptions = Options(2),
|
|
ResourceIsolationClassifier = Mock.Of<IResourceIsolationClassifier>(),
|
|
RateLimitOptions = new ServerRateLimitOptions
|
|
{
|
|
Enabled = enabled,
|
|
ConnectionRateLimitEnabled = connectionEnabled,
|
|
ConnectionsPerSecond = 1,
|
|
ConnectionBurst = 1
|
|
}
|
|
};
|
|
server.InitializeResourceIsolation(Configuration(), telemetry);
|
|
server.InitializeRateLimiting();
|
|
|
|
Assert.That(server.ResourceIsolationProvider, Is.TypeOf<DefaultServerResourceIsolationProvider>());
|
|
Assert.That(server.RateLimiterProvider, Is.TypeOf<DefaultServerRateLimiterProvider>());
|
|
Assert.That(server.RateLimiterProvider!.ConnectionRateLimiter, Is.Null);
|
|
Assert.That(server.RateLimitOptions.ConnectionsPerSecond, Is.EqualTo(1));
|
|
Assert.That(server.RateLimitOptions.ConnectionBurst, Is.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public async Task CustomRateProviderPrecedesProtectedMinimumValidationAsync(
|
|
[Values(0, 1, 2)] int trustedOwnerCount)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
var custom = new Mock<IServerRateLimiterProvider>(MockBehavior.Strict);
|
|
await using (var server = new StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
ResourceIsolationOptions = Options(trustedOwnerCount),
|
|
ResourceIsolationClassifier = Mock.Of<IResourceIsolationClassifier>(),
|
|
RateLimiterProvider = custom.Object,
|
|
RateLimitOptions = new ServerRateLimitOptions { ConnectionsPerSecond = 1, ConnectionBurst = 1 }
|
|
})
|
|
{
|
|
server.InitializeResourceIsolation(Configuration(), telemetry);
|
|
server.InitializeRateLimiting();
|
|
|
|
Assert.That(server.ResourceIsolationProvider, Is.TypeOf<DefaultServerResourceIsolationProvider>());
|
|
Assert.That(server.RateLimiterProvider, Is.SameAs(custom.Object));
|
|
Assert.That(server.RateLimitOptions.ConnectionsPerSecond, Is.EqualTo(1));
|
|
Assert.That(server.RateLimitOptions.ConnectionBurst, Is.EqualTo(1));
|
|
}
|
|
|
|
custom.Verify(p => p.Dispose(), Times.Never);
|
|
custom.VerifyNoOtherCalls();
|
|
}
|
|
|
|
[TestCase(2, 3, "connectionsPerSecond")]
|
|
[TestCase(3, 2, "burst")]
|
|
public async Task InvalidRateTotalDoesNotReplaceOrDisposeExistingLimiterAsync(
|
|
int rate,
|
|
int burst,
|
|
string parameterName)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
await using var server = new StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
ResourceIsolationOptions = Options(),
|
|
RateLimitOptions = new ServerRateLimitOptions { ConnectionsPerSecond = 3, ConnectionBurst = 3 }
|
|
};
|
|
server.InitializeResourceIsolation(Configuration(), telemetry);
|
|
server.InitializeRateLimiting();
|
|
IServerRateLimiterProvider? previous = server.RateLimiterProvider;
|
|
server.RateLimitOptions.ConnectionsPerSecond = rate;
|
|
server.RateLimitOptions.ConnectionBurst = burst;
|
|
|
|
Assert.That(() => server.InitializeRateLimiting(), Throws.ArgumentException
|
|
.With.Property(nameof(ArgumentException.ParamName)).EqualTo(parameterName));
|
|
Assert.That(server.RateLimiterProvider, Is.SameAs(previous));
|
|
Assert.That(previous!.ConnectionRateLimiter!.TryAdmitConnection(null, out _), Is.True);
|
|
Assert.That(previous.ConnectionRateLimiter.TryAdmitConnection(null, out _), Is.False);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Proves failed validation left the provider usable rather than merely retaining its reference.
|
|
/// </summary>
|
|
private static void AssertProviderAdmitsConnection(DefaultServerResourceIsolationProvider provider)
|
|
{
|
|
ResourceIsolationOwner owner = provider.ClassifyConnection(null);
|
|
Assert.That(provider.TryAcquire(ResourceIsolationStage.Connection, owner, 1,
|
|
out IDisposable? lease, out _), Is.True);
|
|
Assert.That(lease, Is.Not.Null);
|
|
lease!.Dispose();
|
|
Assert.That(provider.GetUsage(ResourceIsolationStage.Connection), Is.Zero);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates finite capacity sufficient for the requested number of provisioned rate buckets.
|
|
/// </summary>
|
|
private static DefaultServerResourceIsolationProvider CreateProvider(int trustedOwnerCount)
|
|
{
|
|
return new DefaultServerResourceIsolationProvider(
|
|
Options(trustedOwnerCount).CreateRuntimePlan(Configuration(), new ServerRateLimitOptions()),
|
|
NUnitTelemetryContext.Create(), classifier: Mock.Of<IResourceIsolationClassifier>());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Keeps memory footprints small while preserving explicit protected reservations.
|
|
/// </summary>
|
|
private static ServerResourceIsolationOptions Options(int trustedOwnerCount = 0)
|
|
{
|
|
var owners = new TrustedResourceOwnerOptions[trustedOwnerCount];
|
|
for (int ii = 0; ii < owners.Length; ii++)
|
|
{
|
|
owners[ii] = new TrustedResourceOwnerOptions { Key = "tenant-" + ii };
|
|
}
|
|
return new ServerResourceIsolationOptions
|
|
{
|
|
Mode = trustedOwnerCount == 0
|
|
? ServerResourceIsolationMode.Balanced
|
|
: ServerResourceIsolationMode.TrustedReservations,
|
|
MaxRetainedMessageBytes = 10,
|
|
TrustedOwners = owners
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Supplies finite totals with room for all protected classes and ordinary reconnect capacity.
|
|
/// </summary>
|
|
private static ApplicationConfiguration Configuration(int maxRequestThreadCount = 100)
|
|
{
|
|
return new ApplicationConfiguration
|
|
{
|
|
ServerConfiguration = new ServerConfiguration
|
|
{
|
|
MaxSessionCount = 2,
|
|
MaxChannelCount = 100,
|
|
MinRequestThreadCount = 1,
|
|
MaxRequestThreadCount = maxRequestThreadCount
|
|
},
|
|
TransportQuotas = new TransportQuotas { MaxMessageSize = 10, MaxBufferSize = 8192 }
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Exposes listener configuration without certificates, network sockets or server worker threads.
|
|
/// </summary>
|
|
private sealed class ListenerSettingsServer(ITelemetryContext telemetry)
|
|
: StandardServer(telemetry, new FakeTimeProvider())
|
|
{
|
|
/// <summary>
|
|
/// Runs the production listener-settings hook after startup option validation.
|
|
/// </summary>
|
|
public TransportListenerSettings CreateListenerSettings()
|
|
{
|
|
var settings = new TransportListenerSettings();
|
|
ConfigureTransportListenerSettings(settings, new Uri("opc.tcp://localhost:4840"));
|
|
return settings;
|
|
}
|
|
}
|
|
}
|
|
}
|