Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ConnectionLimitTests.cs « InMemory.FunctionalTests « test « Kestrel « Servers « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: eb9898c5bd1f60d40d1e8b3e5bdb918026c6fe96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport;
using Microsoft.AspNetCore.Server.Kestrel.Tests;
using Microsoft.AspNetCore.Testing;
using Xunit;

namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests;

public class ConnectionLimitTests : LoggedTest
{
    [Fact]
    public async Task ResetsCountWhenConnectionClosed()
    {
        var requestTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var releasedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var lockedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
        var counter = new EventRaisingResourceCounter(ResourceCounter.Quota(1));
        counter.OnLock += (s, e) => lockedTcs.TrySetResult(e);
        counter.OnRelease += (s, e) => releasedTcs.TrySetResult();

        await using (var server = CreateServerWithMaxConnections(async context =>
        {
            await context.Response.WriteAsync("Hello");
            await requestTcs.Task;
        }, counter))
        {
            using (var connection = server.CreateConnection())
            {
                await connection.SendEmptyGetAsKeepAlive(); ;
                await connection.Receive("HTTP/1.1 200 OK");
                Assert.True(await lockedTcs.Task.DefaultTimeout());
                requestTcs.TrySetResult();
            }
        }

        await releasedTcs.Task.DefaultTimeout();
    }

    [Fact]
    public async Task UpgradedConnectionsCountsAgainstDifferentLimit()
    {
        await using (var server = CreateServerWithMaxConnections(async context =>
        {
            var feature = context.Features.Get<IHttpUpgradeFeature>();
            if (feature.IsUpgradableRequest)
            {
                var stream = await feature.UpgradeAsync();
                // keep it running until aborted
                while (!context.RequestAborted.IsCancellationRequested)
                {
                    await Task.Delay(100);
                }
            }
        }, max: 1))
        {
            using (var disposables = new DisposableStack<InMemoryConnection>())
            {
                var upgraded = server.CreateConnection();
                disposables.Push(upgraded);

                await upgraded.SendEmptyGetWithUpgrade();
                await upgraded.Receive("HTTP/1.1 101");
                // once upgraded, normal connection limit is decreased to allow room for more "normal" connections

                var connection = server.CreateConnection();
                disposables.Push(connection);

                await connection.SendEmptyGetAsKeepAlive();
                await connection.Receive("HTTP/1.1 200 OK");

                using (var rejected = server.CreateConnection())
                {
                    try
                    {
                        // this may throw IOException, depending on how fast Kestrel closes the socket
                        await rejected.SendEmptyGetAsKeepAlive();
                    }
                    catch { }

                    // connection should close without sending any data
                    await rejected.WaitForConnectionClose();
                }
            }
        }
    }

    [Fact]
    public async Task RejectsConnectionsWhenLimitReached()
    {
        const int max = 10;
        var requestTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);

        await using (var server = CreateServerWithMaxConnections(async context =>
        {
            await context.Response.WriteAsync("Hello");
            await requestTcs.Task;
        }, max))
        {
            using (var disposables = new DisposableStack<InMemoryConnection>())
            {
                for (var i = 0; i < max; i++)
                {
                    var connection = server.CreateConnection();
                    disposables.Push(connection);

                    await connection.SendEmptyGetAsKeepAlive();
                    await connection.Receive("HTTP/1.1 200 OK");
                }

                // limit has been reached
                for (var i = 0; i < 10; i++)
                {
                    using (var connection = server.CreateConnection())
                    {
                        try
                        {
                            // this may throw IOException, depending on how fast Kestrel closes the socket
                            await connection.SendEmptyGetAsKeepAlive();
                        }
                        catch { }

                        // connection should close without sending any data
                        await connection.WaitForConnectionClose();
                    }
                }

                requestTcs.TrySetResult();
            }
        }
    }

    [Fact]
    public async Task ConnectionCountingReturnsToZero()
    {
        const int count = 100;
        var opened = 0;
        var closed = 0;
        var openedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var closedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);

        var counter = new EventRaisingResourceCounter(ResourceCounter.Quota(uint.MaxValue));

        counter.OnLock += (o, e) =>
        {
            if (e && Interlocked.Increment(ref opened) >= count)
            {
                openedTcs.TrySetResult();
            }
        };

        counter.OnRelease += (o, e) =>
        {
            if (Interlocked.Increment(ref closed) >= count)
            {
                closedTcs.TrySetResult();
            }
        };

        await using (var server = CreateServerWithMaxConnections(_ => Task.CompletedTask, counter))
        {
            // open a bunch of connections in parallel
            Parallel.For(0, count, async i =>
            {
                try
                {
                    using (var connection = server.CreateConnection())
                    {
                        await connection.SendEmptyGetAsKeepAlive();
                        await connection.Receive("HTTP/1.1 200");
                    }
                }
                catch (Exception ex)
                {
                    openedTcs.TrySetException(ex);
                }
            });

            // wait until resource counter has called lock for each connection
            await openedTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(120));
            // wait until resource counter has released all normal connections
            await closedTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(120));
            Assert.Equal(count, opened);
            Assert.Equal(count, closed);
        }
    }

    private TestServer CreateServerWithMaxConnections(RequestDelegate app, long max)
    {
        var serviceContext = new TestServiceContext(LoggerFactory);
        serviceContext.ServerOptions.Limits.MaxConcurrentConnections = max;
        return new TestServer(app, serviceContext);
    }

    private TestServer CreateServerWithMaxConnections(RequestDelegate app, ResourceCounter concurrentConnectionCounter)
    {
        var serviceContext = new TestServiceContext(LoggerFactory);

        var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0));
        listenOptions.Use(next =>
        {
            var middleware = new ConnectionLimitMiddleware<ConnectionContext>(c => next(c), concurrentConnectionCounter, serviceContext.Log);
            return middleware.OnConnectionAsync;
        });

        return new TestServer(app, serviceContext, listenOptions);
    }
}