Path: redb-route/tests/redb.Route.Tests.RabbitMQ/RabbitMQChannelRecoveryTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.RabbitMQ/RabbitMQChannelRecoveryTests.cs ---- using RabbitMQ.Client; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RabbitMQ; using Xunit.Abstractions; namespace redb.Route.Tests.RabbitMQ; /// /// The broker closes a channel on a channel-level error — a publish to an exchange that does not exist is the everyday /// case (404 NOT_FOUND). The connection stays up, so connection recovery does nothing for it. Expects RabbitMQ at /// localhost:5672 (admin/admin). /// [Trait("Category", "Integration")] public sealed class RabbitMQChannelRecoveryTests { private readonly ITestOutputHelper _output; public RabbitMQChannelRecoveryTests(ITestOutputHelper output) => _output = output; [Fact] public async Task Producer_sends_again_after_the_broker_closed_its_channel() { var queue = $"test-chan-recover-{Guid.NewGuid():N}"; await using (var setup = await ConnectAsync()) await using (var channel = await setup.CreateChannelAsync()) { // Durable: RabbitMQ 4.3 refuses transient non-exclusive queues (541, transient_nonexcl_queues). await channel.QueueDeclareAsync(queue, durable: true, exclusive: false, autoDelete: false); await channel.QueueBindAsync(queue, "amq.direct", queue); } var endpoint = (RabbitMQEndpoint)new RabbitMQComponent().CreateEndpoint(EndpointUriParser.Parse( $"rabbitmq://?host=localhost&port=5672&username=admin&password=admin&exchange=${{header.target}}&routingKey={queue}")); var producer = (RabbitMQProducer)endpoint.CreateProducer(); await producer.Start(); var typo = new Exchange(new Message("to nowhere")); typo.In.Headers["target"] = $"no-such-exchange-{Guid.NewGuid():N}"; var first = () => producer.Process(typo); (await first.Should().ThrowAsync()).Which.Message.Should().Contain("NOT_FOUND"); var good = new Exchange(new Message("delivered")); good.In.Headers["target"] = "amq.direct"; await producer.Process(good); await producer.Stop(); await endpoint.Stop(); await using var check = await ConnectAsync(); await using var checkChannel = await check.CreateChannelAsync(); (await checkChannel.QueueDeclarePassiveAsync(queue)).MessageCount.Should().Be(1, "the next send opens a new channel instead of failing on the one the broker closed"); await checkChannel.QueueDeleteAsync(queue); } [Fact] public async Task Consumer_subscribes_again_when_the_broker_cancels_it_and_says_nothing_when_it_stops() { var logs = new CapturingLoggerFactory(); var queue = $"test-cancelled-{Guid.NewGuid():N}"; var (consumer, endpoint) = await StartConsumerAsync(logs, queue, new CountingProcessor()); try { await using (var admin = await ConnectAsync()) await using (var channel = await admin.CreateChannelAsync()) await channel.QueueDeleteAsync(queue); (await Until(() => endpoint.Reconnects >= 1)).Should().BeTrue( "a consumer whose queue was deleted subscribes again (declare=true declares the queue anew)"); await PublishAsync(queue, "after the cancel"); (await Until(() => consumer.ProcessedCount == 1)).Should().BeTrue("the new subscription reads the queue"); logs.Warnings.Should().Contain(w => w.Contains("cancelled by the broker") && w.Contains(queue), "the loss is said while it lasts"); logs.Errors.Should().BeEmpty("a subscription that comes back is not an error"); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); } finally { await consumer.Stop(); await endpoint.Stop(); } var quiet = new CapturingLoggerFactory(); var (stopped, stoppedEndpoint) = await StartConsumerAsync(quiet, $"test-stopped-{Guid.NewGuid():N}", new CountingProcessor()); await stopped.Stop(); await stoppedEndpoint.Stop(); quiet.Errors.Should().BeEmpty("stopping the route cancels the subscription on purpose"); quiet.Warnings.Should().NotContain(w => w.Contains("lost its connection"), "a stop is not a loss"); } [Fact] public async Task Consumer_reads_again_after_a_double_ack_closed_its_channel() { var logs = new CapturingLoggerFactory(); var queue = $"test-double-ack-{Guid.NewGuid():N}"; var processor = new CountingProcessor(); var (consumer, endpoint) = await StartConsumerAsync(logs, queue, processor); try { await PublishAsync(queue, "first"); (await Until(() => consumer.ProcessedCount == 1)).Should().BeTrue("the first message is read and acked"); // A second ack of a tag the channel no longer holds: the client does not throw, the broker closes the channel // with 406 PRECONDITION_FAILED and keeps the connection, so connection recovery does nothing for it. var channel = consumer.ConsumeChannel!; await channel.BasicAckAsync(1, multiple: false); (await Until(() => !channel.IsOpen)).Should().BeTrue("the broker closes the channel on an unknown delivery tag"); (await Until(() => endpoint.Reconnects == 1)).Should().BeTrue("the consumer opens a new channel and subscribes again"); await PublishAsync(queue, "second"); (await Until(() => consumer.ProcessedCount == 2)).Should().BeTrue("the new subscription reads the queue"); endpoint.Reconnects.Should().Be(1); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); logs.Warnings.Should().Contain(w => w.Contains("406") && w.Contains(queue)); processor.Count.Should().Be(2, "each message goes through the route once"); } finally { await consumer.Stop(); await endpoint.Stop(); } } private static async Task<(RabbitMQConsumer, RabbitMQEndpoint)> StartConsumerAsync( CapturingLoggerFactory logs, string queue, redb.Route.Abstractions.IProcessor processor) { var context = new RouteContext(loggerFactory: logs); var component = new RabbitMQComponent(); context.AddComponent(component); var endpoint = (RabbitMQEndpoint)component.CreateEndpoint(EndpointUriParser.Parse( $"rabbitmq://{queue}?host=localhost&port=5672&username=admin&password=admin&declare=true&autoDelete=true")); var consumer = (RabbitMQConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); return (consumer, endpoint); } private static async Task PublishAsync(string queue, string body) { await using var connection = await ConnectAsync(); await using var channel = await connection.CreateChannelAsync(); await channel.BasicPublishAsync("", queue, System.Text.Encoding.UTF8.GetBytes(body)); } private static async Task Until(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(15); while (!condition()) { if (DateTime.UtcNow > deadline) return false; await Task.Delay(50); } return true; } private sealed class CountingProcessor : redb.Route.Abstractions.IProcessor { private int _count; public int Count => Volatile.Read(ref _count); public Task Process(redb.Route.Abstractions.IExchange exchange, CancellationToken ct = default) { Interlocked.Increment(ref _count); return Task.CompletedTask; } } private sealed class CapturingLoggerFactory : Microsoft.Extensions.Logging.ILoggerFactory { private readonly System.Collections.Concurrent.ConcurrentQueue _errors = new(); private readonly System.Collections.Concurrent.ConcurrentQueue _warnings = new(); public IReadOnlyCollection Errors => _errors.ToArray(); public IReadOnlyCollection Warnings => _warnings.ToArray(); public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new Logger(_errors, _warnings); public void AddProvider(Microsoft.Extensions.Logging.ILoggerProvider provider) { } public void Dispose() { } private sealed class Logger( System.Collections.Concurrent.ConcurrentQueue errors, System.Collections.Concurrent.ConcurrentQueue warnings) : Microsoft.Extensions.Logging.ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true; public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception? exception, Func formatter) { if (logLevel >= Microsoft.Extensions.Logging.LogLevel.Error) errors.Enqueue(formatter(state, exception)); else if (logLevel == Microsoft.Extensions.Logging.LogLevel.Warning) warnings.Enqueue(formatter(state, exception)); } } } private static async Task ConnectAsync() => await new ConnectionFactory { HostName = "localhost", Port = 5672, UserName = "admin", Password = "admin" }.CreateConnectionAsync(); }