Path: redb-route/tests/redb.Route.Tests/Processors/ToProcessorTests.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/Processors/ToProcessorTests.cs ---- using System.Linq; using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class ToProcessorTests { /// Sends exchange to the endpoint producer. [Fact] public async Task Process_SendsToProducer() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("kafka://orders").Returns(endpoint); var processor = new ToProcessor("kafka://orders", context); var exchange = new Exchange(new Message("order-1")); await processor.Process(exchange); await producer.Received(1).Process(exchange, Arg.Any()); } /// Producer is cached after first use. [Fact] public async Task Process_CachesProducer() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("kafka://orders").Returns(endpoint); var processor = new ToProcessor("kafka://orders", context); await processor.Process(new Exchange()); await processor.Process(new Exchange()); endpoint.Received(1).CreateProducer(); // Only once } /// EndpointUri property returns the configured URI. [Fact] public void EndpointUri_ReturnsConfigured() { var context = Substitute.For(); var processor = new ToProcessor("redis:SET:key", context); processor.EndpointUri.Should().Be("redis:SET:key"); } /// Null URI throws. [Fact] public void Constructor_NullUri_Throws() { var context = Substitute.For(); var act = () => new ToProcessor(null!, context); act.Should().Throw(); } /// Null context throws. [Fact] public void Constructor_NullContext_Throws() { var act = () => new ToProcessor("kafka://x", null!); act.Should().Throw(); } /// RecordMessageOut is called on the endpoint after successful processing. [Fact] public async Task Process_Success_RecordsMessageOut() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("direct://stats").Returns(endpoint); var processor = new ToProcessor("direct://stats", context); await processor.Process(new Exchange(new Message("data"))); ((IEndpointStatistics)endpoint).Received(1).RecordMessageOut(); ((IEndpointStatistics)endpoint).DidNotReceive().RecordError(); } /// RecordError is called on the endpoint when the producer throws. [Fact] public async Task Process_Error_RecordsError() { var producer = Substitute.For(); producer.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("boom"))); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("direct://stats-err").Returns(endpoint); var processor = new ToProcessor("direct://stats-err", context); var act = () => processor.Process(new Exchange(new Message("data"))); await act.Should().ThrowAsync(); // Production records the error WITH the exception (ToProcessor calls RecordError(ex)), // so assert the Exception overload — RecordError() (parameterless) is a different call. ((IEndpointStatistics)endpoint).Received(1).RecordError(Arg.Any()); ((IEndpointStatistics)endpoint).DidNotReceive().RecordMessageOut(); } /// No error when endpoint does not implement IEndpointStatistics. [Fact] public async Task Process_NonStatsEndpoint_NoError() { var producer = Substitute.For(); var endpoint = Substitute.For(); // No IEndpointStatistics endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("mock://no-stats").Returns(endpoint); var processor = new ToProcessor("mock://no-stats", context); await processor.Process(new Exchange(new Message("data"))); // Should not throw — graceful when endpoint doesn't implement stats await producer.Received(1).Process(Arg.Any(), Arg.Any()); } // ── Cold-start race regression (RabbitMQ 3.2.2 native concurrency exposed this) ──── /// /// Under concurrent cold start the producer must be started exactly once, and NO exchange may reach /// producer.Process() before Start() has fully completed — otherwise a half-initialised /// producer (e.g. a Redis producer whose _db is still null) throws an NRE. Regression for the /// lazy-start race that surfaced once RabbitMQ ConcurrentConsumers(N) actually parallelised. /// [Fact] public async Task Process_ConcurrentColdStart_StartsOnce_AndNeverProcessesBeforeStartCompletes() { var startGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var started = 0; var startCalls = 0; var processedBeforeStart = 0; var producer = Substitute.For(); // Start() blocks until the gate is released, then marks the producer "started". producer.Start(Arg.Any()).Returns(async _ => { Interlocked.Increment(ref startCalls); await startGate.Task.ConfigureAwait(false); Volatile.Write(ref started, 1); }); // Process() records any call that arrives before Start() has completed — that must never happen. producer.Process(Arg.Any(), Arg.Any()).Returns(_ => { if (Volatile.Read(ref started) == 0) Interlocked.Increment(ref processedBeforeStart); return Task.CompletedTask; }); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("redis:SET:k").Returns(endpoint); var to = new ToProcessor("redis:SET:k", context); // 20 exchanges hit the cold producer at once (mirrors ConcurrentConsumers(20) dispatch). var calls = Enumerable.Range(0, 20) .Select(_ => Task.Run(() => to.Process(new Exchange(new Message())))).ToArray(); await Task.Delay(50); // let them all pile up on the single in-flight start startGate.SetResult(); await Task.WhenAll(calls); startCalls.Should().Be(1, "single-flight: the producer is created + started exactly once"); endpoint.Received(1).CreateProducer(); processedBeforeStart.Should().Be(0, "no exchange may reach Process() before Start() fully completes"); await producer.Received(20).Process(Arg.Any(), Arg.Any()); } /// /// A must not report IsStarted until ConnectAsync has /// completed, and two concurrent Start() calls must await the SAME connect (connect once). /// [Fact] public async Task ConnectableProducer_NotStartedUntilConnectCompletes_ConcurrentStartConnectsOnce() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var endpoint = Substitute.For(); var producer = new GatedProducer(gate, endpoint); var s1 = producer.Start(); var s2 = producer.Start(); // concurrent — must join the same connect, not start a second await Task.Delay(30); producer.IsStarted.Should().BeFalse("ConnectAsync has not completed — must not report started"); gate.SetResult(); await Task.WhenAll(s1, s2); producer.IsStarted.Should().BeTrue(); producer.Ready.Should().BeTrue("resources are assigned inside ConnectAsync"); producer.ConnectCalls.Should().Be(1, "concurrent Start() calls await the same ConnectAsync"); } /// Test double: a ConnectableProducer whose ConnectAsync is gated and assigns state only when released. private sealed class GatedProducer : ConnectableProducer { private readonly TaskCompletionSource _gate; private readonly IEndpoint _endpoint; public int ConnectCalls; public volatile bool Ready; public GatedProducer(TaskCompletionSource gate, IEndpoint endpoint) { _gate = gate; _endpoint = endpoint; } protected override IEndpoint ProducerEndpoint => _endpoint; protected override string ProducerName => "test:gated"; protected override async Task ConnectAsync(CancellationToken ct) { Interlocked.Increment(ref ConnectCalls); await _gate.Task.ConfigureAwait(false); // simulate a slow connection Ready = true; // resources assigned ONLY after the connect settles } public override Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); return Task.CompletedTask; } } }