Path: redb-route/tests/redb.Route.Tests/Processors/ExceptionAndThreadSafetyTests.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/ExceptionAndThreadSafetyTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Tests for exception propagation, thread safety, and resource disposal in processors. /// public class ExceptionAndThreadSafetyTests { // ============================================================== // Condition strings - fail-fast on an invalid expression // (LogicalExpression was removed with the second parser, 2026-08-28) // ============================================================== [Fact] public void ConditionString_InvalidExpression_ThrowsAtBuildTime() { var act = () => redb.Route.Predicates.PredicateFactory.FromString("~~~INVALID~~~ >"); act.Should().Throw(); } [Fact] public void ConditionString_ValidExpression_StillWorks() { var pred = redb.Route.Predicates.PredicateFactory.FromString("property.x > 0"); var exchange = new Exchange(new Message("body")); exchange.Properties["x"] = 5; pred.Matches(exchange).Should().BeTrue(); } // ══════════════════════════════════════════════════════════════ // DebounceProcessor — downstream errors are logged and recorded // ══════════════════════════════════════════════════════════════ [Fact] public async Task Debounce_DownstreamThrows_SetsExchangeException() { var expected = new InvalidOperationException("boom"); IExchange? capturedExchange = null; var failingNext = new DelegateProcessor(ex => { capturedExchange = ex; throw expected; }); // Row 67: the quiet period runs on a FakeTimeProvider and the test waits for the error log line, which the // processor writes after it has set the exception. A fixed 200 ms wait failed on a loaded release stand. var time = new FakeTimeProvider(); var logger = new ErrorSignalLogger(); var processor = new DebounceProcessor( failingNext, e => e.In.Headers.TryGetValue("key", out var v) ? v?.ToString() ?? "" : "", TimeSpan.FromMilliseconds(50), logger, time); var exchange = Exchange.Create(new Message("data"), null); exchange.In.Headers["key"] = "k1"; await processor.Process(exchange); time.Advance(TimeSpan.FromMilliseconds(50)); var logged = await logger.Error.Task.WaitAsync(TimeSpan.FromSeconds(10)); logged.Should().BeSameAs(expected); capturedExchange.Should().NotBeNull(); capturedExchange!.Exception.Should().BeSameAs(expected); await processor.DisposeAsync(); } /// A logger that completes with the exception of the first error it is given. private sealed class ErrorSignalLogger : ILogger { public TaskCompletionSource Error { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (logLevel == LogLevel.Error) Error.TrySetResult(exception); } } [Fact] public async Task Debounce_FlushAsync_DownstreamThrows_SetsExchangeException() { var expected = new InvalidOperationException("flush-boom"); IExchange? capturedExchange = null; var failingNext = new DelegateProcessor(ex => { capturedExchange = ex; throw expected; }); var logger = Substitute.For(); var processor = new DebounceProcessor( failingNext, e => e.In.Headers.TryGetValue("key", out var v) ? v?.ToString() ?? "" : "", TimeSpan.FromHours(1), // Long quiet period — won't fire by itself logger); var exchange = Exchange.Create(new Message("data"), null); exchange.In.Headers["key"] = "k1"; await processor.Process(exchange); // Force flush instead of waiting for timer await processor.FlushAsync(); capturedExchange.Should().NotBeNull(); capturedExchange!.Exception.Should().BeSameAs(expected); logger.ReceivedCalls().Should().NotBeEmpty(); processor.Dispose(); } // ══════════════════════════════════════════════════════════════ // DynamicRouterProcessor — thread safety under concurrent access // ══════════════════════════════════════════════════════════════ [Fact] public async Task DynamicRouter_ConcurrentAccess_NoCorruption() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(_ => Substitute.For()); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); var exceptions = new ConcurrentBag(); // 10 concurrent tasks each routing to different URIs var tasks = Enumerable.Range(0, 10).Select(i => Task.Run(async () => { try { var router = new DynamicRouterProcessor(context, ex => { var body = ex.In.Body?.ToString(); return body == "done" ? null : $"direct://target-{i}"; }); var exchange = new Exchange(new Message("go")); // After first hop, mark as done so it stops var hop = 0; var drRouter = new DynamicRouterProcessor(context, _ => { hop++; return hop <= 1 ? $"direct://t{i}" : null; }); await drRouter.Process(new Exchange(new Message("data"))); } catch (Exception ex) { exceptions.Add(ex); } })); await Task.WhenAll(tasks); exceptions.Should().BeEmpty("concurrent access should not cause corruption"); } // ══════════════════════════════════════════════════════════════ // DynamicRouterProcessor — DisposeAsync stops cached producers // ══════════════════════════════════════════════════════════════ [Fact] public async Task DynamicRouter_DisposeAsync_StopsAllProducers() { var producerA = Substitute.For(); var producerB = Substitute.For(); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); var endpointB = Substitute.For(); endpointB.CreateProducer().Returns(producerB); var context = Substitute.For(); context.GetEndpoint("direct://a").Returns(endpointA); context.GetEndpoint("direct://b").Returns(endpointB); var hops = new Queue(["direct://a", "direct://b", null]); var router = new DynamicRouterProcessor(context, _ => hops.Dequeue()); await router.Process(new Exchange(new Message("data"))); await router.DisposeAsync(); await producerA.Received(1).Stop(Arg.Any()); await producerB.Received(1).Stop(Arg.Any()); } // ══════════════════════════════════════════════════════════════ // RecipientListProcessor — DisposeAsync stops cached producers // ══════════════════════════════════════════════════════════════ [Fact] public async Task RecipientList_DisposeAsync_StopsAllProducers() { var producerA = Substitute.For(); var producerB = Substitute.For(); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); var endpointB = Substitute.For(); endpointB.CreateProducer().Returns(producerB); var context = Substitute.For(); context.GetEndpoint("seda://a").Returns(endpointA); context.GetEndpoint("seda://b").Returns(endpointB); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b" }); await processor.Process(new Exchange(new Message("data"))); await processor.DisposeAsync(); await producerA.Received(1).Stop(Arg.Any()); await producerB.Received(1).Stop(Arg.Any()); } [Fact] public async Task RecipientList_DisposeAsync_IdempotentAfterDispose() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("seda://x").Returns(endpoint); var processor = new RecipientListProcessor(context, _ => new[] { "seda://x" }); await processor.Process(new Exchange(new Message("data"))); await processor.DisposeAsync(); await processor.DisposeAsync(); // Second call should be safe await producer.Received(1).Stop(Arg.Any()); } }