feat: enforce MaxConnections limit in accept loop

This commit is contained in:
Joseph Doherty
2026-02-22 21:44:18 -05:00
parent 19e8c65f6d
commit 0c12b0f6e3
2 changed files with 93 additions and 0 deletions

View File

@@ -124,3 +124,69 @@ public class ServerTests : IAsyncLifetime
msg.ShouldContain("MSG foo.bar 1 5\r\n");
}
}
public class MaxConnectionsTests : IAsyncLifetime
{
private readonly NatsServer _server;
private readonly int _port;
private readonly CancellationTokenSource _cts = new();
public MaxConnectionsTests()
{
_port = GetFreePort();
_server = new NatsServer(new NatsOptions { Port = _port, MaxConnections = 2 }, NullLoggerFactory.Instance);
}
public async Task InitializeAsync()
{
_ = _server.StartAsync(_cts.Token);
await _server.WaitForReadyAsync();
}
public async Task DisposeAsync()
{
await _cts.CancelAsync();
_server.Dispose();
}
private static int GetFreePort()
{
using var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(new IPEndPoint(IPAddress.Loopback, 0));
return ((IPEndPoint)sock.LocalEndPoint!).Port;
}
[Fact]
public async Task Server_rejects_connection_when_max_reached()
{
using var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
// Connect two clients (at limit)
var client1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client1.ConnectAsync(IPAddress.Loopback, _port);
var buf = new byte[4096];
var n = await client1.ReceiveAsync(buf, SocketFlags.None, readCts.Token);
Encoding.ASCII.GetString(buf, 0, n).ShouldStartWith("INFO ");
var client2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client2.ConnectAsync(IPAddress.Loopback, _port);
n = await client2.ReceiveAsync(buf, SocketFlags.None, readCts.Token);
Encoding.ASCII.GetString(buf, 0, n).ShouldStartWith("INFO ");
// Third client should be rejected
var client3 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client3.ConnectAsync(IPAddress.Loopback, _port);
n = await client3.ReceiveAsync(buf, SocketFlags.None, readCts.Token);
var response = Encoding.ASCII.GetString(buf, 0, n);
response.ShouldContain("-ERR 'maximum connections exceeded'");
// Connection should be closed
n = await client3.ReceiveAsync(buf, SocketFlags.None, readCts.Token);
n.ShouldBe(0);
client1.Dispose();
client2.Dispose();
client3.Dispose();
}
}