Path: redb-route/tests/redb.Route.Tests/Core/PushConsumerTests.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/Core/PushConsumerTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Tests.Core; /// /// with a fake client: the outcome of each message (Accepted, Rejected after the retries, /// Refused once a stop began, Returned when the stop ends it or the work after the route fails), the order of a stop /// (stop accepting, drain, then unsubscribe), the concurrency limit, and a lost subscription brought back by /// on the supervisor's schedule while the endpoint's health follows. /// public sealed class PushConsumerTests : IAsyncLifetime { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private RouteContext _context = null!; private FakeEndpoint _endpoint = null!; public Task InitializeAsync() { _context = new RouteContext(options: new RouteEngineOptions { Reconnect = new ReconnectOptions { Delay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(400) }, }); _context.AddComponent(new FakeComponent()); _endpoint = (FakeEndpoint)_context.GetEndpoint("fake://queue"); return Task.CompletedTask; } public async Task DisposeAsync() => await _context.DisposeAsync(); private FakeConsumer Consumer(Func route, int? maxConcurrency = null) => new(_endpoint, new DelegateProcessor(route), maxConcurrency); [Fact] public async Task A_route_that_ends_well_is_Accepted_and_a_failing_one_Rejected_after_its_attempts() { var runs = 0; var consumer = Consumer((ex, _) => { Interlocked.Increment(ref runs); if ((string)ex.In.Body! == "bad") ex.Exception = new InvalidOperationException("route failed"); return Task.CompletedTask; }); await consumer.Start(); (await consumer.Deliver("good")).Outcome.Should().Be(PushOutcome.Accepted); var bad = await consumer.Deliver("bad", new PushRetry(3, TimeSpan.Zero)); bad.Outcome.Should().Be(PushOutcome.Rejected); bad.Failure!.Message.Should().Be("route failed"); runs.Should().Be(4, "one run for the good message, three attempts for the bad one"); consumer.CreatedExchanges.Should().Be(4, "each attempt runs on a fresh exchange"); await consumer.Stop(); } [Fact] public async Task A_thrown_failure_and_a_rollback_only_exchange_are_Rejected_too() { var consumer = Consumer((ex, _) => (string)ex.In.Body! == "throw" ? throw new InvalidOperationException("escaped") : MarkRollbackOnly(ex)); await consumer.Start(); (await consumer.Deliver("throw")).Outcome.Should().Be(PushOutcome.Rejected); (await consumer.Deliver("rollback")).Outcome.Should().Be(PushOutcome.Rejected); await consumer.Stop(); } [Fact] public async Task A_message_after_the_stop_began_is_Refused_and_not_run() { var runs = 0; var consumer = Consumer((_, _) => { Interlocked.Increment(ref runs); return Task.CompletedTask; }); await consumer.Start(); await consumer.Stop(); (await consumer.Deliver("late")).Outcome.Should().Be(PushOutcome.Refused); runs.Should().Be(0); } [Fact] public async Task A_message_waiting_for_a_slot_when_the_stop_begins_is_Refused() { var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var runs = 0; var consumer = Consumer(async (_, _) => { Interlocked.Increment(ref runs); await release.Task; }, maxConcurrency: 1); await consumer.Start(); var first = consumer.Deliver("first"); (await Until(() => Volatile.Read(ref runs) == 1)).Should().BeTrue(); var waiting = consumer.Deliver("waiting"); var stop = consumer.Stop(); release.SetResult(); (await first).Outcome.Should().Be(PushOutcome.Accepted, "the message in work drains"); (await waiting).Outcome.Should().Be(PushOutcome.Refused, "the stop began while it waited for its slot"); await stop; runs.Should().Be(1); } [Fact] public async Task A_stop_behind_a_stuck_message_ends_by_the_drain_window_and_Refuses_the_one_waiting_for_its_slot() { // The slot wait takes no token: what bounds the stop is the drain, which cancels the stuck message; its slot // goes to the waiter, which then sees the stop and is refused without running. var runs = 0; var consumer = Consumer(async (_, ct) => { Interlocked.Increment(ref runs); await Task.Delay(Timeout.Infinite, ct); }, maxConcurrency: 1); consumer.SetDrainTimeout(TimeSpan.FromMilliseconds(200)); await consumer.Start(); var stuck = consumer.Deliver("stuck"); (await Until(() => consumer.InWork == 1)).Should().BeTrue(); var waiting = consumer.Deliver("waiting"); await Task.Delay(50); var clock = System.Diagnostics.Stopwatch.StartNew(); await consumer.Stop().WaitAsync(Wait); clock.Stop(); (await stuck.WaitAsync(Wait)).Outcome.Should().Be(PushOutcome.Returned, "the drain window cancelled it"); (await waiting.WaitAsync(Wait)).Outcome.Should().Be(PushOutcome.Refused, "it got its slot only after the stop began"); runs.Should().Be(1, "the waiting message never ran"); clock.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(3), "the stop is bounded by the 200 ms drain window"); } [Fact] public async Task The_stop_stops_accepting_drains_and_then_unsubscribes() { var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var consumer = Consumer(async (_, _) => await release.Task); await consumer.Start(); var inWork = consumer.Deliver("in work"); (await Until(() => consumer.InWork == 1)).Should().BeTrue(); var stop = consumer.Stop(); (await Until(() => consumer.Steps.Contains("stop accepting"))).Should().BeTrue(); await Task.Delay(200); consumer.Steps.Should().NotContain("unsubscribe", "the drain waits for the message in work"); release.SetResult(); await stop; (await inWork).Outcome.Should().Be(PushOutcome.Accepted); consumer.Steps.Should().Equal("subscribe", "stop accepting", "unsubscribe"); } [Fact] public async Task A_message_whose_drain_window_runs_out_is_Returned() { var consumer = Consumer(async (_, ct) => await Task.Delay(Timeout.Infinite, ct)); consumer.SetDrainTimeout(TimeSpan.FromMilliseconds(200)); await consumer.Start(); var inWork = consumer.Deliver("slow"); (await Until(() => consumer.InWork == 1)).Should().BeTrue(); await consumer.Stop().WaitAsync(Wait); (await inWork).Outcome.Should().Be(PushOutcome.Returned); } [Fact] public async Task A_stop_during_the_pause_before_the_next_attempt_Returns_the_message() { var runs = 0; var consumer = Consumer((ex, _) => { Interlocked.Increment(ref runs); ex.Exception = new InvalidOperationException("route failed"); return Task.CompletedTask; }); await consumer.Start(); var retried = consumer.Deliver("bad", new PushRetry(5, TimeSpan.FromSeconds(30))); (await Until(() => Volatile.Read(ref runs) == 1)).Should().BeTrue(); await consumer.Stop().WaitAsync(Wait); (await retried).Outcome.Should().Be(PushOutcome.Returned); runs.Should().Be(1); } [Fact] public async Task A_failing_follow_up_after_the_route_Returns_the_message_with_its_failure() { var consumer = Consumer((_, _) => Task.CompletedTask); await consumer.Start(); var dispatch = await consumer.Deliver("reply", afterRoute: (_, _) => throw new IOException("reply channel gone")); dispatch.Outcome.Should().Be(PushOutcome.Returned); dispatch.Failure.Should().BeOfType(); await consumer.Stop(); } [Fact] public async Task No_more_messages_run_at_once_than_the_concurrency_limit() { var running = 0; var peak = 0; var consumer = Consumer(async (_, _) => { var now = Interlocked.Increment(ref running); InterlockedMax(ref peak, now); await Task.Delay(50); Interlocked.Decrement(ref running); }, maxConcurrency: 2); await consumer.Start(); var all = await Task.WhenAll(Enumerable.Range(0, 10).Select(i => consumer.Deliver($"m{i}"))); all.Should().AllSatisfy(d => d.Outcome.Should().Be(PushOutcome.Accepted)); peak.Should().Be(2); await consumer.Stop(); } [Fact] public async Task A_lost_subscription_is_brought_back_on_the_schedule_and_health_follows() { var consumer = Consumer((_, _) => Task.CompletedTask); await consumer.Start(); consumer.FailNextSubscribes = 1; var resubscribe = consumer.LoseSubscription(); _endpoint.HealthStatus.Should().NotBe(EndpointHealthStatus.Healthy, "the subscription is lost"); consumer.LoseSubscription().Should().BeSameAs(resubscribe, "one loop at a time"); (await resubscribe.WaitAsync(Wait)).Should().BeTrue(); consumer.Steps.Should().Equal("subscribe", "subscribe failed", "subscribe"); _endpoint.Reconnects.Should().Be(1); _endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); await consumer.Stop(); _endpoint.HealthReason.Should().NotContain("fake channel", "the stopped consumer's supervisor is removed"); } [Fact] public async Task A_stop_during_a_resubscribe_ends_it_and_nothing_subscribes_after_the_stop() { var consumer = Consumer((_, _) => Task.CompletedTask); await consumer.Start(); consumer.FailNextSubscribes = int.MaxValue; var resubscribe = consumer.LoseSubscription(); (await Until(() => consumer.Steps.Count(s => s == "subscribe failed") >= 1)).Should().BeTrue(); await consumer.Stop().WaitAsync(Wait); (await resubscribe.WaitAsync(Wait)).Should().BeFalse("the stop ended the loop"); var steps = consumer.Steps.Length; await Task.Delay(600); consumer.Steps.Length.Should().Be(steps, "no attempt after the stop"); consumer.Steps.Last().Should().Be("unsubscribe"); } private static Task MarkRollbackOnly(IExchange exchange) { exchange.MarkRollbackOnly(); return Task.CompletedTask; } private static void InterlockedMax(ref int target, int value) { int current; while ((current = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, current) != current) { } } private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (DateTime.UtcNow < deadline) { if (done()) return true; await Task.Delay(20); } return done(); } private sealed class FakeConsumer(FakeEndpoint endpoint, IProcessor processor, int? maxConcurrency) : PushConsumer(processor, maxConcurrency) { private readonly ConcurrentQueue _steps = new(); private ConnectionSupervisor? _channel; private int _created; public string[] Steps => _steps.ToArray(); public int CreatedExchanges => Volatile.Read(ref _created); public int InWork => InflightCount; public int FailNextSubscribes; protected override IEndpoint ConsumerEndpoint => endpoint; protected override string ConsumerName => "fake:queue"; public void SetDrainTimeout(TimeSpan timeout) => DrainTimeout = timeout; protected override Task SubscribeAsync(CancellationToken ct) { _channel ??= SuperviseConnection("fake channel"); return Subscribe(); } private Task Subscribe() { if (Interlocked.Decrement(ref FailNextSubscribes) >= 0) { _steps.Enqueue("subscribe failed"); throw new IOException("channel refused"); } Interlocked.Exchange(ref FailNextSubscribes, 0); _steps.Enqueue("subscribe"); return Task.CompletedTask; } protected override Task StopAcceptingAsync(CancellationToken ct) { _steps.Enqueue("stop accepting"); return Task.CompletedTask; } protected override Task UnsubscribeAsync(CancellationToken ct) { _steps.Enqueue("unsubscribe"); _channel = null; return Task.CompletedTask; } /// The broker closed the channel: report it and resubscribe, as a connector's shutdown handler does. public Task LoseSubscription() { _channel!.Lost(new IOException("channel closed by the broker")); return ResubscribeAsync(_channel, _ => Subscribe()); } public Task Deliver(string body, PushRetry? retry = null, Func? afterRoute = null) => Task.Run(() => DispatchAsync(() => { Interlocked.Increment(ref _created); return new Exchange(new Message(body)); }, default(TransportSpan), retry, afterRoute)); } private sealed class FakeComponent : ComponentBase { public override string Scheme => "fake"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new FakeEndpoint(uri, this); } private sealed class FakeOptions : EndpointOptions { public override void Validate() { } } private sealed class FakeEndpoint(EndpointUri uri, IComponent component) : EndpointBase(uri, component, new FakeOptions()) { public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); } }