feat(mqtt): add MQTT listener, client creation, and shutdown wiring

Wire up the MQTT server-side orchestration layer (Task 1 of 7):
- Create NatsServer.Mqtt.cs with StartMqttListener(), CreateMqttClient(), MqttAddr()
- Forward MqttHandler.StartMqtt() to server.StartMqttListener()
- Add _mqttListener to Shutdown() doneExpected counting
- Fix ReadyForConnections to recognize active MQTT listener
- Handle RandomPort (-1) as ephemeral for MQTT listener
- Remove duplicate Mqtt field from ClientConnection.cs (already in ClientConnection.Mqtt.cs)
- Add 2 MQTT boot integration tests (accept + shutdown lifecycle)
This commit is contained in:
Joseph Doherty
2026-03-01 15:35:41 -05:00
parent 60bb56a90c
commit 6fb7f43335
7 changed files with 266 additions and 6 deletions

View File

@@ -88,6 +88,78 @@ public sealed class ServerBootTests : IDisposable
}
}
/// <summary>
/// Validates that a server can boot with an MQTT listener on an ephemeral port,
/// accept a TCP connection on the MQTT port, and register it as a client.
/// </summary>
[Fact]
public async Task MqttBoot_AcceptsConnection_ShouldSucceed()
{
var opts = new ServerOptions
{
Host = "127.0.0.1",
Port = 0,
Mqtt = { Port = -1, Host = "127.0.0.1" },
};
var (server, err) = NatsServer.NewServer(opts);
err.ShouldBeNull("NewServer should succeed");
server.ShouldNotBeNull();
try
{
server!.Start();
// Verify MQTT listener is up
var mqttAddr = server.MqttAddr();
mqttAddr.ShouldNotBeNull("MqttAddr should return the MQTT listener address");
mqttAddr!.Port.ShouldBeGreaterThan(0);
// ReadyForConnections should include MQTT
server.ReadyForConnections(TimeSpan.FromSeconds(5)).ShouldBeTrue();
// Connect a raw TCP client to the MQTT port
using var tcp = new System.Net.Sockets.TcpClient();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await tcp.ConnectAsync(mqttAddr.Address, mqttAddr.Port, cts.Token);
tcp.Connected.ShouldBeTrue();
// Give CreateMqttClient a moment to register
await Task.Delay(100);
server.NumClients().ShouldBeGreaterThan(0);
}
finally
{
server!.Shutdown();
}
}
/// <summary>
/// Validates that an MQTT listener starts and shuts down cleanly.
/// </summary>
[Fact]
public void MqttBoot_StartAndShutdown_ShouldSucceed()
{
var opts = new ServerOptions
{
Host = "127.0.0.1",
Port = 0,
DontListen = true,
Mqtt = { Port = -1, Host = "127.0.0.1" },
};
var (server, err) = NatsServer.NewServer(opts);
err.ShouldBeNull();
server.ShouldNotBeNull();
server!.Start();
server.Running().ShouldBeTrue();
server.MqttAddr().ShouldNotBeNull();
server.Shutdown();
server.Running().ShouldBeFalse();
}
/// <summary>
/// Validates that Shutdown() after Start() completes cleanly.
/// Uses DontListen to skip TCP binding — tests lifecycle only.