Bundle: redb-route / tests/redb.Route.Tests (tests.redb.Route.Tests.2.txt), 71 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/tests/redb.Route.Tests/Processors/ResequencerProcessorTests.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/ResequencerProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class ResequencerProcessorTests { [Fact] public async Task Process_BatchComplete_FlushesInOrder() { var order = new List(); var next = new DelegateProcessor(ex => order.Add((long)ex.In.Body!)); var reseq = new ResequencerProcessor(next, keySelector: ex => (long)ex.In.Body!, batchSize: 3); // Send out-of-order: 3, 1, 2 await reseq.Process(new Exchange(new Message(3L))); await reseq.Process(new Exchange(new Message(1L))); await reseq.Process(new Exchange(new Message(2L))); // triggers flush at batchSize=3 order.Should().Equal(1L, 2L, 3L); } [Fact] public async Task Process_BelowBatchSize_DoesNotFlush() { var order = new List(); var next = new DelegateProcessor(ex => order.Add((long)ex.In.Body!)); var reseq = new ResequencerProcessor(next, keySelector: ex => (long)ex.In.Body!, batchSize: 5); await reseq.Process(new Exchange(new Message(2L))); await reseq.Process(new Exchange(new Message(1L))); order.Should().BeEmpty("batch not full yet"); (await reseq.GetBufferedCount()).Should().Be(2); } [Fact] public async Task Flush_DrainsPendingBuffer() { var order = new List(); var next = new DelegateProcessor(ex => order.Add((long)ex.In.Body!)); var reseq = new ResequencerProcessor(next, keySelector: ex => (long)ex.In.Body!, batchSize: 100); await reseq.Process(new Exchange(new Message(5L))); await reseq.Process(new Exchange(new Message(2L))); await reseq.Process(new Exchange(new Message(8L))); order.Should().BeEmpty(); await reseq.Flush(); order.Should().Equal(2L, 5L, 8L); (await reseq.GetBufferedCount()).Should().Be(0); } [Fact] public async Task Flush_EmptyBuffer_DoesNothing() { var callCount = 0; var next = new DelegateProcessor(_ => callCount++); var reseq = new ResequencerProcessor(next, keySelector: ex => 0, batchSize: 10); await reseq.Flush(); callCount.Should().Be(0); } [Fact] public async Task Process_MultipleBatches_EachFlushesIndependently() { var batches = new List>(); var currentBatch = new List(); var next = new DelegateProcessor(ex => { currentBatch.Add((long)ex.In.Body!); }); var reseq = new ResequencerProcessor(next, keySelector: ex => (long)ex.In.Body!, batchSize: 2); // Batch 1: 4, 1 → sorted: 1, 4 await reseq.Process(new Exchange(new Message(4L))); await reseq.Process(new Exchange(new Message(1L))); batches.Add([.. currentBatch]); currentBatch.Clear(); // Batch 2: 3, 2 → sorted: 2, 3 await reseq.Process(new Exchange(new Message(3L))); await reseq.Process(new Exchange(new Message(2L))); batches.Add([.. currentBatch]); batches[0].Should().Equal(1L, 4L); batches[1].Should().Equal(2L, 3L); } [Fact] public async Task Process_DuplicateKeys_AllProcessed() { var bodies = new List(); var next = new DelegateProcessor(ex => bodies.Add((string)ex.In.Body!)); var reseq = new ResequencerProcessor(next, keySelector: _ => 1L, // Same key for all batchSize: 3); await reseq.Process(new Exchange(new Message("a"))); await reseq.Process(new Exchange(new Message("b"))); await reseq.Process(new Exchange(new Message("c"))); bodies.Should().HaveCount(3); } [Fact] public void Constructor_NullNext_Throws() { var act = () => new ResequencerProcessor(null!, _ => 0); act.Should().Throw().WithParameterName("next"); } [Fact] public void Constructor_NullKeySelector_Throws() { var act = () => new ResequencerProcessor(new DelegateProcessor(_ => { }), null!); act.Should().Throw().WithParameterName("keySelector"); } [Fact] public void Constructor_ZeroBatchSize_Throws() { var act = () => new ResequencerProcessor(new DelegateProcessor(_ => { }), _ => 0, batchSize: 0); act.Should().Throw().WithParameterName("batchSize"); } [Fact] public async Task GetBufferedCount_ReflectsCurrentState() { var next = new DelegateProcessor(_ => { }); var reseq = new ResequencerProcessor(next, _ => 1, batchSize: 10); (await reseq.GetBufferedCount()).Should().Be(0); await reseq.Process(new Exchange()); (await reseq.GetBufferedCount()).Should().Be(1); await reseq.Process(new Exchange()); (await reseq.GetBufferedCount()).Should().Be(2); } [Fact] public async Task Process_StoppedExchange_StopsProcessingBatch() { var processed = new List(); var next = new DelegateProcessor(ex => { processed.Add((long)ex.In.Body!); if ((long)ex.In.Body! == 2L) ex.Stop(); }); var reseq = new ResequencerProcessor(next, keySelector: ex => (long)ex.In.Body!, batchSize: 3); await reseq.Process(new Exchange(new Message(3L))); await reseq.Process(new Exchange(new Message(1L))); await reseq.Process(new Exchange(new Message(2L))); // Sorted: 1, 2, 3. Stop at 2 → should process 1, 2 but not 3 processed.Should().Equal(1L, 2L); } } Path: redb-route/tests/redb.Route.Tests/Processors/RichLogProcessorTests.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/RichLogProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for and the rich Log scope DSL. public class RichLogProcessorTests { // ── Processor direct tests ── [Fact] public async Task Process_StaticMessage_OutputsMessage() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["hello world"], messageFuncs: [], headerNames: [], propertyNames: [], showRouteId: false); await processor.Process(new Exchange(new Message("body"))); getLog().Should().Be("hello world"); } [Fact] public async Task Process_MultipleMessages_EachOnOwnLine() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["msg1", "msg2"], messageFuncs: [], headerNames: [], propertyNames: [], showRouteId: false); await processor.Process(new Exchange()); getLog().Should().Be($"msg1{Environment.NewLine}msg2"); } [Fact] public async Task Process_DynamicMessage_ExecutesFunc() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Warning, messages: [], messageFuncs: [ex => $"body={ex.In.Body}"], headerNames: [], propertyNames: [], showRouteId: false); await processor.Process(new Exchange(new Message("test"))); getLog().Should().Be("body=test"); } [Fact] public async Task Process_TemplateMessage_ResolvesPlaceholders() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["Processing ${body}"], messageFuncs: [], headerNames: [], propertyNames: [], showRouteId: false); await processor.Process(new Exchange(new Message("order-42"))); getLog().Should().Be("Processing order-42"); } [Fact] public async Task Process_Headers_OutputsHeaderValues() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["done"], messageFuncs: [], headerNames: ["correlationId", "source"], propertyNames: [], showRouteId: false); var msg = new Message("x"); msg.Headers["correlationId"] = "abc-123"; msg.Headers["source"] = "api"; await processor.Process(new Exchange(msg)); getLog().Should().Be("[h:correlationId=abc-123] [h:source=api] done"); } [Fact] public async Task Process_Properties_OutputsPropertyValues() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["ok"], messageFuncs: [], headerNames: [], propertyNames: ["traceId"], showRouteId: false); var exchange = new Exchange(); exchange.Properties["traceId"] = "t-999"; await processor.Process(exchange); getLog().Should().Be("[p:traceId=t-999] ok"); } [Fact] public async Task Process_ShowRouteId_IncludesRouteIdPrefix() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["hi"], messageFuncs: [], headerNames: [], propertyNames: [], showRouteId: true); var exchange = new Exchange(); exchange.RouteId = "myRoute"; await processor.Process(exchange); getLog().Should().Be("[rId:myRoute] hi"); } [Fact] public async Task Process_AllCombined_OutputInCorrectOrder() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Debug, messages: ["Processing ${body}"], messageFuncs: [ex => $"count={ex.In.Headers.Count}"], headerNames: ["action"], propertyNames: ["step"], showRouteId: true); var msg = new Message("order"); msg.Headers["action"] = "create"; var exchange = new Exchange(msg); exchange.RouteId = "r1"; exchange.Properties["step"] = "validate"; await processor.Process(exchange); // Order: [rId:...] [p:...] [h:...] messages (each on own line) funcs getLog().Should().Be($"[rId:r1] [p:step=validate] [h:action=create] Processing order{Environment.NewLine}count=1"); } [Fact] public async Task Process_MissingHeader_Skipped() { var (logger, getLog) = CreateCapturingLogger(); var processor = new RichLogProcessor(logger, LogLevel.Information, messages: ["msg"], messageFuncs: [], headerNames: ["missing"], propertyNames: [], showRouteId: false); await processor.Process(new Exchange()); getLog().Should().Be("msg"); } [Fact] public async Task Process_DisabledLogLevel_DoesNothing() { var logger = new DisabledLogger(); var processor = new RichLogProcessor(logger, LogLevel.Trace, messages: ["never seen"], messageFuncs: [], headerNames: [], propertyNames: [], showRouteId: false); await processor.Process(new Exchange()); logger.WasCalled.Should().BeFalse(); } // ── DSL scope tests ── [Fact] public async Task DSL_RichLog_MessageOnly() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://rich-log1") .Log(LogLevel.Information) .Message("Step 1 done") .Message("Step 2 done") .EndLog() .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://rich-log1").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); await context.DisposeAsync(); } [Fact] public async Task DSL_RichLog_ParameterlessLog_DefaultsToInformation() { var context = new RouteContext(); IExchange? received = null; RichLogScopeDefinition? scope = null; context.AddRoutes(r => { // Canonical form: .Log().Message().Header().Property()....EndLog() scope = r.From("direct://rich-log-noarg").Log(); scope.Message("no-arg log") .Header("correlationId") .Property("traceId") .ShowRouteId() .EndLog() .Process(ex => received = ex); }); await context.Start(); scope!.Level.Should().Be(LogLevel.Information, "parameterless .Log() opens the scope at Information"); var producer = context.GetEndpoint("direct://rich-log-noarg").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); await context.DisposeAsync(); } [Fact] public async Task DSL_RichLog_WithHeadersAndProperties() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://rich-log2") .Log(LogLevel.Warning) .Message("Processing exchange") .Header("correlationId") .Property("traceId") .ShowRouteId() .EndLog() .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://rich-log2").CreateProducer(); await producer.Start(); var msg = new Message("payload"); msg.Headers["correlationId"] = "c-1"; var ex = new Exchange(msg); ex.Properties["traceId"] = "t-1"; await producer.Process(ex); received.Should().NotBeNull(); await context.DisposeAsync(); } [Fact] public async Task DSL_RichLog_WithDynamicMessage() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://rich-log3") .Log(LogLevel.Error) .Message(ex => $"body={ex.In.Body}") .Message("static after dynamic") .EndLog() .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://rich-log3").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test-body"))); received.Should().NotBeNull(); await context.DisposeAsync(); } [Fact] public async Task DSL_RichLog_EndAlsoWorks() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://rich-log4") .Log(LogLevel.Debug) .Message("via End()") .End() // End() instead of EndLog() .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://rich-log4").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); await context.DisposeAsync(); } [Fact] public void DSL_RichLog_RecordsRichLogStep() { var def = new RouteDefinition(); def.From("direct://test") .Log(LogLevel.Warning) .Message("msg1") .Message(ex => "dynamic") .Header("h1") .Property("p1") .ShowRouteId() .EndLog(); var richLog = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; richLog.Level.Should().Be(LogLevel.Warning); richLog.Messages.Should().ContainSingle().Which.Should().Be("msg1"); richLog.MessageFuncs.Should().HaveCount(1); richLog.HeaderNames.Should().ContainSingle().Which.Should().Be("h1"); richLog.PropertyNames.Should().ContainSingle().Which.Should().Be("p1"); richLog.IncludeRouteId.Should().BeTrue(); } [Fact] public void DSL_Message_OutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://test").Message("oops"); act.Should().Throw().WithMessage("*Log() scope*"); } [Fact] public void DSL_Header_OutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://test").Header("x"); act.Should().Throw().WithMessage("*Log() scope*"); } [Fact] public void DSL_Property_OutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://test").Property("x"); act.Should().Throw().WithMessage("*Log() scope*"); } [Fact] public void DSL_ShowRouteId_OutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://test").ShowRouteId(); act.Should().Throw().WithMessage("*Log*scope*"); } [Fact] public void DSL_EndLog_OutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://test").EndLog(); act.Should().Throw().WithMessage("*Log*scope*"); } // ── Simple Log one-liners still work ── [Fact] public async Task SimpleLog_StillWorks() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://simple-log") .Log("simple message") .Log(ex => $"dynamic {ex.In.Body}") .Log("template ${body}") .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://simple-log").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); await context.DisposeAsync(); } // ── Helper ── /// /// Simple in-memory logger that captures the formatted message string. /// private sealed class CapturingLogger : ILogger { public string? LastMessage { get; private set; } public LogLevel? LastLevel { get; private set; } 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) { LastLevel = logLevel; LastMessage = formatter(state, exception); } } private sealed class DisabledLogger : ILogger { public bool WasCalled { get; private set; } public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => false; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { WasCalled = true; } } private static (CapturingLogger logger, Func getLastMessage) CreateCapturingLogger() { var logger = new CapturingLogger(); return (logger, () => logger.LastMessage); } } Path: redb-route/tests/redb.Route.Tests/Processors/RoutingSlipIntegrationTests.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/RoutingSlipIntegrationTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Integration tests for the Routing Slip EIP through the DSL → Compiler → Engine pipeline, /// using real in-process direct:// endpoints. /// public class RoutingSlipIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task StartAndGetProducer(string fromUri) { await _context.Start(); var producer = _context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task RoutingSlip_StringSlip_PipesThroughEndpoints_InOrder() { var visited = new List(); _context.AddRoutes(r => { r.From("direct://slip-a").Process(_ => visited.Add("a")); r.From("direct://slip-b").Process(_ => visited.Add("b")); r.From("direct://slip-c").Process(_ => visited.Add("c")); r.From("direct://slip-in") .RoutingSlip("direct://slip-a,direct://slip-b,direct://slip-c"); }); var producer = await StartAndGetProducer("direct://slip-in"); await producer.Process(new Exchange(new Message("data"))); visited.Should().Equal("a", "b", "c"); } [Fact] public async Task RoutingSlip_ChainsBodyAlongSlip_OutToIn() { _context.AddRoutes(r => { r.From("direct://chain-a").Process(e => e.In.Body = e.In.Body?.ToString() + ":a"); r.From("direct://chain-b").Process(e => e.In.Body = e.In.Body?.ToString() + ":b"); r.From("direct://chain-in") .RoutingSlip("direct://chain-a,direct://chain-b"); }); var producer = await StartAndGetProducer("direct://chain-in"); var exchange = new Exchange(new Message("start")); await producer.Process(exchange); exchange.In.Body.Should().Be("start:a:b"); } [Fact] public async Task RoutingSlip_FromHeaderTemplate_ResolvesSlipPerMessage() { var visited = new List(); _context.AddRoutes(r => { r.From("direct://h-a").Process(_ => visited.Add("a")); r.From("direct://h-b").Process(_ => visited.Add("b")); // The slip is taken from a header, resolved per message. r.From("direct://h-in").RoutingSlip("${header.mySlip}"); }); var producer = await StartAndGetProducer("direct://h-in"); var exchange = new Exchange(new Message("data")); exchange.In.Headers["mySlip"] = "direct://h-a,direct://h-b"; await producer.Process(exchange); visited.Should().Equal("a", "b"); } [Fact] public async Task RoutingSlip_FactoryOverload_ComputesSlipFromExchange() { var visited = new List(); _context.AddRoutes(r => { r.From("direct://f-a").Process(_ => visited.Add("a")); r.From("direct://f-b").Process(_ => visited.Add("b")); r.From("direct://f-in").RoutingSlip(ex => ((string)ex.In.Body!).Split('|')); }); var producer = await StartAndGetProducer("direct://f-in"); await producer.Process(new Exchange(new Message("direct://f-a|direct://f-b"))); visited.Should().Equal("a", "b"); } [Fact] public async Task RoutingSlip_IgnoreInvalidEndpoints_SkipsUnknown() { var visited = new List(); _context.AddRoutes(r => { r.From("direct://i-a").Process(_ => visited.Add("a")); r.From("direct://i-c").Process(_ => visited.Add("c")); // "bogus://" has no registered component, so it fails endpoint resolution — exactly what // ignoreInvalidEndpoints skips (Camel semantics: invalid = unresolvable, not a runtime error). r.From("direct://i-in").RoutingSlip( "direct://i-a,bogus://missing,direct://i-c", uriDelimiter: ",", ignoreInvalidEndpoints: true); }); var producer = await StartAndGetProducer("direct://i-in"); await producer.Process(new Exchange(new Message("data"))); visited.Should().Equal("a", "c"); } } Path: redb-route/tests/redb.Route.Tests/Processors/RoutingSlipProcessorTests.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/RoutingSlipProcessorTests.cs ---- 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 RoutingSlipProcessorTests { private static (IRouteContext context, List visitOrder) SetupContext(params string[] uris) { var visitOrder = new List(); var context = Substitute.For(); foreach (var uri in uris) { var capturedUri = uri; var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(_ => visitOrder.Add(capturedUri)); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); context.GetEndpoint(uri).Returns(endpoint); } return (context, visitOrder); } [Fact] public async Task Process_VisitsEachEndpoint_InSlipOrder() { var (context, order) = SetupContext("direct://a", "direct://b", "direct://c"); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://a", "direct://b", "direct://c" }); await slip.Process(new Exchange(new Message("data"))); order.Should().Equal("direct://a", "direct://b", "direct://c"); } [Fact] public async Task Process_SlipComputedOnce_NotPerHop() { // The defining property of Routing Slip vs Dynamic Router: the slip factory runs ONCE. var (context, _) = SetupContext("direct://a", "direct://b", "direct://c"); var factoryCalls = 0; var slip = new RoutingSlipProcessor(context, _ => { factoryCalls++; return new[] { "direct://a", "direct://b", "direct://c" }; }); await slip.Process(new Exchange(new Message("data"))); factoryCalls.Should().Be(1); } [Fact] public async Task Process_PipelinesOutToIn_BetweenHops() { var seenByB = new List(); var context = Substitute.For(); // "a" produces an Out; the next hop must see it as In. var producerA = Substitute.For(); producerA.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().Out = new Message("from-a")); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); context.GetEndpoint("direct://a").Returns(endpointA); var producerB = Substitute.For(); producerB.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => seenByB.Add(ci.Arg().In.Body)); var endpointB = Substitute.For(); endpointB.CreateProducer().Returns(producerB); context.GetEndpoint("direct://b").Returns(endpointB); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://a", "direct://b" }); await slip.Process(new Exchange(new Message("original"))); seenByB.Should().ContainSingle().Which.Should().Be("from-a"); } [Fact] public async Task Process_FinalHopOut_LeftIntactForInOutCaller() { var context = Substitute.For(); var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().Out = new Message("reply")); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); context.GetEndpoint("direct://only").Returns(endpoint); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://only" }); var exchange = new Exchange(new Message("q")); await slip.Process(exchange); exchange.HasOut.Should().BeTrue(); exchange.Out!.Body.Should().Be("reply"); } [Fact] public async Task Process_SetsSlipEndpointProperty() { var (context, _) = SetupContext("direct://a", "direct://b"); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://a", "direct://b" }); var exchange = new Exchange(new Message("data")); await slip.Process(exchange); // Property carries the last endpoint processed (Camel: CamelSlipEndpoint). exchange.Properties[RoutingSlipProcessor.SlipEndpointProperty].Should().Be("direct://b"); } [Fact] public async Task Process_IgnoreInvalidEndpoints_SkipsAndContinues() { var (context, order) = SetupContext("direct://a", "direct://c"); context.GetEndpoint("direct://bad").Returns(_ => throw new InvalidOperationException("no such endpoint")); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://a", "direct://bad", "direct://c" }, ignoreInvalidEndpoints: true); await slip.Process(new Exchange(new Message("data"))); order.Should().Equal("direct://a", "direct://c"); } [Fact] public async Task Process_InvalidEndpoint_ThrowsWhenNotIgnored() { var context = Substitute.For(); context.GetEndpoint("direct://bad").Returns(_ => throw new InvalidOperationException("no such endpoint")); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://bad" }); var act = () => slip.Process(new Exchange()); await act.Should().ThrowAsync(); } [Fact] public async Task Process_StoppedExchange_BreaksSlip() { var (context, order) = SetupContext("direct://b"); var producerA = Substitute.For(); producerA.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().Stop()); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); context.GetEndpoint("direct://a").Returns(endpointA); var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://a", "direct://b" }); await slip.Process(new Exchange()); order.Should().BeEmpty(); // "b" not reached after "a" stopped the exchange } [Fact] public async Task Process_EmptySlip_DoesNothing() { var context = Substitute.For(); var slip = new RoutingSlipProcessor(context, _ => Array.Empty()); await slip.Process(new Exchange()); context.DidNotReceive().GetEndpoint(Arg.Any()); } [Fact] public async Task Process_CachesProducerPerUri() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("direct://x").Returns(endpoint); // Same URI twice in one slip. var slip = new RoutingSlipProcessor(context, _ => new[] { "direct://x", "direct://x" }); await slip.Process(new Exchange()); endpoint.Received(1).CreateProducer(); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new RoutingSlipProcessor(null!, _ => Array.Empty()); act.Should().Throw().WithParameterName("context"); } [Fact] public void Constructor_NullSlipFactory_Throws() { var act = () => new RoutingSlipProcessor(Substitute.For(), null!); act.Should().Throw().WithParameterName("slipFactory"); } } Path: redb-route/tests/redb.Route.Tests/Processors/SagaIntegrationTests.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/SagaIntegrationTests.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Integration tests for Saga using full route compilation and pipeline execution. /// [Trait("Category", "Integration")] public class SagaIntegrationTests { private readonly RouteContext _context = new(); private static IExchange CreateExchange(object? body = null) => Exchange.Create(new Message(body), null); // ══════════════════════════════════════════════════════════════ // Callback style — compiled pipeline: all steps succeed // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_AllSucceed_RunsAllSteps() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(e => log.Add("A"), e => log.Add("A-comp")) .Step(e => log.Add("B"), e => log.Add("B-comp")) .Step(e => log.Add("C"))); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange(); await pipeline.Process(exchange); log.Should().Equal("A", "B", "C"); } // ══════════════════════════════════════════════════════════════ // Callback style — compiled pipeline: failure triggers compensation // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_Failure_CompensatesInReverse() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(e => log.Add("A"), e => log.Add("A-comp")) .Step(e => log.Add("B"), e => log.Add("B-comp")) .Step(e => throw new InvalidOperationException("boom"), e => log.Add("C-comp"))); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange(); var act = () => pipeline.Process(exchange); await act.Should().ThrowAsync(); log.Should().Equal("A", "B", "B-comp", "A-comp"); } // ══════════════════════════════════════════════════════════════ // Callback style — with completion callback // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_WithCompletion_InvokedOnSuccess() { var completed = false; var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(e => { }) .OnCompletion(e => completed = true)); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange()); completed.Should().BeTrue(); } // ══════════════════════════════════════════════════════════════ // Fluent chain — compiled pipeline: all steps succeed // ══════════════════════════════════════════════════════════════ [Fact] public async Task FluentChain_AllSucceed_RunsAllSteps() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga() .SagaStep(e => log.Add("X"), e => log.Add("X-comp")) .SagaStep(e => log.Add("Y")) .EndSaga(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange()); log.Should().Equal("X", "Y"); } // ══════════════════════════════════════════════════════════════ // Fluent chain — failure triggers compensation // ══════════════════════════════════════════════════════════════ [Fact] public async Task FluentChain_Failure_CompensatesInReverse() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga() .SagaStep(e => log.Add("A"), e => log.Add("A-comp")) .SagaStep(e => throw new InvalidOperationException("fail"), e => log.Add("B-comp")) .EndSaga(); var pipeline = def.CreateProcessor(_context); var act = () => pipeline.Process(CreateExchange()); await act.Should().ThrowAsync(); log.Should().Equal("A", "A-comp"); } // ══════════════════════════════════════════════════════════════ // Fluent chain with End() — closes scope // ══════════════════════════════════════════════════════════════ [Fact] public async Task FluentChain_End_ClosesScope() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga() .SagaStep(e => log.Add("done")) .End(); // Steps after saga def.Process(e => log.Add("after-saga")); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange()); log.Should().Equal("done", "after-saga"); } // ══════════════════════════════════════════════════════════════ // Saga + downstream steps: saga failure does not run downstream // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_SagaFailure_DownstreamNotExecuted() { var downstreamRan = false; var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(e => throw new InvalidOperationException("fail"))); def.Process(e => downstreamRan = true); var pipeline = def.CreateProcessor(_context); var act = () => pipeline.Process(CreateExchange()); await act.Should().ThrowAsync(); downstreamRan.Should().BeFalse(); } // ══════════════════════════════════════════════════════════════ // Async steps — compiled pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_AsyncSteps_AllSucceed() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(async (e, ct) => { await Task.Yield(); log.Add("async-A"); }, async (e, ct) => { await Task.Yield(); log.Add("async-A-comp"); }) .Step(async (e, ct) => { await Task.Yield(); log.Add("async-B"); })); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange()); log.Should().Equal("async-A", "async-B"); } // ══════════════════════════════════════════════════════════════ // Exchange body preserved across saga steps // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_StepsModifyExchangeBody() { var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(e => e.In.Body = "first") .Step(e => e.In.Body = $"{e.In.Body}+second")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("init"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("first+second"); } // ══════════════════════════════════════════════════════════════ // Compensation restores exchange state // ══════════════════════════════════════════════════════════════ [Fact] public async Task Callback_CompensationRestoresBody() { var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga(saga => saga .Step(e => e.In.Body = "modified", e => e.In.Body = "restored") .Step(e => throw new InvalidOperationException("fail"))); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("original"); var act = () => pipeline.Process(exchange); await act.Should().ThrowAsync(); exchange.In.Body.Should().Be("restored"); } // ══════════════════════════════════════════════════════════════ // Fluent chain — async with completion // ══════════════════════════════════════════════════════════════ [Fact] public async Task FluentChain_AsyncWithCompletion() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Saga() .SagaStep( async (e, ct) => { await Task.Yield(); log.Add("step"); }, async (e, ct) => { await Task.Yield(); log.Add("comp"); }) .OnSagaCompletion(async (e, ct) => { await Task.Yield(); log.Add("completed"); }) .EndSaga(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange()); log.Should().Equal("step", "completed"); } // ══════════════════════════════════════════════════════════════ // Saga preceded and followed by other steps // ══════════════════════════════════════════════════════════════ [Fact] public async Task Pipeline_SagaBetweenOtherSteps() { var log = new List(); var def = new RouteDefinition(); def.From("direct://saga-test"); def.Process(e => log.Add("before")); def.Saga(saga => saga .Step(e => log.Add("saga-step"))); def.Process(e => log.Add("after")); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange()); log.Should().Equal("before", "saga-step", "after"); } } Path: redb-route/tests/redb.Route.Tests/Processors/SagaTests.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/SagaTests.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Unit tests for Saga processor, DSL, definition, and step creation. /// public class SagaTests { private static IExchange CreateExchange(object? body = null) => Exchange.Create(new Message(body), null); // ══════════════════════════════════════════════════════════════ // SagaDefinition validation // ══════════════════════════════════════════════════════════════ [Fact] public void Definition_NoSteps_CreateProcessorThrows() { var def = new SagaDefinition(); var act = () => def.CreateProcessor(new RouteContext()); act.Should().Throw(); } [Fact] public void Definition_NullSyncAction_Throws() { var def = new SagaDefinition(); var act = () => def.Step((Action)null!); act.Should().Throw(); } [Fact] public void Definition_NullAsyncAction_Throws() { var def = new SagaDefinition(); var act = () => def.Step((Func)null!); act.Should().Throw(); } [Fact] public void Definition_NullSyncCompensate_Throws() { var def = new SagaDefinition(); var act = () => def.Step(e => { }, (Action)null!); act.Should().Throw(); } [Fact] public void Definition_NullAsyncCompensate_Throws() { var def = new SagaDefinition(); Func action = (e, ct) => Task.CompletedTask; var act = () => def.Step(action, (Func)null!); act.Should().Throw(); } [Fact] public void Definition_NullSyncCompletion_Throws() { var def = new SagaDefinition(); var act = () => def.OnCompletion((Action)null!); act.Should().Throw(); } [Fact] public void Definition_NullAsyncCompletion_Throws() { var def = new SagaDefinition(); var act = () => def.OnCompletion((Func)null!); act.Should().Throw(); } [Fact] public void Definition_SingleStep_RecordsEntry() { var def = new SagaDefinition(); def.Step(e => { }); def.Entries.Should().HaveCount(1); def.CompletionCallback.Should().BeNull(); } [Fact] public void Definition_MultipleSteps_RecordsInOrder() { var def = new SagaDefinition(); def.Step(e => { }, e => { }); def.Step(e => { }); def.Step((e, ct) => Task.CompletedTask, (e, ct) => Task.CompletedTask); def.Entries.Should().HaveCount(3); def.Entries[0].Compensate.Should().NotBeNull(); def.Entries[1].Compensate.Should().BeNull(); def.Entries[2].Compensate.Should().NotBeNull(); } [Fact] public void Definition_WithCompletion_AttachesCallback() { var def = new SagaDefinition(); def.Step(e => { }); def.OnCompletion(e => { }); def.CompletionCallback.Should().NotBeNull(); } // ══════════════════════════════════════════════════════════════ // SagaProcessor — all steps succeed // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_AllStepsSucceed_ExecutesInOrder() { var log = new List(); var steps = new[] { new SagaStepEntry((e, ct) => { log.Add("A"); return Task.CompletedTask; }, (e, ct) => { log.Add("A-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => { log.Add("B"); return Task.CompletedTask; }, (e, ct) => { log.Add("B-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => { log.Add("C"); return Task.CompletedTask; }, null), }; var processor = new SagaProcessor(steps); var exchange = CreateExchange(); await processor.Process(exchange); log.Should().Equal("A", "B", "C"); } [Fact] public async Task Processor_AllSucceed_CompletionCallbackInvoked() { var completed = false; var steps = new[] { new SagaStepEntry((e, ct) => Task.CompletedTask, null), }; var processor = new SagaProcessor(steps, (e, ct) => { completed = true; return Task.CompletedTask; }); var exchange = CreateExchange(); await processor.Process(exchange); completed.Should().BeTrue(); } // ══════════════════════════════════════════════════════════════ // SagaProcessor — failure triggers compensation // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_SecondStepFails_CompensatesFirstOnly() { var log = new List(); var steps = new[] { new SagaStepEntry((e, ct) => { log.Add("A"); return Task.CompletedTask; }, (e, ct) => { log.Add("A-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => throw new InvalidOperationException("boom"), (e, ct) => { log.Add("B-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => { log.Add("C"); return Task.CompletedTask; }, (e, ct) => { log.Add("C-comp"); return Task.CompletedTask; }), }; var processor = new SagaProcessor(steps); var exchange = CreateExchange(); var act = () => processor.Process(exchange); await act.Should().ThrowAsync().WithMessage("boom"); // Only A executed, B failed (not counted as completed), C never ran // Compensation: only A-comp runs (B wasn't completed) log.Should().Equal("A", "A-comp"); } [Fact] public async Task Processor_ThirdStepFails_CompensatesSecondThenFirst() { var log = new List(); var steps = new[] { new SagaStepEntry((e, ct) => { log.Add("A"); return Task.CompletedTask; }, (e, ct) => { log.Add("A-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => { log.Add("B"); return Task.CompletedTask; }, (e, ct) => { log.Add("B-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => throw new InvalidOperationException("fail"), (e, ct) => { log.Add("C-comp"); return Task.CompletedTask; }), }; var processor = new SagaProcessor(steps); var act = () => processor.Process(CreateExchange()); await act.Should().ThrowAsync(); // A, B executed; C failed. Compensation runs for B then A (reverse). log.Should().Equal("A", "B", "B-comp", "A-comp"); } [Fact] public async Task Processor_Failure_CompletionCallbackNotInvoked() { var completed = false; var steps = new[] { new SagaStepEntry((e, ct) => throw new InvalidOperationException("fail"), null), }; var processor = new SagaProcessor(steps, (e, ct) => { completed = true; return Task.CompletedTask; }); var act = () => processor.Process(CreateExchange()); await act.Should().ThrowAsync(); completed.Should().BeFalse(); } // ══════════════════════════════════════════════════════════════ // SagaProcessor — forward-only steps (no compensation) // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_ForwardOnlyStep_SkippedDuringCompensation() { var log = new List(); var steps = new[] { new SagaStepEntry((e, ct) => { log.Add("A"); return Task.CompletedTask; }, null), new SagaStepEntry((e, ct) => { log.Add("B"); return Task.CompletedTask; }, (e, ct) => { log.Add("B-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => throw new InvalidOperationException("fail"), (e, ct) => { log.Add("C-comp"); return Task.CompletedTask; }), }; var processor = new SagaProcessor(steps); var act = () => processor.Process(CreateExchange()); await act.Should().ThrowAsync(); // A has no compensate → skipped; B has compensate → runs log.Should().Equal("A", "B", "B-comp"); } // ══════════════════════════════════════════════════════════════ // SagaProcessor — compensation failure is swallowed // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_CompensationFails_ContinuesRemainingCompensations() { var log = new List(); var steps = new[] { new SagaStepEntry((e, ct) => { log.Add("A"); return Task.CompletedTask; }, (e, ct) => { log.Add("A-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => { log.Add("B"); return Task.CompletedTask; }, (e, ct) => throw new InvalidOperationException("comp-fail")), new SagaStepEntry((e, ct) => throw new InvalidOperationException("step-fail"), (e, ct) => { log.Add("C-comp"); return Task.CompletedTask; }), }; var logger = Substitute.For(); var processor = new SagaProcessor(steps, logger: logger); var act = () => processor.Process(CreateExchange()); await act.Should().ThrowAsync().WithMessage("step-fail"); // B-comp throws but A-comp still runs log.Should().Equal("A", "B", "A-comp"); } // ══════════════════════════════════════════════════════════════ // SagaProcessor — exchange body modification // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_StepsCanModifyExchangeBody() { var steps = new[] { new SagaStepEntry((e, ct) => { e.In.Body = "step1"; return Task.CompletedTask; }, null), new SagaStepEntry((e, ct) => { e.In.Body = $"{e.In.Body}+step2"; return Task.CompletedTask; }, null), }; var processor = new SagaProcessor(steps); var exchange = CreateExchange("init"); await processor.Process(exchange); exchange.In.Body.Should().Be("step1+step2"); } [Fact] public async Task Processor_CompensationCanModifyExchange() { var steps = new[] { new SagaStepEntry((e, ct) => { e.In.Body = "step1"; return Task.CompletedTask; }, (e, ct) => { e.In.Body = "rolled-back"; return Task.CompletedTask; }), new SagaStepEntry((e, ct) => throw new InvalidOperationException("fail"), null), }; var processor = new SagaProcessor(steps); var exchange = CreateExchange("init"); var act = () => processor.Process(exchange); await act.Should().ThrowAsync(); exchange.In.Body.Should().Be("rolled-back"); } // ══════════════════════════════════════════════════════════════ // Callback-style DSL recording // ══════════════════════════════════════════════════════════════ [Fact] public void Dsl_CallbackStyle_RecordsSagaStep() { var def = new RouteDefinition(); def.Saga(saga => saga .Step(e => { }, e => { }) .Step(e => { }) .OnCompletion(e => { })); var sagaDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sagaDef.Entries.Should().HaveCount(2); sagaDef.CompletionCallback.Should().NotBeNull(); } [Fact] public void Dsl_CallbackStyle_NullConfigureThrows() { var def = new RouteDefinition(); var act = () => def.Saga((Action)null!); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // Fluent chain DSL recording // ══════════════════════════════════════════════════════════════ [Fact] public void Dsl_FluentChain_RecordsSagaStep() { var def = new RouteDefinition(); def.Saga() .SagaStep(e => { }, e => { }) .SagaStep(e => { }) .OnSagaCompletion(e => { }) .EndSaga(); var sagaDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sagaDef.Entries.Should().HaveCount(2); sagaDef.CompletionCallback.Should().NotBeNull(); } [Fact] public void Dsl_FluentChain_End_ClosesScope() { var def = new RouteDefinition(); def.Saga() .SagaStep(e => { }, e => { }) .End(); def.Outputs.Should().ContainSingle().Which.Should().BeOfType(); } [Fact] public void Dsl_FluentChain_AsyncSteps() { var def = new RouteDefinition(); def.Saga() .SagaStep( (e, ct) => Task.CompletedTask, (e, ct) => Task.CompletedTask) .SagaStep((e, ct) => Task.CompletedTask) .EndSaga(); var sagaDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sagaDef.Entries.Should().HaveCount(2); } [Fact] public void Dsl_FluentChain_SagaStepOutsideScope_Throws() { var def = new RouteDefinition(); def.From("direct://test"); var act = () => def.SagaStep(e => { }); act.Should().Throw(); } [Fact] public void Dsl_FluentChain_EndSagaOutsideScope_Throws() { var def = new RouteDefinition(); def.From("direct://test"); var act = () => def.EndSaga(); act.Should().Throw(); } [Fact] public void Dsl_FluentChain_OnSagaCompletionOutsideScope_Throws() { var def = new RouteDefinition(); def.From("direct://test"); var act = () => def.OnSagaCompletion(e => { }); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // First step failure — no compensations to run // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_FirstStepFails_NoCompensation() { var log = new List(); var steps = new[] { new SagaStepEntry((e, ct) => throw new InvalidOperationException("first-fail"), (e, ct) => { log.Add("A-comp"); return Task.CompletedTask; }), new SagaStepEntry((e, ct) => { log.Add("B"); return Task.CompletedTask; }, (e, ct) => { log.Add("B-comp"); return Task.CompletedTask; }), }; var processor = new SagaProcessor(steps); var act = () => processor.Process(CreateExchange()); await act.Should().ThrowAsync().WithMessage("first-fail"); // First step fails → 0 completed → no compensations log.Should().BeEmpty(); } // ══════════════════════════════════════════════════════════════ // Single step saga — success and failure // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_SingleStepSuccess() { var executed = false; var steps = new[] { new SagaStepEntry((e, ct) => { executed = true; return Task.CompletedTask; }, null), }; var processor = new SagaProcessor(steps); await processor.Process(CreateExchange()); executed.Should().BeTrue(); } [Fact] public async Task Processor_NoCompletionCallback_DoesNotThrow() { var steps = new[] { new SagaStepEntry((e, ct) => Task.CompletedTask, null), }; var processor = new SagaProcessor(steps, onCompletion: null); var exchange = CreateExchange(); await processor.Process(exchange); // No exception = success } } Path: redb-route/tests/redb.Route.Tests/Processors/SamplingIntegrationTests.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/SamplingIntegrationTests.cs ---- using System; using System.Threading.Tasks; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Integration tests for Sampling using full route compilation and pipeline execution. /// [Trait("Category", "Integration")] public class SamplingIntegrationTests { private readonly RouteContext _context = new(); private static IExchange CreateExchange(object? body = null) => Exchange.Create(new Message(body), null); // ══════════════════════════════════════════════════════════════ // Count-based: compiled pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_CompiledPipeline_SamplesEveryNth() { var def = new RouteDefinition(); def.From("direct://sample"); def.Sample(3); def.Transform(e => $"sampled:{e.In.Body}"); var pipeline = def.CreateProcessor(_context); // Message 1 (passes) — gets transformed var e1 = CreateExchange("A"); await pipeline.Process(e1); e1.In.Body.Should().Be("sampled:A"); // Message 2 (dropped) — body unchanged var e2 = CreateExchange("B"); await pipeline.Process(e2); e2.In.Body.Should().Be("B"); // Message 3 (dropped) — body unchanged var e3 = CreateExchange("C"); await pipeline.Process(e3); e3.In.Body.Should().Be("C"); // Message 4 (passes) — gets transformed var e4 = CreateExchange("D"); await pipeline.Process(e4); e4.In.Body.Should().Be("sampled:D"); } // ══════════════════════════════════════════════════════════════ // Count-based: frequency=1 passes all // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_FrequencyOne_AllPass() { var def = new RouteDefinition(); def.From("direct://sample"); def.Sample(1); def.SetHeader("Sampled", "true"); var pipeline = def.CreateProcessor(_context); for (int i = 0; i < 5; i++) { var exchange = CreateExchange(i); await pipeline.Process(exchange); exchange.In.Headers.Should().ContainKey("Sampled", $"message {i} should pass with frequency=1"); } } // ══════════════════════════════════════════════════════════════ // Time-based: compiled pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task TimeBased_CompiledPipeline_FirstPasses_RestDropped() { var def = new RouteDefinition(); def.From("direct://sample-time"); def.Sample(TimeSpan.FromMinutes(10)); // Very long period def.Transform(e => $"sampled:{e.In.Body}"); var pipeline = def.CreateProcessor(_context); // First message passes var e1 = CreateExchange("first"); await pipeline.Process(e1); e1.In.Body.Should().Be("sampled:first"); // Immediate follow-ups are dropped for (int i = 0; i < 3; i++) { var exchange = CreateExchange($"drop-{i}"); await pipeline.Process(exchange); exchange.In.Body.Should().Be($"drop-{i}", "transform should not apply to dropped messages"); } } // ══════════════════════════════════════════════════════════════ // Count-based: chaining with subsequent steps // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_ChainsWithFilter() { var def = new RouteDefinition(); def.From("direct://sample"); def.Sample(2); // Every 2nd = 1, 3, 5, ... def.Transform(e => $"ok:{e.In.Body}"); var pipeline = def.CreateProcessor(_context); var results = new string?[4]; for (int i = 0; i < 4; i++) { var exchange = CreateExchange(i); await pipeline.Process(exchange); results[i] = exchange.In.Body?.ToString(); } // 1st passes (transformed), 2nd dropped, 3rd passes (transformed), 4th dropped results.Should().Equal("ok:0", "1", "ok:2", "3"); } // ══════════════════════════════════════════════════════════════ // Properties preserved // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_PreservesProperties() { var def = new RouteDefinition(); def.From("direct://sample"); def.Sample(1); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("data"); exchange.Properties["traceId"] = "abc-123"; await pipeline.Process(exchange); exchange.Properties["traceId"].Should().Be("abc-123"); } // ══════════════════════════════════════════════════════════════ // Headers preserved on dropped messages // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_DroppedMessage_HeadersPreserved() { var def = new RouteDefinition(); def.From("direct://sample"); def.Sample(100); // Only first passes def.SetHeader("Applied", "yes"); var pipeline = def.CreateProcessor(_context); // First passes — header set var e1 = CreateExchange("first"); await pipeline.Process(e1); e1.In.Headers.Should().ContainKey("Applied"); // Second dropped — header NOT set var e2 = CreateExchange("second"); e2.In.Headers["Original"] = "keep"; await pipeline.Process(e2); e2.In.Headers.Should().NotContainKey("Applied"); e2.In.Headers["Original"].Should().Be("keep"); } } Path: redb-route/tests/redb.Route.Tests/Processors/SamplingTests.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/SamplingTests.cs ---- using System; using System.Linq; using System.Threading.Tasks; using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Unit tests for Sampling processor, DSL, and step creation. /// public class SamplingTests { private static IExchange CreateExchange(object? body = null) => Exchange.Create(new Message(body), null); // ══════════════════════════════════════════════════════════════ // Constructor validation // ══════════════════════════════════════════════════════════════ [Fact] public void CountBased_ZeroFrequency_Throws() { var act = () => new SamplingProcessor(0); act.Should().Throw(); } [Fact] public void CountBased_NegativeFrequency_Throws() { var act = () => new SamplingProcessor(-5); act.Should().Throw(); } [Fact] public void TimeBased_ZeroPeriod_Throws() { var act = () => new SamplingProcessor(TimeSpan.Zero); act.Should().Throw(); } [Fact] public void TimeBased_NegativePeriod_Throws() { var act = () => new SamplingProcessor(TimeSpan.FromSeconds(-1)); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // Count-based: frequency=1 (passes all) // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_FrequencyOne_PassesAll() { var processor = new SamplingProcessor(1); for (int i = 0; i < 10; i++) { var exchange = CreateExchange($"msg-{i}"); await processor.Process(exchange); exchange.IsStopped.Should().BeFalse($"message {i} should pass with frequency=1"); } } // ══════════════════════════════════════════════════════════════ // Count-based: frequency=3 (every 3rd) // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_FrequencyThree_PassesEveryThird() { var processor = new SamplingProcessor(3); var results = new bool[9]; for (int i = 0; i < 9; i++) { var exchange = CreateExchange(i); await processor.Process(exchange); results[i] = !exchange.IsStopped; } // Messages 1,4,7 (0-indexed: 0,3,6) should pass results.Should().Equal(true, false, false, true, false, false, true, false, false); } // ══════════════════════════════════════════════════════════════ // Count-based: first message always passes // ══════════════════════════════════════════════════════════════ [Fact] public async Task CountBased_FirstMessageAlwaysPasses() { var processor = new SamplingProcessor(100); var exchange = CreateExchange("first"); await processor.Process(exchange); exchange.IsStopped.Should().BeFalse(); } // ══════════════════════════════════════════════════════════════ // Time-based: first message always passes // ══════════════════════════════════════════════════════════════ [Fact] public async Task TimeBased_FirstMessageAlwaysPasses() { var processor = new SamplingProcessor(TimeSpan.FromHours(1)); var exchange = CreateExchange("first"); await processor.Process(exchange); exchange.IsStopped.Should().BeFalse(); } // ══════════════════════════════════════════════════════════════ // Time-based: rapid messages are dropped // ══════════════════════════════════════════════════════════════ [Fact] public async Task TimeBased_RapidMessages_DroppedAfterFirst() { var processor = new SamplingProcessor(TimeSpan.FromMinutes(10)); var first = CreateExchange("first"); await processor.Process(first); first.IsStopped.Should().BeFalse("first message passes"); // Immediately send more — they should all be dropped for (int i = 0; i < 5; i++) { var exchange = CreateExchange($"rapid-{i}"); await processor.Process(exchange); exchange.IsStopped.Should().BeTrue($"rapid message {i} should be dropped"); } } // ══════════════════════════════════════════════════════════════ // DSL — step recording // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_SampleCount_AddsSampleCountStep() { var def = new RouteDefinition(); def.Sample(5); var node = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; node.MessageFrequency.Should().Be(5); } [Fact] public void DSL_SamplePeriod_AddsSamplePeriodStep() { var def = new RouteDefinition(); def.Sample(TimeSpan.FromSeconds(30)); var node = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; node.Period.Should().Be(TimeSpan.FromSeconds(30)); } [Fact] public void DSL_SampleCount_ZeroFrequency_Throws() { var def = new RouteDefinition(); var act = () => def.Sample(0); act.Should().Throw(); } [Fact] public void DSL_SamplePeriod_ZeroPeriod_Throws() { var def = new RouteDefinition(); var act = () => def.Sample(TimeSpan.Zero); act.Should().Throw(); } [Fact] public void DSL_SampleCount_Chaining() { var def = new RouteDefinition(); var result = def.Sample(10); result.Should().BeSameAs(def); } [Fact] public void DSL_SamplePeriod_Chaining() { var def = new RouteDefinition(); var result = def.Sample(TimeSpan.FromSeconds(1)); result.Should().BeSameAs(def); } } Path: redb-route/tests/redb.Route.Tests/Processors/ScatterGatherIntegrationTests.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/ScatterGatherIntegrationTests.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Integration tests for using real DirectComponent endpoints. /// Tests the full pipeline: scatter (clone + send to each recipient) → gather (aggregate responses). /// [Trait("Category", "Integration")] public class ScatterGatherIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly List _consumers = []; /// /// Registers a consumer on a direct endpoint that processes exchanges via a delegate. /// private async Task RegisterConsumer(string name, Func handler) { var endpoint = (DirectEndpoint)_context.GetEndpoint($"direct:{name}"); var processor = new DelegateProcessor(handler); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); _consumers.Add(consumer); } /// /// Registers a simple consumer that sets a header on the exchange. /// private Task RegisterPriceConsumer(string name, decimal price) { return RegisterConsumer(name, (exchange, _) => { exchange.In.Headers["price"] = price; exchange.In.Headers["supplier"] = name; return Task.CompletedTask; }); } // ══════════════════════════════════════════════════════════════ // Parallel — all succeed // ══════════════════════════════════════════════════════════════ [Fact] public async Task Parallel_AllSucceed_AggregatesBestPrice() { await RegisterPriceConsumer("sg-p-a", 100m); await RegisterPriceConsumer("sg-p-b", 50m); await RegisterPriceConsumer("sg-p-c", 75m); var sg = new ScatterGatherProcessor( _context, ["direct:sg-p-a", "direct:sg-p-b", "direct:sg-p-c"], (best, current) => { var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }); var exchange = new Exchange(new Message("get-quote")); await sg.Process(exchange); // Best price is 50 from supplier sg-p-b exchange.In.Headers["price"].Should().Be(50m); exchange.In.Headers["supplier"].Should().Be("sg-p-b"); } // ══════════════════════════════════════════════════════════════ // Sequential — all succeed // ══════════════════════════════════════════════════════════════ [Fact] public async Task Sequential_AllSucceed_AggregatesResults() { await RegisterPriceConsumer("sg-s-a", 200m); await RegisterPriceConsumer("sg-s-b", 150m); await RegisterPriceConsumer("sg-s-c", 300m); var sg = new ScatterGatherProcessor( _context, ["direct:sg-s-a", "direct:sg-s-b", "direct:sg-s-c"], (best, current) => { var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }, parallelProcessing: false); var exchange = new Exchange(new Message("get-quote")); await sg.Process(exchange); exchange.In.Headers["price"].Should().Be(150m); exchange.In.Headers["supplier"].Should().Be("sg-s-b"); } // ══════════════════════════════════════════════════════════════ // Dynamic recipients // ══════════════════════════════════════════════════════════════ [Fact] public async Task DynamicRecipients_ResolvedAtRuntime() { await RegisterPriceConsumer("sg-d-a", 10m); await RegisterPriceConsumer("sg-d-b", 20m); var sg = new ScatterGatherProcessor( _context, recipientFactory: e => e.In.GetHeader("targets")!.Split(','), aggregationStrategy: (best, current) => { var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }); var exchange = new Exchange(new Message("rfq")); exchange.In.Headers["targets"] = "direct:sg-d-a,direct:sg-d-b"; await sg.Process(exchange); exchange.In.Headers["price"].Should().Be(10m); } // ══════════════════════════════════════════════════════════════ // Timeout + stopOnException → TimeoutException // ══════════════════════════════════════════════════════════════ [Fact] public async Task Timeout_StopOnException_ThrowsTimeoutException() { await RegisterPriceConsumer("sg-t1-a", 100m); await RegisterConsumer("sg-t1-slow", async (_, ct) => { await Task.Delay(TimeSpan.FromSeconds(5), ct); }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-t1-a", "direct:sg-t1-slow"], (a, b) => a, stopOnException: true, timeout: TimeSpan.FromMilliseconds(200)); var exchange = new Exchange(new Message("test")); var act = () => sg.Process(exchange); await act.Should().ThrowAsync(); } // ══════════════════════════════════════════════════════════════ // Timeout + best-effort → partial results // ══════════════════════════════════════════════════════════════ [Fact] public async Task Timeout_BestEffort_AggregatesPartialResults() { await RegisterPriceConsumer("sg-t2-fast", 42m); await RegisterConsumer("sg-t2-slow", async (exchange, ct) => { await Task.Delay(TimeSpan.FromSeconds(5), ct); exchange.In.Headers["price"] = 999m; }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-t2-fast", "direct:sg-t2-slow"], (best, current) => { var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }, stopOnException: false, timeout: TimeSpan.FromMilliseconds(300)); var exchange = new Exchange(new Message("test")); await sg.Process(exchange); // Only the fast endpoint's response is aggregated exchange.In.Headers["price"].Should().Be(42m); } // ══════════════════════════════════════════════════════════════ // One endpoint fails — stopOnException=true → exception // ══════════════════════════════════════════════════════════════ [Fact] public async Task OneEndpointFails_StopOnException_Throws() { await RegisterPriceConsumer("sg-f1-a", 100m); await RegisterConsumer("sg-f1-err", (_, _) => throw new InvalidOperationException("Supplier unavailable")); var sg = new ScatterGatherProcessor( _context, ["direct:sg-f1-a", "direct:sg-f1-err"], (a, b) => a, stopOnException: true); var exchange = new Exchange(new Message("test")); var act = () => sg.Process(exchange); await act.Should().ThrowAsync() .WithMessage("Supplier unavailable"); } // ══════════════════════════════════════════════════════════════ // One endpoint fails — best-effort → aggregates rest // ══════════════════════════════════════════════════════════════ [Fact] public async Task OneEndpointFails_BestEffort_AggregatesRest() { await RegisterPriceConsumer("sg-f2-a", 100m); await RegisterPriceConsumer("sg-f2-b", 80m); await RegisterConsumer("sg-f2-err", (_, _) => throw new InvalidOperationException("Supplier down")); // Aggregation: pick cheapest from non-failed responses var sg = new ScatterGatherProcessor( _context, ["direct:sg-f2-a", "direct:sg-f2-err", "direct:sg-f2-b"], (best, current) => { // Skip failed exchanges if (current.Exception != null) return best; if (best.Exception != null) return current; var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }, stopOnException: false); var exchange = new Exchange(new Message("test")); await sg.Process(exchange); // Best non-failed price is 80 from sg-f2-b exchange.In.Headers["price"].Should().Be(80m); } // ══════════════════════════════════════════════════════════════ // Sequential — timeout + best-effort → partial results // ══════════════════════════════════════════════════════════════ [Fact] public async Task Sequential_Timeout_BestEffort_AggregatesPartial() { await RegisterPriceConsumer("sg-st-fast1", 10m); await RegisterPriceConsumer("sg-st-fast2", 20m); await RegisterConsumer("sg-st-slow", async (exchange, ct) => { await Task.Delay(TimeSpan.FromSeconds(5), ct); exchange.In.Headers["price"] = 5m; }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-st-fast1", "direct:sg-st-fast2", "direct:sg-st-slow"], (best, current) => { var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }, parallelProcessing: false, stopOnException: false, timeout: TimeSpan.FromMilliseconds(300)); var exchange = new Exchange(new Message("test")); await sg.Process(exchange); // fast1 (10) and fast2 (20) succeeded before timeout; slow didn't finish exchange.In.Headers["price"].Should().Be(10m); } // ══════════════════════════════════════════════════════════════ // Concurrent scatter-gathers — no data loss // ══════════════════════════════════════════════════════════════ [Fact] public async Task Concurrent_NoInterference() { // Each scatter-gather invocation accumulates bodies into a list await RegisterConsumer("sg-c-a", (exchange, _) => { exchange.In.Body = $"A:{exchange.In.Body}"; return Task.CompletedTask; }); await RegisterConsumer("sg-c-b", (exchange, _) => { exchange.In.Body = $"B:{exchange.In.Body}"; return Task.CompletedTask; }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-c-a", "direct:sg-c-b"], (acc, cur) => { acc.In.Body = $"{acc.In.Body}|{cur.In.Body}"; return acc; }); var results = new ConcurrentBag(); var tasks = Enumerable.Range(0, 50).Select(async i => { var exchange = new Exchange(new Message($"msg-{i}")); await sg.Process(exchange); results.Add((string)exchange.In.Body!); }); await Task.WhenAll(tasks); results.Should().HaveCount(50); // Each result should contain both A: and B: prefixes foreach (var result in results) { result.Should().Contain("A:"); result.Should().Contain("B:"); } } // ══════════════════════════════════════════════════════════════ // Preserves exchange properties after aggregation // ══════════════════════════════════════════════════════════════ [Fact] public async Task PreservesPropertiesAfterAggregation() { await RegisterConsumer("sg-prop-a", (exchange, _) => { exchange.Properties["source"] = "A"; exchange.In.Headers["result"] = "from-A"; return Task.CompletedTask; }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-prop-a"], (acc, cur) => cur); var exchange = new Exchange(new Message("test")); await sg.Process(exchange); exchange.In.Headers["result"].Should().Be("from-A"); exchange.Properties["source"].Should().Be("A"); } // ══════════════════════════════════════════════════════════════ // MaxDOP=1 forces sequential-like execution // ══════════════════════════════════════════════════════════════ [Fact] public async Task MaxDop1_LimitsParallelism() { var concurrency = 0; var maxConcurrency = 0; var lockObj = new object(); await RegisterConsumer("sg-dop-a", async (exchange, ct) => { var c = Interlocked.Increment(ref concurrency); lock (lockObj) { if (c > maxConcurrency) maxConcurrency = c; } await Task.Delay(50, ct); Interlocked.Decrement(ref concurrency); exchange.In.Headers["done"] = true; }); await RegisterConsumer("sg-dop-b", async (exchange, ct) => { var c = Interlocked.Increment(ref concurrency); lock (lockObj) { if (c > maxConcurrency) maxConcurrency = c; } await Task.Delay(50, ct); Interlocked.Decrement(ref concurrency); exchange.In.Headers["done"] = true; }); await RegisterConsumer("sg-dop-c", async (exchange, ct) => { var c = Interlocked.Increment(ref concurrency); lock (lockObj) { if (c > maxConcurrency) maxConcurrency = c; } await Task.Delay(50, ct); Interlocked.Decrement(ref concurrency); exchange.In.Headers["done"] = true; }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-dop-a", "direct:sg-dop-b", "direct:sg-dop-c"], (acc, cur) => cur, parallelProcessing: true, maxDegreeOfParallelism: 1); var exchange = new Exchange(new Message("test")); await sg.Process(exchange); // With DOP=1, max concurrency should be 1 maxConcurrency.Should().Be(1); } // ══════════════════════════════════════════════════════════════ // Builder DSL — full integration // ══════════════════════════════════════════════════════════════ [Fact] public async Task Builder_FullConfig_IntegrationTest() { await RegisterPriceConsumer("sg-bld-a", 500m); await RegisterPriceConsumer("sg-bld-b", 250m); var def = new RouteDefinition(); def.From("direct://sg-builder-test"); def.ScatterGather(sg => sg .Recipients("direct:sg-bld-a", "direct:sg-bld-b") .AggregationStrategy((best, current) => { var bestPrice = (decimal)best.In.Headers["price"]; var currentPrice = (decimal)current.In.Headers["price"]; return currentPrice < bestPrice ? current : best; }) .ParallelProcessing()); // Verify definition was created correctly var sgDef = def.Outputs.OfType().Single(); sgDef.StaticRecipients.Should().HaveCount(2); sgDef.ParallelProcessing.Should().BeTrue(); } // ══════════════════════════════════════════════════════════════ // Dynamic recipients — empty list throws // ══════════════════════════════════════════════════════════════ [Fact] public async Task DynamicRecipients_EmptyList_Throws() { var sg = new ScatterGatherProcessor( _context, recipientFactory: _ => [], aggregationStrategy: (a, b) => a); var exchange = new Exchange(new Message("test")); var act = () => sg.Process(exchange); await act.Should().ThrowAsync() .WithMessage("*at least one recipient*"); } // ══════════════════════════════════════════════════════════════ // Caller cancellation — always propagated // ══════════════════════════════════════════════════════════════ [Fact] public async Task CallerCancellation_PropagatesImmediately() { await RegisterConsumer("sg-cancel", async (_, ct) => { await Task.Delay(TimeSpan.FromSeconds(5), ct); }); var sg = new ScatterGatherProcessor( _context, ["direct:sg-cancel"], (a, b) => a); using var cts = new CancellationTokenSource(); cts.Cancel(); var exchange = new Exchange(new Message("test")); var act = () => sg.Process(exchange, cts.Token); await act.Should().ThrowAsync(); } // ══════════════════════════════════════════════════════════════ // Dispose // ══════════════════════════════════════════════════════════════ public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { foreach (var consumer in _consumers) if (consumer is IAsyncDisposable d) await d.DisposeAsync(); await _context.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests/Processors/ScatterGatherTests.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/ScatterGatherTests.cs ---- using System; using System.Collections.Generic; using System.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Unit tests for Scatter-Gather DSL, step creation, and builder validation. /// Full pipeline tests are in . /// public class ScatterGatherTests { // ══════════════════════════════════════════════════════════════ // DSL — simple overload // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_Simple_AddsStep() { var def = new RouteDefinition(); Func agg = (a, b) => a; def.ScatterGather(agg, "http://a:8080", "http://b:8080"); var sgDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sgDef.StaticRecipients.Should().BeEquivalentTo(["http://a:8080", "http://b:8080"]); sgDef.DynamicRecipients.Should().BeNull(); sgDef.AggregationStrategy.Should().BeSameAs(agg); sgDef.ParallelProcessing.Should().BeTrue(); sgDef.Timeout.Should().Be(TimeSpan.Zero); } [Fact] public void DSL_Simple_NullStrategy_Throws() { var def = new RouteDefinition(); var act = () => def.ScatterGather(null!, "http://a:8080"); act.Should().Throw(); } [Fact] public void DSL_Simple_NoRecipients_Throws() { var def = new RouteDefinition(); var act = () => def.ScatterGather((a, b) => a); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // DSL — builder overload // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_Builder_FullConfig_AddsStep() { var def = new RouteDefinition(); Func agg = (a, b) => a; def.ScatterGather(sg => sg .Recipients("http://a:8080", "http://b:8080", "http://c:8080") .AggregationStrategy(agg) .Timeout(TimeSpan.FromSeconds(5)) .ParallelProcessing(false) .MaxDegreeOfParallelism(2) .StopOnException()); var sgDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sgDef.StaticRecipients.Should().HaveCount(3); sgDef.DynamicRecipients.Should().BeNull(); sgDef.AggregationStrategy.Should().BeSameAs(agg); sgDef.ParallelProcessing.Should().BeFalse(); sgDef.MaxDegreeOfParallelism.Should().Be(2); sgDef.StopOnException.Should().BeTrue(); sgDef.Timeout.Should().Be(TimeSpan.FromSeconds(5)); } [Fact] public void DSL_Builder_DynamicRecipients_AddsStep() { var def = new RouteDefinition(); Func> factory = e => e.In.GetHeader("targets")!.Split(','); def.ScatterGather(sg => sg .Recipients(factory) .AggregationStrategy((a, b) => a)); var sgDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sgDef.StaticRecipients.Should().BeNull(); sgDef.DynamicRecipients.Should().BeSameAs(factory); } [Fact] public void DSL_Builder_NoStrategy_Throws() { var def = new RouteDefinition(); var act = () => def.ScatterGather(sg => sg .Recipients("http://a:8080")); act.Should().Throw() .WithMessage("*AggregationStrategy*"); } [Fact] public void DSL_Builder_NoRecipients_Throws() { var def = new RouteDefinition(); var act = () => def.ScatterGather(sg => sg .AggregationStrategy((a, b) => a)); act.Should().Throw() .WithMessage("*Recipients*"); } [Fact] public void DSL_Builder_NegativeTimeout_Throws() { var act = () => { var def = new RouteDefinition(); def.ScatterGather(sg => sg .Recipients("http://a:8080") .AggregationStrategy((a, b) => a) .Timeout(TimeSpan.FromSeconds(-1))); }; act.Should().Throw(); } [Fact] public void DSL_Builder_NegativeMaxDop_Throws() { var act = () => { var def = new RouteDefinition(); def.ScatterGather(sg => sg .Recipients("http://a:8080") .AggregationStrategy((a, b) => a) .MaxDegreeOfParallelism(-1)); }; act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // Builder — Recipients override // ══════════════════════════════════════════════════════════════ [Fact] public void Builder_StaticRecipients_OverridesDynamic() { var def = new RouteDefinition(); def.ScatterGather(sg => sg .Recipients(e => ["http://dynamic:8080"]) .Recipients("http://static:8080") // override: static wins .AggregationStrategy((a, b) => a)); var sgDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sgDef.StaticRecipients.Should().NotBeNull(); sgDef.DynamicRecipients.Should().BeNull(); } [Fact] public void Builder_DynamicRecipients_OverridesStatic() { var def = new RouteDefinition(); Func> factory = e => ["http://dynamic:8080"]; def.ScatterGather(sg => sg .Recipients("http://static:8080") .Recipients(factory) // override: dynamic wins .AggregationStrategy((a, b) => a)); var sgDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; sgDef.StaticRecipients.Should().BeNull(); sgDef.DynamicRecipients.Should().BeSameAs(factory); } // ══════════════════════════════════════════════════════════════ // Constructor validation // ══════════════════════════════════════════════════════════════ [Fact] public void Constructor_NullContext_Throws() { var act = () => new ScatterGatherProcessor( null!, ["http://a:8080"], (a, b) => a); act.Should().Throw(); } [Fact] public void Constructor_NullRecipients_Throws() { var context = new RouteContext(); var act = () => new ScatterGatherProcessor( context, (IReadOnlyList)null!, (a, b) => a); act.Should().Throw(); } [Fact] public void Constructor_EmptyRecipients_Throws() { var context = new RouteContext(); var act = () => new ScatterGatherProcessor( context, Array.Empty(), (a, b) => a); act.Should().Throw(); } [Fact] public void Constructor_NullAggregation_Throws() { var context = new RouteContext(); var act = () => new ScatterGatherProcessor( context, ["http://a:8080"], null!); act.Should().Throw(); } [Fact] public void Constructor_NullDynamicFactory_Throws() { var context = new RouteContext(); var act = () => new ScatterGatherProcessor( context, (Func>)null!, (a, b) => a); act.Should().Throw(); } [Fact] public void Constructor_NegativeTimeout_Throws() { var context = new RouteContext(); var act = () => new ScatterGatherProcessor( context, ["http://a:8080"], (a, b) => a, timeout: TimeSpan.FromSeconds(-1)); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════════════════════ private static IExchange CreateExchange(object? body = null) => new Exchange(new Message { Body = body ?? "test" }); } Path: redb-route/tests/redb.Route.Tests/Processors/ScopeLifecycleTests.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/ScopeLifecycleTests.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Tests verifying DI scope lifecycle across processors: /// - Sequential children share parent scope (same connection, same TX) /// - Parallel children get own scopes, released per-part /// - ReleaseScopes is idempotent and thread-safe /// public class ScopeLifecycleTests { // ── Shared helpers ── private class ScopeTracker : IDisposable { public bool IsDisposed { get; private set; } public Guid Id { get; } = Guid.NewGuid(); public void Dispose() => IsDisposed = true; } private static (IServiceScopeFactory factory, ServiceProvider root) CreateTrackedFactory() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); return (services.GetRequiredService(), services); } // ══════════════════════════════════════════════════════════════ // Exchange.CreateLinkedChild / CloneLinked — scope sharing // ══════════════════════════════════════════════════════════════ [Fact] public void CreateLinkedChild_SharesParentServiceProvider() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var parent = Exchange.Create(new Message("parent"), factory); var child = parent.CreateLinkedChild(new Message("child")); child.ServiceProvider.Should().BeSameAs(parent.ServiceProvider); } [Fact] public void CloneLinked_SharesParentServiceProvider() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var parent = Exchange.Create(new Message("parent"), factory); var clone = parent.CloneLinked(); clone.ServiceProvider.Should().BeSameAs(parent.ServiceProvider); } [Fact] public async Task LinkedChild_Dispose_DoesNotDisposeParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var parent = Exchange.Create(new Message("parent"), factory); var tracker = parent.ServiceProvider!.GetRequiredService(); var child = parent.CreateLinkedChild(new Message("child")); await child.DisposeAsync(); // Parent scope must still work tracker.IsDisposed.Should().BeFalse(); parent.ServiceProvider.Should().NotBeNull(); } [Fact] public async Task LinkedClone_Dispose_DoesNotDisposeParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var parent = Exchange.Create(new Message("parent"), factory); var tracker = parent.ServiceProvider!.GetRequiredService(); var clone = parent.CloneLinked(); await clone.DisposeAsync(); tracker.IsDisposed.Should().BeFalse(); parent.ServiceProvider.Should().NotBeNull(); } // ══════════════════════════════════════════════════════════════ // ReleaseScopes — idempotency and thread safety // ══════════════════════════════════════════════════════════════ [Fact] public async Task ReleaseScopes_CalledTwice_IsIdempotent() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var exchange = Exchange.Create(new Message(), factory); await exchange.ReleaseScopes(); await exchange.ReleaseScopes(); // should not throw exchange.ServiceProvider.Should().BeNull(); } [Fact] public async Task ReleaseScopes_ConcurrentCalls_NoDoubleDispose() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var exchange = Exchange.Create(new Message(), factory); // Hammer from multiple threads var tasks = Enumerable.Range(0, 50) .Select(_ => Task.Run(async () => await exchange.ReleaseScopes())) .ToArray(); await Task.WhenAll(tasks); exchange.ServiceProvider.Should().BeNull(); } [Fact] public async Task ReleaseScopes_KeepsBodyAlive() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var exchange = Exchange.Create(new Message("important-data"), factory); exchange.In.Headers["key"] = "value"; await exchange.ReleaseScopes(); exchange.In.Body.Should().Be("important-data"); exchange.In.Headers["key"].Should().Be("value"); } // ══════════════════════════════════════════════════════════════ // Splitter — sequential shares scope, parallel releases early // ══════════════════════════════════════════════════════════════ [Fact] public async Task Splitter_Sequential_ChildrenShareParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedProviders = new List(); var splitter = new SplitterProcessor( ex => ((int[])ex.In.Body!).Cast(), new DelegateProcessor(ex => { observedProviders.Add(ex.ServiceProvider!); }), parallelProcessing: false); var exchange = Exchange.Create(new Message(new[] { 1, 2, 3 }), factory); var parentProvider = exchange.ServiceProvider; await splitter.Process(exchange); observedProviders.Should().HaveCount(3); // All sequential children share parent's ServiceProvider observedProviders.Should().AllSatisfy(sp => sp.Should().BeSameAs(parentProvider)); } [Fact] public async Task Splitter_Parallel_EachChildGetsOwnScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedIds = new ConcurrentBag(); var splitter = new SplitterProcessor( ex => ((int[])ex.In.Body!).Cast(), new DelegateProcessor(ex => { var tracker = ex.ServiceProvider!.GetRequiredService(); observedIds.Add(tracker.Id); }), parallelProcessing: true, maxDegreeOfParallelism: 4); var exchange = Exchange.Create(new Message(new[] { 1, 2, 3, 4 }), factory); var parentTracker = exchange.ServiceProvider!.GetRequiredService(); await splitter.Process(exchange); // Each parallel child should have its own scope (distinct tracker IDs) observedIds.Distinct().Should().HaveCount(4); // None should be the parent's observedIds.Should().NotContain(parentTracker.Id); } [Fact] public async Task Splitter_Parallel_ScopesReleasedAfterProcessing() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var trackers = new ConcurrentBag(); var splitter = new SplitterProcessor( ex => ((int[])ex.In.Body!).Cast(), new DelegateProcessor(ex => { var tracker = ex.ServiceProvider!.GetRequiredService(); trackers.Add(tracker); }), parallelProcessing: true); var exchange = Exchange.Create(new Message(new[] { 1, 2, 3 }), factory); await splitter.Process(exchange); // All child scopes should be disposed after processing trackers.Should().HaveCount(3); trackers.Should().AllSatisfy(t => t.IsDisposed.Should().BeTrue()); } // ══════════════════════════════════════════════════════════════ // Multicast — sequential shares scope, parallel releases early // ══════════════════════════════════════════════════════════════ [Fact] public async Task Multicast_Sequential_ChildrenShareParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedProviders = new List(); var mc = new MulticastProcessor(parallelProcessing: false); mc.AddTarget(new DelegateProcessor(ex => observedProviders.Add(ex.ServiceProvider!))); mc.AddTarget(new DelegateProcessor(ex => observedProviders.Add(ex.ServiceProvider!))); mc.AddTarget(new DelegateProcessor(ex => observedProviders.Add(ex.ServiceProvider!))); var exchange = Exchange.Create(new Message("test"), factory); var parentProvider = exchange.ServiceProvider; await mc.Process(exchange); observedProviders.Should().HaveCount(3); observedProviders.Should().AllSatisfy(sp => sp.Should().BeSameAs(parentProvider)); } [Fact] public async Task Multicast_Parallel_EachChildGetsOwnScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedIds = new ConcurrentBag(); var mc = new MulticastProcessor(parallelProcessing: true, maxDegreeOfParallelism: 3); for (var i = 0; i < 3; i++) { mc.AddTarget(new DelegateProcessor(ex => { var tracker = ex.ServiceProvider!.GetRequiredService(); observedIds.Add(tracker.Id); })); } var exchange = Exchange.Create(new Message("test"), factory); var parentTracker = exchange.ServiceProvider!.GetRequiredService(); await mc.Process(exchange); observedIds.Distinct().Should().HaveCount(3); observedIds.Should().NotContain(parentTracker.Id); } [Fact] public async Task Multicast_Parallel_ScopesReleasedAfterProcessing() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var trackers = new ConcurrentBag(); var mc = new MulticastProcessor(parallelProcessing: true, maxDegreeOfParallelism: 3); for (var i = 0; i < 3; i++) { mc.AddTarget(new DelegateProcessor(ex => { trackers.Add(ex.ServiceProvider!.GetRequiredService()); })); } var exchange = Exchange.Create(new Message("test"), factory); await mc.Process(exchange); trackers.Should().HaveCount(3); trackers.Should().AllSatisfy(t => t.IsDisposed.Should().BeTrue()); } // ══════════════════════════════════════════════════════════════ // Loop — copy mode shares scope by default, iterations disposed // ══════════════════════════════════════════════════════════════ [Fact] public async Task Loop_CopyMode_ShareScope_IterationsShareParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedProviders = new List(); var loop = new LoopProcessor( new DelegateProcessor(ex => observedProviders.Add(ex.ServiceProvider!)), 3, copy: true, shareScope: true); var exchange = Exchange.Create(new Message("data"), factory); var parentProvider = exchange.ServiceProvider; await loop.Process(exchange); observedProviders.Should().HaveCount(3); // snapshot is CloneLinked, iteration targets are CloneLinked from snapshot // all should resolve from the same scope as parent observedProviders.Should().AllSatisfy(sp => sp.Should().BeSameAs(parentProvider)); } [Fact] public async Task Loop_CopyMode_NoShareScope_IterationsGetOwnScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedIds = new List(); var loop = new LoopProcessor( new DelegateProcessor(ex => { observedIds.Add(ex.ServiceProvider!.GetRequiredService().Id); }), 3, copy: true, shareScope: false); var exchange = Exchange.Create(new Message("data"), factory); var parentId = exchange.ServiceProvider!.GetRequiredService().Id; await loop.Process(exchange); observedIds.Should().HaveCount(3); // All iterations share snapshot scope (not parent, not each other — snapshot has own scope) // With shareScope=false, snapshot = Clone() (own scope), iterations = CloneLinked from snapshot // So all 3 see snapshot's tracker, but NOT parent's observedIds.Should().AllSatisfy(id => id.Should().NotBe(parentId)); } // ══════════════════════════════════════════════════════════════ // StreamingSplitter — sequential, shares parent scope // ══════════════════════════════════════════════════════════════ [Fact] public async Task StreamingSplitter_ChildrenShareParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var observedProviders = new List(); var splitter = new StreamingSplitterProcessor( ex => ToAsyncEnumerable((int[])ex.In.Body!), new DelegateProcessor(ex => observedProviders.Add(ex.ServiceProvider!))); var exchange = Exchange.Create(new Message(new[] { 1, 2, 3 }), factory); var parentProvider = exchange.ServiceProvider; await splitter.Process(exchange); observedProviders.Should().HaveCount(3); observedProviders.Should().AllSatisfy(sp => sp.Should().BeSameAs(parentProvider)); } private static async IAsyncEnumerable ToAsyncEnumerable(int[] items) { foreach (var item in items) { await Task.Yield(); yield return item; } } // ══════════════════════════════════════════════════════════════ // Enricher — shares parent scope // ══════════════════════════════════════════════════════════════ [Fact] public async Task Enrich_Clone_SharesParentScope() { var (factory, root) = CreateTrackedFactory(); using var _ = root; var parent = Exchange.Create(new Message("data"), factory); var parentProvider = parent.ServiceProvider; // CloneLinked is what EnrichProcessor now uses internally var clone = parent.CloneLinked(); clone.ServiceProvider.Should().BeSameAs(parentProvider); await clone.DisposeAsync(); parent.ServiceProvider.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests/Processors/SplitterProcessorTests.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/SplitterProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class SplitterProcessorTests { /// Splits array body into individual exchanges. [Fact] public async Task Process_SplitsArray_IntoIndividualExchanges() { var parts = new List(); var target = new DelegateProcessor(ex => parts.Add(ex.In.Body)); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var data = new object[] { "a", "b", "c" }; await splitter.Process(new Exchange(new Message(data))); parts.Should().Equal("a", "b", "c"); } /// Split metadata are exchange properties of each part, as Camel's, never message headers. [Fact] public async Task Process_SetsSplitMetadataProperties() { var indices = new List(); var sizes = new List(); var completes = new List(); var correlationIds = new List(); var metadataHeaders = new List(); var target = new DelegateProcessor(ex => { indices.Add(ex.GetProperty(ExchangePropertyKeys.SplitIndex)); sizes.Add(ex.GetProperty(ExchangePropertyKeys.SplitSize)); completes.Add(ex.GetProperty(ExchangePropertyKeys.SplitComplete)); correlationIds.Add(ex.GetProperty(ExchangePropertyKeys.CorrelationId)); metadataHeaders.AddRange(ex.In.Headers.Keys.Where(k => k.StartsWith("Camel", StringComparison.Ordinal))); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var parent = new Exchange(new Message(new object[] { 1, 2, 3 })); await splitter.Process(parent); indices.Should().Equal(0, 1, 2); sizes.Should().OnlyContain(s => s == 3); completes.Should().Equal(false, false, true); correlationIds.Should().OnlyContain(id => id == parent.ExchangeId); metadataHeaders.Should().BeEmpty(); } /// /// An element becomes the part's message, as Camel's Message element: its own body, headers /// and content type, none of the parent's headers; the part gets a copy, so the parent's collection is untouched. /// [Fact] public async Task Process_MessageElement_BecomesThePartMessage_AsACopy() { var first = new Message("one") { ContentType = "text/plain" }; first.Headers["key"] = "k1"; var second = new Message(new byte[] { 2 }); second.Headers["key"] = "k2"; var seen = new List<(object? Body, string? Key, string? ContentType, bool HasParentHeader)>(); var target = new DelegateProcessor(ex => { seen.Add((ex.In.Body, ex.In.GetHeader("key"), ex.In.ContentType, ex.In.Headers.ContainsKey("parent"))); ex.In.Body = "changed by the part"; ex.In.Headers["key"] = "changed"; }); var splitter = new SplitterProcessor(ex => (IEnumerable)ex.In.Body!, target); var batch = new List { first, second }; var parentMessage = new Message(batch); parentMessage.Headers["parent"] = "p"; await splitter.Process(new Exchange(parentMessage)); seen.Should().HaveCount(2); seen[0].Should().Be(((object?)"one", "k1", "text/plain", false)); seen[1].Body.Should().BeEquivalentTo(new byte[] { 2 }); seen[1].Key.Should().Be("k2"); seen[1].HasParentHeader.Should().BeFalse(); first.Body.Should().Be("one"); first.Headers["key"].Should().Be("k1"); second.Headers["key"].Should().Be("k2"); } /// Original headers are copied to split exchanges. [Fact] public async Task Process_CopiesHeaders() { string? capturedHeader = null; var target = new DelegateProcessor(ex => { capturedHeader = ex.In.GetHeader("source"); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var msg = new Message(new object[] { "x" }); msg.Headers["source"] = "test-source"; await splitter.Process(new Exchange(msg)); capturedHeader.Should().Be("test-source"); } /// Properties are copied to split exchanges. [Fact] public async Task Process_CopiesProperties() { object? capturedProp = null; var target = new DelegateProcessor(ex => { capturedProp = ex.Properties["routeId"]; }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var exchange = new Exchange(new Message(new object[] { "x" })); exchange.Properties["routeId"] = "route-1"; await splitter.Process(exchange); capturedProp.Should().Be("route-1"); } /// Exchange.Stop() breaks splitting early. [Fact] public async Task Process_ExchangeStopped_BreaksSplit() { var count = 0; var exchange = new Exchange(new Message(new object[] { 1, 2, 3, 4, 5 })); var target = new DelegateProcessor(_ => { count++; if (count >= 2) exchange.Stop(); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); await splitter.Process(exchange); count.Should().Be(2); } /// Empty split produces no exchanges. [Fact] public async Task Process_EmptySplit_NoProcessing() { var count = 0; var target = new DelegateProcessor(_ => count++); var splitter = new SplitterProcessor(_ => Enumerable.Empty(), target); await splitter.Process(new Exchange()); count.Should().Be(0); } // ── Parallel Error Handling ── /// Single parallel split failure: exchange.Exception is that single exception. [Fact] public async Task ProcessParallel_SingleFailure_SetsExchangeException() { var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((string)ex.In.Body! == "bad") throw new InvalidOperationException("split-fail"); return Task.CompletedTask; }), parallelProcessing: true, stopOnException: false); var exchange = new Exchange(new Message(new object[] { "good", "bad" })); await splitter.Process(exchange); exchange.Exception.Should().BeOfType(); } /// Multiple parallel split failures produce AggregateException. [Fact] public async Task ProcessParallel_MultipleFailures_SetsAggregateException() { var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => throw new InvalidOperationException($"fail-{ex.In.Body}")), parallelProcessing: true, stopOnException: false); var exchange = new Exchange(new Message(new object[] { "a", "b", "c" })); await splitter.Process(exchange); exchange.Exception.Should().BeOfType(); var agg = (AggregateException)exchange.Exception!; agg.InnerExceptions.Should().HaveCount(3); } /// stopOnException=true rethrows in parallel mode. [Fact] public async Task ProcessParallel_StopOnException_Rethrows() { var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((_, _) => throw new InvalidOperationException("stop")), parallelProcessing: true, stopOnException: true); var exchange = new Exchange(new Message(new object[] { "a" })); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync().WithMessage("stop"); } /// Sequential stopOnException stops processing remaining parts. [Fact] public async Task ProcessSequential_StopOnException_SkipsRemaining() { var processed = new List(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { var body = (string)ex.In.Body!; processed.Add(body); if (body == "b") throw new InvalidOperationException("seq-stop"); return Task.CompletedTask; }), parallelProcessing: false, stopOnException: true); var exchange = new Exchange(new Message(new object[] { "a", "b", "c" })); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync().WithMessage("seq-stop"); processed.Should().Equal("a", "b"); // "c" was skipped } // ── Aggregation Strategy: Camel-compatible null-old contract ── /// T6.1 Sequential aggregation: first part goes through strategy with oldExchange=null. [Fact] public async Task Sequential_AggregationStrategy_FirstPartGoesThroughStrategy_WithNullOld() { var calls = new List<(IExchange? Old, object? NewBody)>(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => { }), parallelProcessing: false, aggregationStrategy: (old, cur) => { calls.Add((old, cur.In.Body)); if (old == null) return cur; return old; }); await splitter.Process(new Exchange(new Message(new object[] { 10, 20, 30 }))); calls.Should().HaveCount(3); calls[0].Old.Should().BeNull(); calls[0].NewBody.Should().Be(10); calls[1].Old.Should().NotBeNull(); calls[2].Old.Should().NotBeNull(); } /// T6.2 Parallel aggregation: first part goes through strategy with oldExchange=null. [Fact] public async Task Parallel_AggregationStrategy_FirstPartGoesThroughStrategy_WithNullOld() { var calls = new List<(IExchange? Old, object? NewBody)>(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => { }), parallelProcessing: true, aggregationStrategy: (old, cur) => { calls.Add((old, cur.In.Body)); if (old == null) return cur; return old; }); await splitter.Process(new Exchange(new Message(new object[] { 10, 20, 30 }))); // Deterministic post-pass over split exchanges in input order. calls.Should().HaveCount(3); calls[0].Old.Should().BeNull(); calls[0].NewBody.Should().Be(10); calls[1].NewBody.Should().Be(20); calls[2].NewBody.Should().Be(30); } /// T6.3 Parallel + stopOnException: failure skips final aggregation (no partial result on exchange). [Fact] public async Task ProcessParallel_StopOnException_SkipsFinalAggregation() { var aggCalls = 0; var originalBody = new object[] { 1, 2, 3 }; var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((int)ex.In.Body! == 2) throw new InvalidOperationException("boom"); return Task.CompletedTask; }), parallelProcessing: true, aggregationStrategy: (old, cur) => { Interlocked.Increment(ref aggCalls); return cur; }, stopOnException: true); var exchange = new Exchange(new Message(originalBody)); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync(); aggCalls.Should().Be(0); // ApplyAggregation skipped entirely exchange.In.Body.Should().BeSameAs(originalBody); } /// T6.4 Sequential + stopOnException: failure leaves exchange body untouched (no partial aggregation visible). [Fact] public async Task ProcessSequential_StopOnException_DoesNotPublishPartialAggregation() { var originalBody = new object[] { 1, 2, 3 }; var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((int)ex.In.Body! == 2) throw new InvalidOperationException("boom"); return Task.CompletedTask; }), parallelProcessing: false, aggregationStrategy: (old, cur) => { if (old == null) return cur; return old; }, stopOnException: true); var exchange = new Exchange(new Message(originalBody)); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync(); exchange.In.Body.Should().BeSameAs(originalBody); // ApplyAggregation skipped } /// T6.5 parallelAggregate=true: aggregation runs in-task under lock; counter sees all parts. [Fact] public async Task ProcessParallel_WithParallelAggregate_AggregatesAllPartsThreadSafely() { var aggCalls = 0; var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => { }), parallelProcessing: true, maxDegreeOfParallelism: 4, aggregationStrategy: (old, cur) => { aggCalls++; // safe: under processor's lock when parallelAggregate=true return old ?? cur; }, stopOnException: false, parallelAggregate: true); var parts = Enumerable.Range(1, 20).Cast().ToArray(); await splitter.Process(new Exchange(new Message(parts))); aggCalls.Should().Be(20); } /// T6.6 aggregateOnException=true: failed split parts still feed into the strategy. [Fact] public async Task ProcessSequential_AggregateOnException_FeedsFailedPartsToStrategy() { var seenBodies = new List(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((int)ex.In.Body! == 1) throw new InvalidOperationException("boom"); return Task.CompletedTask; }), parallelProcessing: false, aggregationStrategy: (old, cur) => { seenBodies.Add(cur.In.Body); return old ?? cur; }, stopOnException: false, aggregateOnException: true); await splitter.Process(new Exchange(new Message(new object[] { 0, 1, 2 }))); seenBodies.Should().Equal(0, 1, 2); // failed part (1) included } } Path: redb-route/tests/redb.Route.Tests/Processors/StepIdentityTests.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/StepIdentityTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Validation; namespace redb.Route.Tests.Processors; /// /// Step identity and label in message history. Id("...") replaces the /// generated node id, Description("...") replaces the type-derived label; neither shifts /// the generated ids of neighbouring nodes, and a duplicate step id fails route validation. /// public class StepIdentityTests { private static async Task RunAsync(RouteContext context, string fromUri, IExchange exchange) { await context.Start(); var producer = context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } [Fact] public async Task StepId_BecomesNodeId_AndNeighbourCounterDoesNotShift() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://si-id").MessageHistory() .Process(_ => { }).Id("validate-input") .Process(_ => { })); var exchange = await RunAsync(context, "direct://si-id", new Exchange(new Message("x"))); var entries = MessageHistory.GetEntries(exchange); entries.Should().HaveCount(2); entries[0].NodeId.Should().Be("validate-input"); entries[0].Label.Should().Be("processAction", "Id() names the node, the label stays type-derived"); // The named node still consumes the counter, so its neighbour keeps the id it had without Id(). entries[1].NodeId.Should().Be("processAction2"); } [Fact] public async Task StepDescription_ReplacesLabel_NodeIdUnchanged() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://si-descr").MessageHistory() .Process(_ => { }).Description("Validate the order") .Process(_ => { })); var exchange = await RunAsync(context, "direct://si-descr", new Exchange(new Message("x"))); var entries = MessageHistory.GetEntries(exchange); entries.Should().HaveCount(2); entries[0].Label.Should().Be("Validate the order"); entries[0].NodeId.Should().Be("processAction1", "Description() must not touch node identity"); entries[1].NodeId.Should().Be("processAction2"); entries[1].Label.Should().Be("processAction"); } [Fact] public async Task IdAndDescription_Together_NameAndLabelTheSameNode() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://si-both").MessageHistory() .Process(_ => { }).Id("enrich-step").Description("Enrich with CRM data")); var exchange = await RunAsync(context, "direct://si-both", new Exchange(new Message("x"))); var entry = MessageHistory.GetEntries(exchange).Should().ContainSingle().Subject; entry.NodeId.Should().Be("enrich-step"); entry.Label.Should().Be("Enrich with CRM data"); } [Fact] public async Task DuplicateStepId_FailsRouteValidation_AtStart() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://si-dup") .Process(_ => { }).Id("dup-step") .Process(_ => { }).Id("DUP-STEP")); var act = () => context.Start(); (await act.Should().ThrowAsync()) .WithMessage("*Duplicate step id 'DUP-STEP'*"); } [Fact] public async Task Description_BeforeAnyStep_DescribesTheRouteItself() { IRouteDefinition? captured = null; await using var context = new RouteContext(); context.AddRoutes(r => captured = r.From("direct://si-route").Description("Order intake")); await context.Start(); // builder lambdas are deferred and run at Start() ((ProcessorDefinition)captured!).StepDescription.Should().Be("Order intake"); } } Path: redb-route/tests/redb.Route.Tests/Processors/StreamCachingProcessorTests.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/StreamCachingProcessorTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Processors; using AwesomeAssertions; namespace redb.Route.Tests.Processors; public class StreamCachingProcessorTests { [Fact] public async Task StreamBody_WrappedInStreamCache() { var data = "test data"u8.ToArray(); object? capturedBody = null; var next = new DelegateProcessor(ex => capturedBody = ex.In.Body); var processor = new StreamCachingProcessor(next, new StreamCacheOptions()); var exchange = new Exchange(new Message(new MemoryStream(data))); await processor.Process(exchange).ConfigureAwait(false); capturedBody.Should().BeOfType(); var cache = (StreamCache)capturedBody!; cache.CanSeek.Should().BeTrue(); cache.Length.Should().Be(data.Length); } [Fact] public async Task NonStreamBody_PassedThrough() { var next = new DelegateProcessor(_ => { }); var processor = new StreamCachingProcessor(next, new StreamCacheOptions()); var exchange = new Exchange(new Message("hello")); await processor.Process(exchange).ConfigureAwait(false); exchange.In.Body.Should().Be("hello"); } [Fact] public async Task AlreadyStreamCache_NotDoubleWrapped() { var original = new StreamCache(); await original.CacheFromSourceAsync(new MemoryStream("hello"u8.ToArray())).ConfigureAwait(false); object? capturedBody = null; var next = new DelegateProcessor(ex => capturedBody = ex.In.Body); var processor = new StreamCachingProcessor(next, new StreamCacheOptions()); var exchange = new Exchange(new Message(original)); await processor.Process(exchange).ConfigureAwait(false); capturedBody.Should().BeSameAs(original); } [Fact] public async Task CachedStream_CanBeReread() { var data = "rereadable content"u8.ToArray(); var results = new ConcurrentBag(); var next = new DelegateProcessor(async ex => { var stream = (Stream)ex.In.Body!; using var reader = new StreamReader(stream, leaveOpen: true); results.Add(await reader.ReadToEndAsync().ConfigureAwait(false)); stream.Position = 0; }); var processor = new StreamCachingProcessor(next, new StreamCacheOptions()); var exchange = new Exchange(new Message(new MemoryStream(data))); await processor.Process(exchange).ConfigureAwait(false); results.Should().ContainSingle().Which.Should().Be("rereadable content"); // Verify we can still re-read var stream = (Stream)exchange.In.Body!; stream.Position = 0; using var postReader = new StreamReader(stream, leaveOpen: true); var postText = await postReader.ReadToEndAsync().ConfigureAwait(false); postText.Should().Be("rereadable content"); } [Fact] public async Task NullBody_PassedThrough() { var next = new DelegateProcessor(_ => { }); var processor = new StreamCachingProcessor(next, new StreamCacheOptions()); var exchange = new Exchange(new Message()); await processor.Process(exchange).ConfigureAwait(false); exchange.In.Body.Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests/Processors/StreamingIntegrationTests.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/StreamingIntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Processors; /// /// Integration tests for the streaming/large-data pipeline: /// StreamCaching, StreamingSplitter (async), Tokenizers (Lines/Xml/Json) /// through the DSL → Compiler → Engine chain. /// public class StreamingIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ────────── StreamCaching ────────── [Fact] public async Task StreamCaching_InRoute_BodyRereadableAfterProcess() { var firstRead = string.Empty; var secondRead = string.Empty; _context.AddRoutes(r => { r.From("direct://cache-in") .StreamCaching() .Process(e => { var stream = (Stream)e.In.Body!; using var reader = new StreamReader(stream, leaveOpen: true); firstRead = reader.ReadToEnd(); stream.Position = 0; // rewind — only possible because cached }) .Process(e => { var stream = (Stream)e.In.Body!; using var reader = new StreamReader(stream, leaveOpen: true); secondRead = reader.ReadToEnd(); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://cache-in").CreateProducer(); await producer.Start(); var body = new MemoryStream(Encoding.UTF8.GetBytes("cached-payload")); await producer.Process(new Exchange(new Message(body))); firstRead.Should().Be("cached-payload"); secondRead.Should().Be("cached-payload"); } // ────────── Streaming Split (IAsyncEnumerable) ────────── [Fact] public async Task StreamingSplit_ConfigureStyle_ProcessesAllParts() { var parts = new ConcurrentBag(); _context.AddRoutes(r => { r.From("direct://stream-split") .Split( ex => ToAsyncEnumerable("a", "b", "c"), sub => sub.Process(e => parts.Add((string)e.In.Body!))); }); await _context.Start(); var producer = _context.GetEndpoint("direct://stream-split").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("source"))); parts.Should().HaveCount(3); parts.Should().Contain("a").And.Contain("b").And.Contain("c"); } [Fact] public async Task StreamingSplit_FluentStyle_ProcessesAllParts() { var parts = new ConcurrentBag(); _context.AddRoutes(r => { r.From("direct://stream-split-fluent") .Split(ex => ToAsyncEnumerable("x", "y")) .Process(e => parts.Add((string)e.In.Body!)) .EndSplit(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://stream-split-fluent").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("source"))); parts.Should().HaveCount(2); parts.Should().Contain("x").And.Contain("y"); } [Fact] public async Task StreamingSplit_StopOnException_StopsEarly() { var processedParts = new ConcurrentBag(); _context.AddRoutes(r => { r.From("direct://stream-split-stop") .Split( ex => ToAsyncEnumerable("a", "b", "c", "d"), sub => sub.Process(e => { var body = (string)e.In.Body!; processedParts.Add(body); if (body == "b") throw new InvalidOperationException("fail on b"); }), stopOnException: true); }); await _context.Start(); var producer = _context.GetEndpoint("direct://stream-split-stop").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("source")); // The exception propagates through the DirectProducer pipeline var act = async () => await producer.Process(exchange); await act.Should().ThrowAsync() .WithMessage("fail on b"); processedParts.Should().HaveCountLessThanOrEqualTo(2); } // ────────── StreamCaching + Streaming Split pipeline ────────── [Fact] public async Task StreamCaching_ThenStreamingSplit_WorksTogether() { var parts = new ConcurrentBag(); _context.AddRoutes(r => { r.From("direct://cache-then-split") .StreamCaching() .ConvertBody() .Split( ex => ToAsyncEnumerable( ((string)ex.In.Body!).Split('\n')), sub => sub.Process(e => parts.Add((string)e.In.Body!))); }); await _context.Start(); var producer = _context.GetEndpoint("direct://cache-then-split").CreateProducer(); await producer.Start(); var body = new MemoryStream(Encoding.UTF8.GetBytes("line1\nline2\nline3")); await producer.Process(new Exchange(new Message(body))); parts.Should().HaveCount(3); parts.Should().Contain("line1").And.Contain("line2").And.Contain("line3"); } // ────────── ConvertBody + Stream ────────── [Fact] public async Task ConvertBody_StreamToString_InRoute() { var captured = string.Empty; _context.AddRoutes(r => { r.From("direct://convert-stream") .ConvertBody() .Process(e => captured = (string)e.In.Body!); }); await _context.Start(); var producer = _context.GetEndpoint("direct://convert-stream").CreateProducer(); await producer.Start(); var body = new MemoryStream(Encoding.UTF8.GetBytes("stream-data")); await producer.Process(new Exchange(new Message(body))); captured.Should().Be("stream-data"); } [Fact] public async Task ConvertBody_StreamToByteArray_InRoute() { byte[]? captured = null; _context.AddRoutes(r => { r.From("direct://convert-stream-bytes") .ConvertBody() .Process(e => captured = (byte[])e.In.Body!); }); await _context.Start(); var producer = _context.GetEndpoint("direct://convert-stream-bytes").CreateProducer(); await producer.Start(); var body = new MemoryStream(Encoding.UTF8.GetBytes("hello")); await producer.Process(new Exchange(new Message(body))); captured.Should().NotBeNull(); Encoding.UTF8.GetString(captured!).Should().Be("hello"); } // ────────── Exchange body dispose end-to-end ────────── [Fact] public async Task Exchange_DisposeAsync_DisposesStreamBody() { var stream = new MemoryStream(new byte[] { 1, 2, 3 }); var exchange = new Exchange(new Message(stream)); stream.CanRead.Should().BeTrue(); await exchange.DisposeAsync(); stream.CanRead.Should().BeFalse(); } // ── Helper ── private static async IAsyncEnumerable ToAsyncEnumerable(params string[] items) { foreach (var item in items) { await Task.Yield(); yield return item; } } } Path: redb-route/tests/redb.Route.Tests/Processors/StreamingSplitterProcessorTests.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/StreamingSplitterProcessorTests.cs ---- using System.Collections.Concurrent; using System.Runtime.CompilerServices; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using AwesomeAssertions; namespace redb.Route.Tests.Processors; public class StreamingSplitterProcessorTests { [Fact] public async Task Process_SplitsAsyncEnumerable_IntoIndividualExchanges() { var parts = new ConcurrentBag(); var target = new DelegateProcessor(ex => parts.Add(ex.In.Body)); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("a", "b", "c"), target); await splitter.Process(new Exchange(new Message("source"))).ConfigureAwait(false); parts.Should().HaveCount(3); parts.Should().Contain("a").And.Contain("b").And.Contain("c"); } [Fact] public async Task Process_EmptyEnumerable_ZeroExchanges() { var callCount = 0; var target = new DelegateProcessor(_ => Interlocked.Increment(ref callCount)); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable(), target); var exchange = new Exchange(new Message("source")); await splitter.Process(exchange).ConfigureAwait(false); callCount.Should().Be(0); exchange.Properties["CamelSplitSize"].Should().Be(0); } [Fact] public async Task Process_SetsSplitMetadataProperties_SizeOnTheLastPartOnly() { var seen = new List<(int Index, bool Complete, bool HasSize, int Size, bool HasHeader)>(); var target = new DelegateProcessor(ex => seen.Add(( ex.GetProperty(ExchangePropertyKeys.SplitIndex), ex.GetProperty(ExchangePropertyKeys.SplitComplete), ex.Properties.ContainsKey(ExchangePropertyKeys.SplitSize), ex.GetProperty(ExchangePropertyKeys.SplitSize), ex.In.Headers.Keys.Any(k => k.StartsWith("CamelSplit", StringComparison.Ordinal))))); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable(1, 2, 3), target); await splitter.Process(new Exchange(new Message("source"))).ConfigureAwait(false); seen.Should().Equal((0, false, false, 0, false), (1, false, false, 0, false), (2, true, true, 3, false)); } [Fact] public async Task Process_MessageElement_BecomesThePartMessage_WithoutParentHeaders() { var element = new Message("record"); element.Headers["key"] = "k1"; var seen = new List<(object? Body, string? Key, bool HasParentHeader)>(); var target = new DelegateProcessor(ex => { seen.Add((ex.In.Body, ex.In.GetHeader("key"), ex.In.Headers.ContainsKey("parent"))); ex.In.Headers["key"] = "changed"; }); var splitter = new StreamingSplitterProcessor(_ => ToAsyncEnumerable(element), target); var parent = new Message("source"); parent.Headers["parent"] = "p"; await splitter.Process(new Exchange(parent)).ConfigureAwait(false); seen.Should().Equal(((object?)"record", "k1", false)); element.Headers["key"].Should().Be("k1"); } [Fact] public async Task Process_SetsSplitSize() { var target = new DelegateProcessor(_ => { }); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("a", "b", "c"), target); var exchange = new Exchange(new Message("source")); await splitter.Process(exchange).ConfigureAwait(false); exchange.Properties["CamelSplitSize"].Should().Be(3); } [Fact] public async Task Process_CopiesOriginalHeaders() { var capturedHeaders = new ConcurrentBag(); var target = new DelegateProcessor(ex => capturedHeaders.Add((string)ex.In.Headers["OriginalKey"]!)); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("x"), target); var msg = new Message("source"); msg.Headers["OriginalKey"] = "OriginalValue"; await splitter.Process(new Exchange(msg)).ConfigureAwait(false); capturedHeaders.Should().ContainSingle().Which.Should().Be("OriginalValue"); } [Fact] public async Task StopOnException_True_StopsOnFirstError() { var processedCount = 0; var target = new DelegateProcessor(ex => { Interlocked.Increment(ref processedCount); if ((string)ex.In.Body! == "b") throw new InvalidOperationException("fail on b"); }); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("a", "b", "c"), target, stopOnException: true); var exchange = new Exchange(new Message("source")); var act = () => splitter.Process(exchange); await act.Should().ThrowAsync() .WithMessage("fail on b").ConfigureAwait(false); processedCount.Should().BeLessThanOrEqualTo(2); exchange.Exception.Should().BeOfType(); } [Fact] public async Task StopOnException_False_ContinuesToEnd() { var processedParts = new ConcurrentBag(); var target = new DelegateProcessor(ex => { var body = (string)ex.In.Body!; processedParts.Add(body); if (body == "b") throw new InvalidOperationException("fail on b"); }); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("a", "b", "c"), target, stopOnException: false); var exchange = new Exchange(new Message("source")); await splitter.Process(exchange).ConfigureAwait(false); processedParts.Should().HaveCount(3); processedParts.Should().Contain("a").And.Contain("b").And.Contain("c"); } [Fact] public async Task Cancellation_StopsProcessing() { using var cts = new CancellationTokenSource(); var processedCount = 0; var target = new DelegateProcessor(ex => { if (Interlocked.Increment(ref processedCount) == 2) cts.Cancel(); }); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("a", "b", "c", "d", "e"), target); var act = () => splitter.Process(new Exchange(new Message("source")), cts.Token); await act.Should().ThrowAsync().ConfigureAwait(false); } [Fact] public async Task IsStopped_BreaksSplitLoop() { var processedCount = 0; var exchange = new Exchange(new Message("source")); var target = new DelegateProcessor(ex => { Interlocked.Increment(ref processedCount); if ((string)ex.In.Body! == "b") exchange.Stop(); // stop the parent exchange }); var splitter = new StreamingSplitterProcessor( _ => ToAsyncEnumerable("a", "b", "c", "d", "e"), target); await splitter.Process(exchange).ConfigureAwait(false); // "a" processed, then "b" stops parent → loop breaks before "c" processedCount.Should().BeLessThanOrEqualTo(2); } private static async IAsyncEnumerable ToAsyncEnumerable( T[] items, [EnumeratorCancellation] CancellationToken ct = default) { foreach (var item in items) { ct.ThrowIfCancellationRequested(); await Task.Yield(); yield return item; } } private static IAsyncEnumerable ToAsyncEnumerable(params T[] items) => ToAsyncEnumerable(items, CancellationToken.None); } Path: redb-route/tests/redb.Route.Tests/Processors/ThreadsProcessorTests.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/ThreadsProcessorTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Tests for the Threads EIP (.Threads(N) / ) — Camel-style /// concurrency handoff. Covers: real concurrency up to the pool size, serial behaviour at N=1, /// async hand-off (a serial source keeps dispatching), error routing to OnException, graceful /// drain-on-stop (no in-flight lost), per-exchange clone isolation, and argument validation. /// public class ThreadsProcessorTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ── Concurrency ────────────────────────────────────────────────────────────── [Fact] public async Task Threads_SerialSource_ReachesPoolSizeConcurrency() { const int pool = 5, total = 20; var current = 0; var max = 0; var maxLock = new object(); var processed = 0; _context.AddRoutes(r => { r.From("direct://threads-conc") .Threads(pool) .Process(async (e, ct) => { var c = Interlocked.Increment(ref current); lock (maxLock) { if (c > max) max = c; } await Task.Delay(50, ct); Interlocked.Decrement(ref current); Interlocked.Increment(ref processed); }) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://threads-conc").CreateProducer(); await producer.Start(); // A serial source: each send is awaited before the next (mirrors a poll loop). for (var i = 0; i < total; i++) await producer.Process(new Exchange(new Message { Body = i })); await WaitForCondition(() => Volatile.Read(ref processed) >= total, TimeSpan.FromSeconds(15)); processed.Should().Be(total, "every exchange must be processed"); max.Should().Be(pool, "the pool runs exactly poolSize workers concurrently — never more, and it saturates"); } [Fact] public async Task Threads_PoolSizeOne_IsSerialAndOrdered() { const int total = 10; var current = 0; var max = 0; var maxLock = new object(); var received = new List(); _context.AddRoutes(r => { r.From("direct://threads-serial") .Threads(1) .Process(async (e, ct) => { var c = Interlocked.Increment(ref current); lock (maxLock) { if (c > max) max = c; } await Task.Delay(5, ct); lock (received) received.Add((int)e.In.Body!); Interlocked.Decrement(ref current); }) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://threads-serial").CreateProducer(); await producer.Start(); for (var i = 0; i < total; i++) await producer.Process(new Exchange(new Message { Body = i })); await WaitForCondition(() => received.Count >= total, TimeSpan.FromSeconds(10)); max.Should().Be(1, "poolSize 1 must never run two bodies at once"); received.Should().HaveCount(total); received.Should().BeInAscendingOrder("a single worker preserves order"); } [Fact] public async Task Threads_AsyncHandoff_ProducerReturnsBeforeBodyCompletes() { var bodyStarted = false; var bodyDone = false; var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _context.AddRoutes(r => { r.From("direct://threads-handoff") .Threads(1) .Process(async (e, ct) => { Volatile.Write(ref bodyStarted, true); await gate.Task; Volatile.Write(ref bodyDone, true); }) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://threads-handoff").CreateProducer(); await producer.Start(); // The send completes via the async hand-off even though the body is blocked on the gate. await producer.Process(new Exchange(new Message { Body = "x" })); await WaitForCondition(() => Volatile.Read(ref bodyStarted), TimeSpan.FromSeconds(5)); Volatile.Read(ref bodyDone).Should().BeFalse( "the producer returned after hand-off while the body is still running — that is the concurrency win"); gate.SetResult(); await WaitForCondition(() => Volatile.Read(ref bodyDone), TimeSpan.FromSeconds(5)); } // ── Error routing ──────────────────────────────────────────────────────────── [Fact] public async Task Threads_BodyException_RoutedToOnException_OthersSucceed() { const int total = 8; var handled = new ConcurrentBag(); var succeeded = new ConcurrentBag(); _context.AddRoutes(r => { // The builder's OnException is kept for this route's HandleException; the detached pool worker // routes to it through IRouteContext.HandleException. r.OnException() .Handled() .Process(e => handled.Add((int)e.In.Body!)); r.From("direct://threads-error") .Threads(3) .Process(async (e, ct) => { await Task.Delay(5, ct); var n = (int)e.In.Body!; if (n % 2 == 0) throw new InvalidOperationException($"boom-{n}"); succeeded.Add(n); }) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://threads-error").CreateProducer(); await producer.Start(); for (var i = 0; i < total; i++) await producer.Process(new Exchange(new Message { Body = i })); await WaitForCondition(() => handled.Count + succeeded.Count >= total, TimeSpan.FromSeconds(10)); handled.Should().BeEquivalentTo(new[] { 0, 2, 4, 6 }, "even items throw and must reach OnException, not be lost"); succeeded.Should().BeEquivalentTo(new[] { 1, 3, 5, 7 }, "odd items succeed"); } // ── Drain on stop ──────────────────────────────────────────────────────────── [Fact] public async Task Threads_DrainOnStop_AllInflightProcessed_NoneLost() { const int total = 12; var processed = new ConcurrentBag(); _context.AddRoutes(r => { r.From("direct://threads-drain") .Threads(3) .Process(async (e, ct) => { await Task.Delay(60, ct); processed.Add((int)e.In.Body!); }) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://threads-drain").CreateProducer(); await producer.Start(); for (var i = 0; i < total; i++) await producer.Process(new Exchange(new Message { Body = i })); // Stop immediately — the pool must drain every in-flight/queued exchange, losing none. using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); await _context.Stop(cts.Token); processed.Should().HaveCount(total, "graceful drain-on-stop must not drop any in-flight exchange"); } // ── Processor-level: clone isolation + validation ───────────────────────────── [Fact] public async Task Threads_ClonesExchangePerHandoff_BodyGetsDistinctInstance() { IExchange? seenByBody = null; var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var body = new DelegateProcessor(e => { seenByBody = e; done.TrySetResult(); }); var processor = new ThreadsProcessor(body, poolSize: 1, maxQueueSize: 0, _context); var original = new Exchange(new Message { Body = "orig" }); await processor.Process(original); await done.Task.WaitAsync(TimeSpan.FromSeconds(5)); seenByBody.Should().NotBeNull(); ReferenceEquals(seenByBody, original).Should().BeFalse( "each hand-off clones the exchange so the worker never shares the caller's mutable exchange/scope"); } [Theory] [InlineData(0)] [InlineData(-1)] public void Threads_InvalidPoolSize_Throws(int poolSize) { var body = new DelegateProcessor(_ => { }); var act = () => new ThreadsProcessor(body, poolSize, maxQueueSize: 0, _context); act.Should().Throw(); } // ── InOut / RPC (adaptive by pattern — inline gate on the SAME exchange) ─────── [Fact] public async Task Threads_InOut_ReplyOnOut_Preserved() { // InOut runs the body inline on the SAME exchange — a reply written to Out is simply there. var body = new DelegateProcessor(e => { e.Out ??= e.In.Clone(); e.Out.Body = $"reply:{e.In.Body}"; }); var processor = new ThreadsProcessor(body, poolSize: 2, maxQueueSize: 0, _context); var ex = new Exchange(new Message { Body = "ping" }) { Pattern = ExchangePattern.InOut }; await processor.Process(ex); ex.Out.Should().NotBeNull("InOut must preserve the reply across the threads gate"); ex.Out!.Body.Should().Be("reply:ping"); } [Fact] public async Task Threads_InOut_ReplyOnIn_Preserved() { // Many redb.Route routes (e.g. the HTTP consumer's `HasOut ? Out : In` fallback) write the // response into In, not Out. The inline gate must preserve that too — nothing is cloned/copied. var body = new DelegateProcessor(e => { e.In.Body = $"in-reply:{e.In.Body}"; e.In.Headers["redbHttp.ResponseCode"] = 404; }); var processor = new ThreadsProcessor(body, poolSize: 2, maxQueueSize: 0, _context); var ex = new Exchange(new Message { Body = "ping" }) { Pattern = ExchangePattern.InOut }; await processor.Process(ex); ex.HasOut.Should().BeFalse("the body wrote to In, not Out"); ex.In.Body.Should().Be("in-reply:ping", "an In-based response must survive the gate"); ex.In.Headers["redbHttp.ResponseCode"].Should().Be(404, "In headers (status code) must survive too"); } [Fact] public async Task Threads_InOut_UnhandledBodyException_PropagatesToCaller() { // Inline gate: the fault propagates straight up to the awaiting caller (no OnException here). var body = new DelegateProcessor(_ => throw new InvalidOperationException("boom")); var processor = new ThreadsProcessor(body, poolSize: 1, maxQueueSize: 0, _context); var ex = new Exchange(new Message { Body = "x" }) { Pattern = ExchangePattern.InOut }; var act = async () => await processor.Process(ex); await act.Should().ThrowAsync().WithMessage("boom"); } [Fact] public async Task Threads_InOut_HandledException_DoesNotThrow_AndReplyFlowsBack() { // Inline: the fault propagates up to the route's outer OnException wrapper exactly as an // un-threaded route. A handled exception must NOT surface to the caller; the recovery flows back. _context.AddRoutes(r => { r.OnException() .Handled() .Process(e => { e.Out ??= e.In.Clone(); e.Out.Body = "recovered"; }); r.From("direct://threads-inout-handled") .Threads(2) .Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom")) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://threads-inout-handled").CreateProducer(); await producer.Start(); var ex = new Exchange(new Message { Body = "x" }) { Pattern = ExchangePattern.InOut }; var act = async () => await producer.Process(ex); await act.Should().NotThrowAsync("a handled exception must not surface to the InOut caller"); ex.Out.Should().NotBeNull(); ex.Out!.Body.Should().Be("recovered", "the OnException recovery reply flows back to the caller"); } [Fact] public async Task Threads_InOut_GateCapsConcurrencyAtPoolSize() { // The gate must cap concurrent InOut bodies at poolSize even when many requests arrive at once. const int pool = 3, total = 12; var current = 0; var max = 0; var maxLock = new object(); var body = new DelegateProcessor(async (_, ct) => { var c = Interlocked.Increment(ref current); lock (maxLock) { if (c > max) max = c; } await Task.Delay(40, ct); Interlocked.Decrement(ref current); }); var processor = new ThreadsProcessor(body, poolSize: pool, maxQueueSize: 0, _context); var calls = Enumerable.Range(0, total).Select(i => processor.Process(new Exchange(new Message { Body = i }) { Pattern = ExchangePattern.InOut })); await Task.WhenAll(calls); max.Should().Be(pool, "the InOut gate runs exactly poolSize bodies concurrently — never more, and it saturates"); } [Fact] public async Task Threads_InOut_GateTimeout_ThrowsWhenSaturated() { // poolSize 1: the first InOut takes the only permit and blocks in its body; a second InOut can't // acquire a permit within EnqueueTimeout and fails fast with TimeoutException. var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var body = new DelegateProcessor(async (_, _) => await release.Task); var processor = new ThreadsProcessor(body, poolSize: 1, maxQueueSize: 0, _context) { EnqueueTimeout = TimeSpan.FromMilliseconds(200) }; // Fire the first InOut WITHOUT awaiting — it holds the single permit, blocked on `release`. var first = processor.Process(new Exchange(new Message { Body = 1 }) { Pattern = ExchangePattern.InOut }); try { await Task.Delay(50); // ensure the permit is taken var act = async () => await processor.Process( new Exchange(new Message { Body = 2 }) { Pattern = ExchangePattern.InOut }); await act.Should().ThrowAsync("the gate is full ⇒ no permit within the timeout"); } finally { release.SetResult(); await first; } } [Fact] public async Task Threads_EnqueueTimeout_ThrowsWhenPoolSaturated() { // InOnly path: poolSize 1 + queue 1: worker takes #1 and blocks, #2 fills the single slot, #3 // finds no free slot within EnqueueTimeout and fails fast instead of waiting indefinitely. var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var body = new DelegateProcessor(async (_, _) => await release.Task); var processor = new ThreadsProcessor(body, poolSize: 1, maxQueueSize: 1, _context) { EnqueueTimeout = TimeSpan.FromMilliseconds(200) }; try { await processor.Process(new Exchange(new Message { Body = 1 })); // worker picks up, blocks await processor.Process(new Exchange(new Message { Body = 2 })); // fills the queue slot await Task.Delay(50); // let #1 be dequeued + blocked var act = async () => await processor.Process(new Exchange(new Message { Body = 3 })); await act.Should().ThrowAsync("pool busy + queue full ⇒ no slot within the timeout"); } finally { release.SetResult(); } } // ── Helper ──────────────────────────────────────────────────────────────────── private static async Task WaitForCondition(Func condition, TimeSpan timeout) { using var cts = new CancellationTokenSource(timeout); while (!condition()) { cts.Token.ThrowIfCancellationRequested(); await Task.Delay(10, cts.Token); } } } Path: redb-route/tests/redb.Route.Tests/Processors/ThrottleProcessorTests.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/ThrottleProcessorTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class ThrottleProcessorTests { [Fact] public async Task Process_SingleMessage_PassesThrough() { var processed = false; var next = new DelegateProcessor(_ => processed = true); var throttle = new ThrottleProcessor(next, maxPerPeriod: 10); await throttle.Process(new Exchange(new Message("hello"))); processed.Should().BeTrue(); } [Fact] public async Task Process_UnderLimit_AllPassImmediately() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); var throttle = new ThrottleProcessor(next, maxPerPeriod: 5, period: TimeSpan.FromSeconds(2)); for (int i = 0; i < 5; i++) await throttle.Process(new Exchange(new Message(i))); count.Should().Be(5); } [Fact] public async Task Process_ExceedLimit_ThrottlesExcess() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); var throttle = new ThrottleProcessor(next, maxPerPeriod: 2, period: TimeSpan.FromMilliseconds(500)); var sw = Stopwatch.StartNew(); // Send 3 messages — first 2 pass immediately, 3rd must wait for a slot var t1 = throttle.Process(new Exchange()); var t2 = throttle.Process(new Exchange()); await Task.WhenAll(t1, t2); var fast = sw.ElapsedMilliseconds; await throttle.Process(new Exchange()); sw.Stop(); count.Should().Be(3); // Third message should have been delayed sw.ElapsedMilliseconds.Should().BeGreaterThanOrEqualTo(400); // ~500ms period } [Fact] public async Task Process_PreservesExchangeBody() { object? captured = null; var next = new DelegateProcessor(ex => captured = ex.In.Body); var throttle = new ThrottleProcessor(next, maxPerPeriod: 10); await throttle.Process(new Exchange(new Message("payload"))); captured.Should().Be("payload"); } [Fact] public void Constructor_NullNext_Throws() { var act = () => new ThrottleProcessor(null!, 5); act.Should().Throw().WithParameterName("next"); } [Fact] public void Constructor_ZeroMax_Throws() { var act = () => new ThrottleProcessor(new DelegateProcessor(_ => { }), 0); act.Should().Throw().WithParameterName("maxPerPeriod"); } [Fact] public void Constructor_NegativeMax_Throws() { var act = () => new ThrottleProcessor(new DelegateProcessor(_ => { }), -1); act.Should().Throw().WithParameterName("maxPerPeriod"); } [Fact] public async Task Process_Cancellation_ThrowsOperationCanceled() { var next = new DelegateProcessor(_ => { }); var throttle = new ThrottleProcessor(next, maxPerPeriod: 1, period: TimeSpan.FromSeconds(10)); // Exhaust the single slot await throttle.Process(new Exchange()); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); var act = () => throttle.Process(new Exchange(), cts.Token); await act.Should().ThrowAsync(); } [Fact] public async Task Process_ConcurrentAccess_ThreadSafe() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); var throttle = new ThrottleProcessor(next, maxPerPeriod: 50, period: TimeSpan.FromSeconds(2)); var tasks = Enumerable.Range(0, 50) .Select(_ => throttle.Process(new Exchange())) .ToArray(); await Task.WhenAll(tasks); count.Should().Be(50); } } 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; } } } Path: redb-route/tests/redb.Route.Tests/Processors/TryCatchProcessorTests.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/TryCatchProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for and . public class TryCatchProcessorTests { /// Body executes normally when no exception. [Fact] public async Task Process_NoException_BodyExecutes() { var executed = false; var tryCatch = new TryCatchProcessor(new DelegateProcessor(_ => executed = true)); await tryCatch.Process(new Exchange()); executed.Should().BeTrue(); } /// Matching catch clause handles exception. [Fact] public async Task Process_MatchingCatch_HandlesException() { var handled = false; var tryCatch = new TryCatchProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("fail"))) .Catch(new DelegateProcessor(ex => { handled = true; ex.Exception.Should().BeOfType(); })); var exchange = new Exchange(); await tryCatch.Process(exchange); handled.Should().BeTrue(); exchange.ExceptionHandled.Should().BeTrue(); exchange.Exception.Should().BeOfType(); } /// Non-matching clause rethrows. [Fact] public async Task Process_NoMatchingCatch_Rethrows() { var tryCatch = new TryCatchProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("fail"))) .Catch(new DelegateProcessor(_ => { })); var act = () => tryCatch.Process(new Exchange()); await act.Should().ThrowAsync(); } /// Finally block always executes — on success. [Fact] public async Task Process_Finally_ExecutesOnSuccess() { var finallyRan = false; var tryCatch = new TryCatchProcessor(new DelegateProcessor(_ => { })) .SetFinally(new DelegateProcessor(_ => finallyRan = true)); await tryCatch.Process(new Exchange()); finallyRan.Should().BeTrue(); } /// Finally block executes on handled exception. [Fact] public async Task Process_Finally_ExecutesOnHandledException() { var finallyRan = false; var tryCatch = new TryCatchProcessor( new DelegateProcessor(_ => throw new InvalidOperationException())) .Catch(new DelegateProcessor(_ => { })) .SetFinally(new DelegateProcessor(_ => finallyRan = true)); await tryCatch.Process(new Exchange()); finallyRan.Should().BeTrue(); } /// Finally block executes on unhandled exception. [Fact] public async Task Process_Finally_ExecutesOnUnhandledException() { var finallyRan = false; var tryCatch = new TryCatchProcessor( new DelegateProcessor(_ => throw new InvalidOperationException())) .SetFinally(new DelegateProcessor(_ => finallyRan = true)); var act = () => tryCatch.Process(new Exchange()); await act.Should().ThrowAsync(); finallyRan.Should().BeTrue(); } /// CatchClause.For creates typed clause. [Fact] public void CatchClause_For_CreatesTyped() { var clause = CatchClause.For(new DelegateProcessor(_ => { })); clause.ExceptionType.Should().Be(typeof(ArgumentException)); clause.Matches(new ArgumentException()).Should().BeTrue(); clause.Matches(new InvalidOperationException()).Should().BeFalse(); } /// CatchClause with When predicate filters further. [Fact] public void CatchClause_WithWhen_Filters() { var clause = CatchClause.For( new DelegateProcessor(_ => { }), ex => ex.ParamName == "test"); clause.Matches(new ArgumentException("msg", "test")).Should().BeTrue(); clause.Matches(new ArgumentException("msg", "other")).Should().BeFalse(); } /// A genuine cancellation is never caught — the caller's token is what makes it one. [Fact] public async Task Process_CallerCancellation_NeverCaught() { using var cts = new CancellationTokenSource(); cts.Cancel(); var tryCatch = new TryCatchProcessor( new DelegateProcessor(_ => throw new OperationCanceledException())) .Catch(new DelegateProcessor(_ => { })); var act = () => tryCatch.Process(new Exchange(), cts.Token); await act.Should().ThrowAsync(); } /// A downstream timeout (an OperationCanceledException with our token still live) is named a /// TimeoutException and reaches the catch clause. [Fact] public async Task Process_Timeout_CaughtAsTimeoutException() { Exception? caught = null; var tryCatch = new TryCatchProcessor( new DelegateProcessor(_ => throw new TaskCanceledException("downstream deadline"))) .Catch(new DelegateProcessor(ex => caught = ex.Exception)); var exchange = new Exchange(); await tryCatch.Process(exchange); // ct is not cancelled → not a cancellation caught.Should().BeOfType(); caught!.InnerException.Should().BeOfType( "the original timeout symptom is kept as the cause"); exchange.ExceptionHandled.Should().BeTrue(); } /// Invalid exception type in CatchClause throws. [Fact] public void CatchClause_InvalidType_Throws() { var act = () => new CatchClause(typeof(string), new DelegateProcessor(_ => { })); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Processors/Wave1FeatureTests.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/Wave1FeatureTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Wave 1 feature tests: enhanced splitter, multicast, wire-tap, on-exception, /// and new DSL step types (RemoveProperty, RemoveBody, ThrowException, DelayFactory, Log with LogLevel). /// public class Wave1FeatureTests { // ── SplitterProcessor: Parallel Processing ── /// Parallel splitter processes all parts concurrently. [Fact] public async Task Splitter_Parallel_ProcessesAllParts() { var bodies = new System.Collections.Concurrent.ConcurrentBag(); var target = new DelegateProcessor(ex => bodies.Add(ex.In.Body)); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: true); await splitter.Process(new Exchange(new Message(new object[] { "a", "b", "c" }))); bodies.Should().HaveCount(3); bodies.Should().Contain("a").And.Contain("b").And.Contain("c"); } /// Parallel splitter with aggregation merges results pair-wise. [Fact] public async Task Splitter_Parallel_WithAggregation_MergesResults() { var target = new DelegateProcessor(ex => { ex.In.Body = (int)ex.In.Body! * 10; }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: true, aggregationStrategy: (agg, cur) => { if (agg == null) return cur; // first part: seed (Camel-compatible) agg.In.Body = (int)agg.In.Body! + (int)cur.In.Body!; return agg; }); var exchange = new Exchange(new Message(new object[] { 1, 2, 3 })); await splitter.Process(exchange); exchange.In.Body.Should().Be(60); // (1*10) + (2*10) + (3*10) = 60 } /// Sequential splitter with aggregation merges results pair-wise. [Fact] public async Task Splitter_Sequential_WithAggregation_MergesResults() { var target = new DelegateProcessor(ex => { ex.In.Body = (int)ex.In.Body! * 2; }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: false, aggregationStrategy: (agg, cur) => { if (agg == null) return cur; // first part: seed (Camel-compatible) agg.In.Body = (int)agg.In.Body! + (int)cur.In.Body!; return agg; }); var exchange = new Exchange(new Message(new object[] { 1, 2, 3 })); await splitter.Process(exchange); exchange.In.Body.Should().Be(12); // (1*2) + (2*2) + (3*2) = 12 } /// StopOnException stops parallel processing on first error. [Fact] public async Task Splitter_Parallel_StopOnException_StopsOnFirstError() { var target = new DelegateProcessor(ex => { if ((int)ex.In.Body! == 2) throw new InvalidOperationException("boom"); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: true, stopOnException: true); var exchange = new Exchange(new Message(new object[] { 1, 2, 3 })); var act = () => splitter.Process(exchange); await act.Should().ThrowAsync(); exchange.Exception.Should().BeOfType(); } /// Sequential splitter with stopOnException=false collects all errors. [Fact] public async Task Splitter_Sequential_StopOnExceptionFalse_ContinuesProcessing() { var processed = new List(); var target = new DelegateProcessor(ex => { var val = (int)ex.In.Body!; processed.Add(val); if (val == 2) throw new InvalidOperationException("boom"); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: false, stopOnException: false); var exchange = new Exchange(new Message(new object[] { 1, 2, 3 })); await splitter.Process(exchange); processed.Should().Equal(1, 2, 3); } /// Timeout causes TimeoutException in splitter. [Fact] public async Task Splitter_Timeout_ThrowsTimeoutException() { var target = new DelegateProcessor(async (_, ct) => { await Task.Delay(TimeSpan.FromSeconds(5), ct); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: false, timeout: TimeSpan.FromMilliseconds(50)); var exchange = new Exchange(new Message(new object[] { 1 })); var act = () => splitter.Process(exchange); await act.Should().ThrowAsync(); } /// MaxDegreeOfParallelism limits concurrency in parallel splitter. [Fact] public async Task Splitter_Parallel_MaxDegreeOfParallelism_LimitsConcurrency() { var concurrent = 0; var maxConcurrent = 0; var lockObj = new object(); var target = new DelegateProcessor(async (_, ct) => { var c = Interlocked.Increment(ref concurrent); lock (lockObj) { if (c > maxConcurrent) maxConcurrent = c; } await Task.Delay(50, ct); Interlocked.Decrement(ref concurrent); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target, parallelProcessing: true, maxDegreeOfParallelism: 2); var exchange = new Exchange(new Message(Enumerable.Range(1, 10).Cast().ToArray())); await splitter.Process(exchange); maxConcurrent.Should().BeLessThanOrEqualTo(2); } // ── MulticastProcessor: Enhanced Features ── /// Sequential multicast preserves order with pair-wise aggregation. [Fact] public async Task Multicast_Sequential_PairWiseAggregation() { var multicast = new MulticastProcessor( parallelProcessing: false, aggregationStrategy: (agg, cur) => { agg.In.Body = $"{agg.In.Body},{cur.In.Body}"; return agg; }) .AddTarget(new DelegateProcessor(ex => ex.In.Body = "A")) .AddTarget(new DelegateProcessor(ex => ex.In.Body = "B")) .AddTarget(new DelegateProcessor(ex => ex.In.Body = "C")); var exchange = new Exchange(new Message("_")); await multicast.Process(exchange); exchange.In.Body.Should().Be("A,B,C"); } /// StopOnException in multicast stops on first error. [Fact] public async Task Multicast_StopOnException_StopsOnFirstError() { var multicast = new MulticastProcessor( parallelProcessing: false, stopOnException: true) .AddTarget(new DelegateProcessor(_ => { })) .AddTarget(new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .AddTarget(new DelegateProcessor(_ => { })); var act = () => multicast.Process(new Exchange()); await act.Should().ThrowAsync(); } /// Timeout in multicast throws TimeoutException. [Fact] public async Task Multicast_Timeout_ThrowsTimeoutException() { var multicast = new MulticastProcessor( parallelProcessing: false, timeout: TimeSpan.FromMilliseconds(50)) .AddTarget(new DelegateProcessor(async (_, ct) => { await Task.Delay(TimeSpan.FromSeconds(5), ct); })); var act = () => multicast.Process(new Exchange()); await act.Should().ThrowAsync(); } /// Parallel multicast with max-degree limits concurrency. [Fact] public async Task Multicast_Parallel_MaxDegreeOfParallelism() { var concurrent = 0; var maxConcurrent = 0; var lockObj = new object(); var multicast = new MulticastProcessor( parallelProcessing: true, maxDegreeOfParallelism: 2); for (int i = 0; i < 8; i++) { multicast.AddTarget(new DelegateProcessor(async (_, ct) => { var c = Interlocked.Increment(ref concurrent); lock (lockObj) { if (c > maxConcurrent) maxConcurrent = c; } await Task.Delay(50, ct); Interlocked.Decrement(ref concurrent); })); } await multicast.Process(new Exchange()); maxConcurrent.Should().BeLessThanOrEqualTo(2); } // ── WireTapProcessor: OnPrepare & NewBodyFactory ── /// OnPrepare callback modifies the cloned exchange. [Fact] public async Task WireTap_OnPrepare_ModifiesClone() { IExchange? tapped = null; var wireTap = new WireTapProcessor( new DelegateProcessor(ex => tapped = ex), onPrepare: ex => ex.In.Headers["tap-flag"] = true); var exchange = new Exchange(new Message("original")); await wireTap.Process(exchange); await Task.Delay(100); // Wait for fire-and-forget tapped.Should().NotBeNull(); tapped!.In.Headers["tap-flag"].Should().Be(true); exchange.In.Headers.ContainsKey("tap-flag").Should().BeFalse(); // Original not affected } /// NewBodyFactory replaces the body on the tapped clone. [Fact] public async Task WireTap_NewBodyFactory_ReplacesCloneBody() { IExchange? tapped = null; var wireTap = new WireTapProcessor( new DelegateProcessor(ex => tapped = ex), newBodyFactory: ex => $"audit: {ex.In.Body}"); var exchange = new Exchange(new Message("data")); await wireTap.Process(exchange); await Task.Delay(100); // Wait for fire-and-forget tapped.Should().NotBeNull(); tapped!.In.Body.Should().Be("audit: data"); exchange.In.Body.Should().Be("data"); // Original unchanged } // ── OnExceptionProcessor: Redelivery Delay ── /// OnException with redelivery delay pauses between retries. [Fact] public async Task OnException_RedeliveryDelay_PausesBetweenRetries() { var attempts = 0; var timestamps = new List(); var body = new DelegateProcessor(_ => { timestamps.Add(DateTime.UtcNow); attempts++; throw new InvalidOperationException($"attempt {attempts}"); }); var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(_ => { }), maxRedeliveries: 2, redeliveryDelay: TimeSpan.FromMilliseconds(50)); await processor.Process(new Exchange()); attempts.Should().Be(3); // 1 initial + 2 redeliveries // Verify some delay occurred between attempts if (timestamps.Count >= 2) { var gap = timestamps[^1] - timestamps[0]; gap.TotalMilliseconds.Should().BeGreaterThanOrEqualTo(50); } } /// OnException with exponential backoff increases delay between retries. [Fact] public async Task OnException_ExponentialBackoff_IncreasesDelay() { var attempts = 0; var timestamps = new List(); var body = new DelegateProcessor(_ => { timestamps.Add(DateTime.UtcNow); attempts++; throw new InvalidOperationException("fail"); }); var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(_ => { }), maxRedeliveries: 2, redeliveryDelay: TimeSpan.FromMilliseconds(30), backoffMultiplier: 2.0, useExponentialBackoff: true); await processor.Process(new Exchange()); attempts.Should().Be(3); // First gap ~30ms, second gap ~60ms if (timestamps.Count >= 3) { var gap1 = timestamps[1] - timestamps[0]; var gap2 = timestamps[2] - timestamps[1]; gap2.TotalMilliseconds.Should().BeGreaterThanOrEqualTo(gap1.TotalMilliseconds * 0.8); } } // ── LogProcessor: LogLevel ── /// LogProcessor with Warning level logs at Warning. [Fact] public void LogProcessor_WithLevel_LogsAtSpecifiedLevel() { var logger = Substitute.For(); var processor = new LogProcessor(logger, "test warning", LogLevel.Warning); processor.Process(new Exchange()); logger.Received(1).Log( LogLevel.Warning, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>()); } /// LogProcessor with dynamic message and Error level. [Fact] public void LogProcessor_DynamicMessage_WithLevel() { var logger = Substitute.For(); var processor = new LogProcessor(logger, ex => $"body: {ex.In.Body}", LogLevel.Error); processor.Process(new Exchange(new Message("hello"))); logger.Received(1).Log( LogLevel.Error, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>()); } // ── DSL: New Step Types ── /// RemoveProperty removes a property from the exchange via DSL. [Fact] public async Task DSL_RemoveProperty_RemovesFromExchange() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://remove-prop-in") .SetProperty("myKey", "myValue") .RemoveProperty("myKey") .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://remove-prop-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); received!.Properties.ContainsKey("myKey").Should().BeFalse(); await context.DisposeAsync(); } /// RemoveBody nulls out the exchange body via DSL. [Fact] public async Task DSL_RemoveBody_NullsBody() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://remove-body-in") .SetBody("something") .RemoveBody() .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://remove-body-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); received!.In.Body.Should().BeNull(); await context.DisposeAsync(); } /// ThrowException(instance) throws the exception in the pipeline. [Fact] public async Task DSL_ThrowException_ThrowsSpecifiedException() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://throw-ex") .ThrowException(new InvalidOperationException("boom")); }); await context.Start(); var producer = context.GetEndpoint("direct://throw-ex").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync().WithMessage("boom"); await context.DisposeAsync(); } /// ThrowException(type, message) constructs and throws the exception. [Fact] public async Task DSL_ThrowExceptionType_ConstructsAndThrows() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://throw-ex-type") .ThrowException(typeof(ArgumentException), "bad argument"); }); await context.Start(); var producer = context.GetEndpoint("direct://throw-ex-type").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync().WithMessage("bad argument"); await context.DisposeAsync(); } /// ThrowException() with no args rethrows exchange.Exception. [Fact] public async Task DSL_ThrowException_Rethrow_RethrowsExchangeException() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://rethrow") .Process(ex => ex.Exception = new ArgumentException("original")) .ThrowException(); }); await context.Start(); var producer = context.GetEndpoint("direct://rethrow").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync().WithMessage("original"); await context.DisposeAsync(); } /// ThrowException() with no exchange exception throws InvalidOperationException. [Fact] public async Task DSL_ThrowException_Rethrow_NoException_ThrowsInvalidOperation() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://rethrow-none") .ThrowException(); }); await context.Start(); var producer = context.GetEndpoint("direct://rethrow-none").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync(); await context.DisposeAsync(); } /// ThrowException(string message) throws a new Exception with message. [Fact] public async Task DSL_ThrowException_Message_ThrowsNewException() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://throw-msg") .ThrowException("something went wrong"); }); await context.Start(); var producer = context.GetEndpoint("direct://throw-msg").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync().WithMessage("something went wrong"); await context.DisposeAsync(); } /// ThrowException<T>(message) constructs and throws typed exception. [Fact] public async Task DSL_ThrowException_Generic_WithMessage() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://throw-generic-msg") .ThrowException("generic boom"); }); await context.Start(); var producer = context.GetEndpoint("direct://throw-generic-msg").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync().WithMessage("generic boom"); await context.DisposeAsync(); } /// ThrowException<T>() with no message uses parameterless constructor. [Fact] public async Task DSL_ThrowException_Generic_NoMessage() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://throw-generic-no-msg") .ThrowException(); }); await context.Start(); var producer = context.GetEndpoint("direct://throw-generic-no-msg").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange()); await act.Should().ThrowAsync(); await context.DisposeAsync(); } /// Dynamic delay computes delay from the exchange. [Fact] public async Task DSL_DelayFactory_DynamicDelay() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://delay-factory") .Delay(ex => TimeSpan.FromMilliseconds(50)) .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://delay-factory").CreateProducer(); await producer.Start(); var sw = System.Diagnostics.Stopwatch.StartNew(); await producer.Process(new Exchange(new Message("data"))); sw.Stop(); received.Should().NotBeNull(); sw.ElapsedMilliseconds.Should().BeGreaterThanOrEqualTo(30); // Some tolerance await context.DisposeAsync(); } /// Log with explicit LogLevel via DSL. [Fact] public async Task DSL_LogWithLevel_RecordsLevel() { var context = new RouteContext(); IExchange? received = null; context.AddRoutes(r => { r.From("direct://log-level") .Log("warning message", LogLevel.Warning) .Log(ex => $"body: {ex.In.Body}", LogLevel.Error) .Process(ex => received = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://log-level").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received.Should().NotBeNull(); await context.DisposeAsync(); } /// Enhanced Split via DSL with parallelProcessing option. [Fact] public async Task DSL_Split_WithParallelProcessing() { var context = new RouteContext(); var parts = new System.Collections.Concurrent.ConcurrentBag(); context.AddRoutes(r => { r.From("direct://split-parallel") .Split(ex => ((IEnumerable)ex.In.Body!)) .ParallelProcessing() .Process(ex => parts.Add(ex.In.Body)) .End(); }); await context.Start(); var producer = context.GetEndpoint("direct://split-parallel").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(new object[] { "x", "y", "z" }))); parts.Should().HaveCount(3); parts.Should().Contain("x").And.Contain("y").And.Contain("z"); await context.DisposeAsync(); } /// Enhanced Multicast via DSL with explicit options. [Fact] public async Task DSL_Multicast_WithOptions() { var context = new RouteContext(); var received1 = false; var received2 = false; context.AddRoutes(r => { r.From("direct://mcast-opt-in") .Multicast( new[] { "direct://mcast-opt-out1", "direct://mcast-opt-out2" }, parallelProcessing: false, stopOnException: true); }); context.AddRoutes(r => { r.From("direct://mcast-opt-out1").Process(_ => received1 = true); }); context.AddRoutes(r => { r.From("direct://mcast-opt-out2").Process(_ => received2 = true); }); await context.Start(); var producer = context.GetEndpoint("direct://mcast-opt-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); received1.Should().BeTrue(); received2.Should().BeTrue(); await context.DisposeAsync(); } /// Enhanced WireTap via DSL with onPrepare callback. [Fact] public async Task DSL_WireTap_WithOnPrepare() { var context = new RouteContext(); IExchange? tapped = null; context.AddRoutes(r => { r.From("direct://wt-prep-in") .WireTap("direct://wt-prep-out", onPrepare: ex => ex.In.Headers["prepared"] = true); }); context.AddRoutes(r => { r.From("direct://wt-prep-out").Process(ex => tapped = ex); }); await context.Start(); var producer = context.GetEndpoint("direct://wt-prep-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); await Task.Delay(200); // Wait for fire-and-forget tapped.Should().NotBeNull(); tapped!.In.Headers["prepared"].Should().Be(true); await context.DisposeAsync(); } /// Enhanced OnException DSL with redelivery delay (processor level test). [Fact] public async Task DSL_OnException_WithRedeliveryDelay() { var attempts = 0; var handled = false; var body = new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException("fail"); }); var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(_ => handled = true), maxRedeliveries: 2, redeliveryDelay: TimeSpan.FromMilliseconds(10)); await processor.Process(new Exchange(new Message("data"))); handled.Should().BeTrue(); attempts.Should().Be(3); // 1 initial + 2 redeliveries } } Path: redb-route/tests/redb.Route.Tests/Processors/WireTapProcessorTests.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/WireTapProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class WireTapProcessorTests { /// Tap receives a clone of the exchange. [Fact] public async Task Process_TapReceivesClone() { IExchange? tapped = null; var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { tapped = ex; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap); var original = new Exchange(new Message("data")); await processor.Process(original); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); tapped.Should().NotBeNull(); tapped!.In.Body.Should().Be("data"); tapped.Should().NotBeSameAs(original); // It's a clone } /// Original exchange is not modified by tap. [Fact] public async Task Process_OriginalUnchanged() { var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { ex.In.Body = "modified-by-tap"; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap); var original = new Exchange(new Message("original")); await processor.Process(original); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); original.In.Body.Should().Be("original"); } /// Null tap throws. [Fact] public void Constructor_NullTap_Throws() { var act = () => new WireTapProcessor(null!); act.Should().Throw(); } /// If the tap processor throws, the main pipeline completes normally. [Fact] public async Task Process_TapFailure_DoesNotAffectMainPipeline() { var tap = new DelegateProcessor((_, _) => throw new InvalidOperationException("tap boom")); var processor = new WireTapProcessor(tap); var original = new Exchange(new Message("data")); // Main pipeline should NOT throw even though tap throws var act = async () => await processor.Process(original); await act.Should().NotThrowAsync(); original.In.Body.Should().Be("data"); } /// OperationCanceledException in tap is silently swallowed. [Fact] public async Task Process_TapCancellation_IsSilentlySwallowed() { var tap = new DelegateProcessor((_, _) => throw new OperationCanceledException()); var processor = new WireTapProcessor(tap); var act = async () => await processor.Process(new Exchange(new Message("data"))); await act.Should().NotThrowAsync(); } /// onPrepare callback is invoked on the clone before tap processing. [Fact] public async Task Process_OnPrepare_InvokedOnClone() { IExchange? tapped = null; var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { tapped = ex; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap, onPrepare: clone => { clone.In.Headers["prepared"] = true; }); await processor.Process(new Exchange(new Message("orig"))); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); tapped!.In.Headers["prepared"].Should().Be(true); } /// newBodyFactory replaces body on clone but original is unaffected. [Fact] public async Task Process_NewBodyFactory_ReplacesCloneBody() { IExchange? tapped = null; var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { tapped = ex; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap, newBodyFactory: ex => "replaced-" + ex.In.Body); var original = new Exchange(new Message("orig")); await processor.Process(original); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); tapped!.In.Body.Should().Be("replaced-orig"); original.In.Body.Should().Be("orig"); } } Path: redb-route/tests/redb.Route.Tests/Reference/DslChoiceReferenceTests.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/Reference/DslChoiceReferenceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Reference; /// /// Reference / canonical DSL examples for the Choice content-based router EIP. /// /// Every branch is a real multi-step pipeline — WhenDefinition, /// OtherwiseDefinition and the inner FilterDefinition each own their /// own Outputs list, and ChoiceProcessor compiles those lists with /// BuildPipeline into a real PipelineProcessor. The tests below /// deliberately chain SetHeader → SetProperty → Transform → Process inside the /// branches so that the pipeline semantics (in particular: header/body/property /// mutation being visible to the next step in the same branch) are exercised /// end-to-end. /// /// Forms covered: /// 1. Two-way Choice with multi-step branches and Otherwise. /// 2. Multi-way Choice with multi-step pipelines per branch. /// 3. Choice without Otherwise — non-matching exchanges fall through untouched. /// 4. Nested Choice inside a When branch with shared pre-step in the outer branch. /// 5. Choice nested-lambda form with multi-step branches. /// 6. EndChoice() restores route scope; tail observes branch mutations. /// 7. Filter-inside-When with its own multi-step pipeline. /// 8. Composite Filter DSL inside When — cascaded Filters as logical AND, plus a /// nested inner Filter forming a 3-predicate gate; per-gate side-effects prove /// each Filter has its own real pipeline. /// 9. Composite Filter DSL inside When — Camel-style chained form using /// Filter(…).Filter(…)…EndFilter().EndFilter() without lambdas. /// 10. Fully chained Camel-style outer Choice with multi-step When branches and /// a chained Filter cascade nested inside the Otherwise branch — zero lambdas. /// 11. Enterprise scenario: priority + size classifier with audit + reject pipelines. /// public class DslChoiceReferenceTests { // ── 1. Two-way Choice with multi-step branches ─────────────────────────── /// /// Each branch is a 4-step pipeline (SetHeader → SetProperty → Transform → Process). /// The terminal Process reads the header set by SetHeader and the property set by /// SetProperty earlier in the same branch, proving the branch is a real pipeline. /// [Fact] public async Task TwoWay_Choice_MultiStepBranches_PipelineExecutesInOrder() { await using var context = new RouteContext(); var observed = new List<(string tag, int original, int transformed)>(); context.AddRoutes(r => { r.From("direct://choice-2way-multi") .Choice() .When(e => (int)e.In.Body! > 0) .SetHeader("branch", "pos") .Process(e => e.Properties["original"] = e.In.Body) .Transform(e => (int)e.In.Body! * 10) .Process(e => observed.Add(( (string)e.In.Headers["branch"]!, (int)e.Properties["original"]!, (int)e.In.Body!))) .Otherwise() .SetHeader("branch", "neg") .Process(e => e.Properties["original"] = e.In.Body) .Transform(e => -(int)e.In.Body!) .Process(e => observed.Add(( (string)e.In.Headers["branch"]!, (int)e.Properties["original"]!, (int)e.In.Body!))) .EndChoice(); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-2way-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 5, -3, 0, 7 }) await producer.Process(new Exchange(new Message(i))); observed.Should().Equal( ("pos", 5, 50), ("neg", -3, 3), ("neg", 0, 0), ("pos", 7, 70)); } // ── 2. Multi-way Choice — first match wins, multi-step pipelines ───────── /// /// Each bucket branch is a real pipeline that stamps the bucket header, /// captures the original value as a property, transforms the body, and /// finally reads all three of those side-effects in the terminal Process. /// [Fact] public async Task MultiWay_Choice_FirstMatchWins_EachBranchIsPipeline() { await using var context = new RouteContext(); var sink = new List<(string bucket, int original, string body)>(); context.AddRoutes(r => { r.From("direct://choice-buckets-multi") .Choice() .When(e => (int)e.In.Body! < 10) .SetHeader("bucket", "small") .Process(e => e.Properties["original"] = e.In.Body) .Transform(e => $"S:{e.In.Body}") .Process(e => sink.Add(( (string)e.In.Headers["bucket"]!, (int)e.Properties["original"]!, (string)e.In.Body!))) .When(e => (int)e.In.Body! < 100) .SetHeader("bucket", "medium") .Process(e => e.Properties["original"] = e.In.Body) .Transform(e => $"M:{e.In.Body}") .Process(e => sink.Add(( (string)e.In.Headers["bucket"]!, (int)e.Properties["original"]!, (string)e.In.Body!))) .When(e => (int)e.In.Body! < 1000) .SetHeader("bucket", "large") .Process(e => e.Properties["original"] = e.In.Body) .Transform(e => $"L:{e.In.Body}") .Process(e => sink.Add(( (string)e.In.Headers["bucket"]!, (int)e.Properties["original"]!, (string)e.In.Body!))) .Otherwise() .SetHeader("bucket", "huge") .Process(e => e.Properties["original"] = e.In.Body) .Transform(e => $"H:{e.In.Body}") .Process(e => sink.Add(( (string)e.In.Headers["bucket"]!, (int)e.Properties["original"]!, (string)e.In.Body!))) .EndChoice(); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-buckets-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 50, 500, 9999 }) await producer.Process(new Exchange(new Message(i))); sink.Should().Equal( ("small", 1, "S:1"), ("medium", 50, "M:50"), ("large", 500, "L:500"), ("huge", 9999, "H:9999")); } // ── 3. Choice without Otherwise — fall-through ─────────────────────────── /// /// The matched branch is a multi-step pipeline that doubles the body and /// stamps a header. Non-matching exchanges skip the Choice entirely and /// reach the tail with their body and headers unchanged. /// [Fact] public async Task Choice_WithoutOtherwise_NonMatching_FallsThroughToTail() { await using var context = new RouteContext(); var matchedSeen = new List<(string tag, int doubled)>(); var tail = new List<(int body, string? tag)>(); context.AddRoutes(r => { r.From("direct://choice-noelse-multi") .Choice() .When(e => (int)e.In.Body! % 2 == 0) .SetHeader("matched", "even") .Transform(e => (int)e.In.Body! * 2) .Process(e => matchedSeen.Add(( (string)e.In.Headers["matched"]!, (int)e.In.Body!))) .EndChoice() .Process(e => tail.Add(( (int)e.In.Body!, e.In.Headers.TryGetValue("matched", out var v) ? (string?)v : null))); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-noelse-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); matchedSeen.Should().Equal(("even", 4), ("even", 8)); tail.Should().Equal( (1, null), (4, "even"), (3, null), (8, "even")); } // ── 4. Nested Choice inside a When branch with shared pre-step ─────────── /// /// Outer "order" branch has a shared pre-step (audit header + receivedAt /// property) that runs BEFORE the inner Choice splits by size. Each inner /// branch is itself a multi-step pipeline that reads what the outer pre-step /// stamped. /// [Fact] public async Task NestedChoice_InsideWhen_SharedPreStep_RunsBeforeInnerSplit() { await using var context = new RouteContext(); var smallOrder = new List<(string audit, string receivedAt, decimal amt)>(); var bigOrder = new List<(string audit, decimal amt, decimal vat)>(); var invoiceLog = new List<(string kind, decimal amt)>(); var unknown = new List(); context.AddRoutes(r => { r.From("direct://nested-choice-multi") .Choice(outer => outer .When(e => (string)e.In.Headers["kind"]! == "order", branch => branch // Shared pre-step for every order, regardless of size. .SetHeader("audit", "order-received") .SetProperty("receivedAt", _ => "2026-01-01T00:00:00Z") .Choice(inner => inner .When(e => (decimal)e.In.Body! < 100m, b => b .SetHeader("tier", "small") .Process(e => smallOrder.Add(( (string)e.In.Headers["audit"]!, (string)e.Properties["receivedAt"]!, (decimal)e.In.Body!)))) .Otherwise(b => b .SetHeader("tier", "big") .SetProperty("vat", e => (decimal)e.In.Body! * 0.2m) .Process(e => bigOrder.Add(( (string)e.In.Headers["audit"]!, (decimal)e.In.Body!, (decimal)e.Properties["vat"]!)))))) .When(e => (string)e.In.Headers["kind"]! == "invoice", branch => branch .SetHeader("audit", "invoice-received") .Process(e => invoiceLog.Add(("invoice", (decimal)e.In.Body!)))) .Otherwise(branch => branch .SetHeader("audit", "rejected") .Transform(e => $"?[{e.In.Headers["kind"]}]:{e.In.Body}") .Process(e => unknown.Add((string)e.In.Body!)))); }); await context.Start(); var producer = context.GetEndpoint("direct://nested-choice-multi").CreateProducer(); await producer.Start(); async Task Send(decimal v, string kind) => await producer.Process(new Exchange(new Message { Body = v, Headers = { ["kind"] = kind } })); await Send(50m, "order"); await Send(500m, "order"); await Send(7m, "invoice"); await Send(999m, "weird"); smallOrder.Should().Equal(("order-received", "2026-01-01T00:00:00Z", 50m)); bigOrder.Should().Equal(("order-received", 500m, 100m)); invoiceLog.Should().Equal(("invoice", 7m)); unknown.Should().Equal("?[weird]:999"); } // ── 5. Choice nested-lambda form with multi-step branches ──────────────── /// /// Demonstrates the lambda form. Each branch lambda is a multi-step pipeline: /// SetHeader → Transform → Process. /// [Fact] public async Task ChoiceLambdaForm_MultiStepBranches_TailRunsForAll() { await using var context = new RouteContext(); var sink = new List<(string parity, int squared)>(); var seen = new List(); context.AddRoutes(r => { r.From("direct://choice-lambda-multi") .Choice(c => c .When(e => (int)e.In.Body! % 2 == 0, b => b .SetHeader("parity", "even") .Transform(e => (int)e.In.Body! * (int)e.In.Body!) .Process(e => sink.Add(( (string)e.In.Headers["parity"]!, (int)e.In.Body!)))) .Otherwise(b => b .SetHeader("parity", "odd") .Transform(e => (int)e.In.Body! * (int)e.In.Body!) .Process(e => sink.Add(( (string)e.In.Headers["parity"]!, (int)e.In.Body!))))) .Process(e => seen.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-lambda-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); sink.Should().Equal( ("odd", 1), ("even", 4), ("odd", 9), ("even", 16)); seen.Should().Equal(1, 4, 9, 16); } // ── 6. EndChoice() restores route scope ────────────────────────────────── /// /// Multi-step branches mutate header and body; the tail after /// EndChoice() observes both mutations, confirming the branches /// are real pipelines AND that scope is properly restored at route level. /// [Fact] public async Task EndChoice_RestoresRouteScope_TailObservesBranchMutations() { await using var context = new RouteContext(); var tail = new List(); context.AddRoutes(r => { r.From("direct://choice-endchoice-multi") .Choice() .When(e => (int)e.In.Body! > 0) .SetHeader("sign", "+") .Transform(e => $"+{e.In.Body}") .Otherwise() .SetHeader("sign", "-") .Transform(e => $"{e.In.Body}") .EndChoice() .Process(e => tail.Add($"{e.In.Headers["sign"]}|{e.In.Body}")); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-endchoice-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 5, -1, 0, 3 }) await producer.Process(new Exchange(new Message(i))); tail.Should().Equal("+|+5", "-|-1", "-|0", "+|+3"); } // ── 7. Filter-inside-When with its own multi-step pipeline ─────────────── /// /// Inner Filter has its own pipeline: SetHeader → Transform → Process. /// Confirms FilterDefinition.Outputs is compiled as a real PipelineProcessor /// inside a When branch. /// [Fact] public async Task Choice_When_WithInnerFilterPipeline_GatesAndTransforms() { await using var context = new RouteContext(); var processed = new List<(string mark, decimal final)>(); context.AddRoutes(r => { r.From("direct://choice-flt-multi") .Choice(c => c .When(e => (string)e.In.Headers["type"]! == "order", b => b .Filter(e => (decimal)e.In.Body! != 0m, fb => fb .SetHeader("mark", "non-zero") .Transform(e => (decimal)e.In.Body! * 1.2m) .Process(e => processed.Add(( (string)e.In.Headers["mark"]!, (decimal)e.In.Body!)))))); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-flt-multi").CreateProducer(); await producer.Start(); async Task Send(decimal v, string type) => await producer.Process(new Exchange(new Message { Body = v, Headers = { ["type"] = type } })); await Send(0m, "order"); // gated by Filter await Send(10m, "order"); // 10 * 1.2 = 12 await Send(0m, "ping"); // gated by When await Send(-5m, "order"); // -5 * 1.2 = -6 await Send(999m, "invoice"); // gated by When processed.Should().Equal(("non-zero", 12m), ("non-zero", -6m)); } // ── 8. Composite Filter DSL inside When ────────────────────────────────── /// /// Inside the "payment" When branch we build a compound gate out of three /// chained Filters (logical AND): currency must be EUR/USD, amount must be /// positive, and the country must be on the allow-list. Each Filter has /// its own non-trivial pipeline that stamps a "gate-N-passed" property so /// that the terminal Process can reconstruct exactly how far each exchange /// got. Exchanges that fail a gate keep partial properties up to that gate /// but never reach the terminal Process. /// /// Demonstrates that Filter DSL is fully composable inside a Choice branch /// and each Filter compiles its Outputs into a real PipelineProcessor. /// [Fact] public async Task Choice_When_CompositeFilterDsl_CascadedGatesActAsAnd() { await using var context = new RouteContext(); var allowedCountries = new HashSet { "DE", "FR", "US" }; var accepted = new List<(decimal amount, string currency, string country, string trace)>(); var rejectedAtGate = new Dictionary(); context.AddRoutes(r => { r.From("direct://choice-composite-filter") // Pre-Choice: always initialize a trace list so the tail observer // can inspect how far each exchange got through the gates. .SetProperty("trace", _ => new List()) .Choice(c => c .When(e => (string)e.In.Headers["kind"]! == "payment", b => b // Gate 1: currency whitelist. .Filter( e => (string)e.In.Headers["currency"]! is "EUR" or "USD", g1 => g1 .Process(e => ((List)e.Properties["trace"]!).Add("currency")) // Gate 2: positive amount (nested inside gate 1). .Filter( e => (decimal)e.In.Body! > 0m, g2 => g2 .Process(e => ((List)e.Properties["trace"]!).Add("amount")) // Gate 3: country allow-list (nested inside gate 2). .Filter( e => allowedCountries.Contains((string)e.In.Headers["country"]!), g3 => g3 .Process(e => ((List)e.Properties["trace"]!).Add("country")) .SetHeader("approved", "true") .Transform(e => (decimal)e.In.Body! * 0.97m) // fee .Process(e => accepted.Add(( (decimal)e.In.Body!, (string)e.In.Headers["currency"]!, (string)e.In.Headers["country"]!, string.Join(">", (List)e.Properties["trace"]!))))))))) // Tail observer: runs for every exchange after Choice returns. .Process(e => { if (!e.In.Headers.TryGetValue("kind", out var k) || (string)k! != "payment") return; var trace = (List)e.Properties["trace"]!; string reason = trace.Count switch { 0 => "currency", 1 => "amount", 2 => "country", _ => "passed" }; if (reason != "passed") rejectedAtGate[reason] = rejectedAtGate.TryGetValue(reason, out var n) ? n + 1 : 1; }); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-composite-filter").CreateProducer(); await producer.Start(); async Task Send(decimal amount, string currency, string country, string kind = "payment") => await producer.Process(new Exchange(new Message { Body = amount, Headers = { ["kind"] = kind, ["currency"] = currency, ["country"] = country } })); await Send(100m, "EUR", "DE"); // all gates pass → 97 await Send(50m, "RUB", "DE"); // gate-1 fails (currency) await Send(-10m, "USD", "US"); // gate-2 fails (amount) await Send(20m, "EUR", "BR"); // gate-3 fails (country) await Send(200m, "USD", "FR"); // all gates pass → 194 await Send(0m, "EUR", "DE"); // gate-2 fails (amount = 0) accepted.Should().Equal( (97m, "EUR", "DE", "currency>amount>country"), (194m, "USD", "FR", "currency>amount>country")); rejectedAtGate.Should().BeEquivalentTo(new Dictionary { ["currency"] = 1, ["amount"] = 2, ["country"] = 1, }); } // ── 9. Composite Filter DSL inside When — chained (Camel-style) ─────────────── /// /// Same 3-gate cascade as form #8, but using chained DSL inside the When /// branch: .Filter(p1).Process(…).Filter(p2).Process(…).Filter(p3)…EndFilter().EndFilter().EndFilter(). /// Because FilterDefinition : RouteDefinition (and WhenDefinition : RouteDefinition), /// every nested Filter attaches to its parent's Outputs, and each /// EndFilter() pops one scope level. The outer Choice is opened in lambda /// form so the chained Filter cascade lives entirely inside the When branch. /// [Fact] public async Task Choice_When_CompositeFilterDsl_ChainedCascade_CamelStyle() { await using var context = new RouteContext(); var stage = new List(); var accepted = new List<(decimal amount, string currency, string country)>(); context.AddRoutes(r => { r.From("direct://choice-composite-filter-chained") .Process(e => stage.Add($"in:{e.In.Headers["kind"]}/{e.In.Headers["currency"]}/{e.In.Body}/{e.In.Headers["country"]}")) .Choice(c => c .When(e => (string)e.In.Headers["kind"]! == "payment", b => b .Filter(e => (string)e.In.Headers["currency"]! is "EUR" or "USD") .Process(e => stage.Add($"currency-ok:{e.In.Body}")) .Filter(e => (decimal)e.In.Body! > 0m) .Process(e => stage.Add($"amount-ok:{e.In.Body}")) .Filter(e => (string)e.In.Headers["country"]! is "DE" or "FR" or "US") .Process(e => stage.Add($"country-ok:{e.In.Body}")) .SetHeader("approved", "true") .Transform(e => Math.Round((decimal)e.In.Body! * 0.97m, 2)) .Process(e => accepted.Add(( (decimal)e.In.Body!, (string)e.In.Headers["currency"]!, (string)e.In.Headers["country"]!))) .EndFilter() // closes country gate .EndFilter() // closes amount gate .EndFilter())); // closes currency gate — back to When body }); await context.Start(); var producer = context.GetEndpoint("direct://choice-composite-filter-chained").CreateProducer(); await producer.Start(); async Task Send(decimal amount, string currency, string country, string kind = "payment") => await producer.Process(new Exchange(new Message { Body = amount, Headers = { ["kind"] = kind, ["currency"] = currency, ["country"] = country } })); await Send(100m, "EUR", "DE"); // all gates pass await Send(50m, "RUB", "DE"); // currency gate stops await Send(-10m, "USD", "US"); // amount gate stops await Send(20m, "EUR", "BR"); // country gate stops await Send(200m, "USD", "FR"); // all gates pass await Send(0m, "EUR", "DE", "refund"); // When gate stops — not a payment accepted.Should().Equal( (97.00m, "EUR", "DE"), (194.00m, "USD", "FR")); stage.Should().Equal( "in:payment/EUR/100/DE", "currency-ok:100", "amount-ok:100", "country-ok:100", "in:payment/RUB/50/DE", "in:payment/USD/-10/US", "currency-ok:-10", "in:payment/EUR/20/BR", "currency-ok:20", "amount-ok:20", "in:payment/USD/200/FR", "currency-ok:200", "amount-ok:200", "country-ok:200", "in:refund/EUR/0/DE"); } // ── 10. Fully chained Camel-style Choice + chained Filter cascade in Otherwise ── /// /// Pure chained DSL, zero lambdas. Outer Choice() has three When branches, /// each a real multi-step pipeline. The Otherwise() branch hosts a chained /// 3-gate Filter cascade (currency → amount → country). Because Otherwise() /// is the last branch and the cascade is the last thing in the route, no explicit /// EndChoice() is required — each scope is opened and closed inline. /// [Fact] public async Task FullyChained_Choice_WithChainedFilterCascadeInOtherwise_CamelStyle() { await using var context = new RouteContext(); var stage = new List(); var vipQueue = new List<(string queue, decimal amt)>(); var bulkQueue = new List<(string queue, decimal amt)>(); var smallQueue = new List<(string queue, decimal amt)>(); var accepted = new List<(decimal amt, string currency, string country)>(); context.AddRoutes(r => { r.From("direct://choice-fully-chained") .Process(e => stage.Add($"in:{e.In.Headers["kind"]}/{e.In.Headers["currency"]}/{e.In.Body}/{e.In.Headers["country"]}")) .Choice() .When(e => (string)e.In.Headers["kind"]! == "vip") .SetHeader("queue", "vip") .Transform(e => (decimal)e.In.Body! * 1.10m) .Process(e => vipQueue.Add(( (string)e.In.Headers["queue"]!, (decimal)e.In.Body!))) .When(e => (string)e.In.Headers["kind"]! == "bulk") .SetHeader("queue", "bulk") .Transform(e => (decimal)e.In.Body! * 0.90m) .Process(e => bulkQueue.Add(( (string)e.In.Headers["queue"]!, (decimal)e.In.Body!))) .When(e => (string)e.In.Headers["kind"]! == "small") .SetHeader("queue", "small") .Transform(e => (decimal)e.In.Body! * 1.00m) .Process(e => smallQueue.Add(( (string)e.In.Headers["queue"]!, (decimal)e.In.Body!))) .Otherwise() // Chained Filter cascade inside the last branch. .Filter(e => (string)e.In.Headers["currency"]! is "EUR" or "USD") .Process(e => stage.Add($"currency-ok:{e.In.Body}")) .Filter(e => (decimal)e.In.Body! > 0m) .Process(e => stage.Add($"amount-ok:{e.In.Body}")) .Filter(e => (string)e.In.Headers["country"]! is "DE" or "FR" or "US") .Process(e => stage.Add($"country-ok:{e.In.Body}")) .SetHeader("approved", "true") .Transform(e => Math.Round((decimal)e.In.Body! * 0.97m, 2)) .Process(e => accepted.Add(( (decimal)e.In.Body!, (string)e.In.Headers["currency"]!, (string)e.In.Headers["country"]!))) .EndFilter() // closes country gate .EndFilter() // closes amount gate .EndFilter(); // closes currency gate (and ends route chain) }); await context.Start(); var producer = context.GetEndpoint("direct://choice-fully-chained").CreateProducer(); await producer.Start(); async Task Send(decimal amount, string kind, string currency = "EUR", string country = "DE") => await producer.Process(new Exchange(new Message { Body = amount, Headers = { ["kind"] = kind, ["currency"] = currency, ["country"] = country, } })); await Send(1000m, "vip"); // vip queue await Send(500m, "bulk"); // bulk queue await Send(50m, "small"); // small queue await Send(100m, "payment", "EUR", "DE"); // otherwise → all gates pass await Send(50m, "payment", "RUB", "DE"); // otherwise → currency gate stops await Send(-10m, "payment", "USD", "US"); // otherwise → amount gate stops await Send(20m, "payment", "EUR", "BR"); // otherwise → country gate stops await Send(200m, "payment", "USD", "FR"); // otherwise → all gates pass vipQueue.Should().Equal(("vip", 1100m)); bulkQueue.Should().Equal(("bulk", 450m)); smallQueue.Should().Equal(("small", 50m)); accepted.Should().Equal( (97.00m, "EUR", "DE"), (194.00m, "USD", "FR")); stage.Should().Equal( "in:vip/EUR/1000/DE", "in:bulk/EUR/500/DE", "in:small/EUR/50/DE", "in:payment/EUR/100/DE", "currency-ok:100", "amount-ok:100", "country-ok:100", "in:payment/RUB/50/DE", "in:payment/USD/-10/US", "currency-ok:-10", "in:payment/EUR/20/BR", "currency-ok:20", "amount-ok:20", "in:payment/USD/200/FR", "currency-ok:200", "amount-ok:200", "country-ok:200"); } // ── 11. Enterprise scenario: priority + size classifier ──────────────────── /// /// Realistic order-classifier pipeline: /// • Pre-Choice normalization (lower-case priority header). /// • Outer Choice routes by priority. VIP wins regardless of size. /// • Normal orders share a "compute VAT" pre-step then cascade into a /// nested Choice by amount, which stamps the queue and dispatches. /// • Unknown priority is rejected through a multi-step audit pipeline: /// stamp reject-reason header, transform body to an audit envelope, /// publish to the reject sink. /// Every branch is a real multi-step pipeline. /// [Fact] public async Task EnterpriseScenario_OrderClassifier_BranchesArePipelines() { await using var context = new RouteContext(); var vipQueue = new List<(string queue, decimal amt, decimal vat)>(); var smallQueue = new List<(string queue, decimal amt, decimal vat)>(); var bulkQueue = new List<(string queue, decimal amt, decimal vat)>(); var rejectQueue = new List(); context.AddRoutes(r => { r.From("direct://orders-classify-multi") .Process(e => { var p = (string?)(e.In.Headers.TryGetValue("priority", out var v) ? v : null); e.In.Headers["priority"] = (p ?? "normal").ToLowerInvariant(); }) .Choice(outer => outer .When(e => (string)e.In.Headers["priority"]! == "vip", b => b .SetHeader("queue", "vip") .SetProperty("vat", e => (decimal)e.In.Body! * 0.2m) .Process(e => vipQueue.Add(( (string)e.In.Headers["queue"]!, (decimal)e.In.Body!, (decimal)e.Properties["vat"]!)))) .When(e => (string)e.In.Headers["priority"]! == "normal", b => b // Pre-step shared by all "normal" sub-branches. .SetProperty("vat", e => (decimal)e.In.Body! * 0.2m) .Choice(inner => inner .When(e => (decimal)e.In.Body! < 100m, sb => sb .SetHeader("queue", "small") .Process(e => smallQueue.Add(( (string)e.In.Headers["queue"]!, (decimal)e.In.Body!, (decimal)e.Properties["vat"]!)))) .Otherwise(sb => sb .SetHeader("queue", "bulk") .Process(e => bulkQueue.Add(( (string)e.In.Headers["queue"]!, (decimal)e.In.Body!, (decimal)e.Properties["vat"]!)))))) .Otherwise(b => b .SetHeader("queue", "reject") .SetHeader("reject-reason", "unknown-priority") .Transform(e => $"R[{e.In.Headers["priority"]}|{e.In.Headers["reject-reason"]}]:{e.In.Body}") .Process(e => rejectQueue.Add((string)e.In.Body!)))); }); await context.Start(); var producer = context.GetEndpoint("direct://orders-classify-multi").CreateProducer(); await producer.Start(); async Task Send(decimal amount, string? priority) { var msg = new Message { Body = amount }; if (priority is not null) msg.Headers["priority"] = priority; await producer.Process(new Exchange(msg)); } await Send(50m, "VIP"); await Send(50m, "normal"); await Send(50m, null); await Send(500m, "normal"); await Send(10m, "fraud"); await Send(9999m, "vip"); vipQueue.Should().Equal( ("vip", 50m, 10m), ("vip", 9999m, 1999.8m)); smallQueue.Should().Equal( ("small", 50m, 10m), ("small", 50m, 10m)); bulkQueue.Should().Equal(("bulk", 500m, 100m)); rejectQueue.Should().Equal("R[fraud|unknown-priority]:10"); } } Path: redb-route/tests/redb.Route.Tests/Reference/DslDoTryReferenceTests.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/Reference/DslDoTryReferenceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Reference; /// /// Reference / canonical DSL examples for the DoTry / DoCatch / /// Finally Enterprise Integration Pattern (Camel doTry/doCatch/doFinally). /// /// Every try body, catch handler and finally block is a real multi-step pipeline. /// TryCatchProcessor sets exchange.Exception before invoking the matched /// handler and flips ExceptionHandled = true after the handler returns, so the /// tail after End() can observe both. Unmatched exceptions propagate out of the /// scope (after running Finally, if present). /// /// Forms covered: /// 1. Leaf DoTry/DoCatch — single typed catch, simple handler. /// 2. Multi-step try body — pipeline runs in order until something throws. /// 3. Multiple typed DoCatch branches — first-match-wins. /// 4. DoCatch with .When(predicate) guard — clause skipped when predicate fails. /// 5. DoTry/DoCatch/Finally — finally runs on success AND on failure. /// 6. Catch handler reads e.Exception and can transform/repair the body. /// 7. Nested DoTry inside an outer DoCatch handler — error escalation pattern. /// 8. DoTry nested inside a Choice When branch — per-message try/catch in a branch. /// 9. Enterprise scenario: payment pipeline with validation, processing, audit /// catch and finally book-keeping. /// public class DslDoTryReferenceTests { // ── 1. Leaf DoTry/DoCatch ──────────────────────────────────────────────── /// /// Simplest possible form. A throwing step inside the try body is caught by the /// matching typed DoCatch. After End() the route scope is restored and the /// tail runs for every exchange — both the ones that threw and the ones that did not. /// [Fact] public async Task Leaf_DoTry_DoCatch_HandlesAndContinues() { await using var context = new RouteContext(); var caught = new List(); var tail = new List(); context.AddRoutes(r => { r.From("direct://doTry-leaf") .DoTry() .Process(e => { if ((int)e.In.Body! % 2 == 0) throw new InvalidOperationException("even-boom"); }) .DoCatch() .Process(e => caught.Add((int)e.In.Body!)) .End() .Process(e => tail.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-leaf").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); caught.Should().Equal(2, 4); tail.Should().Equal(1, 2, 3, 4); } // ── 2. Multi-step try body pipeline ────────────────────────────────────── /// /// Try body is a real pipeline of multiple steps. When step #2 throws, step #3 is /// skipped, the handler runs, and exchange.ExceptionHandled becomes true. /// [Fact] public async Task MultiStep_TryBody_StopsOnFirstException() { await using var context = new RouteContext(); var beforeThrow = new List(); var afterThrow = new List(); var caught = new List<(string msg, bool handled)>(); context.AddRoutes(r => { r.From("direct://doTry-multistep") .DoTry() .Process(e => beforeThrow.Add((int)e.In.Body!)) // always runs .Process(e => { if ((int)e.In.Body! < 0) throw new InvalidOperationException("neg"); }) .Process(e => afterThrow.Add((int)e.In.Body!)) // skipped on throw .DoCatch() .Process(e => caught.Add((e.Exception!.Message, e.ExceptionHandled))) .End(); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-multistep").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, -1, 2, -3 }) await producer.Process(new Exchange(new Message(i))); beforeThrow.Should().Equal(1, -1, 2, -3); afterThrow.Should().Equal(1, 2); // Handler sees the exception; ExceptionHandled flips AFTER the handler returns, // so inside the handler it is still false. caught.Should().Equal(("neg", false), ("neg", false)); } // ── 3. Multiple typed DoCatch — first match wins ───────────────────────── /// /// Catch clauses are evaluated in declaration order. The first one whose /// ExceptionType.IsAssignableFrom(actual) wins; later clauses (including /// broader Exception base) are skipped. /// [Fact] public async Task MultipleCatch_FirstMatchWins_ByDeclarationOrder() { await using var context = new RouteContext(); var caughtInvalid = new List(); var caughtArg = new List(); var caughtAny = new List(); context.AddRoutes(r => { r.From("direct://doTry-multicatch") .DoTry() .Process(e => { switch ((string)e.In.Body!) { case "invalid": throw new InvalidOperationException("inv"); case "arg": throw new ArgumentException("arg"); case "other": throw new ApplicationException("other"); } }) .DoCatch() .Process(e => caughtInvalid.Add(e.Exception!.Message)) .Catch() .Process(e => caughtArg.Add(e.Exception!.Message)) .Catch() .Process(e => caughtAny.Add(e.Exception!.Message)) .End(); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-multicatch").CreateProducer(); await producer.Start(); foreach (var s in new[] { "invalid", "arg", "other", "ok" }) await producer.Process(new Exchange(new Message(s))); caughtInvalid.Should().Equal("inv"); caughtArg.Should().Equal("arg"); caughtAny.Should().Equal("other"); } // ── 4. DoCatch with When predicate ─────────────────────────────────────── /// /// A When predicate on a catch clause acts as a secondary guard: /// the type must match AND the predicate must return true. When the predicate /// fails the clause is skipped and the next clause is tried. /// [Fact] public async Task DoCatch_With_When_Predicate_GuardsTheClause() { await using var context = new RouteContext(); var transient = new List(); var fatal = new List(); context.AddRoutes(r => { r.From("direct://doTry-catchwhen") .DoTry() .Process(e => throw new InvalidOperationException((string)e.In.Body!)) .DoCatch() .When(ex => ex.Message.StartsWith("transient:")) .Process(e => transient.Add(e.Exception!.Message)) .Catch() .Process(e => fatal.Add(e.Exception!.Message)) .End(); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-catchwhen").CreateProducer(); await producer.Start(); foreach (var s in new[] { "transient:timeout", "boom", "transient:retry", "kapow" }) await producer.Process(new Exchange(new Message(s))); transient.Should().Equal("transient:timeout", "transient:retry"); fatal.Should().Equal("boom", "kapow"); } // ── 5. Finally — always runs ───────────────────────────────────────────── /// /// The Finally block runs after the try body on success, and after the /// matched catch handler on failure. It always runs exactly once per exchange. /// [Fact] public async Task DoTry_DoCatch_Finally_AlwaysRuns() { await using var context = new RouteContext(); var done = new List(); var caught = new List(); var finallyRan = new List(); context.AddRoutes(r => { r.From("direct://doTry-finally") .DoTry() .Process(e => { if ((int)e.In.Body! < 0) throw new InvalidOperationException("neg"); done.Add((int)e.In.Body!); }) .DoCatch() .Process(e => caught.Add((int)e.In.Body!)) .Finally() .Process(e => finallyRan.Add((int)e.In.Body!)) .EndTryCatch(); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-finally").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, -2, 3, -4, 5 }) await producer.Process(new Exchange(new Message(i))); done.Should().Equal(1, 3, 5); caught.Should().Equal(-2, -4); finallyRan.Should().Equal(1, -2, 3, -4, 5); } // ── 6. Catch handler repairs the body ──────────────────────────────────── /// /// A catch handler reads e.Exception and writes a replacement body, then /// the tail after End() observes the repaired body. Successful exchanges /// flow through with their original body. /// [Fact] public async Task CatchHandler_RepairsBody_TailSeesRepair() { await using var context = new RouteContext(); var output = new List(); context.AddRoutes(r => { r.From("direct://doTry-repair") .DoTry() .Transform(e => { var s = (string)e.In.Body!; if (!int.TryParse(s, out var n)) throw new FormatException($"bad-int:{s}"); return n * 10; }) .DoCatch() .Transform(e => $"") .End() .Process(e => output.Add(e.In.Body!.ToString()!)); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-repair").CreateProducer(); await producer.Start(); foreach (var s in new[] { "1", "xx", "2", "yy" }) await producer.Process(new Exchange(new Message(s))); output.Should().Equal("10", "", "20", ""); } // ── 7. Nested DoTry inside outer catch handler ─────────────────────────── /// /// Error-escalation pattern: outer catch tries a recovery action that may itself /// fail. The inner DoTry catches the recovery failure and routes the exchange to /// a dead-letter sink. Demonstrates that DoTry composes recursively. /// [Fact] public async Task NestedDoTry_InsideCatch_EscalatesToDeadLetter() { await using var context = new RouteContext(); var primary = new List(); var recovered = new List(); var deadLetter = new List<(int body, string err)>(); context.AddRoutes(r => { r.From("direct://doTry-nested") .DoTry() .Process(e => { // Primary path throws for everything > 0; lets non-positive pass. if ((int)e.In.Body! > 0) throw new InvalidOperationException("primary-down"); primary.Add((int)e.In.Body!); }) .DoCatch() .DoTry() .Process(e => { // Recovery succeeds for even values, fails for odd. if ((int)e.In.Body! % 2 != 0) throw new ApplicationException("recovery-failed"); recovered.Add((int)e.In.Body!); }) .DoCatch() .Process(e => deadLetter.Add(((int)e.In.Body!, e.Exception!.Message))) .End() .End(); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-nested").CreateProducer(); await producer.Start(); foreach (var i in new[] { 0, 1, 2, 3, 4, -1 }) await producer.Process(new Exchange(new Message(i))); primary.Should().Equal(0, -1); recovered.Should().Equal(2, 4); deadLetter.Should().Equal((1, "recovery-failed"), (3, "recovery-failed")); } // ── 8. DoTry inside a Choice When branch ───────────────────────────────── /// /// DoTry composes inside any scope opener — here it is the entire body of a /// Choice When branch. The catch handler only runs for exchanges that fail /// inside this specific branch. /// [Fact] public async Task DoTry_InsideChoiceWhen_BranchLocalErrorHandling() { await using var context = new RouteContext(); var ok = new List<(string kind, int body)>(); var caught = new List<(string kind, string err)>(); context.AddRoutes(r => { r.From("direct://doTry-in-when") .Choice(c => c .When(e => (string)e.In.Headers["kind"]! == "risky", b => b .DoTry() .Process(e => { if ((int)e.In.Body! < 0) throw new InvalidOperationException("risky-neg"); ok.Add(((string)e.In.Headers["kind"]!, (int)e.In.Body!)); }) .DoCatch() .Process(e => caught.Add(((string)e.In.Headers["kind"]!, e.Exception!.Message))) .End()) .Otherwise(b => b .Process(e => ok.Add(((string)e.In.Headers["kind"]!, (int)e.In.Body!))))); }); await context.Start(); var producer = context.GetEndpoint("direct://doTry-in-when").CreateProducer(); await producer.Start(); async Task Send(int v, string kind) => await producer.Process(new Exchange(new Message { Body = v, Headers = { ["kind"] = kind } })); await Send(1, "risky"); await Send(-2, "risky"); await Send(3, "safe"); await Send(-4, "risky"); await Send(5, "safe"); ok.Should().Equal(("risky", 1), ("safe", 3), ("safe", 5)); caught.Should().Equal(("risky", "risky-neg"), ("risky", "risky-neg")); } // ── 9. Enterprise scenario: payment pipeline ───────────────────────────── /// /// Realistic payment pipeline: /// • Try body validates input, then "settles" the payment (may throw). /// • A typed catch handles validation errors and pushes to a reject queue. /// • A broad catch handles every other exception as a transient failure. /// • Finally always book-keeps the attempt count for audit. /// [Fact] public async Task EnterpriseScenario_PaymentPipeline_AuditedTryCatchFinally() { await using var context = new RouteContext(); var settled = new List<(string id, decimal amt)>(); var rejected = new List<(string id, string reason)>(); var transient = new List<(string id, string reason)>(); var attempts = new List(); context.AddRoutes(r => { r.From("direct://payments") .DoTry() .Process(e => { var amount = (decimal)e.In.Body!; if (amount <= 0m) throw new ArgumentException("non-positive"); if (amount > 10_000m) throw new InvalidOperationException("settlement-down"); }) .Process(e => settled.Add(((string)e.In.Headers["id"]!, (decimal)e.In.Body!))) .DoCatch() .Process(e => rejected.Add(((string)e.In.Headers["id"]!, e.Exception!.Message))) .Catch() .Process(e => transient.Add(((string)e.In.Headers["id"]!, e.Exception!.Message))) .Finally() .Process(e => attempts.Add((string)e.In.Headers["id"]!)) .EndTryCatch(); }); await context.Start(); var producer = context.GetEndpoint("direct://payments").CreateProducer(); await producer.Start(); async Task Send(string id, decimal amt) => await producer.Process(new Exchange(new Message { Body = amt, Headers = { ["id"] = id } })); await Send("p1", 100m); // settled await Send("p2", 0m); // rejected (non-positive) await Send("p3", 50_000m); // transient (settlement-down) await Send("p4", -1m); // rejected await Send("p5", 250m); // settled settled.Should().Equal(("p1", 100m), ("p5", 250m)); rejected.Should().Equal(("p2", "non-positive"), ("p4", "non-positive")); transient.Should().Equal(("p3", "settlement-down")); attempts.Should().Equal("p1", "p2", "p3", "p4", "p5"); } } Path: redb-route/tests/redb.Route.Tests/Reference/DslFilterReferenceTests.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/Reference/DslFilterReferenceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Reference; /// /// Reference / canonical DSL examples for the Filter Enterprise Integration Pattern. /// /// These tests are designed to be readable end-to-end demonstrations of every /// useful Filter shape supported by the REDB route DSL. They are intentionally /// over-asserted so that both humans and LLM-driven tooling can use them as /// authoritative documentation of the contract. /// /// Forms covered: /// 1. Leaf Filter(predicate) — tail-consuming, no explicit close. /// 2. Leaf Filter(predicate).EndFilter() — explicit scope close. /// 3. Action-overload Filter(predicate, b => ...) — body closed, tail keeps flowing. /// 4. Nested Filter inside Choice/When. /// 5. Nested Filter inside Split (per-item filtering). /// 6. Nested Filter inside Loop. /// 7. Two sequential Filters (AND-chain). /// 8. Filter inside DoTry — catch sees only matched messages. /// 9. Enterprise scenario: high-value order routing with audit tail. /// 10. Route-level composite Filter DSL cascade — nested action-overload /// filters form a gating chain (logical AND) with per-stage trace. /// 11. Route-level composite Filter DSL cascade — Camel-style chained form /// using Filter(…).Filter(…)…EndFilter().EndFilter() without lambdas. /// public class DslFilterReferenceTests { // ── 1. Leaf form ───────────────────────────────────────────────────────── /// /// Canonical leaf Filter: predicate gates the rest of the route. /// Non-matching exchanges stop after the Filter; matching exchanges flow through. /// [Fact] public async Task Leaf_Filter_TailConsumed_NonMatchingStops() { await using var context = new RouteContext(); var passed = new List(); context.AddRoutes(r => { r.From("direct://leaf-flt") .Filter(e => (int)e.In.Body! >= 10) .Process(e => passed.Add((int)e.In.Body!)); }); await context.Start(); foreach (var i in new[] { 5, 10, 7, 15, 20, 1 }) await context.SendBody("direct://leaf-flt", i); passed.Should().Equal(10, 15, 20); } // ── 2. Explicit EndFilter() ────────────────────────────────────────────── /// /// Same behaviour as the leaf form, but explicitly closes the Filter scope /// with EndFilter(). Camel parity: end() on a filter pops the scope. /// [Fact] public async Task Leaf_Filter_WithEndFilter_ReopensRouteScope() { await using var context = new RouteContext(); var inside = new List(); var afterEnd = new List(); context.AddRoutes(r => { r.From("direct://flt-endflt") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => inside.Add((int)e.In.Body!)) .EndFilter() .Process(e => afterEnd.Add((int)e.In.Body!)); }); await context.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await context.SendBody("direct://flt-endflt", i); inside.Should().Equal(2, 4); // EndFilter() pops the Filter scope and restores the parent (route) scope, // so steps appended after it run for every exchange — matched and not matched. afterEnd.Should().Equal(1, 2, 3, 4); } // ── 3. Action-overload (W4.4 explicit scope form) ──────────────────────── /// /// Filter(predicate, body) closes the filtered body when the inner lambda returns — /// the route tail after the call runs for every exchange (matched and not matched). /// This is the recommended form for embedded filtering. /// [Fact] public async Task ActionOverload_Filter_BodyClosed_TailRunsForAll() { await using var context = new RouteContext(); var inside = new List(); var tail = new List(); context.AddRoutes(r => { r.From("direct://flt-action") .Filter(e => (int)e.In.Body! > 0, b => b .Process(e => inside.Add((int)e.In.Body!))) .Process(e => tail.Add((int)e.In.Body!)); }); await context.Start(); foreach (var i in new[] { -1, 0, 1, 2, -3, 5 }) await context.SendBody("direct://flt-action", i); inside.Should().Equal(1, 2, 5); tail.Should().Equal(-1, 0, 1, 2, -3, 5); } // ── 4. Filter nested in Choice/When ────────────────────────────────────── /// /// Choice → When → Filter(action) → Process. Demonstrates that the When /// branch tail keeps flowing after the inner Filter body closes. /// [Fact] public async Task Filter_InsideChoiceWhen_NestedScope_BranchTailRuns() { await using var context = new RouteContext(); var matched = new List(); var branchTail = new List(); context.AddRoutes(r => { r.From("direct://choice-flt-nested") .Choice(c => c .When(e => (string)e.In.Headers["type"]! == "order", b => b .Filter(e => (decimal)e.In.Body! > 100m, fb => fb .Process(e => matched.Add($"big:{e.In.Body}"))) .Process(e => branchTail.Add($"any:{e.In.Body}")))); }); await context.Start(); Task Send(decimal v, string type) => context.SendBodyAndHeader("direct://choice-flt-nested", v, "type", type); await Send(50m, "order"); await Send(150m, "order"); await Send(500m, "order"); await Send(999m, "invoice"); // skipped by When matched.Should().Equal("big:150", "big:500"); branchTail.Should().Equal("any:50", "any:150", "any:500"); } // ── 5. Filter nested in Split (per-item) ───────────────────────────────── /// /// Split → Filter(action) per element. The Filter body sees only matching /// items; the Split body tail sees every item. /// [Fact] public async Task Filter_InsideSplit_PerItem_BodyConditional_TailEveryItem() { await using var context = new RouteContext(); var kept = new List(); var seen = new List(); context.AddRoutes(r => { r.From("direct://split-flt") .Split(e => (IEnumerable)e.In.Body!, b => b .Filter(e => (int)e.In.Body! % 3 == 0, fb => fb .Process(e => kept.Add((int)e.In.Body!))) .Process(e => seen.Add((int)e.In.Body!))); }); await context.Start(); await context.SendBody("direct://split-flt", new object?[] { 1, 2, 3, 4, 6, 7, 9 }); kept.Should().Equal(3, 6, 9); seen.Should().Equal(1, 2, 3, 4, 6, 7, 9); } // ── 6. Filter nested in Loop ───────────────────────────────────────────── /// /// Loop(n) iterates n times; inner Filter body fires only on matching iterations. /// [Fact] public async Task Filter_InsideLoop_PerIteration_BodyConditional() { await using var context = new RouteContext(); var counter = 0; var evens = 0; var totalIters = 0; context.AddRoutes(r => { r.From("direct://loop-flt") .Loop(6, b => b .Process(_ => counter++) .Filter(_ => counter % 2 == 0, fb => fb .Process(_ => evens++)) .Process(_ => totalIters++)); }); await context.Start(); await context.SendBody("direct://loop-flt", "go"); counter.Should().Be(6); evens.Should().Be(3); // iterations 2,4,6 totalIters.Should().Be(6); // tail every iteration } // ── 7. Two sequential Filters (logical AND) ────────────────────────────── /// /// Two leaf Filters in sequence: the second predicate only sees messages /// that survived the first. Equivalent to a logical AND. /// [Fact] public async Task TwoSequentialFilters_AreLogicalAnd() { await using var context = new RouteContext(); var passed = new List(); context.AddRoutes(r => { r.From("direct://flt-and") .Filter(e => (int)e.In.Body! > 0) // positives .Filter(e => (int)e.In.Body! % 2 == 0) // evens .Process(e => passed.Add((int)e.In.Body!)); }); await context.Start(); foreach (var i in new[] { -2, -1, 0, 1, 2, 3, 4, 5, 6 }) await context.SendBody("direct://flt-and", i); passed.Should().Equal(2, 4, 6); } // ── 8. Filter inside DoTry ─────────────────────────────────────────────── /// /// DoTry → Filter(action) → Process(throw). Catch fires only for messages /// that pass the filter — non-matching messages never reach the throwing step. /// [Fact] public async Task Filter_InsideDoTry_GatesExceptionsToMatchedMessages() { await using var context = new RouteContext(); var caught = new List(); context.AddRoutes(r => { r.From("direct://flt-try") .DoTry() .Filter(e => (int)e.In.Body! >= 10, fb => fb .Process(_ => throw new InvalidOperationException("boom"))) .DoCatch() .Process(e => caught.Add((int)e.In.Body!)) .End(); }); await context.Start(); foreach (var i in new[] { 1, 10, 5, 20, 8, 100 }) await context.SendBody("direct://flt-try", i); caught.Should().Equal(10, 20, 100); } // ── 9. Enterprise scenario: high-value order routing ───────────────────── /// /// Realistic enterprise pipeline. Every order is audited; only high-value /// orders are routed to the priority channel. Demonstrates how Filter /// composes with SetHeader and Process to produce a traceable flow. /// [Fact] public async Task EnterpriseScenario_HighValueOrders_RoutedAndAudited() { await using var context = new RouteContext(); var audit = new List(); var priority = new List(); context.AddRoutes(r => { r.From("direct://orders-in") .SetHeader("audit.timestamp", _ => "T") .Process(e => audit.Add($"audit:{e.In.Body}")) .Filter(e => (decimal)e.In.Body! >= 1000m, fb => fb .SetHeader("priority", "HIGH") .Process(e => priority.Add($"prio:{e.In.Body}:{e.In.Headers["priority"]}"))); }); await context.Start(); foreach (var amount in new[] { 50m, 1500m, 200m, 9999m, 999m }) await context.SendBody("direct://orders-in", amount); audit.Should().Equal("audit:50", "audit:1500", "audit:200", "audit:9999", "audit:999"); priority.Should().Equal("prio:1500:HIGH", "prio:9999:HIGH"); } // ── 10. Route-level composite Filter DSL cascade ───────────────────────── /// /// Composite Filter DSL applied directly at the route level (no Choice wrapper). /// Each nested Filter(predicate, fb => …) is a gate; only exchanges that pass /// every gate reach the innermost Process. Per-stage Process steps record a /// trace so the cascade behaves as a logical AND with observable stop points. /// [Fact] public async Task RouteLevel_CompositeFilterDsl_CascadedGatesActAsAnd() { await using var context = new RouteContext(); var stage = new List(); var accepted = new List<(string cur, decimal amt, string country)>(); context.AddRoutes(r => { r.From("direct://route-composite-filter") .Process(e => stage.Add($"in:{e.In.Headers["currency"]}/{e.In.Body}/{e.In.Headers["country"]}")) .Filter(e => (string)e.In.Headers["currency"]! is "EUR" or "USD", g1 => g1 .Process(e => stage.Add($"currency-ok:{e.In.Body}")) .Filter(e => (decimal)e.In.Body! > 0m, g2 => g2 .Process(e => stage.Add($"amount-ok:{e.In.Body}")) .Filter(e => (string)e.In.Headers["country"]! is "DE" or "FR" or "US", g3 => g3 .Process(e => stage.Add($"country-ok:{e.In.Body}")) .SetHeader("approved", "true") .Transform(e => Math.Round((decimal)e.In.Body! * 0.97m, 2)) .Process(e => accepted.Add(( (string)e.In.Headers["currency"]!, (decimal)e.In.Body!, (string)e.In.Headers["country"]!)))))); }); await context.Start(); Task Send(string currency, decimal amount, string country) => context.SendBodyAndHeaders("direct://route-composite-filter", amount, new Dictionary { ["currency"] = currency, ["country"] = country }); await Send("EUR", 100m, "DE"); // passes all 3 gates await Send("GBP", 100m, "DE"); // stops at currency gate await Send("USD", -5m, "US"); // stops at amount gate await Send("USD", 200m, "RU"); // stops at country gate await Send("USD", 50m, "FR"); // passes all 3 gates accepted.Should().Equal( ("EUR", 97.00m, "DE"), ("USD", 48.50m, "FR")); stage.Should().Equal( // EUR/100/DE — all gates pass "in:EUR/100/DE", "currency-ok:100", "amount-ok:100", "country-ok:100", // GBP/100/DE — currency gate stops the cascade "in:GBP/100/DE", // USD/-5/US — amount gate stops "in:USD/-5/US", "currency-ok:-5", // USD/200/RU — country gate stops "in:USD/200/RU", "currency-ok:200", "amount-ok:200", // USD/50/FR — all gates pass "in:USD/50/FR", "currency-ok:50", "amount-ok:50", "country-ok:50"); } // ── 11. Route-level composite Filter DSL cascade — chained (Camel-style) ────── /// /// Same gating cascade as form #10, but using the chained Camel-style DSL: /// .Filter(pred).Filter(pred2)…EndFilter().EndFilter(). Each nested /// Filter attaches to the previous one as a child (because /// FilterDefinition : RouteDefinition inherits the scope opener), and /// every EndFilter() pops one level back to the parent scope. The tail /// after the final EndFilter() runs for every exchange. /// [Fact] public async Task RouteLevel_CompositeFilterDsl_ChainedCascade_CamelStyle() { await using var context = new RouteContext(); var stage = new List(); var accepted = new List<(string cur, decimal amt, string country)>(); var tail = new List(); context.AddRoutes(r => { r.From("direct://route-composite-filter-chained") .Process(e => stage.Add($"in:{e.In.Headers["currency"]}/{e.In.Body}/{e.In.Headers["country"]}")) .Filter(e => (string)e.In.Headers["currency"]! is "EUR" or "USD") .Process(e => stage.Add($"currency-ok:{e.In.Body}")) .Filter(e => (decimal)e.In.Body! > 0m) .Process(e => stage.Add($"amount-ok:{e.In.Body}")) .Filter(e => (string)e.In.Headers["country"]! is "DE" or "FR" or "US") .Process(e => stage.Add($"country-ok:{e.In.Body}")) .SetHeader("approved", "true") .Transform(e => Math.Round((decimal)e.In.Body! * 0.97m, 2)) .Process(e => accepted.Add(( (string)e.In.Headers["currency"]!, (decimal)e.In.Body!, (string)e.In.Headers["country"]!))) .EndFilter() // closes country gate .EndFilter() // closes amount gate .EndFilter() // closes currency gate — back to route scope .Process(e => tail.Add(1)); }); await context.Start(); Task Send(string currency, decimal amount, string country) => context.SendBodyAndHeaders("direct://route-composite-filter-chained", amount, new Dictionary { ["currency"] = currency, ["country"] = country }); await Send("EUR", 100m, "DE"); await Send("GBP", 100m, "DE"); await Send("USD", -5m, "US"); await Send("USD", 200m, "RU"); await Send("USD", 50m, "FR"); accepted.Should().Equal( ("EUR", 97.00m, "DE"), ("USD", 48.50m, "FR")); // Tail runs for every exchange after EndFilter() pops back to route scope. tail.Should().HaveCount(5); stage.Should().Equal( "in:EUR/100/DE", "currency-ok:100", "amount-ok:100", "country-ok:100", "in:GBP/100/DE", "in:USD/-5/US", "currency-ok:-5", "in:USD/200/RU", "currency-ok:200", "amount-ok:200", "in:USD/50/FR", "currency-ok:50", "amount-ok:50", "country-ok:50"); }} Path: redb-route/tests/redb.Route.Tests/RefusalStatisticsTests.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/RefusalStatisticsTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests; /// /// A request the transport refuses as the caller's fault (malformed, unauthenticated, not what the agreement allows) is /// answered by the protocol before any exchange exists. It is counted in Refused, with the reason of the last /// one, and kept out of Errors, the last error and health: a partner sending what the endpoint cannot accept is /// not a failure of the route, and a storm of such requests must not turn a healthy endpoint red. /// public sealed class RefusalStatisticsTests { private static async Task<(RouteContext Context, IEndpointStatistics Stats)> Endpoint() { var context = new RouteContext(); context.AddRoutes(r => r.From("direct:in").Process(_ => { })); await context.Start(); return (context, (IEndpointStatistics)context.GetEndpoint("direct:in")); } [Fact] public async Task A_refusal_is_counted_with_its_reason_and_is_not_an_error() { var (context, stats) = await Endpoint(); await using var _ = context; stats.RecordRefused("EBMS:0101 for m1: the signature does not verify."); stats.RecordRefused("EBMS:0103 for m2: the message is not signed."); stats.Refused.Should().Be(2); stats.LastRefusalMessage.Should().Be("EBMS:0103 for m2: the message is not signed."); stats.LastRefusalTime.Should().NotBeNull(); stats.Errors.Should().Be(0); stats.LastErrorTime.Should().BeNull(); stats.MessagesIn.Should().Be(0, "no exchange was created"); stats.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); } [Fact] public async Task Reset_clears_the_refusals() { var (context, stats) = await Endpoint(); await using var _ = context; stats.RecordRefused("bad"); stats.ResetStatistics(); stats.Refused.Should().Be(0); stats.LastRefusalMessage.Should().BeEmpty(); stats.LastRefusalTime.Should().BeNull(); } [Fact] public async Task Refusals_are_readable_from_a_route() { var (context, stats) = await Endpoint(); await using var _ = context; stats.RecordRefused("bad request"); ExpressionResolver.ReadStatistic(stats, "refused").Should().Be(1L); ExpressionResolver.ReadStatistic(stats, "lastRefusal").Should().Be("bad request"); ExpressionResolver.IsKnownStatistic("Refused").Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests/RouteEngineTests.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/RouteEngineTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests; /// /// End-to-end tests proving the route engine actually works with DSL + compilation + direct component. /// public class RouteContextTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task Direct_passthrough_route_delivers_exchange() { // Arrange: direct://input → direct://output IExchange? received = null; _context.AddRoutes(r => { r.From("direct://input") .To("direct://output"); }); // Add a second route that captures output _context.AddRoutes(r => { r.From("direct://output") .Process(exchange => received = exchange); }); await _context.Start(); // Act: send a message to direct://input var inputEndpoint = _context.GetEndpoint("direct://input"); var producer = inputEndpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = "Hello World" }); await producer.Process(exchange); // Assert received.Should().NotBeNull(); received!.In.Body.Should().Be("Hello World"); } [Fact] public async Task Route_with_processor_transforms_exchange() { IExchange? received = null; _context.AddRoutes(r => { r.From("direct://input") .Process(e => e.In.Body = $"Processed: {e.In.Body}") .To("direct://output"); }); _context.AddRoutes(r => { r.From("direct://output") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://input").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "test" })); received.Should().NotBeNull(); received!.In.Body.Should().Be("Processed: test"); } [Fact] public async Task Route_with_set_header_and_set_body() { IExchange? received = null; _context.AddRoutes(r => { r.From("direct://start") .SetHeader("X-Processed", true) .SetBody("replaced-body") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://start").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "original" })); received.Should().NotBeNull(); received!.In.Body.Should().Be("replaced-body"); received.In.Headers["X-Processed"].Should().Be(true); } [Fact] public async Task Route_with_filter_stops_non_matching() { var received = new List(); _context.AddRoutes(r => { r.From("direct://filtered") .Filter(e => (int)e.In.Body! > 5) .Process(e => received.Add(e.In.Body)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://filtered").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = 3 })); await producer.Process(new Exchange(new Message { Body = 10 })); await producer.Process(new Exchange(new Message { Body = 1 })); await producer.Process(new Exchange(new Message { Body = 7 })); received.Should().HaveCount(2); received.Should().Contain(10); received.Should().Contain(7); } [Fact] public async Task Route_with_choice_routes_by_content() { var highPriority = new List(); var lowPriority = new List(); _context.AddRoutes(r => { r.From("direct://orders") .Choice() .When(e => (string)e.In.Headers["priority"]! == "high") .Process(e => highPriority.Add((string)e.In.Body!)) .When(e => (string)e.In.Headers["priority"]! == "low") .Process(e => lowPriority.Add((string)e.In.Body!)) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://orders").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "order1", Headers = { ["priority"] = "high" } })); await producer.Process(new Exchange(new Message { Body = "order2", Headers = { ["priority"] = "low" } })); await producer.Process(new Exchange(new Message { Body = "order3", Headers = { ["priority"] = "high" } })); highPriority.Should().BeEquivalentTo("order1", "order3"); lowPriority.Should().BeEquivalentTo("order2"); } [Fact] public async Task Route_with_transform() { IExchange? received = null; _context.AddRoutes(r => { r.From("direct://transform") .Transform(e => ((string)e.In.Body!).ToUpperInvariant()) .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://transform").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "hello" })); received.Should().NotBeNull(); received!.In.Body.Should().Be("HELLO"); } [Fact] public async Task Route_with_try_catch_handles_exception() { IExchange? received = null; Exception? caughtException = null; _context.AddRoutes(r => { r.From("direct://errors") .DoTry() .Process(e => throw new InvalidOperationException("boom")) .DoCatch() .Process(e => { caughtException = e.Exception; e.In.Body = "recovered"; }) .End() .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://errors").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "test" })); caughtException.Should().NotBeNull(); caughtException!.Message.Should().Be("boom"); received.Should().NotBeNull(); received!.In.Body.Should().Be("recovered"); } [Fact] public async Task Route_with_multi_step_pipeline() { var steps = new List(); _context.AddRoutes(r => { r.From("direct://pipeline") .Process(e => steps.Add("step1")) .SetHeader("step", "2") .Process(e => steps.Add($"step{e.In.Headers["step"]}")) .SetBody((Func)(e => $"final-{e.In.Body}")) .Process(e => steps.Add($"step3-{e.In.Body}")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://pipeline").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "data" })); steps.Should().BeEquivalentTo("step1", "step2", "step3-final-data"); } [Fact] public async Task Route_assigns_route_id() { string? capturedRouteId = null; _context.AddRoutes(r => { r.From("direct://identified") .RouteId("my-route") .Process(e => capturedRouteId = e.RouteId); }); await _context.Start(); var producer = _context.GetEndpoint("direct://identified").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "test" })); capturedRouteId.Should().Be("my-route"); } [Fact] public async Task Route_with_delay() { var sw = System.Diagnostics.Stopwatch.StartNew(); bool processed = false; _context.AddRoutes(r => { r.From("direct://delayed") .Delay(TimeSpan.FromMilliseconds(100)) .Process(e => processed = true); }); await _context.Start(); var producer = _context.GetEndpoint("direct://delayed").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "test" })); sw.Stop(); processed.Should().BeTrue(); sw.ElapsedMilliseconds.Should().BeGreaterThanOrEqualTo(80); // account for scheduling jitter } [Fact] public async Task Route_with_stop_halts_pipeline() { var steps = new List(); _context.AddRoutes(r => { r.From("direct://halted") .Process(e => steps.Add("before")) .Stop() .Process(e => steps.Add("after")); // should NOT execute }); await _context.Start(); var producer = _context.GetEndpoint("direct://halted").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "test" })); steps.Should().BeEquivalentTo("before"); } [Fact] public async Task Multiple_routes_in_one_builder() { var results = new List(); _context.AddRoutes(r => { r.From("direct://a") .Process(e => results.Add("route-a")); r.From("direct://b") .Process(e => results.Add("route-b")); }); await _context.Start(); var producerA = _context.GetEndpoint("direct://a").CreateProducer(); await producerA.Start(); await producerA.Process(new Exchange(new Message())); var producerB = _context.GetEndpoint("direct://b").CreateProducer(); await producerB.Start(); await producerB.Process(new Exchange(new Message())); results.Should().BeEquivalentTo("route-a", "route-b"); } [Fact] public async Task Engine_reports_compiled_routes() { _context.AddRoutes(r => { r.From("direct://one").RouteId("r1").Process(_ => { }); r.From("direct://two").RouteId("r2").Process(_ => { }); }); await _context.Start(); _context.Routes.Should().HaveCount(2); _context.Routes.Select(r => r.RouteId).Should().BeEquivalentTo("r1", "r2"); } [Fact] public async Task Route_set_property_is_accessible_in_later_step() { object? capturedProp = null; _context.AddRoutes(r => { r.From("direct://props") .SetProperty("myKey", "myValue") .Process(e => capturedProp = e.Properties["myKey"]); }); await _context.Start(); var producer = _context.GetEndpoint("direct://props").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message())); capturedProp.Should().Be("myValue"); } [Fact] public async Task Route_with_remove_header() { bool headerExists = true; _context.AddRoutes(r => { r.From("direct://remove-hdr") .RemoveHeader("toRemove") .Process(e => headerExists = e.In.Headers.ContainsKey("toRemove")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://remove-hdr").CreateProducer(); await producer.Start(); var msg = new Message { Body = "test" }; msg.Headers["toRemove"] = "value"; await producer.Process(new Exchange(msg)); headerExists.Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests/RouteLifecycleTests.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/RouteLifecycleTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests; /// /// Tests for route lifecycle: start/stop individual routes by routeId, /// route status tracking, and GetRoute API. /// public class RouteLifecycleTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task Start_SetsAllRoutesToStarted() { _context.AddRoutes(r => { r.From("direct://a").RouteId("route-a").Process(_ => { }); }); _context.AddRoutes(r => { r.From("direct://b").RouteId("route-b").Process(_ => { }); }); await _context.Start(); var routeA = _context.GetRoute("route-a"); var routeB = _context.GetRoute("route-b"); routeA.Should().NotBeNull(); routeB.Should().NotBeNull(); routeA!.Status.Should().Be(RouteStatus.Started); routeB!.Status.Should().Be(RouteStatus.Started); } [Fact] public async Task Stop_SetsAllRoutesToStopped() { _context.AddRoutes(r => { r.From("direct://a").RouteId("route-a").Process(_ => { }); }); await _context.Start(); var route = _context.GetRoute("route-a"); route!.Status.Should().Be(RouteStatus.Started); await _context.Stop(); route.Status.Should().Be(RouteStatus.Stopped); } [Fact] public async Task GetRoute_ReturnsNull_WhenNotFound() { _context.AddRoutes(r => { r.From("direct://x").RouteId("exists").Process(_ => { }); }); await _context.Start(); _context.GetRoute("nonexistent").Should().BeNull(); } [Fact] public void GetRoute_ThrowsOnNull() { var act = () => _context.GetRoute(null!); act.Should().Throw(); } [Fact] public async Task GetRoute_CaseInsensitive() { _context.AddRoutes(r => { r.From("direct://ci").RouteId("MyRoute").Process(_ => { }); }); await _context.Start(); _context.GetRoute("myroute").Should().NotBeNull(); _context.GetRoute("MYROUTE").Should().NotBeNull(); _context.GetRoute("MyRoute").Should().NotBeNull(); } [Fact] public async Task StopRoute_StopsIndividualRoute() { _context.AddRoutes(r => { r.From("direct://s1").RouteId("route-1").Process(_ => { }); }); _context.AddRoutes(r => { r.From("direct://s2").RouteId("route-2").Process(_ => { }); }); await _context.Start(); _context.GetRoute("route-1")!.Status.Should().Be(RouteStatus.Started); _context.GetRoute("route-2")!.Status.Should().Be(RouteStatus.Started); await _context.StopRoute("route-1"); _context.GetRoute("route-1")!.Status.Should().Be(RouteStatus.Stopped); _context.GetRoute("route-2")!.Status.Should().Be(RouteStatus.Started); } [Fact] public async Task StartRoute_RestartsStoppedRoute() { _context.AddRoutes(r => { r.From("direct://restart").RouteId("route-restart").Process(_ => { }); }); await _context.Start(); await _context.StopRoute("route-restart"); _context.GetRoute("route-restart")!.Status.Should().Be(RouteStatus.Stopped); await _context.StartRoute("route-restart"); _context.GetRoute("route-restart")!.Status.Should().Be(RouteStatus.Started); } [Fact] public async Task StartRoute_ThrowsIfAlreadyStarted() { _context.AddRoutes(r => { r.From("direct://already").RouteId("route-dup-start").Process(_ => { }); }); await _context.Start(); var act = async () => await _context.StartRoute("route-dup-start"); await act.Should().ThrowAsync() .WithMessage("*already started*"); } [Fact] public async Task StopRoute_ThrowsIfAlreadyStopped() { _context.AddRoutes(r => { r.From("direct://stopped").RouteId("route-dup-stop").Process(_ => { }); }); await _context.Start(); await _context.StopRoute("route-dup-stop"); var act = async () => await _context.StopRoute("route-dup-stop"); await act.Should().ThrowAsync() .WithMessage("*already stopped*"); } [Fact] public async Task StartRoute_ThrowsIfNotFound() { await _context.Start(); var act = async () => await _context.StartRoute("ghost-route"); await act.Should().ThrowAsync() .WithMessage("*not found*"); } [Fact] public async Task StopRoute_ThrowsIfNotFound() { await _context.Start(); var act = async () => await _context.StopRoute("ghost-route"); await act.Should().ThrowAsync() .WithMessage("*not found*"); } [Fact] public async Task CompiledRoute_ExposesRouteProperties() { _context.AddRoutes(r => { r.From("direct://props").RouteId("props-route").Process(_ => { }); }); await _context.Start(); var route = _context.GetRoute("props-route"); route.Should().NotBeNull(); route!.RouteId.Should().Be("props-route"); route.FromUri.Should().Be("direct://props"); route.Definition.Should().NotBeNull(); route.Pipeline.Should().NotBeNull(); route.Consumer.Should().NotBeNull(); route.Endpoint.Should().NotBeNull(); } [Fact] public async Task UnnamedRoute_WithSecretInUri_DoesNotLeakSecretInRouteIdOrFromUri() { // No explicit RouteId(): the id is built from the endpoint (scheme, path, UUID), which // leaves the query out entirely, and FromUri is sanitized — a URI secret never surfaces in // {RouteId}/{FromUri} logs or dashboards. _context.AddRoutes(r => { r.From("direct://svc?password=topsecret").Process(_ => { }); }); await _context.Start(); var route = _context.Routes.Single(); route.RouteId.Should().NotContain("topsecret"); route.RouteId.Should().StartWith("direct-svc-").And.NotContain("****"); route.FromUri.Should().NotContain("topsecret"); route.FromUri.Should().Contain("****"); } [Fact] public void RouteStatus_HasCorrectValues() { RouteStatus.Stopped.Should().Be((RouteStatus)0); RouteStatus.Started.Should().Be((RouteStatus)1); RouteStatus.Starting.Should().Be((RouteStatus)2); RouteStatus.Suspending.Should().Be((RouteStatus)3); RouteStatus.Suspended.Should().Be((RouteStatus)4); RouteStatus.Stopping.Should().Be((RouteStatus)5); RouteStatus.Errored.Should().Be((RouteStatus)6); } [Fact] public async Task StopAndRestart_RouteProcessesExchanges() { var received = new List(); _context.AddRoutes(r => { r.From("direct://cycle") .RouteId("cycle-route") .Process(e => received.Add(e.In.Body)); }); await _context.Start(); // Send first message (route is started) var producer = _context.GetEndpoint("direct://cycle").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "before-stop" })); received.Should().HaveCount(1); received[0].Should().Be("before-stop"); // Stop the route await _context.StopRoute("cycle-route"); // Start it again await _context.StartRoute("cycle-route"); // Send another message await producer.Process(new Exchange(new Message { Body = "after-restart" })); received.Should().HaveCount(2); received[1].Should().Be("after-restart"); } } Path: redb-route/tests/redb.Route.Tests/Serialization/Base64TextTests.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/Serialization/Base64TextTests.cs ---- using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// decodes a value with non-zero unused bits in its last character the same way on .NET 10 /// and .NET 11 (where refuses it), and is otherwise /// . /// public class Base64TextTests { [Theory] [InlineData("YQ==", "61")] [InlineData("YR==", "61")] // two pads: the low 4 bits of 'R' are unused [InlineData("YT==", "61")] [InlineData("YWI=", "6162")] [InlineData("YWJ=", "6162")] // one pad: the low 2 bits of 'J' are unused [InlineData("YWK=", "6162")] [InlineData("YWJj", "616263")] [InlineData("YR==\r\n", "61")] // trailing whitespace is skipped to find the last character [InlineData("YR= =", "61")] [InlineData("", "")] public void Decode_ReadsTheUnusedBitsAsZero(string value, string hex) { Convert.ToHexString(Base64Text.Decode(value)).Should().Be(hex); var buffer = new byte[8]; Base64Text.TryDecode(value, buffer, out var written).Should().BeTrue(); Convert.ToHexString(buffer, 0, written).Should().Be(hex); } [Fact] public void Decode_GivesTheSameBytesAsTheCanonicalSpelling() { Base64Text.Decode("q1w2e3r4t5y6u7i8o9p0aZ==").Should().Equal(Convert.FromBase64String("q1w2e3r4t5y6u7i8o9p0aQ==")); } [Theory] [InlineData("not base64!")] [InlineData("YR")] // missing padding stays an error, as with Convert [InlineData("Y===")] [InlineData("Y*==")] public void Decode_RefusesWhatConvertRefuses(string value) { var act = () => Base64Text.Decode(value); act.Should().Throw(); Base64Text.TryDecode(value, new byte[8], out _).Should().BeFalse(); } [Theory] [InlineData("YR==")] [InlineData("YWJ=")] [InlineData("YR==\r\n")] [InlineData("q1w2e3r4t5y6u7i8o9p0aZ==")] public void TryDecodeCanonical_RefusesNonZeroUnusedBits_OnEveryRuntime(string value) { Base64Text.HasUnusedBitsSet(value).Should().BeTrue(); Base64Text.TryDecodeCanonical(value, new byte[32], out var written).Should().BeFalse(); written.Should().Be(0); } [Theory] [InlineData("YQ==", "61")] [InlineData("YWI=", "6162")] [InlineData("YWJj", "616263")] [InlineData("", "")] public void TryDecodeCanonical_DecodesTheCanonicalSpelling(string value, string hex) { Base64Text.HasUnusedBitsSet(value).Should().BeFalse(); var buffer = new byte[8]; Base64Text.TryDecodeCanonical(value, buffer, out var written).Should().BeTrue(); Convert.ToHexString(buffer, 0, written).Should().Be(hex); } [Theory] [InlineData("not base64!")] [InlineData("YR")] [InlineData("Y*==")] public void HasUnusedBitsSet_IsFalse_ForWhatIsNotBase64_WhichConvertStillRefuses(string value) { Base64Text.HasUnusedBitsSet(value).Should().BeFalse(); Base64Text.TryDecodeCanonical(value, new byte[8], out _).Should().BeFalse(); } [Fact] public void Decode_OfNull_Throws() { var act = () => Base64Text.Decode(null!); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Serialization/ConvertBodyProcessorTests.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/Serialization/ConvertBodyProcessorTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// Tests for with support. /// public class ConvertBodyProcessorTests { private readonly DataFormatRegistry _registry = new(); [Fact] public async Task JsonContentType_DeserializesFromString() { var processor = new ConvertBodyProcessor(typeof(TestOrder), _registry); var exchange = new Exchange(new Message { Body = """{"id":"ORD-1","amount":42.5}""", ContentType = "application/json" }); await processor.Process(exchange); var order = exchange.In.Body.Should().BeOfType().Subject; order.Id.Should().Be("ORD-1"); order.Amount.Should().Be(42.5m); } [Fact] public async Task JsonContentType_DeserializesFromBytes() { var json = new JsonMessageSerializer(); var bytes = json.Serialize(new TestOrder { Id = "ORD-2", Amount = 100m }); var processor = new ConvertBodyProcessor(typeof(TestOrder), _registry); var exchange = new Exchange(new Message { Body = bytes, ContentType = "application/json" }); await processor.Process(exchange); var order = exchange.In.Body.Should().BeOfType().Subject; order.Id.Should().Be("ORD-2"); order.Amount.Should().Be(100m); } [Fact] public async Task JsonWithCharset_StillDeserializes() { var processor = new ConvertBodyProcessor(typeof(TestOrder), _registry); var exchange = new Exchange(new Message { Body = """{"id":"ORD-3","amount":0}""", ContentType = "application/json; charset=utf-8" }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); } [Fact] public async Task StructuredSuffix_PlusJson_Deserializes() { var processor = new ConvertBodyProcessor(typeof(TestOrder), _registry); var exchange = new Exchange(new Message { Body = """{"id":"ORD-4","amount":1}""", ContentType = "application/vnd.company+json" }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); } [Fact] public async Task NoRegistry_FallsBackToSystemConvert() { var processor = new ConvertBodyProcessor(typeof(string)); var exchange = new Exchange(new Message { Body = new byte[] { 72, 101, 108, 108, 111 } // "Hello" }); await processor.Process(exchange); exchange.In.Body.Should().Be("Hello"); } [Fact] public async Task BodyAlreadyTargetType_NoOp() { var original = new TestOrder { Id = "X", Amount = 1 }; var processor = new ConvertBodyProcessor(typeof(TestOrder), _registry); var exchange = new Exchange(new Message { Body = original }); await processor.Process(exchange); exchange.In.Body.Should().BeSameAs(original); } [Fact] public async Task UnknownContentType_NoRegistry_Throws() { var processor = new ConvertBodyProcessor(typeof(TestOrder)); var exchange = new Exchange(new Message { Body = "not-convertible", ContentType = "application/octet-stream" }); var act = () => processor.Process(exchange); await act.Should().ThrowAsync(); } [Fact] public async Task NullBody_NoOp() { var processor = new ConvertBodyProcessor(typeof(TestOrder), _registry); var exchange = new Exchange(new Message { Body = null }); await processor.Process(exchange); exchange.In.Body.Should().BeNull(); } // ── Stream conversion tests ── [Fact] public async Task StreamToString_ReturnsDecodedString() { var data = "hello streaming world"u8.ToArray(); var processor = new ConvertBodyProcessor(typeof(string)); var exchange = new Exchange(new Message(new MemoryStream(data))); await processor.Process(exchange); exchange.In.Body.Should().Be("hello streaming world"); } [Fact] public async Task StreamToByteArray_ReturnsCopiedBytes() { var data = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; var processor = new ConvertBodyProcessor(typeof(byte[])); var exchange = new Exchange(new Message(new MemoryStream(data))); await processor.Process(exchange); exchange.In.Body.Should().BeOfType() .Which.Should().Equal(0xDE, 0xAD, 0xBE, 0xEF); } [Fact] public async Task ByteArrayToStream_ReturnsReadableStream() { var data = new byte[] { 1, 2, 3 }; var processor = new ConvertBodyProcessor(typeof(Stream)); var exchange = new Exchange(new Message(data)); await processor.Process(exchange); var stream = exchange.In.Body.Should().BeAssignableTo().Subject; using var ms = new MemoryStream(); await stream.CopyToAsync(ms).ConfigureAwait(false); ms.ToArray().Should().Equal(1, 2, 3); } [Fact] public async Task StringToStream_ReturnsReadableStream() { var processor = new ConvertBodyProcessor(typeof(Stream)); var exchange = new Exchange(new Message("test data")); await processor.Process(exchange); var stream = exchange.In.Body.Should().BeAssignableTo().Subject; using var reader = new StreamReader(stream); var text = await reader.ReadToEndAsync().ConfigureAwait(false); text.Should().Be("test data"); } [Fact] public async Task EmptyStreamToByteArray_ReturnsEmptyArray() { var processor = new ConvertBodyProcessor(typeof(byte[])); var exchange = new Exchange(new Message(new MemoryStream())); await processor.Process(exchange); exchange.In.Body.Should().BeOfType() .Which.Should().BeEmpty(); } [Fact] public async Task StreamAlreadyStream_NoOp() { var stream = new MemoryStream(new byte[] { 1, 2, 3 }); var processor = new ConvertBodyProcessor(typeof(Stream)); var exchange = new Exchange(new Message(stream)); await processor.Process(exchange); exchange.In.Body.Should().BeSameAs(stream); } public class TestOrder { public string Id { get; set; } = ""; public decimal Amount { get; set; } } } Path: redb-route/tests/redb.Route.Tests/Serialization/DataFormatRegistryTests.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/Serialization/DataFormatRegistryTests.cs ---- using redb.Route.Abstractions; using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// Tests for . /// public class DataFormatRegistryTests { [Fact] public void ExactMatch_Json_ReturnsSerializer() { var registry = new DataFormatRegistry(); var s = registry.GetSerializer("application/json"); s.Should().NotBeNull(); s!.ContentType.Should().Be("application/json"); } [Fact] public void ExactMatch_Xml_ReturnsSerializer() { var registry = new DataFormatRegistry(); registry.GetSerializer("application/xml").Should().NotBeNull(); registry.GetSerializer("text/xml").Should().NotBeNull(); } [Fact] public void WithCharset_StripsParams_ReturnsSerializer() { var registry = new DataFormatRegistry(); var s = registry.GetSerializer("application/json; charset=utf-8"); s.Should().NotBeNull(); s!.ContentType.Should().Be("application/json"); } [Fact] public void StructuredSuffix_PlusJson_ReturnsJsonSerializer() { var registry = new DataFormatRegistry(); var s = registry.GetSerializer("application/vnd.api+json"); s.Should().NotBeNull(); s!.ContentType.Should().Be("application/json"); } [Fact] public void StructuredSuffix_PlusXml_ReturnsXmlSerializer() { var registry = new DataFormatRegistry(); var s = registry.GetSerializer("application/soap+xml"); s.Should().NotBeNull(); s!.ContentType.Should().Be("application/xml"); } [Fact] public void Unknown_ReturnsNull() { var registry = new DataFormatRegistry(); registry.GetSerializer("application/octet-stream").Should().BeNull(); registry.GetSerializer("text/plain").Should().BeNull(); } [Fact] public void CaseInsensitive() { var registry = new DataFormatRegistry(); registry.GetSerializer("APPLICATION/JSON").Should().NotBeNull(); } [Fact] public void CustomRegistration_Overrides() { var registry = new DataFormatRegistry(); var custom = new JsonMessageSerializer(); // reuse for test registry.Register("application/msgpack", custom); registry.GetSerializer("application/msgpack").Should().BeSameAs(custom); } } Path: redb-route/tests/redb.Route.Tests/Serialization/FormUrlEncodedTests.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/Serialization/FormUrlEncodedTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// application/x-www-form-urlencoded as a format registered by default: what a browser posts from an HTML form, /// parsed and written by the WHATWG rules browsers and ASP.NET follow. /// public class FormUrlEncodedTests { private static readonly FormUrlEncodedMessageSerializer Format = new(); private static FormBody Parse(string wire) => Format.Deserialize(Encoding.ASCII.GetBytes(wire))!; [Fact] public void A_browser_form_reads_with_repeated_names_in_order() { var form = Parse("claim=12345&theme=%D0%BF%D1%80%D0%B5%D1%82%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F&tag=a&tag=b¬e=two+words"); form.Get("claim").Should().Be("12345"); form.Get("theme").Should().Be("претензия"); form.GetAll("tag").Should().Equal("a", "b"); form.Get("note").Should().Be("two words", "'+' is a space in form data"); form.Select(f => f.Key).Should().Equal("claim", "theme", "tag", "tag", "note"); } [Fact] public void Edge_forms_follow_the_WHATWG_parser() { var form = Parse("&a=&b&c=1=2&d=%zz&e=%2"); form.Get("a").Should().Be(""); form.Get("b").Should().Be("", "a name without '=' has an empty value"); form.Get("c").Should().Be("1=2", "only the first '=' splits"); form.Get("d").Should().Be("%zz", "a '%' without two hex digits stays as it is"); form.Get("e").Should().Be("%2"); form.Count.Should().Be(5, "an empty pair is skipped"); } [Fact] public void Writing_encodes_as_a_browser_does_and_reads_back() { var form = new FormBody().Add("q", "a b&c=d").Add("name", "Анна").Add("safe", "*-._"); var wire = Encoding.ASCII.GetString(Format.Serialize(form)); wire.Should().Be("q=a+b%26c%3Dd&name=%D0%90%D0%BD%D0%BD%D0%B0&safe=*-._"); Parse(wire).Should().Equal(form); } [Fact] public void A_dictionary_reads_the_first_value_and_writes_like_a_form() { Format.Deserialize>("a=1&a=2&b=3"u8.ToArray()) .Should().BeEquivalentTo(new Dictionary { ["a"] = "1", ["b"] = "3" }); Encoding.ASCII.GetString(Format.Serialize(new Dictionary { ["x"] = "1 2" })).Should().Be("x=1+2"); } [Fact] public void Another_target_or_source_type_is_refused_with_the_format_named() { var read = () => Format.Deserialize("a=1"u8.ToArray()); var write = () => Format.Serialize(42); read.Should().Throw().WithMessage("Form data cannot be read as*"); write.Should().Throw().WithMessage("Form data cannot be written*"); } [Fact] public void Limits_hold_wherever_the_form_came_from() { var small = new FormUrlEncodedMessageSerializer(o => { o.MaxFields = 2; o.MaxValueLength = 3; }); var tooMany = () => small.Deserialize("a=1&b=2&c=3"u8.ToArray()); var tooLong = () => small.Deserialize("a=1234"u8.ToArray()); tooMany.Should().Throw().WithMessage("*more than 2 fields*"); tooLong.Should().Throw().WithMessage("*longer than 3*"); } [Fact] public void Another_encoding_is_an_option_of_the_instance() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var cp1251 = new FormUrlEncodedMessageSerializer(o => o.Encoding = Encoding.GetEncoding(1251)); cp1251.Deserialize("n=%C0%ED%ED%E0"u8.ToArray())!.Get("n").Should().Be("Анна"); } [Fact] public async Task ConvertBody_reads_a_posted_form_through_the_default_registration() { await using var context = new RouteContext($"form-{Guid.NewGuid():N}"); context.AddComponent(new redb.Route.Components.DirectComponent()); FormBody? seen = null; context.AddRoutes(r => r.From("direct://form-in") .ConvertBody() .Process(e => seen = (FormBody)e.In.Body!)); await context.Start(); var template = new ProducerTemplate(context); template.Start(); var message = new Message("claim=7&tag=a&tag=b"u8.ToArray()) { ContentType = "application/x-www-form-urlencoded" }; await template.SendAsync("direct://form-in", message); seen!.Get("claim").Should().Be("7"); seen.GetAll("tag").Should().Equal("a", "b"); } [Fact] public void FormBody_clones_for_a_checkpoint() { var form = new FormBody().Add("a", "1"); var copy = (FormBody)form.Clone(); copy.Add("b", "2"); form.Should().ContainSingle(); } } /// /// A format that implements gets the whole message from Marshal, /// Unmarshal and ConvertBody: the content type with its parameters, the body as it came, the attachments. /// public class MessageDataFormatTests { /// Records what it was given and writes a parameterised content type, as MIME multipart will. private sealed class ProbeMessageFormat : IMessageDataFormat { public string? SeenContentType; public object? SeenBody; public string ContentType => "application/x-probe"; public byte[] Serialize(T value) => throw new NotSupportedException("needs the message"); public T? Deserialize(byte[] data) => throw new NotSupportedException("needs the message"); public object? Deserialize(byte[] data, Type type) => throw new NotSupportedException("needs the message"); public ValueTask UnmarshalAsync(IExchange exchange, Type targetType, CancellationToken ct = default) { var message = exchange.In; SeenContentType = message.ContentType; SeenBody = message.Body; message.Body = $"model of {targetType.Name}"; message.Attachments.Add(new Attachment { Name = "part", Content = AttachmentContent.FromBytes([1, 2]) }); return ValueTask.CompletedTask; } public ValueTask MarshalAsync(IExchange exchange, CancellationToken ct = default) { var message = exchange.In; message.Body = Encoding.UTF8.GetBytes($"{message.Body}+{message.Attachments.Count}"); message.ContentType = "application/x-probe; boundary=b1"; message.Headers["Content-Type"] = message.ContentType; return ValueTask.CompletedTask; } } private static async Task<(RouteContext, ProducerTemplate)> Route(ProbeMessageFormat format, Action build) { var context = new RouteContext($"msgfmt-{Guid.NewGuid():N}"); context.AddComponent(new redb.Route.Components.DirectComponent()); context.AddDataFormat(format); context.AddRoutes(build); await context.Start(); var template = new ProducerTemplate(context); template.Start(); return (context, template); } [Fact] public async Task Unmarshal_hands_the_format_the_stream_and_the_content_type_parameters() { var format = new ProbeMessageFormat(); IExchange? seen = null; var (context, template) = await Route(format, r => r.From("direct://mf-un") .Unmarshal("application/x-probe") .Process(e => seen = e)); await using var _ = context; var stream = new MemoryStream([9]); await template.SendAsync("direct://mf-un", new Message(stream) { ContentType = "application/x-probe; boundary=abc" }); format.SeenContentType.Should().Be("application/x-probe; boundary=abc"); format.SeenBody.Should().BeSameAs(stream, "the step does not buffer the body for a message format"); seen!.In.Body.Should().Be("model of String"); seen.In.Attachments.Should().ContainSingle(); } [Fact] public async Task ConvertBody_to_a_model_uses_the_registered_message_format() { var format = new ProbeMessageFormat(); IExchange? seen = null; var (context, template) = await Route(format, r => r.From("direct://mf-cb") .ConvertBody>() .Process(e => seen = e)); await using var _ = context; await template.SendAsync("direct://mf-cb", new Message("raw") { ContentType = "application/x-probe; boundary=x" }); seen!.In.Body.Should().Be("model of List`1"); } [Fact] public async Task Marshal_keeps_the_content_type_the_format_wrote() { var format = new ProbeMessageFormat(); IExchange? seen = null; var (context, template) = await Route(format, r => r.From("direct://mf-m") .AddAttachment("a", new redb.Route.Expressions.ConstantExpression("x")) .Marshal("application/x-probe") .Process(e => seen = e)); await using var _ = context; await template.SendAsync("direct://mf-m", "model"); Encoding.UTF8.GetString((byte[])seen!.In.Body!).Should().Be("model+1"); seen.In.ContentType.Should().Be("application/x-probe; boundary=b1"); seen.In.Headers["Content-Type"].Should().Be("application/x-probe; boundary=b1"); } } Path: redb-route/tests/redb.Route.Tests/Serialization/JsonMessageSerializerTests.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/Serialization/JsonMessageSerializerTests.cs ---- using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// Tests for . /// public class JsonMessageSerializerTests { private readonly JsonMessageSerializer _sut = new(); [Fact] public void ContentType_IsApplicationJson() { _sut.ContentType.Should().Be("application/json"); } [Fact] public void Serialize_ReturnsNonEmptyBytes() { var bytes = _sut.Serialize(new { Name = "test", Value = 42 }); bytes.Should().NotBeEmpty(); } [Fact] public void Roundtrip_PreservesObject() { var original = new TestDto("Alice", 30); var bytes = _sut.Serialize(original); var restored = _sut.Deserialize(bytes); restored.Should().NotBeNull(); restored!.Name.Should().Be("Alice"); restored.Age.Should().Be(30); } [Fact] public void Deserialize_UntypedOverload_ReturnsCorrectType() { var original = new TestDto("Bob", 25); var bytes = _sut.Serialize(original); var restored = _sut.Deserialize(bytes, typeof(TestDto)); restored.Should().BeOfType(); ((TestDto)restored!).Name.Should().Be("Bob"); } [Fact] public void Serialize_UsesCamelCase() { var obj = new TestDto("Test", 1); var bytes = _sut.Serialize(obj); var json = System.Text.Encoding.UTF8.GetString(bytes); json.Should().Contain("\"name\""); json.Should().Contain("\"age\""); json.Should().NotContain("\"Name\""); } [Fact] public void Deserialize_IsCaseInsensitive() { var json = """{"Name":"Case","Age":10}"""u8.ToArray(); var result = _sut.Deserialize(json); result.Should().NotBeNull(); result!.Name.Should().Be("Case"); result.Age.Should().Be(10); } [Fact] public void Serialize_IgnoresNullValues() { var obj = new NullableDto { Name = "test", Description = null }; var bytes = _sut.Serialize(obj); var json = System.Text.Encoding.UTF8.GetString(bytes); json.Should().NotContain("description"); } public record TestDto(string Name, int Age); public class NullableDto { public string? Name { get; set; } public string? Description { get; set; } } } Path: redb-route/tests/redb.Route.Tests/Serialization/MarshalUnmarshalProcessorTests.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/Serialization/MarshalUnmarshalProcessorTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// Tests for and . /// public class MarshalUnmarshalProcessorTests { private readonly JsonMessageSerializer _serializer = new(); [Fact] public async Task MarshalProcessor_SerializesBodyToBytes() { var processor = new MarshalProcessor(_serializer); var exchange = new Exchange(new Message { Body = new OrderDto("ORD-1", 99.9m) }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); exchange.In.Headers.Should().ContainKey("Content-Type"); exchange.In.Headers["Content-Type"].Should().Be("application/json"); } [Fact] public async Task MarshalProcessor_SkipsIfBodyIsNull() { var processor = new MarshalProcessor(_serializer); var exchange = new Exchange(new Message { Body = null }); await processor.Process(exchange); exchange.In.Body.Should().BeNull(); } [Fact] public async Task MarshalProcessor_SkipsIfBodyIsAlreadyBytes() { var processor = new MarshalProcessor(_serializer); var original = new byte[] { 1, 2, 3 }; var exchange = new Exchange(new Message { Body = original }); await processor.Process(exchange); exchange.In.Body.Should().BeSameAs(original); } [Fact] public async Task UnmarshalProcessor_DeserializesFromBytes() { var original = new OrderDto("ORD-2", 42.5m); var bytes = _serializer.Serialize(original); var processor = new UnmarshalProcessor(_serializer, typeof(OrderDto)); var exchange = new Exchange(new Message { Body = bytes }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); var result = (OrderDto)exchange.In.Body!; result.Id.Should().Be("ORD-2"); result.Amount.Should().Be(42.5m); } [Fact] public async Task UnmarshalProcessor_SkipsIfBodyIsNotBytesStringOrStream() { var processor = new UnmarshalProcessor(_serializer, typeof(OrderDto)); var exchange = new Exchange(new Message { Body = 42 }); await processor.Process(exchange); exchange.In.Body.Should().Be(42); } [Fact] public async Task UnmarshalProcessor_AcceptsStringBody() { // Text formats (JSON, CSV, YAML) arrive as strings far more often than as byte[]. var processor = new UnmarshalProcessor(_serializer, typeof(OrderDto)); var exchange = new Exchange(new Message { Body = """{"id":"ORD-9","amount":5}""" }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType().Which.Id.Should().Be("ORD-9"); } [Fact] public async Task UnmarshalProcessor_AcceptsStreamBody() { var processor = new UnmarshalProcessor(_serializer, typeof(OrderDto)); var exchange = new Exchange(new Message { Body = new MemoryStream("""{"id":"ORD-10","amount":1}"""u8.ToArray()) }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType().Which.Id.Should().Be("ORD-10"); } [Fact] public async Task MarshalThenUnmarshal_Roundtrip() { var marshal = new MarshalProcessor(_serializer); var unmarshal = new UnmarshalProcessor(_serializer, typeof(OrderDto)); var original = new OrderDto("ORD-3", 100m); var exchange = new Exchange(new Message { Body = original }); await marshal.Process(exchange); exchange.In.Body.Should().BeOfType(); await unmarshal.Process(exchange); exchange.In.Body.Should().BeOfType(); var result = (OrderDto)exchange.In.Body!; result.Id.Should().Be("ORD-3"); result.Amount.Should().Be(100m); } public record OrderDto(string Id, decimal Amount); // ── XML Serializer tests ── [Fact] public async Task MarshalProcessor_Xml_SerializesBodyToBytes() { var xmlSerializer = new XmlMessageSerializer(); var processor = new MarshalProcessor(xmlSerializer); var exchange = new Exchange(new Message { Body = new XmlOrderDto { Id = "ORD-X1", Amount = 55m } }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); exchange.In.Headers["Content-Type"].Should().Be("application/xml"); } [Fact] public async Task UnmarshalProcessor_Xml_DeserializesFromBytes() { var xmlSerializer = new XmlMessageSerializer(); var original = new XmlOrderDto { Id = "ORD-X2", Amount = 77m }; var bytes = xmlSerializer.Serialize(original); var processor = new UnmarshalProcessor(xmlSerializer, typeof(XmlOrderDto)); var exchange = new Exchange(new Message { Body = bytes }); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); var result = (XmlOrderDto)exchange.In.Body!; result.Id.Should().Be("ORD-X2"); result.Amount.Should().Be(77m); } [Fact] public async Task MarshalThenUnmarshal_Xml_Roundtrip() { var xmlSerializer = new XmlMessageSerializer(); var marshal = new MarshalProcessor(xmlSerializer); var unmarshal = new UnmarshalProcessor(xmlSerializer, typeof(XmlOrderDto)); var original = new XmlOrderDto { Id = "ORD-X3", Amount = 200m }; var exchange = new Exchange(new Message { Body = original }); await marshal.Process(exchange); exchange.In.Body.Should().BeOfType(); await unmarshal.Process(exchange); exchange.In.Body.Should().BeOfType(); var result = (XmlOrderDto)exchange.In.Body!; result.Id.Should().Be("ORD-X3"); result.Amount.Should().Be(200m); } /// DTO for XML tests. Must be public with parameterless ctor. public class XmlOrderDto { public string? Id { get; set; } public decimal Amount { get; set; } } } Path: redb-route/tests/redb.Route.Tests/Serialization/XmlMessageSerializerTests.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/Serialization/XmlMessageSerializerTests.cs ---- using System.Xml; using redb.Route.Serialization; namespace redb.Route.Tests.Serialization; /// /// Tests for . /// public class XmlMessageSerializerTests { private readonly XmlMessageSerializer _sut = new(); [Fact] public void ContentType_IsApplicationXml() { _sut.ContentType.Should().Be("application/xml"); } [Fact] public void Serialize_ReturnsNonEmptyBytes() { var bytes = _sut.Serialize(new XmlTestOrder { Id = "ORD-1", Amount = 99.5m }); bytes.Should().NotBeEmpty(); } [Fact] public void Serialize_ProducesValidXml() { var bytes = _sut.Serialize(new XmlTestOrder { Id = "ORD-1", Amount = 42m }); var xml = System.Text.Encoding.UTF8.GetString(bytes); xml.Should().Contain("ORD-1"); xml.Should().Contain("42"); } [Fact] public void Serialize_OmitsXmlDeclarationByDefault() { var bytes = _sut.Serialize(new XmlTestOrder { Id = "X" }); var xml = System.Text.Encoding.UTF8.GetString(bytes); xml.Should().NotContain("(bytes); restored.Should().NotBeNull(); restored!.Id.Should().Be("ORD-2"); restored.Amount.Should().Be(100.25m); } [Fact] public void Deserialize_UntypedOverload_ReturnsCorrectType() { var original = new XmlTestOrder { Id = "ORD-3", Amount = 50m }; var bytes = _sut.Serialize(original); var restored = _sut.Deserialize(bytes, typeof(XmlTestOrder)); restored.Should().BeOfType(); ((XmlTestOrder)restored!).Id.Should().Be("ORD-3"); } [Fact] public void Deserialize_NullData_Throws() { var act = () => _sut.Deserialize(null!); act.Should().Throw(); } [Fact] public void Deserialize_Untyped_NullData_Throws() { var act = () => _sut.Deserialize(null!, typeof(XmlTestOrder)); act.Should().Throw(); } [Fact] public void Deserialize_Untyped_NullType_Throws() { var act = () => _sut.Deserialize(new byte[] { 1 }, null!); act.Should().Throw(); } [Fact] public void CustomSettings_WithXmlDeclaration_IncludesDeclaration() { var writerSettings = new XmlWriterSettings { OmitXmlDeclaration = false, Indent = true }; var sut = new XmlMessageSerializer(writerSettings, XmlMessageSerializer.DefaultReaderSettings); var bytes = sut.Serialize(new XmlTestOrder { Id = "X" }); var xml = System.Text.Encoding.UTF8.GetString(bytes); xml.Should().Contain(" new XmlMessageSerializer(null!, XmlMessageSerializer.DefaultReaderSettings); act.Should().Throw(); } [Fact] public void Constructor_NullReaderSettings_Throws() { var act = () => new XmlMessageSerializer(XmlMessageSerializer.DefaultWriterSettings, null!); act.Should().Throw(); } /// Test DTO for XML serialization. Must be public with parameterless ctor for XmlSerializer. public class XmlTestOrder { public string? Id { get; set; } public decimal Amount { get; set; } } } Path: redb-route/tests/redb.Route.Tests/StatisticsOwnershipTests.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/StatisticsOwnershipTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests; /// /// The statistics-ownership audit (plan KAFKA_HARDENING_AND_OPTIONS_SWEEP_PLAN, owner question 0). /// One owner for pipeline statistics: the core. StatisticsProcessor wraps every From(), ToProcessor /// counts every routed To(), and the ProducerTemplate counts its sends the same way - it used to /// bypass statistics entirely, so a template send was invisible unless the connector /// self-recorded, and a self-recording connector then double-counted in routes. /// public sealed class StatisticsOwnershipTests { [Fact] public async Task TemplateSend_CountsMessagesOut_OnTheEndpoint() { await using var context = new RouteContext(); await context.Start(); // seda: buffers without a consumer, and no route touches the endpoint - so the ONLY // possible writer of its statistics is the template itself. using var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("seda:solo", "one"); ((IEndpointStatistics)context.GetEndpoint("seda:solo")).MessagesOut.Should().Be(1, "template-otpravka must be counted like a routed .To()"); } [Fact] public async Task TemplateSend_Failure_CountsBothLegs_OfAnInMemoryBridge() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:boom").Process(_ => throw new InvalidOperationException("no"))); await context.Start(); using var template = new ProducerTemplate(context); template.Start(); Func act = () => template.SendAsync("direct:boom", "one"); await act.Should().ThrowAsync(); // direct: is one endpoint object playing both roles, and each leg records ITS error: // the send leg (CountedSend) and the pipeline leg (StatisticsProcessor). Exactly two - // a third writer would mean a self-recording regression. ((IEndpointStatistics)context.GetEndpoint("direct:boom")).Errors.Should().Be(2, "exactly two legs: the send error + the pipeline error, there must be no third writer"); } [Fact] public async Task RoutedToAnInMemoryBridge_CountsMessagesOutOnce() { // direct:mid is a producer target for the first route AND the From() of the second - // the same endpoint object. MessagesOut is producer-side only: ToProcessor writes 1, // and the consumer wrapper must not add its own on pipeline success. await using var context = new RouteContext(); context.AddRoutes(r => { r.From("direct:in").To("direct:mid"); r.From("direct:mid").To("mock:out"); }); await context.Start(); using var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct:in", "one"); var mid = (IEndpointStatistics)context.GetEndpoint("direct:mid"); mid.MessagesOut.Should().Be(1, "MessagesOut is written by the producer side only"); mid.MessagesIn.Should().Be(1, "MessagesIn is written by the consumer wrapper only"); } [Fact] public async Task RecipientListSend_CountsMessagesOut_LikeARoutedTo() { // The sending EIPs drive a producer directly (no ToProcessor). Their sends must land in // the same producer-side counters - they used to bypass statistics entirely. await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:rl").RecipientList(_ => new[] { "seda:rl-target" })); await context.Start(); using var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct:rl", "one"); ((IEndpointStatistics)context.GetEndpoint("seda:rl-target")).MessagesOut.Should().Be(1, "a send through RecipientList counts as the route's .To()"); } [Fact] public async Task EnrichSend_CountsMessagesOut_LikeARoutedTo() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:enr").Enrich("mock:enr-svc").To("mock:enr-out")); await context.Start(); using var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct:enr", "one"); ((IEndpointStatistics)context.GetEndpoint("mock:enr-svc")).MessagesOut.Should().Be(1, "an enrichment request is a send through the producer too"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/InMemoryTelemetryTests.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/Telemetry/InMemoryTelemetryTests.cs ---- using System.Diagnostics; using NSubstitute; using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; using redb.Route.Processors; using redb.Route.Telemetry; using Xunit; namespace redb.Route.Tests.Telemetry; /// /// Comprehensive telemetry tests using the OpenTelemetry SDK in-memory exporters. /// Verifies both new metric instruments declared in /// and transport spans opened via . /// [Collection("Telemetry")] public sealed class InMemoryTelemetryTests : IDisposable { private readonly List _metrics = []; private readonly List _activities = []; private readonly MeterProvider _meterProvider; private readonly TracerProvider _tracerProvider; public InMemoryTelemetryTests() { _meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(RouteMetrics.MeterName) .AddInMemoryExporter(_metrics) .Build()!; _tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource(RouteActivitySource.SourceName) .AddInMemoryExporter(_activities) .Build()!; } public void Dispose() { _meterProvider.Dispose(); _tracerProvider.Dispose(); } private long Sum(string name) { _meterProvider.ForceFlush(1000); long total = 0; foreach (var m in _metrics.Where(x => x.Name == name)) foreach (var point in m.GetMetricPoints()) { total += m.MetricType switch { MetricType.LongSum => point.GetSumLong(), MetricType.LongSumNonMonotonic => point.GetSumLong(), MetricType.Histogram => point.GetHistogramCount(), _ => 0 }; } return total; } private static IExchange NewExchange(string body = "x") => new Exchange(new Message(body)); // ───────────────────────────────────────────────────────────────────── // Telemetry name is shared by Meter and ActivitySource // ───────────────────────────────────────────────────────────────────── [Fact] public void TelemetryName_IsShared_BetweenMeterAndActivitySource() { RouteMetrics.MeterName.Should().Be(RouteActivitySource.SourceName); RouteMetrics.MeterName.Should().Be(RouteActivitySource.TelemetryName); RouteMetrics.MeterName.Should().Be("redb.Route"); } // ───────────────────────────────────────────────────────────────────── // WireTap // ───────────────────────────────────────────────────────────────────── [Fact] public async Task WireTap_SuccessfulBranch_IncrementsDispatched() { var tap = Substitute.For(); tap.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); var wt = new WireTapProcessor(tap); await wt.Process(NewExchange()); // WireTap is fire-and-forget; allow the background task to run. await Task.Delay(100); Sum("redb.route.wiretap.dispatched").Should().BeGreaterThanOrEqualTo(1); } [Fact] public async Task WireTap_FailingBranch_IncrementsFailed_AndDoesNotPropagate() { var tap = Substitute.For(); tap.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("boom"))); var wt = new WireTapProcessor(tap); Func act = async () => await wt.Process(NewExchange()); await act.Should().NotThrowAsync(); await Task.Delay(100); Sum("redb.route.wiretap.failed").Should().BeGreaterThanOrEqualTo(1); } // ───────────────────────────────────────────────────────────────────── // Multicast // ───────────────────────────────────────────────────────────────────── [Fact] public async Task Multicast_RecordsBranchesCount() { var mc = new MulticastProcessor(parallelProcessing: false); mc.AddTarget(Substitute.For()); mc.AddTarget(Substitute.For()); mc.AddTarget(Substitute.For()); await mc.Process(NewExchange()); Sum("redb.route.multicast.branches").Should().BeGreaterThanOrEqualTo(1); } [Fact] public async Task Multicast_FailingBranch_IncrementsFailedBranches() { var ok = Substitute.For(); var bad = Substitute.For(); bad.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("bad"))); var mc = new MulticastProcessor(parallelProcessing: false); mc.AddTarget(ok); mc.AddTarget(bad); await mc.Process(NewExchange()); Sum("redb.route.multicast.failed_branches").Should().BeGreaterThanOrEqualTo(1); } // ───────────────────────────────────────────────────────────────────── // Idempotent consumer // ───────────────────────────────────────────────────────────────────── [Fact] public async Task Idempotent_NewKey_IncrementsPassed() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var idem = new IdempotentConsumerProcessor(inner, repo, ex => "k-new"); await idem.Process(NewExchange()); Sum("redb.route.idempotent.passed").Should().BeGreaterThanOrEqualTo(1); } [Fact] public async Task Idempotent_DuplicateKey_IncrementsDuplicate() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var idem = new IdempotentConsumerProcessor(inner, repo, ex => "dup-key"); await idem.Process(NewExchange()); await idem.Process(NewExchange()); // duplicate Sum("redb.route.idempotent.duplicate").Should().BeGreaterThanOrEqualTo(1); } // ───────────────────────────────────────────────────────────────────── // Retry // ───────────────────────────────────────────────────────────────────── [Fact] public async Task Retry_EventualSuccess_IncrementsAttemptsAndSuccess() { var calls = 0; var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(_ => { calls++; return calls < 3 ? Task.FromException(new InvalidOperationException("transient")) : Task.CompletedTask; }); var policy = new RetryPolicy { MaxRetries = 5, InitialDelay = TimeSpan.Zero, MaxDelay = TimeSpan.Zero }; var retry = new RetryProcessor(inner, policy); await retry.Process(NewExchange()); Sum("redb.route.retry.attempts").Should().BeGreaterThanOrEqualTo(2); Sum("redb.route.retry.success").Should().BeGreaterThanOrEqualTo(1); } [Fact] public async Task Retry_ExhaustsAttempts_IncrementsExhausted() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("always-fails"))); var policy = new RetryPolicy { MaxRetries = 2, InitialDelay = TimeSpan.Zero, MaxDelay = TimeSpan.Zero }; var retry = new RetryProcessor(inner, policy); var act = () => retry.Process(NewExchange()); await act.Should().ThrowAsync(); Sum("redb.route.retry.exhausted").Should().BeGreaterThanOrEqualTo(1); } // ───────────────────────────────────────────────────────────────────── // Transport span helper // ───────────────────────────────────────────────────────────────────── [Fact] public void StartTransportSpan_EmitsSemanticTags() { using (var act = RouteTelemetryExtensions.StartTransportSpan( "my-queue publish", ActivityKind.Producer, "messaging.system", "rabbitmq", "rabbitmq://localhost/my-queue", destination: "my-queue", operation: "publish")) { act.Should().NotBeNull(); } _tracerProvider.ForceFlush(1000); _activities.Should().ContainSingle(a => a.OperationName == "my-queue publish"); var span = _activities.Single(a => a.OperationName == "my-queue publish"); span.Kind.Should().Be(ActivityKind.Producer); span.Tags.Should().Contain(t => t.Key == "messaging.system" && t.Value == "rabbitmq"); span.Tags.Should().Contain(t => t.Key == "messaging.destination.name" && t.Value == "my-queue"); span.Tags.Should().Contain(t => t.Key == "messaging.operation" && t.Value == "publish"); span.Tags.Should().Contain(t => t.Key == "redb.route.endpoint"); } // ───────────────────────────────────────────────────────────────────── // MeteredProcessor tag enrichment // ───────────────────────────────────────────────────────────────────── [Fact] public async Task MeteredProcessor_EmitsEndpointAndSchemeTags() { var inner = Substitute.For(); var metered = new MeteredProcessor( inner, routeId: "test-route", endpointUri: "http://example.com", endpointScheme: "http"); await metered.Process(NewExchange()); _meterProvider.ForceFlush(1000); var processed = _metrics.SingleOrDefault(m => m.Name == "redb.route.exchanges.processed"); processed.Should().NotBeNull(); var found = false; foreach (var point in processed!.GetMetricPoints()) { var endpointSeen = false; var schemeSeen = false; var routeIdSeen = false; foreach (var tag in point.Tags) { if (tag.Key == "redb.route.endpoint" && Equals(tag.Value, "http://example.com")) endpointSeen = true; if (tag.Key == "redb.route.scheme" && Equals(tag.Value, "http")) schemeSeen = true; if (tag.Key == "redb.route.id" && Equals(tag.Value, "test-route")) routeIdSeen = true; } if (endpointSeen && schemeSeen && routeIdSeen) { found = true; break; } } found.Should().BeTrue("MeteredProcessor must emit redb.route.id, redb.route.endpoint and redb.route.scheme tags"); } // ───────────────────────────────────────────────────────────────────── // Activity exception event (InstrumentedProcessor.ActivityExtensions) // ───────────────────────────────────────────────────────────────────── [Fact] public async Task InstrumentedProcessor_OnFailure_RecordsExceptionEventOnSpan() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("kaboom"))); var ip = new InstrumentedProcessor(inner, "route:test"); var act = () => ip.Process(NewExchange()); await act.Should().ThrowAsync(); _tracerProvider.ForceFlush(1000); var span = _activities.SingleOrDefault(a => a.OperationName == "route:test"); span.Should().NotBeNull(); span!.Events.Should().Contain(e => e.Name == "exception"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/MeteredDslTests.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/Telemetry/MeteredDslTests.cs ---- using System.Collections.Concurrent; using System.Diagnostics.Metrics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// Tests for the .Metered() DSL — inline delegates, inline processors, and block scopes. /// Verifies compilation, execution, metric recording, and cardinality protection. /// [Collection("Telemetry")] public class MeteredDslTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly MeterListener _listener; private readonly ConcurrentBag<(string Name, object Value, KeyValuePair[] Tags)> _measurements = []; public MeteredDslTests() { _listener = new MeterListener(); _listener.InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name == RouteMetrics.MeterName) listener.EnableMeasurementEvents(instrument); }; _listener.SetMeasurementEventCallback((instrument, value, tags, _) => { _measurements.Add((instrument.Name, value, tags.ToArray())); }); _listener.SetMeasurementEventCallback((instrument, value, tags, _) => { _measurements.Add((instrument.Name, value, tags.ToArray())); }); _listener.Start(); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.Stop(); _listener.Dispose(); } private KeyValuePair[] GetTags(string instrumentName) => _measurements.First(m => m.Name == instrumentName).Tags; /// Filter measurements by step tag name — isolates from cross-test noise. private IEnumerable<(string Name, object Value, KeyValuePair[] Tags)> ForStep(string stepName) => _measurements.Where(m => m.Tags.Any(t => t.Key == "redb.route.step" && (string)t.Value! == stepName)); // ── Inline delegate (sync) ── [Fact] public async Task Metered_InlineSync_ExecutesAndRecordsMetrics() { var processed = false; _context.AddRoutes(r => { r.From("direct://metered-sync-in") .Metered("validate", e => processed = true) .To("direct://metered-sync-out"); }); _context.AddRoutes(r => { r.From("direct://metered-sync-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-sync-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); processed.Should().BeTrue(); var step = ForStep("validate").ToList(); step.Should().Contain(m => m.Name == "redb.route.step.processed"); step.Should().Contain(m => m.Name == "redb.route.step.duration"); step.Should().NotContain(m => m.Name == "redb.route.step.failed"); var tags = step.First(m => m.Name == "redb.route.step.processed").Tags; tags.Should().Contain(t => t.Key == "redb.route.step" && (string)t.Value! == "validate"); } // ── Inline delegate (async) ── [Fact] public async Task Metered_InlineAsync_ExecutesAndRecordsMetrics() { var processed = false; _context.AddRoutes(r => { r.From("direct://metered-async-in") .Metered("enrich", async (e, ct) => { await Task.Yield(); processed = true; }) .To("direct://metered-async-out"); }); _context.AddRoutes(r => { r.From("direct://metered-async-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-async-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); processed.Should().BeTrue(); var step = ForStep("enrich").ToList(); step.Should().Contain(m => m.Name == "redb.route.step.processed"); step.Should().Contain(m => m.Name == "redb.route.step.duration"); } // ── Inline IProcessor ── [Fact] public async Task Metered_InlineProcessor_ExecutesAndRecordsMetrics() { var processed = false; var processor = new DelegateProcessor(e => processed = true); _context.AddRoutes(r => { r.From("direct://metered-proc-in") .Metered("transform", processor) .To("direct://metered-proc-out"); }); _context.AddRoutes(r => { r.From("direct://metered-proc-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-proc-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); processed.Should().BeTrue(); ForStep("transform").Should().Contain(m => m.Name == "redb.route.step.processed"); } // ── Block scope ── [Fact] public async Task Metered_BlockScope_WrapsMultipleSteps() { var step1 = false; var step2 = false; _context.AddRoutes(r => { r.From("direct://metered-block-in") .Metered("pipeline") .Process(e => step1 = true) .Process(e => step2 = true) .EndMetered() .To("direct://metered-block-out"); }); _context.AddRoutes(r => { r.From("direct://metered-block-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-block-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); step1.Should().BeTrue(); step2.Should().BeTrue(); // Should record 1 processed count for entire block, not per inner step var step = ForStep("pipeline").ToList(); step.Where(m => m.Name == "redb.route.step.processed").Should().ContainSingle(); step.Where(m => m.Name == "redb.route.step.duration").Should().ContainSingle(); } // ── Block scope with End() ── [Fact] public async Task Metered_BlockScope_EndClosesScope() { var processed = false; _context.AddRoutes(r => { r.From("direct://metered-end-in") .Metered("step-a") .Process(e => processed = true) .End() // generic End() should close Metered too .To("direct://metered-end-out"); }); _context.AddRoutes(r => { r.From("direct://metered-end-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-end-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); processed.Should().BeTrue(); ForStep("step-a").Should().Contain(m => m.Name == "redb.route.step.processed"); } // ── Failure recording ── [Fact] public async Task Metered_FailedStep_RecordsFailureMetric() { _context.AddRoutes(r => { r.From("direct://metered-fail-in") .Metered("will-fail", e => throw new InvalidOperationException("boom")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-fail-in").CreateProducer(); await producer.Start(); try { await producer.Process(new Exchange(new Message("test"))); } catch { // Expected — exception propagates } _listener.RecordObservableInstruments(); var step = ForStep("will-fail").ToList(); step.Should().Contain(m => m.Name == "redb.route.step.failed"); step.Should().NotContain(m => m.Name == "redb.route.step.processed"); step.Should().Contain(m => m.Name == "redb.route.step.duration"); var tags = step.First(m => m.Name == "redb.route.step.failed").Tags; tags.Should().Contain(t => t.Key == "redb.route.step" && (string)t.Value! == "will-fail"); } // ── Duration recording ── [Fact] public async Task Metered_RecordsDurationInMilliseconds() { _context.AddRoutes(r => { r.From("direct://metered-dur-in") .Metered("slow-step", async (e, ct) => await Task.Delay(50, ct)) .To("direct://metered-dur-out"); }); _context.AddRoutes(r => { r.From("direct://metered-dur-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-dur-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); var duration = _measurements.First(m => m.Name == "redb.route.step.duration"); ((double)duration.Value).Should().BeGreaterThan(40); // at least ~50ms } // ── Cardinality protection ── [Fact] public void Metered_DynamicName_ThrowsArgumentException() { var rd = new RouteDefinition(); var act = () => rd.Metered("order-${header.type}"); act.Should().Throw() .WithMessage("*cardinality*"); } [Fact] public void Metered_NullName_ThrowsException() { var rd = new RouteDefinition(); var act = () => rd.Metered(null!); act.Should().Throw(); } [Fact] public void Metered_EmptyName_ThrowsException() { var rd = new RouteDefinition(); var act = () => rd.Metered(""); act.Should().Throw(); } [Fact] public void EndMetered_OutsideScope_ThrowsException() { var rd = new RouteDefinition(); var act = () => rd.EndMetered(); act.Should().Throw() .WithMessage("*Metered*"); } // ── Route ID tag ── [Fact] public async Task Metered_TagsIncludeRouteId() { _context.AddRoutes(r => { r.From("direct://metered-routeid-in") .RouteId("order-route") .Metered("check", e => { }) .To("direct://metered-routeid-out"); }); _context.AddRoutes(r => { r.From("direct://metered-routeid-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-routeid-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); var tags = ForStep("check").First(m => m.Name == "redb.route.step.processed").Tags; tags.Should().Contain(t => t.Key == "redb.route.id" && ((string)t.Value!).Contains("order-route")); } // ── Multiple metered steps ── [Fact] public async Task Metered_MultipleSteps_RecordsSeparateMetrics() { _context.AddRoutes(r => { r.From("direct://metered-multi-in") .Metered("step-a", e => { }) .Metered("step-b", e => { }) .To("direct://metered-multi-out"); }); _context.AddRoutes(r => { r.From("direct://metered-multi-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-multi-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); var stepA = ForStep("step-a").ToList(); var stepB = ForStep("step-b").ToList(); stepA.Should().Contain(m => m.Name == "redb.route.step.processed"); stepB.Should().Contain(m => m.Name == "redb.route.step.processed"); } // ── Traced + Metered composability ── [Fact] public async Task Metered_InsideTraced_BothRecord() { var processed = false; using var activityListener = new System.Diagnostics.ActivityListener { ShouldListenTo = source => source.Name == RouteActivitySource.SourceName, Sample = (ref System.Diagnostics.ActivityCreationOptions _) => System.Diagnostics.ActivitySamplingResult.AllDataAndRecorded }; System.Diagnostics.ActivitySource.AddActivityListener(activityListener); _context.AddRoutes(r => { r.From("direct://metered-traced-in") .Traced("order-span") .Metered("order-validate", e => processed = true) .EndTraced() .To("direct://metered-traced-out"); }); _context.AddRoutes(r => { r.From("direct://metered-traced-out").Process(e => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://metered-traced-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); processed.Should().BeTrue(); ForStep("order-validate").Should().Contain(m => m.Name == "redb.route.step.processed"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/MetricsSnapshotTests.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/Telemetry/MetricsSnapshotTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// — the opt-in, in-process subscriber that makes the OpenTelemetry /// layer readable. The "redb.Route" meter is process-global, so /// keys carry the route id and step tags; tests use unique route ids to stay isolated from /// whatever else the test process measures. /// public sealed class MetricsSnapshotTests { private static async Task Started(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public void Without_registration_there_is_no_snapshot_and_no_listener_tax() { new RouteContext().GetMetricsSnapshot().Should().BeNull( "nobody pays for a per-measurement callback without asking for it"); } [Fact] public async Task A_metered_step_becomes_readable_from_the_process() { var routeId = $"snap-{Guid.NewGuid():N}"; await using var context = new RouteContext(); context.UseMetricsSnapshot(); context.AddRoutes(r => r.From("direct:snap-step").RouteId(routeId) .Metered("work", _ => { })); var producer = await Started(context, "direct:snap-step"); for (var i = 0; i < 3; i++) await producer.Process(new Exchange(new Message("m"))); var snapshot = context.GetMetricsSnapshot()!; snapshot.Value("redb.route.step.processed", routeId, "work").Should().Be(3); var duration = snapshot.Point("redb.route.step.duration", routeId, "work"); duration.Should().NotBeNull(); duration!.Value.Count.Should().Be(3); duration.Value.Min.Should().BeLessThanOrEqualTo(duration.Value.Max); } [Fact] public async Task Parallel_measurements_are_not_lost() { var routeId = $"snap-par-{Guid.NewGuid():N}"; await using var context = new RouteContext(); context.UseMetricsSnapshot(); context.AddRoutes(r => r.From("direct:snap-par").RouteId(routeId) .Metered("hot", _ => { })); var producer = await Started(context, "direct:snap-par"); await Parallel.ForEachAsync( Enumerable.Range(0, 800), new ParallelOptions { MaxDegreeOfParallelism = 8 }, async (_, ct) => await producer.Process(new Exchange(new Message("m")), ct)); context.GetMetricsSnapshot()!.Value("redb.route.step.processed", routeId, "hot") .Should().Be(800, "the accumulator must not drop concurrent increments"); } [Fact] public async Task Registering_twice_keeps_one_subscriber() { await using var context = new RouteContext(); context.UseMetricsSnapshot(); var first = context.GetMetricsSnapshot(); context.UseMetricsSnapshot(); context.GetMetricsSnapshot().Should().BeSameAs(first); } [Fact] public async Task Collected_points_survive_the_context_stopping() { var routeId = $"snap-stop-{Guid.NewGuid():N}"; var context = new RouteContext(); context.UseMetricsSnapshot(); context.AddRoutes(r => r.From("direct:snap-stop").RouteId(routeId) .Metered("tail", _ => { })); var producer = await Started(context, "direct:snap-stop"); await producer.Process(new Exchange(new Message("m"))); var snapshot = context.GetMetricsSnapshot()!; await context.DisposeAsync(); snapshot.Value("redb.route.step.processed", routeId, "tail").Should().Be(1, "an operator inspecting a stopped context still sees what it measured"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/ProcessorMetricsTests.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/Telemetry/ProcessorMetricsTests.cs ---- using System.Collections.Concurrent; using System.Diagnostics.Metrics; using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; using Xunit; namespace redb.Route.Tests.Telemetry; /// /// Tests for processor-level metrics (ProcessorMetrics). /// Verifies that each processor increments the correct counters. /// /// Only lower bounds. A is process state and the processor counters /// carry no route tag, so every measurement of every test in flight lands in the same sum. An /// assertion may therefore say "at least one" (nobody else can subtract) and never "exactly N" or /// "unchanged" — those were the flaky ones. Traces have the discriminator metrics lack /// (redb.route.id on the span, see RouteTelemetryProbe); giving the counters the same /// per-route attribution is a separate piece of work. /// /// [Collection("Telemetry")] public class ProcessorMetricsTests : IDisposable { private readonly MeterListener _listener; private readonly ConcurrentBag<(string Name, long Value)> _measurements = []; public ProcessorMetricsTests() { _listener = new MeterListener(); _listener.InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name == RouteMetrics.MeterName) listener.EnableMeasurementEvents(instrument); }; _listener.SetMeasurementEventCallback((instrument, value, _, _) => { _measurements.Add((instrument.Name, value)); }); _listener.Start(); } public void Dispose() { _listener.Dispose(); } private long Sum(string instrumentName) => _measurements.Where(m => m.Name == instrumentName).Sum(m => m.Value); // ═══════════════════════════════════════════════════════════════════ // Circuit Breaker metrics // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task CircuitBreaker_Tripped_IncrementsMetric() { var failingNext = Substitute.For(); failingNext.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("fail"))); var cb = new CircuitBreakerProcessor(failingNext, failureThreshold: 2); // Trigger 2 failures to trip the breaker for (int i = 0; i < 2; i++) { var ex = new Exchange(new Message("test")); await cb.Process(ex); } _listener.RecordObservableInstruments(); Sum("redb.route.circuitbreaker.tripped").Should().BeGreaterThanOrEqualTo(1); } [Fact] public async Task CircuitBreaker_Rejected_IncrementsMetric() { var failingNext = Substitute.For(); failingNext.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("fail"))); var cb = new CircuitBreakerProcessor(failingNext, failureThreshold: 1, resetTimeout: TimeSpan.FromHours(1)); // Trip the circuit var ex1 = new Exchange(new Message("test")); await cb.Process(ex1); // Next call should be rejected var ex2 = new Exchange(new Message("test")); await cb.Process(ex2); _listener.RecordObservableInstruments(); Sum("redb.route.circuitbreaker.rejected").Should().BeGreaterThanOrEqualTo(1); } // ═══════════════════════════════════════════════════════════════════ // Filter metrics // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Filter_DroppedExchange_IncrementsMetric() { var next = Substitute.For(); var filter = new FilterProcessor(_ => false, next); await filter.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); Sum("redb.route.filter.dropped").Should().BeGreaterThanOrEqualTo(1); await next.DidNotReceive().Process(Arg.Any(), Arg.Any()); } [Fact] public async Task Filter_PassedExchange_ForwardsAndCountsNothingOfItsOwn() { var next = Substitute.For(); var filter = new FilterProcessor(_ => true, next); await filter.Process(new Exchange(new Message("test"))); // The observable claim is the behaviour: a passing predicate forwards. The counter is process // state without a route tag, so "it did not move" can never be proved here — another test's // filter may drop a message in the same instant. See the class remark on lower bounds. await next.Received(1).Process(Arg.Any(), Arg.Any()); } // ═══════════════════════════════════════════════════════════════════ // Splitter metrics // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Splitter_RecordsPartCount() { var target = Substitute.For(); var splitter = new SplitterProcessor( ex => new object[] { "a", "b", "c" }, target); var before = Sum("redb.route.splitter.parts"); await splitter.Process(new Exchange(new Message("test"))); _listener.RecordObservableInstruments(); Sum("redb.route.splitter.parts").Should().BeGreaterThanOrEqualTo(before + 3); } // ═══════════════════════════════════════════════════════════════════ // Debounce metrics // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Debounce_Discarded_IncrementsMetric() { var next = Substitute.For(); var db = new DebounceProcessor(next, _ => "key1", TimeSpan.FromHours(1)); var before = Sum("redb.route.debounce.discarded"); // First message — creates entry, no discard await db.Process(new Exchange(new Message("first"))); // Second message — replaces first, should discard await db.Process(new Exchange(new Message("second"))); _listener.RecordObservableInstruments(); Sum("redb.route.debounce.discarded").Should().BeGreaterThanOrEqualTo(before + 1); db.Dispose(); } [Fact] public async Task Debounce_Flushed_IncrementsMetric() { var next = Substitute.For(); var db = new DebounceProcessor(next, _ => "key1", TimeSpan.FromMilliseconds(50)); await db.Process(new Exchange(new Message("test"))); // Wait well beyond quiet period for the async flush to complete await Task.Delay(500); _listener.RecordObservableInstruments(); // Global counter: just verify _next was actually called (the flush happened) await next.Received(1).Process(Arg.Any(), Arg.Any()); // And the metric was incremented at least once (shared counter across tests) Sum("redb.route.debounce.flushed").Should().BeGreaterThanOrEqualTo(1); db.Dispose(); } // ═══════════════════════════════════════════════════════════════════ // Timeout metrics // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Timeout_Expired_IncrementsMetric() { var slowNext = Substitute.For(); slowNext.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ct = ci.ArgAt(1); await Task.Delay(TimeSpan.FromSeconds(5), ct); }); var tp = new TimeoutProcessor(slowNext, TimeSpan.FromMilliseconds(100), "test-route"); var before = Sum("redb.route.timeout.expired"); var exchange = new Exchange(new Message("test")); await Assert.ThrowsAsync(() => tp.Process(exchange, CancellationToken.None)); _listener.RecordObservableInstruments(); Sum("redb.route.timeout.expired").Should().BeGreaterThanOrEqualTo(before + 1); } // ═══════════════════════════════════════════════════════════════════ // Throttle metrics // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Throttle_Delayed_IncrementsWhenSlotsExhausted() { var next = Substitute.For(); // Slow processing to occupy the single slot next.Process(Arg.Any(), Arg.Any()) .Returns(Task.Delay(200)); var throttle = new ThrottleProcessor(next, maxPerPeriod: 1, period: TimeSpan.FromSeconds(10)); var before = Sum("redb.route.throttle.delayed"); // First call takes the slot; second will be delayed var t1 = throttle.Process(new Exchange(new Message("1"))); await Task.Delay(10); // let t1 acquire the semaphore var t2 = Task.Run(() => throttle.Process(new Exchange(new Message("2")))); // Wait for t2 to be counted rather than for a fixed 10 ms: on a loaded machine t2 may reach the slot check // later (findings register row 18). The bound only keeps a broken run from hanging. var deadline = DateTime.UtcNow.AddSeconds(5); do { _listener.RecordObservableInstruments(); if (Sum("redb.route.throttle.delayed") >= before + 1) break; await Task.Delay(10); } while (DateTime.UtcNow < deadline); Sum("redb.route.throttle.delayed").Should().BeGreaterThanOrEqualTo(before + 1); await t1; throttle.Dispose(); // t2 may throw ObjectDisposedException — that's expected } } Path: redb-route/tests/redb.Route.Tests/Telemetry/RouteMetricsCountExchangesTests.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/Telemetry/RouteMetricsCountExchangesTests.cs ---- using System.Diagnostics.Metrics; using AwesomeAssertions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// The route metrics and the route span count exchanges, as METRICS.md says and the endpoint statistics do: one /// exchange redelivered by an error handler is one measurement and one span, with its final outcome. They sat inside /// the handlers declared on the route builder, so every redelivery attempt went through them again — /// redb.route.exchanges.failed grew by the attempts, not by the exchanges. /// public class RouteMetricsCountExchangesTests { private sealed class Counts : IDisposable { private readonly MeterListener _listener = new(); private readonly string _routeId; public int Processed; public int Failed; public Counts(string routeId) { _routeId = routeId; _listener.InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name == RouteMetrics.MeterName && instrument.Name is "redb.route.exchanges.processed" or "redb.route.exchanges.failed") listener.EnableMeasurementEvents(instrument); }; _listener.SetMeasurementEventCallback((instrument, value, tags, _) => { foreach (var tag in tags) if (tag.Key == "redb.route.id" && Equals(tag.Value, _routeId)) { if (instrument.Name == "redb.route.exchanges.processed") Interlocked.Add(ref Processed, (int)value); else Interlocked.Add(ref Failed, (int)value); } }); _listener.Start(); } public void Dispose() => _listener.Dispose(); } private static async Task Route(string routeId, bool handled) { var context = new RouteContext($"metrics-{routeId}"); context.AddComponent(new DirectComponent()); context.AddRoutes(r => { var onException = r.OnException().MaximumRedeliveries(2).RedeliveryDelay(TimeSpan.Zero); if (handled) onException.Handled(); r.From($"direct://{routeId}").RouteId(routeId).Process(_ => throw new InvalidOperationException("down")); }); await context.Start(); return context; } private static async Task Send(RouteContext context, string routeId) { var template = new ProducerTemplate(context); template.Start(); try { await template.SendAsync($"direct://{routeId}", "x"); } catch (InvalidOperationException) { } finally { await template.DisposeAsync(); } } [Fact] public async Task A_redelivered_exchange_that_fails_is_one_failed_exchange_and_one_span() { var routeId = $"metrics-failed-{Guid.NewGuid():N}"; using var counts = new Counts(routeId); using var spans = RouteTelemetryProbe.ForRouteIdPrefix(routeId); await using var context = await Route(routeId, handled: false); await Send(context, routeId); counts.Failed.Should().Be(1, "three attempts are one exchange"); counts.Processed.Should().Be(0); spans.Activities.Should().ContainSingle(); } [Fact] public async Task A_redelivered_exchange_the_handler_handles_is_one_processed_exchange() { var routeId = $"metrics-handled-{Guid.NewGuid():N}"; using var counts = new Counts(routeId); await using var context = await Route(routeId, handled: true); await Send(context, routeId); counts.Processed.Should().Be(1); counts.Failed.Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/RouteTelemetryProbe.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/Telemetry/RouteTelemetryProbe.cs ---- using System.Diagnostics; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// Collects the spans of one test from the process-wide route . /// /// An is process state: filtering by source name alone (the obvious /// spelling, and the one used until 2026-09-01) makes a test see the spans of every route any other /// test is running at that moment. That is why the telemetry tests flaked under a full parallel run /// and were always green in isolation — six clean runs of the untouched tree produced two failures. /// Serialising the tests by collection cannot help: the listener is not per collection. /// /// /// So the probe keeps the source filter (there is only one source) and adds the real discriminator: /// a predicate over the finished activity, normally its redb.route.id tag. Spans of other /// tests are seen and dropped. /// /// /// One copy: a connector's test project links this file /// (<Compile Include="../redb.Route.Tests/Telemetry/RouteTelemetryProbe.cs" Link="Shared/RouteTelemetryProbe.cs" />) /// and imports redb.Route.Tests.Telemetry. /// /// internal sealed class RouteTelemetryProbe : IDisposable { /// Tag every route span carries: the id of the route the exchange was travelling. public const string RouteIdTag = "redb.route.id"; /// Tag a transport span carries: the (sanitized) endpoint URI. public const string EndpointTag = "redb.route.endpoint"; private readonly ActivityListener _listener; private readonly List _collected = []; // A plain object as the lock. private readonly object _sync = new(); private readonly Func _isMine; /// Collects the finished spans accepts. public RouteTelemetryProbe(Func isMine) { _isMine = isMine ?? throw new ArgumentNullException(nameof(isMine)); _listener = new ActivityListener { ShouldListenTo = source => source.Name == RouteActivitySource.SourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, ActivityStopped = Collect, }; ActivitySource.AddActivityListener(_listener); } /// Collects spans whose redb.route.id begins with . public static RouteTelemetryProbe ForRouteIdPrefix(string routeIdPrefix) => new(activity => Tag(activity, RouteIdTag)?.StartsWith(routeIdPrefix, StringComparison.Ordinal) == true); /// Collects spans whose redb.route.endpoint contains (a port, a path). public static RouteTelemetryProbe ForEndpointContaining(string fragment) => new(activity => Tag(activity, EndpointTag)?.Contains(fragment, StringComparison.Ordinal) == true); /// The spans collected so far, oldest first. public IReadOnlyList Activities { get { lock (_sync) return [.. _collected]; } } /// Value of on , or null. public static string? Tag(Activity activity, string tag) => activity.GetTagItem(tag)?.ToString(); /// public void Dispose() => _listener.Dispose(); // ActivityStopped fires on whatever thread finished the span, and several routes may finish at once. private void Collect(Activity activity) { if (!_isMine(activity)) return; lock (_sync) _collected.Add(activity); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/RouteTracingTests.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/Telemetry/RouteTracingTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Telemetry; /// /// The route-level .Tracing() switch: a route may opt out of the global /// RouteEngineOptions.EnableTelemetry, so a service route (a health check, a metric summary /// on a timer) opens no span of its own and its single-span traces stop crowding the collector. /// [Collection("Telemetry")] public class RouteTracingTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.Stop(); GC.SuppressFinalize(this); } [Fact] public async Task TracingFalse_OpensNoRouteSpan() { using var probe = RouteTelemetryProbe.ForRouteIdPrefix("direct-notrace-"); _context.AddRoutes(r => r.From("direct://notrace-in") .Tracing(false) .Process(e => e.In.Body = "done")); await _context.Start(); var producer = _context.GetEndpoint("direct://notrace-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("x"))); probe.Activities.Should().BeEmpty("the route opted out of tracing"); } [Fact] public async Task TracingTrue_OpensTheRouteSpan() { using var probe = RouteTelemetryProbe.ForRouteIdPrefix("direct-traceon-"); _context.AddRoutes(r => r.From("direct://traceon-in") .Tracing(true) .Process(e => e.In.Body = "done")); await _context.Start(); var producer = _context.GetEndpoint("direct://traceon-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("x"))); probe.Activities.Should().Contain(a => (RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.RouteIdTag) ?? "").StartsWith("direct-traceon-"), "the route span carries its route id"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/SpanTagTests.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/Telemetry/SpanTagTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// .SpanTag(key, value, target): which span receives the attribute, what value it gets, when nothing is set, /// and which keys are refused. Every test opens a root span of a source of its own — standing for the host's span of /// a request — and collects only the route spans of that trace, so parallel tests do not interfere. The inbound span /// is opened the way a connector opens it ( with /// ), since no core component has one. /// [Collection("Telemetry")] public sealed class SpanTagTests : IAsyncLifetime { private const string HostSourceName = "redb.Route.Tests.SpanTag.Host"; private static readonly ActivitySource Host = new(HostSourceName); private readonly RouteContext _context = new(); private readonly ActivityListener _hostListener; private ActivityTraceId _traceId; private readonly RouteTelemetryProbe _probe; public SpanTagTests() { _hostListener = new ActivityListener { // By name, not `source == Host`: the first instance initializes Host from inside AddActivityListener, // and the new source asks this listener while the field is still null. ShouldListenTo = source => source.Name == HostSourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, }; ActivitySource.AddActivityListener(_hostListener); _probe = new RouteTelemetryProbe(activity => activity.TraceId == _traceId); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); _probe.Dispose(); _hostListener.Dispose(); } // ── Enclosing ── [Fact] public async Task Enclosing_TagsTheRouteSpan() { _context.AddRoutes(r => r.From("direct://spantag-route") .SpanTag("sap.order.id", new HeaderExpression("orderNo")) .Process(_ => { })); await _context.Start(); using (var host = StartHost()) await Send("direct://spantag-route", headers: new() { ["orderNo"] = "A-42" }); RouteSpan().GetTagItem("sap.order.id").Should().Be("A-42"); } [Fact] public async Task Enclosing_InsideTraced_TagsTheTracedSpanOnly() { _context.AddRoutes(r => r.From("direct://spantag-traced") .Traced("sap-ack") .SpanTag("sap.order.id", "fixed") .EndTraced()); await _context.Start(); using (StartHost()) await Send("direct://spantag-traced"); Span("sap-ack").GetTagItem("sap.order.id").Should().Be("fixed"); RouteSpan().GetTagItem("sap.order.id").Should().BeNull("the nearest span of the engine receives it"); } [Fact] public async Task Value_FromATemplateOverAProperty() { _context.AddRoutes(r => r.From("direct://spantag-template") .SetProperty("batch", "b-7") .SpanTag("flow.batch", RouteBuilder.Expr("batch ${property.batch}"))); await _context.Start(); using (StartHost()) await Send("direct://spantag-template"); RouteSpan().GetTagItem("flow.batch").Should().Be("batch b-7"); } [Fact] public async Task Value_KeepsItsPrimitiveType() { _context.AddRoutes(r => r.From("direct://spantag-typed") .SpanTag("order.lines", new HeaderExpression("lines"))); await _context.Start(); using (StartHost()) await Send("direct://spantag-typed", headers: new() { ["lines"] = 3 }); RouteSpan().GetTagItem("order.lines").Should().Be(3); } [Fact] public async Task Value_NullOrEmpty_SetsNothing() { _context.AddRoutes(r => r.From("direct://spantag-empty") .SpanTag("order.missing", new HeaderExpression("absent")) .SpanTag("order.empty", new HeaderExpression("blank"))); await _context.Start(); using (StartHost()) await Send("direct://spantag-empty", headers: new() { ["blank"] = "" }); var span = RouteSpan(); span.GetTagItem("order.missing").Should().BeNull(); span.GetTagItem("order.empty").Should().BeNull(); } [Fact] public async Task Value_ThatFailsToEvaluate_SetsNothing_AndTheExchangeSucceeds() { _context.AddRoutes(r => r.From("direct://spantag-failing") .SpanTag("order.id", new ThrowingExpression()) .SetHeader("after", true)); await _context.Start(); IExchange exchange; using (StartHost()) exchange = await Send("direct://spantag-failing"); exchange.Exception.Should().BeNull("telemetry does not change the outcome of the message"); exchange.In.Headers.Should().ContainKey("after"); RouteSpan().GetTagItem("order.id").Should().BeNull(); } [Fact] public async Task RouteTracingOff_SetsNothing_NotEvenOnTheTransportSpan_AndDoesNotEvaluate() { var evaluations = new CountingExpression("v"); _context.AddRoutes(r => r.From("direct://spantag-untraced") .Tracing(false) .SpanTag("order.id", evaluations)); await _context.Start(); using (StartHost()) using (var inbound = StartInbound()) await Send("direct://spantag-untraced"); evaluations.Count.Should().Be(0, "without a span to write to, the value is not evaluated"); Span("orders receive").GetTagItem("order.id").Should().BeNull("the transport span is not the enclosing one"); } // ── Inbound ── [Fact] public async Task Inbound_TagsTheTransportSpan_NotTheRouteNorTheHost() { _context.AddRoutes(r => r.From("direct://spantag-inbound") .SpanTag("sap.order.id", new HeaderExpression("orderNo"), SpanTarget.Inbound)); await _context.Start(); Activity host; using (host = StartHost()) using (StartInbound()) await Send("direct://spantag-inbound", headers: new() { ["orderNo"] = "A-1" }); Span("orders receive").GetTagItem("sap.order.id").Should().Be("A-1"); RouteSpan().GetTagItem("sap.order.id").Should().BeNull(); host.GetTagItem("sap.order.id").Should().BeNull("the host's span belongs to the host"); } [Fact] public async Task Inbound_InARouteCalledThroughDirect_IsTheCallersInboundSpan() { _context.AddRoutes(r => r.From("direct://spantag-caller").To("direct://spantag-callee")); _context.AddRoutes(r => r.From("direct://spantag-callee") .SpanTag("sap.order.id", "from-callee", SpanTarget.Inbound)); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-caller"); Span("orders receive").GetTagItem("sap.order.id").Should().Be("from-callee"); } [Fact] public async Task Inbound_WithoutATransportSpan_SetsNothing() { _context.AddRoutes(r => r.From("direct://spantag-noinbound") .SpanTag("sap.order.id", "x", SpanTarget.Inbound)); await _context.Start(); using (StartHost()) await Send("direct://spantag-noinbound"); _probe.Activities.Should().NotContain(a => a.GetTagItem("sap.order.id") != null); } [Fact] public async Task Inbound_FromADetachedBranch_AfterTheRequestEnded_SetsNothing() { var requestEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var tapDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _context.AddRoutes(r => r.From("direct://spantag-main").WireTap("direct://spantag-tap")); _context.AddRoutes(r => r.From("direct://spantag-tap") .Process(async (_, ct) => await requestEnded.Task.WaitAsync(ct)) .SpanTag("sap.order.id", "late", SpanTarget.Inbound) .Process(_ => tapDone.TrySetResult())); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-main"); requestEnded.SetResult(); await tapDone.Task.WaitAsync(TimeSpan.FromSeconds(5)); Span("orders receive").GetTagItem("sap.order.id").Should().BeNull("the span had ended when the branch ran"); } // ── In an OnException body ── [Fact] public async Task InABuildersOnException_Inbound_TagsTheTransportSpanOfTheFailedRequest() { _context.AddRoutes(r => { r.OnException().Handled(true) .SpanTag("sap.order.id", new PropertyExpression("orderNo"), SpanTarget.Inbound); r.From("direct://spantag-failed") .Process(e => { e.Properties["orderNo"] = "A-500"; throw new InvalidOperationException("boom"); }); }); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-failed"); Span("orders receive").GetTagItem("sap.order.id").Should().Be("A-500", "a trace that ended in a failure is found by the business key too"); } [Fact] public async Task InARoutesOnException_Inbound_TagsTheTransportSpan() { _context.AddRoutes(r => r.From("direct://spantag-failed-route") .OnException().Handled(true) .SpanTag("sap.order.id", new PropertyExpression("orderNo"), SpanTarget.Inbound) .End() .Process(e => { e.Properties["orderNo"] = "A-501"; throw new InvalidOperationException("boom"); })); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-failed-route"); Span("orders receive").GetTagItem("sap.order.id").Should().Be("A-501"); } [Fact] public async Task InAnOnException_Enclosing_TagsTheRouteSpan() { _context.AddRoutes(r => { r.OnException().Handled(true) .SpanTag("sap.order.id", new PropertyExpression("orderNo")); r.From("direct://spantag-failed-enclosing") .Process(e => { e.Properties["orderNo"] = "A-502"; throw new InvalidOperationException("boom"); }); }); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-failed-enclosing"); RouteSpan().GetTagItem("sap.order.id").Should().Be("A-502"); } [Fact] public async Task InTheCallersOnException_AFailureOfARouteCalledThroughDirect_TagsTheInboundSpan() { _context.AddRoutes(r => { r.OnException().Handled(true) .SpanTag("sap.order.id", new PropertyExpression("orderNo"), SpanTarget.Inbound); r.From("direct://spantag-failed-caller").To("direct://spantag-failed-callee"); }); _context.AddRoutes(r => r.From("direct://spantag-failed-callee") .Process(e => { e.Properties["orderNo"] = "A-503"; throw new InvalidOperationException("boom"); })); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-failed-caller"); Span("orders receive").GetTagItem("sap.order.id").Should().Be("A-503"); } [Fact] public async Task InARouteConfigurationsOnException_Inbound_TagsTheTransportSpan() { // Handlers declared apart from the routes: the handler's steps are compiled into the failed route, so the // inbound span of its request is theirs to tag. _context.AddRouteConfiguration(c => c.OnException().Handled(true) .SpanTag("sap.order.id", new PropertyExpression("orderNo"), SpanTarget.Inbound)); _context.AddRoutes(r => r.From("direct://spantag-failed-configuration") .Process(e => { e.Properties["orderNo"] = "A-504"; throw new InvalidOperationException("boom"); })); await _context.Start(); using (StartHost()) using (StartInbound()) await Send("direct://spantag-failed-configuration"); Span("orders receive").GetTagItem("sap.order.id").Should().Be("A-504"); } // ── Keys and literals ── [Theory] [InlineData("redb.route.id")] [InlineData("http.request.method")] [InlineData("messaging.destination.name")] [InlineData("exception.message")] [InlineData("sap.api.token")] [InlineData("order.password")] [InlineData("${header.key}")] [InlineData("Order.Id")] [InlineData("order..id")] [InlineData("order id")] public void Key_IsRefusedWhenTheRouteIsBuilt(string key) { var act = () => new RouteDefinition().From("direct://spantag-key").SpanTag(key, "v"); act.Should().Throw(); } [Fact] public void Literal_Empty_IsRefused() { var act = () => new RouteDefinition().From("direct://spantag-literal").SpanTag("order.id", ""); act.Should().Throw(); } [Fact] public void Literal_IsNotATemplate() { var definition = new RouteDefinition(); definition.From("direct://spantag-literal-template").SpanTag("order.text", "${header.x}"); definition.Outputs.OfType().Single().Value.Should().BeOfType(); } // ── Helpers ── private Activity StartHost() { var host = Host.StartActivity("host-request", ActivityKind.Server) ?? throw new InvalidOperationException("The test's own listener must sample the host span."); _traceId = host.TraceId; return host; } // The span a consumer opens around the route; HostRequest keeps the host span as its parent. private TransportSpan StartInbound() => RouteTelemetryExtensions.StartConsumerSpan( _context, "orders receive", ActivityKind.Consumer, "messaging.system", "test", "test://orders", null, static (_, _) => null, InboundParent.HostRequest); private async Task Send(string uri, Dictionary? headers = null) { var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); var message = new Message("body"); foreach (var (key, value) in headers ?? []) message.Headers[key] = value; var exchange = new Exchange(message); await producer.Process(exchange); return exchange; } private Activity RouteSpan() => _probe.Activities.Single(a => a.OperationName.StartsWith("route:", StringComparison.Ordinal)); private Activity Span(string name) => _probe.Activities.Single(a => a.OperationName == name); private sealed class ThrowingExpression : Expression { public override T Evaluate(IExchange exchange) => throw new FormatException("not a number"); public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException(); } private sealed class CountingExpression(object value) : Expression { private int _count; public int Count => Volatile.Read(ref _count); public override T Evaluate(IExchange exchange) { Interlocked.Increment(ref _count); return (T)value; } public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException(); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/TelemetryCollection.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/Telemetry/TelemetryCollection.cs ---- namespace redb.Route.Tests.Telemetry; /// /// The classes that listen to the route's ActivitySource and Meter, which are process-wide. Their own classes run one /// after another, and since the collection disables parallelization they also never run beside any other test: a span /// or a measurement of a test running at the same time cannot reach their exporters, and their listeners cannot change /// what another test's code records (findings register row 44). /// [CollectionDefinition("Telemetry", DisableParallelization = true)] public class TelemetryCollection; Path: redb-route/tests/redb.Route.Tests/Telemetry/TelemetryProcessorTests.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/Telemetry/TelemetryProcessorTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// Tests for and . /// [Collection("Telemetry")] public class TelemetryProcessorTests { [Fact] public async Task InstrumentedProcessor_DelegatesToInner() { var called = false; var inner = new DelegateProcessor(_ => called = true); var sut = new InstrumentedProcessor(inner, "test-op"); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); called.Should().BeTrue(); } [Fact] public async Task InstrumentedProcessor_PropagatesException() { var inner = new DelegateProcessor(async (_, _) => { throw new InvalidOperationException("traced failure"); }); var sut = new InstrumentedProcessor(inner, "failing-op"); var exchange = new Exchange(new Message { Body = "data" }); var act = () => sut.Process(exchange); await act.Should().ThrowAsync() .WithMessage("traced failure"); } [Fact] public async Task MeteredProcessor_DelegatesToInner() { var called = false; var inner = new DelegateProcessor(_ => called = true); var sut = new MeteredProcessor(inner, "test-route"); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); called.Should().BeTrue(); } [Fact] public async Task MeteredProcessor_PropagatesException() { var inner = new DelegateProcessor(async (_, _) => { throw new InvalidOperationException("metered failure"); }); var sut = new MeteredProcessor(inner, "test-route"); var exchange = new Exchange(new Message { Body = "data" }); var act = () => sut.Process(exchange); await act.Should().ThrowAsync() .WithMessage("metered failure"); } [Fact] public void RouteActivitySource_HasCorrectName() { RouteActivitySource.Source.Name.Should().Be("redb.Route"); } [Fact] public void RouteMetrics_MeterName_IsCorrect() { RouteMetrics.MeterName.Should().Be("redb.Route"); } /// The span's correlation tag comes from the CamelCorrelationId property, as Camel keeps it. [Fact] public async Task InstrumentedProcessor_TagsCorrelationId_FromTheProperty() { var operation = "correlation-op-" + Guid.NewGuid().ToString("N"); string? tag = null; using var listener = new System.Diagnostics.ActivityListener { ShouldListenTo = s => s.Name == RouteActivitySource.SourceName, Sample = (ref System.Diagnostics.ActivityCreationOptions _) => System.Diagnostics.ActivitySamplingResult.AllDataAndRecorded, ActivityStopped = a => { if (a.OperationName == operation) tag = a.GetTagItem("redb.correlation.id") as string; }, }; System.Diagnostics.ActivitySource.AddActivityListener(listener); var exchange = new Exchange(new Message("data")); exchange.Properties[ExchangePropertyKeys.CorrelationId] = "parent-1"; exchange.In.Headers["CamelCorrelationId"] = "from-a-header"; await new InstrumentedProcessor(new DelegateProcessor(_ => { }), operation).Process(exchange); tag.Should().Be("parent-1"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/TracedDslTests.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/Telemetry/TracedDslTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// Tests for the .Traced() DSL — inline delegates, inline processors, and block scopes. /// Verifies compilation, execution, Activity creation, and expression template support. /// [Collection("Telemetry")] public class TracedDslTests : IAsyncLifetime { private readonly RouteContext _context = new(); // Every route of this class consumes from direct://traced-…, so its spans carry a route id with // that prefix. The probe drops the spans of routes other tests are running at the same time; an // activity listener is process state, so filtering by source name alone would collect theirs too. private readonly RouteTelemetryProbe _probe = RouteTelemetryProbe.ForRouteIdPrefix("direct-traced-"); private IReadOnlyList _completedActivities => _probe.Activities; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.Stop(); _probe.Dispose(); } // ── Inline delegate (sync) ── [Fact] public async Task Traced_InlineSync_ExecutesAndCreatesSpan() { var processed = false; _context.AddRoutes(r => { r.From("direct://traced-sync-in") .Traced("validate-order", e => { processed = true; }) .To("direct://traced-sync-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-sync-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-sync-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); processed.Should().BeTrue(); received.Should().NotBeNull(); _completedActivities.Should().Contain(a => a.DisplayName == "validate-order"); } // ── Inline delegate (async) ── [Fact] public async Task Traced_InlineAsync_ExecutesAndCreatesSpan() { var processed = false; _context.AddRoutes(r => { r.From("direct://traced-async-in") .Traced("enrich-data", async (e, ct) => { await Task.Delay(1, ct); processed = true; }) .To("direct://traced-async-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-async-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-async-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); processed.Should().BeTrue(); received.Should().NotBeNull(); _completedActivities.Should().Contain(a => a.DisplayName == "enrich-data"); } // ── Inline IProcessor ── [Fact] public async Task Traced_InlineProcessor_ExecutesAndCreatesSpan() { var processed = false; var inner = new DelegateProcessor(_ => processed = true); _context.AddRoutes(r => { r.From("direct://traced-proc-in") .Traced("transform-step", inner) .To("direct://traced-proc-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-proc-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-proc-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); processed.Should().BeTrue(); received.Should().NotBeNull(); _completedActivities.Should().Contain(a => a.DisplayName == "transform-step"); } // ── Block scope ── [Fact] public async Task Traced_BlockScope_WrapsMultipleStepsInSingleSpan() { var step1 = false; var step2 = false; _context.AddRoutes(r => { r.From("direct://traced-block-in") .Traced("order-pipeline") .Process(e => step1 = true) .Process(e => step2 = true) .EndTraced() .To("direct://traced-block-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-block-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-block-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); step1.Should().BeTrue(); step2.Should().BeTrue(); received.Should().NotBeNull(); _completedActivities.Should().Contain(a => a.DisplayName == "order-pipeline"); } // ── Block scope with End() ── [Fact] public async Task Traced_BlockScope_EndAlsoWorks() { var executed = false; _context.AddRoutes(r => { r.From("direct://traced-end-in") .Traced("my-block") .Process(e => executed = true) .End() .To("direct://traced-end-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-end-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-end-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); executed.Should().BeTrue(); received.Should().NotBeNull(); _completedActivities.Should().Contain(a => a.DisplayName == "my-block"); } // ── Expression template in span name ── [Fact] public async Task Traced_ExpressionInName_ResolvesAtRuntime() { #pragma warning disable CS0618 // v1 DSL — Traced expression templates require v1 semantics _context.AddRoutes((InlineRouteBuilder r) => { r.From("direct://traced-expr-in") .Traced("process-${header.orderType}", e => { e.In.Body = "processed"; }) .To("direct://traced-expr-out"); }); #pragma warning restore CS0618 IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-expr-out") .Process(e => received = e); }); await _context.Start(); var msg = new Message("data"); msg.Headers["orderType"] = "PREMIUM"; var exchange = new Exchange(msg); var producer = _context.GetEndpoint("direct://traced-expr-in").CreateProducer(); await producer.Start(); await producer.Process(exchange); received.Should().NotBeNull(); received!.In.Body.Should().Be("processed"); _completedActivities.Should().Contain(a => a.DisplayName == "process-PREMIUM"); } // ── Block scope with expression ── [Fact] public async Task Traced_BlockScope_ExpressionInName() { #pragma warning disable CS0618 // v1 DSL — Traced expression templates require v1 semantics _context.AddRoutes((InlineRouteBuilder r) => { r.From("direct://traced-block-expr-in") .Traced("pipeline-${header.region}") .SetHeader("processed", "yes") .EndTraced() .To("direct://traced-block-expr-out"); }); #pragma warning restore CS0618 IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-block-expr-out") .Process(e => received = e); }); await _context.Start(); var msg = new Message("data"); msg.Headers["region"] = "EU"; var exchange = new Exchange(msg); var producer = _context.GetEndpoint("direct://traced-block-expr-in").CreateProducer(); await producer.Start(); await producer.Process(exchange); received.Should().NotBeNull(); received!.In.Headers["processed"].Should().Be("yes"); _completedActivities.Should().Contain(a => a.DisplayName == "pipeline-EU"); } // ── Multiple Traced steps ── [Fact] public async Task Traced_MultipleInline_AllCreateSpans() { _context.AddRoutes(r => { r.From("direct://traced-multi-in") .Traced("step-1", e => e.In.Headers["s1"] = "done") .Traced("step-2", e => e.In.Headers["s2"] = "done") .Traced("step-3", e => e.In.Headers["s3"] = "done") .To("direct://traced-multi-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-multi-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-multi-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); received.Should().NotBeNull(); received!.In.Headers["s1"].Should().Be("done"); received.In.Headers["s2"].Should().Be("done"); received.In.Headers["s3"].Should().Be("done"); _completedActivities.Should().Contain(a => a.DisplayName == "step-1"); _completedActivities.Should().Contain(a => a.DisplayName == "step-2"); _completedActivities.Should().Contain(a => a.DisplayName == "step-3"); } // ── Nested: Block inside inline ── [Fact] public async Task Traced_Nested_BlockInsideRoute() { _context.AddRoutes(r => { r.From("direct://traced-nested-in") .Traced("outer-block") .Traced("inner-step", e => e.In.Body = "nested") .EndTraced() .To("direct://traced-nested-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-nested-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-nested-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); received.Should().NotBeNull(); received!.In.Body.Should().Be("nested"); _completedActivities.Should().Contain(a => a.DisplayName == "outer-block"); _completedActivities.Should().Contain(a => a.DisplayName == "inner-step"); } // ── Error handling inside traced ── [Fact] public async Task Traced_Exception_PropagatesAndRecordsOnSpan() { _context.AddRoutes(r => { r.From("direct://traced-error-in") .Traced("failing-step", e => { throw new InvalidOperationException("traced failure"); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-error-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); // InstrumentedProcessor records but rethrows — but route-level handler catches // The exchange should have the exception set try { await producer.Process(exchange); } catch { // Expected — exception propagates } _completedActivities.Should().Contain(a => a.DisplayName == "failing-step"); } // ── Validation ── [Fact] public void Traced_NullSpanName_Throws() { var rd = new RouteDefinition(); var act = () => rd.Traced(null!, e => { }); act.Should().Throw(); } [Fact] public void Traced_EmptySpanName_Throws() { var rd = new RouteDefinition(); var act = () => rd.Traced("", e => { }); act.Should().Throw(); } [Fact] public void EndTraced_OutsideScope_Throws() { var rd = new RouteDefinition(); var act = () => rd.EndTraced(); act.Should().Throw() .WithMessage("*Traced*scope*"); } // ── Body modification flows through ── [Fact] public async Task Traced_BodyModification_FlowsThrough() { _context.AddRoutes(r => { r.From("direct://traced-flow-in") .Traced("step-a", e => e.In.Body = "modified-by-a") .Traced("step-b", e => { var prev = e.In.Body?.ToString(); e.In.Body = prev + "+b"; }) .To("direct://traced-flow-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://traced-flow-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://traced-flow-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("original"))); received.Should().NotBeNull(); received!.In.Body.Should().Be("modified-by-a+b"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/TransportSpanSanitizationTests.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/Telemetry/TransportSpanSanitizationTests.cs ---- using System.Diagnostics; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// The transport-span helper is the one funnel every connector's Client/Consumer span goes /// through. redb.route.endpoint was already sanitized; messaging.destination.name /// used to carry the raw destination — with the userinfo password when the URL had one. /// [Collection("Telemetry")] public class TransportSpanSanitizationTests { [Fact] public void Destination_IsSanitized() { using var probe = new RouteTelemetryProbe(a => a.DisplayName == "sanitize-probe"); using (var activity = RouteTelemetryExtensions.StartTransportSpan( "sanitize-probe", ActivityKind.Client, "http.method", "POST", endpointUri: "http:partner.example/orders", destination: "http://edi:s3cr3t@partner.example/orders?apiKey=k123")) { activity.Should().NotBeNull(); } var span = probe.Activities.Should().ContainSingle().Subject; var destination = RouteTelemetryProbe.Tag(span, "messaging.destination.name"); destination.Should().NotBeNull(); destination.Should().NotContain("s3cr3t", "the userinfo password must not go into spans"); destination.Should().NotContain("k123", "a sensitive query parameter is masked too"); destination.Should().Contain("partner.example/orders", "masking keeps the format, it does not erase the address"); } [Fact] public void PlainDestination_PassesThroughUnchanged() { using var probe = new RouteTelemetryProbe(a => a.DisplayName == "sanitize-probe-plain"); using (RouteTelemetryExtensions.StartTransportSpan( "sanitize-probe-plain", ActivityKind.Producer, "messaging.system", "kafka", endpointUri: "kafka:orders", destination: "orders")) { } var span = probe.Activities.Should().ContainSingle().Subject; RouteTelemetryProbe.Tag(span, "messaging.destination.name").Should().Be("orders", "non-URI destinations (queue/topic names) must stay byte for byte"); } } Path: redb-route/tests/redb.Route.Tests/Telemetry/TransportTraceContractTests.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/Telemetry/TransportTraceContractTests.cs ---- using System.Diagnostics; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Tests.Telemetry; /// /// The tracing contract every transport shares, kept in the core once: an inbound span takes its parent from the /// message or is a root, never a child of the receiving thread's ambient activity; the sender's baggage comes back; /// the context goes out on a send; a failed call marks its span; and EnableTelemetry=false opens no transport /// span either, so a trace never holds one without its route. /// public class TransportTraceContractTests { private static readonly TraceHeaderReader> Read = static (headers, name) => headers.TryGetValue(name, out var value) ? value : null; private static readonly TraceHeaderWriter> Write = static (headers, name, value) => headers[name] = value; private static string Endpoint() => $"probe://contract-{Guid.NewGuid():N}"; private static TransportSpan Receive(Dictionary headers, string endpoint, InboundParent parent = InboundParent.Carrier, global::redb.Route.Core.RouteContext? context = null) => RouteTelemetryExtensions.StartConsumerSpan(context, "orders receive", ActivityKind.Consumer, "messaging.system", "probe", endpoint, headers, Read, parent, destination: "orders", operation: "receive"); [Fact] public void An_inbound_span_continues_the_trace_the_message_carries() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); var sender = new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded); var headers = new Dictionary { ["traceparent"] = $"00-{sender.TraceId}-{sender.SpanId}-01" }; using (var span = Receive(headers, endpoint)) { span.Activity.Should().NotBeNull(); span.Activity!.TraceId.Should().Be(sender.TraceId); span.Activity.ParentSpanId.Should().Be(sender.SpanId); span.Activity.Kind.Should().Be(ActivityKind.Consumer); } probe.Activities.Should().ContainSingle(); } [Fact] public void Without_a_context_in_the_message_the_span_is_a_root_and_the_ambient_comes_back() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using var ambient = new Activity("poll-loop").Start(); using (var span = Receive([], endpoint)) { span.Activity.Should().NotBeNull(); span.Activity!.ParentSpanId.Should().Be(default(ActivitySpanId), "the poll loop did not send this message"); span.Activity.TraceId.Should().NotBe(ambient.TraceId); } Activity.Current.Should().BeSameAs(ambient); } [Fact] public void With_a_host_request_span_the_host_span_is_the_parent() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using var host = new Activity("Microsoft.AspNetCore.Hosting.HttpRequestIn").Start(); var other = $"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01"; using (var span = Receive(new() { ["traceparent"] = other }, endpoint, InboundParent.HostRequest)) { span.Activity!.ParentSpanId.Should().Be(host.SpanId); span.Activity.TraceId.Should().Be(host.TraceId); } Activity.Current.Should().BeSameAs(host); } [Fact] public void Without_a_host_span_the_host_request_mode_reads_the_carrier() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); var traceId = ActivityTraceId.CreateRandom(); using var span = Receive(new() { ["traceparent"] = $"00-{traceId}-{ActivitySpanId.CreateRandom()}-01" }, endpoint, InboundParent.HostRequest); span.Activity!.TraceId.Should().Be(traceId); } [Fact] public void The_baggage_a_sender_injects_comes_back_on_the_inbound_span() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); var headers = new Dictionary(); using (var send = new Activity("send").Start()) { send.AddBaggage("tenant", "t1"); send.AddBaggage("region", "eu"); RouteTelemetryExtensions.InjectTraceContext(send, headers, Write); } using var span = Receive(headers, endpoint); span.Activity!.GetBaggageItem("tenant").Should().Be("t1"); span.Activity.GetBaggageItem("region").Should().Be("eu"); } [Fact] public void Inject_replaces_a_context_copied_from_the_previous_hop() { var headers = new Dictionary { ["traceparent"] = $"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01" }; using var send = new Activity("send").Start(); RouteTelemetryExtensions.InjectTraceContext(null, headers, Write); headers["traceparent"].Should().Be(send.Id, "without its own span the send carries the ambient context"); } [Fact] public void Inject_writes_nothing_without_a_context() { var saved = Activity.Current; Activity.Current = null; try { var headers = new Dictionary(); RouteTelemetryExtensions.InjectTraceContext(null, headers, Write); headers.Should().BeEmpty(); } finally { Activity.Current = saved; } } [Fact] public void A_failure_marks_the_span_red_with_an_exception_event() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using (var span = Receive([], endpoint)) span.Activity.RecordFailure(new InvalidOperationException("broker gone")); var activity = probe.Activities.Single(); activity.Status.Should().Be(ActivityStatusCode.Error); activity.StatusDescription.Should().Be("broker gone"); activity.Events.Should().Contain(e => e.Name == "exception"); } [Fact] public void Tracing_off_for_the_context_opens_no_transport_span() { var endpoint = Endpoint(); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); var context = new global::redb.Route.Core.RouteContext(options: new RouteEngineOptions { EnableTelemetry = false }); using var ambient = new Activity("host").Start(); using (var span = Receive(new() { ["traceparent"] = $"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01" }, endpoint, context: context)) { span.Activity.Should().BeNull(); Activity.Current.Should().BeSameAs(ambient); } RouteTelemetryExtensions.StartTransportSpan(context, "send", ActivityKind.Producer, "messaging.system", "probe", endpoint) .Should().BeNull(); probe.Activities.Should().BeEmpty(); context.IsTracingEnabled().Should().BeFalse(); ((global::redb.Route.Abstractions.IRouteContext?)null).IsTracingEnabled().Should().BeTrue(); } [Fact] public void Every_inbound_span_carries_the_sanitized_endpoint() { var endpoint = Endpoint() + "?password=s3cret"; using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint.Substring(0, endpoint.IndexOf('?'))); string? tag; using (var span = Receive([], endpoint)) tag = RouteTelemetryProbe.Tag(span.Activity!, RouteTelemetryProbe.EndpointTag); tag.Should().StartWith(endpoint.Substring(0, endpoint.IndexOf('?'))).And.NotContain("s3cret"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedActionsOwnershipTests.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/Transactions/TransactedActionsOwnershipTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// The set of deferred transport actions belongs to the block that opened it, .Transacted() or /// .BeginTransaction() ... .CommitTransaction(). A transacted send outside a block, or after the /// block has closed, has nobody to commit it, so it is refused rather than deferred into a set nobody reads. /// public class TransactedActionsOwnershipTests { private sealed class NoopAction : ITransactedAction { public Task Commit(CancellationToken ct = default) => Task.CompletedTask; public Task Rollback(CancellationToken ct = default) => Task.CompletedTask; } private static Exchange NewExchange() => new(new Message("body")); private static Task InTransaction(IExchange exchange, Func body) => new TransactedProcessor(new DelegateProcessor(body), TransactionPolicy.Default).Process(exchange); private static Action RegisterSend(IExchange exchange) => () => TransactedActions.Register(exchange, $"send-{Guid.NewGuid():N}", new NoopAction(), "broker:orders"); [Fact] public void Register_outside_any_block_throws_naming_the_endpoint() { var exchange = NewExchange(); RegisterSend(exchange).Should().Throw() .WithMessage("'broker:orders' is transacted*Transacted()*"); } [Fact] public async Task Transacted_block_opens_the_set_on_entry_and_removes_it_on_exit() { var exchange = NewExchange(); bool? activeInside = null; await InTransaction(exchange, (ex, _) => { activeInside = TransactedActions.IsActive(ex); return Task.CompletedTask; }); activeInside.Should().BeTrue(); TransactedActions.IsActive(exchange).Should().BeFalse(); RegisterSend(exchange).Should().Throw(); } [Fact] public async Task Transacted_block_removes_the_set_when_it_rolls_back() { var exchange = NewExchange(); var failed = () => InTransaction(exchange, (_, _) => throw new InvalidOperationException("unit of work failed")); await failed.Should().ThrowAsync().WithMessage("unit of work failed"); TransactedActions.IsActive(exchange).Should().BeFalse(); } [Fact] public async Task Nested_transacted_block_leaves_the_set_to_the_outer_block() { var exchange = NewExchange(); bool? activeAfterInner = null; await InTransaction(exchange, async (ex, ct) => { await InTransaction(ex, (_, _) => Task.CompletedTask); activeAfterInner = TransactedActions.IsActive(ex); }); activeAfterInner.Should().BeTrue("the outer block is still running"); TransactedActions.IsActive(exchange).Should().BeFalse(); } [Fact] public async Task Send_after_commitTransaction_is_refused() { var exchange = NewExchange(); await new BeginTransactionProcessor().Process(exchange); TransactedActions.IsActive(exchange).Should().BeTrue(); await new CommitTransactionProcessor().Process(exchange); TransactedActions.IsActive(exchange).Should().BeFalse(); RegisterSend(exchange).Should().Throw(); } [Fact] public async Task Send_after_rollbackTransaction_is_refused() { var exchange = NewExchange(); await new BeginTransactionProcessor().Process(exchange); await new RollbackTransactionProcessor().Process(exchange); TransactedActions.IsActive(exchange).Should().BeFalse(); RegisterSend(exchange).Should().Throw(); } [Fact] public async Task Imperative_transaction_inside_transacted_leaves_the_outer_set() { var exchange = NewExchange(); bool? activeAfterCommit = null; await InTransaction(exchange, async (ex, ct) => { await new BeginTransactionProcessor().Process(ex, ct); await new CommitTransactionProcessor().Process(ex, ct); activeAfterCommit = TransactedActions.IsActive(ex); }); activeAfterCommit.Should().BeTrue("the enclosing .Transacted() opened the set and still owns it"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedAnnouncementAfterDedupTests.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/Transactions/TransactedAnnouncementAfterDedupTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; using Xunit; namespace redb.Route.Tests.Transactions; /// /// Where the announcement goes relative to the dedup key. The database commits first, so the one failure the /// order leaves open is "the work is stored, the message did not go out". The broker then redelivers — and the dedup /// key, committed with the work, recognises the redelivery. If the send sits inside the dedup block it is skipped /// with the work and the announcement is lost for good; after the block it runs again and goes out. /// public class TransactedAnnouncementAfterDedupTests { private sealed class FlakySend : ITransactedAction { private readonly Func _fail; public FlakySend(Func fail) => _fail = fail; public static int Sent; public Task Commit(CancellationToken ct = default) { if (_fail()) throw new InvalidOperationException("broker down after the database committed"); Interlocked.Increment(ref Sent); return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) => Task.CompletedTask; } private static void Register(IExchange ex, ITransactedAction action) => ((ConcurrentDictionary)ex.Properties[TransactedProcessor.TransactActionPropertyKey]!) [$"send-{Guid.NewGuid():N}"] = action; private static Exchange Delivery() => new(new Message("order-1") { Headers = { ["messageId"] = "m-1" } }); [Fact] public async Task Send_after_the_dedup_block_goes_out_on_the_redelivery() { FlakySend.Sent = 0; var work = 0; var firstSend = true; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://announce-after") .Transacted() .IdempotentConsumer(new InMemoryIdempotentRepository(), ex => ex.In.GetHeader("messageId")!) .Process(_ => work++) .EndIdempotentConsumer() .Process(ex => Register(ex, new FlakySend(() => { var f = firstSend; firstSend = false; return f; }))) .End()); await context.Start(); var producer = context.GetEndpoint("direct://announce-after").CreateProducer(); await producer.Start(); // First delivery: the work commits, the send fails after the commit, the failure propagates (no ack). var first = () => producer.Process(Delivery()); await first.Should().ThrowAsync(); // The broker redelivers: the dedup key skips the work, the send runs again and goes out. await producer.Process(Delivery()); work.Should().Be(1, "the dedup key keeps the work from being done twice"); FlakySend.Sent.Should().Be(1, "the announcement is not lost: it goes out on the redelivery"); } [Fact] public async Task Send_inside_the_dedup_block_is_lost_when_it_failed_after_the_commit() { FlakySend.Sent = 0; var work = 0; var firstSend = true; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://announce-inside") .Transacted() .IdempotentConsumer(new InMemoryIdempotentRepository(), ex => ex.In.GetHeader("messageId")!) .Process(_ => work++) .Process(ex => Register(ex, new FlakySend(() => { var f = firstSend; firstSend = false; return f; }))) .EndIdempotentConsumer() .End()); await context.Start(); var producer = context.GetEndpoint("direct://announce-inside").CreateProducer(); await producer.Start(); var first = () => producer.Process(Delivery()); await first.Should().ThrowAsync(); await producer.Process(Delivery()); work.Should().Be(1); FlakySend.Sent.Should().Be(0, "inside the dedup block the redelivery is skipped whole, the send with it: this is the shape to avoid"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedAsyncBoundaryTests.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/Transactions/TransactedAsyncBoundaryTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// A transaction belongs to the flow that opened it. An exchange handed over asynchronously (seda:, vm:, /// .Threads() for InOnly) is a unit of work of its own, and a copy that outlives its block must not see the block /// as still running: a send registered there would be committed by nobody and lost. /// public class TransactedAsyncBoundaryTests : IAsyncLifetime { private readonly ServiceProvider _services; private readonly RouteContext _context; public TransactedAsyncBoundaryTests() { var services = new ServiceCollection(); services.AddSingleton(new SharedVmRegistry()); // vm: endpoints need it _services = services.BuildServiceProvider(); _context = new RouteContext(_services, "tx-boundary"); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); await _services.DisposeAsync(); GC.SuppressFinalize(this); } private sealed class NoopAction : ITransactedAction { public Task Commit(CancellationToken ct = default) => Task.CompletedTask; public Task Rollback(CancellationToken ct = default) => Task.CompletedTask; } [Fact] public async Task A_copy_that_outlives_its_block_does_not_see_the_block_as_running() { IExchange? copy = null; await new TransactedProcessor(new DelegateProcessor(ex => copy = ex.Clone()), TransactionPolicy.Default) .Process(new Exchange(new Message("m"))); TransactedActions.IsActive(copy!).Should().BeFalse("the block the copy came from has ended"); var register = () => TransactedActions.Register(copy!, "late", new NoopAction(), "broker:late"); register.Should().Throw("a send nobody would commit must fail, not vanish"); } /// /// The sending block stays open until the other side has looked at the exchange, so what is checked is the hand-off /// itself, not a block that has already ended. /// [Theory] [InlineData("seda")] [InlineData("vm")] public async Task Exchange_handed_over_asynchronously_starts_outside_the_sending_block(string scheme) { var target = $"{scheme}://tx-boundary-{Guid.NewGuid():N}"; bool? activeOnTheOtherSide = null; var looked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _context.AddRoutes(r => { r.From($"direct://tx-boundary-{scheme}") .Transacted() .To(target) .Process((_, ct) => looked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct)) .End(); r.From(target) .Process(ex => { activeOnTheOtherSide = TransactedActions.IsActive(ex); looked.TrySetResult(); }); }); await _context.Start(); var producer = _context.GetEndpoint($"direct://tx-boundary-{scheme}").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); activeOnTheOtherSide.Should().BeFalse($"{scheme}: is an asynchronous hand-off, a unit of work of its own"); } [Fact] public async Task InOnly_threads_worker_starts_outside_the_sending_block() { bool? heldTheBlockSet = null; var looked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _context.AddRoutes(r => { r.From("direct://tx-boundary-threads") .Transacted() .Threads(2) .Process(ex => { heldTheBlockSet = ex.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey); looked.TrySetResult(); }) .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-boundary-threads").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m")) { Pattern = ExchangePattern.InOnly }); await looked.Task.WaitAsync(TimeSpan.FromSeconds(10)); heldTheBlockSet.Should().BeFalse(".Threads() for InOnly hands the exchange to a worker: a unit of work of its own"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedCommitOrderTests.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/Transactions/TransactedCommitOrderTests.cs ---- using System.Collections.Concurrent; using System.Transactions; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; using Xunit; namespace redb.Route.Tests.Transactions; /// /// The order a unit of work commits in: the database first, the brokers after. The next service is told about /// the work through a message and then reads the work by its id, so the failure window must be "written but not /// announced" (a redelivery the idempotent consumer absorbs), never "announced but not written" (a message /// pointing at rows nobody can see). /// public class TransactedCommitOrderTests { private sealed class RecordingAction : ITransactedAction { public bool? AmbientTransactionAtCommit; public int Commits; public int Rollbacks; public Exception? FailWith; public Task Commit(CancellationToken ct = default) { AmbientTransactionAtCommit = Transaction.Current is not null; Commits++; return FailWith is null ? Task.CompletedTask : Task.FromException(FailWith); } public Task Rollback(CancellationToken ct = default) { Rollbacks++; return Task.CompletedTask; } } private static ConcurrentDictionary Register(IExchange exchange, params (string Key, ITransactedAction Action)[] actions) { var bag = new ConcurrentDictionary(); foreach (var (key, action) in actions) bag[key] = action; exchange.Properties[TransactedProcessor.TransactActionPropertyKey] = bag; return bag; } [Fact] public async Task Broker_actions_commit_after_the_database_transaction_is_closed() { var send = new RecordingAction(); ConcurrentDictionary? bag = null; var processor = new TransactedProcessor( new DelegateProcessor(ex => bag = Register(ex, ("send-1", send))), new TransactionPolicy()); await processor.Process(new Exchange(new Message("m"))); send.Commits.Should().Be(1); send.AmbientTransactionAtCommit.Should().BeFalse( "the database transaction must be complete and closed before a message goes out"); bag.Should().NotBeNull(); bag!.Should().BeEmpty("a committed action is done and must not be committed again by a later attempt"); } [Fact] public async Task A_rolled_back_attempt_leaves_no_actions_behind() { var send = new RecordingAction(); ConcurrentDictionary? bag = null; var processor = new TransactedProcessor( new DelegateProcessor(ex => { bag = Register(ex, ("send-1", send)); throw new InvalidOperationException("boom"); }), new TransactionPolicy()); var act = () => processor.Process(new Exchange(new Message("m"))); await act.Should().ThrowAsync(); send.Rollbacks.Should().Be(1); send.Commits.Should().Be(0); bag!.Should().BeEmpty("the next attempt starts from an empty set, not from the failed one"); } [Fact] public async Task A_broker_that_fails_after_the_database_committed_does_not_swallow_the_failure() { var send = new RecordingAction { FailWith = new InvalidOperationException("broker down") }; var processor = new TransactedProcessor( new DelegateProcessor(ex => Register(ex, ("send-1", send))), new TransactionPolicy()); var act = () => processor.Process(new Exchange(new Message("m"))); await act.Should().ThrowAsync().WithMessage("*broker down*"); send.AmbientTransactionAtCommit.Should().BeFalse("the database was already committed and cannot be undone"); } [Fact] public async Task An_unhandled_failure_left_on_the_exchange_still_rolls_everything_back() { var send = new RecordingAction(); var processor = new TransactedProcessor( new DelegateProcessor(ex => { Register(ex, ("send-1", send)); ex.Exception = new InvalidOperationException("handled:false"); }), new TransactionPolicy()); await processor.Process(new Exchange(new Message("m"))); send.Rollbacks.Should().Be(1); send.Commits.Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedProcessorTerminalStateTests.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/Transactions/TransactedProcessorTerminalStateTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; using Xunit; namespace redb.Route.Tests.Transactions; /// /// The transaction must decide commit vs. rollback from the exchange's terminal state, not only from /// whether the inner processor threw: an OnException without Handled(true) leaves the /// exception on the exchange and returns normally, and that is still a failure. /// public class TransactedProcessorTerminalStateTests { private sealed class TrackingAction : ITransactedAction { public bool Committed { get; private set; } public bool RolledBack { get; private set; } public Task Commit(CancellationToken ct = default) { Committed = true; return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { RolledBack = true; return Task.CompletedTask; } } /// A transport step that defers inside the block, then the rest of the route. private static IProcessor Sending(ITransactedAction action, IProcessor rest) => new DelegateProcessor(async (ex, ct) => { TransactedActions.Register(ex, "send-1", action, "test-transport"); await rest.Process(ex, ct); }); [Fact] public async Task UnhandledExceptionLeftOnExchange_RollsBack_DoesNotCommit() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(ci => { ci.Arg().Exception = new InvalidOperationException("boom"); return Task.CompletedTask; }); var action = new TrackingAction(); var processor = new TransactedProcessor(Sending(action, inner), TransactionPolicy.Default); var exchange = new Exchange(new Message { Body = "x" }); await processor.Process(exchange); action.RolledBack.Should().BeTrue("an unhandled failure on the exchange is a failed transaction"); action.Committed.Should().BeFalse("nothing must be committed on a failed exchange"); exchange.Exception.Should().NotBeNull("the failure stays on the exchange for the consumer to settle"); } [Fact] public async Task HandledExceptionOnExchange_Commits() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var ex = ci.Arg(); ex.Exception = new InvalidOperationException("handled"); ex.ExceptionHandled = true; return Task.CompletedTask; }); var action = new TrackingAction(); var processor = new TransactedProcessor(Sending(action, inner), TransactionPolicy.Default); var exchange = new Exchange(new Message { Body = "x" }); await processor.Process(exchange); action.Committed.Should().BeTrue("a handled exception is a completed exchange"); action.RolledBack.Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedProcessorTests.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/Transactions/TransactedProcessorTests.cs ---- using System.Collections.Concurrent; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// Tests for . /// public class TransactedProcessorTests { // ── Helpers ── private static Exchange CreateExchange(object? body = null) => new(new Message { Body = body ?? "test" }); private sealed class TrackingTransactedAction : ITransactedAction { public bool Committed { get; private set; } public bool RolledBack { get; private set; } public Task Commit(CancellationToken ct = default) { Committed = true; return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { RolledBack = true; return Task.CompletedTask; } } private sealed class FailingRollbackAction : ITransactedAction { public Task Commit(CancellationToken ct = default) => Task.CompletedTask; public Task Rollback(CancellationToken ct = default) => throw new InvalidOperationException("Rollback failed deliberately."); } private const string TransportStepsKey = "test:transport-steps"; /// /// Arranges a tracking action that a transport step registers once the block runs, the only place a deferred /// action can be registered ( refuses it outside a block). /// private static TrackingTransactedAction RegisterAction(IExchange exchange, string key = "test-action") { var action = new TrackingTransactedAction(); RegisterInBlock(exchange, key, action); return action; } private static void RegisterInBlock(IExchange exchange, string key, ITransactedAction action) { if (!exchange.Properties.TryGetValue(TransportStepsKey, out var raw) || raw is not List<(string Key, ITransactedAction Action)> steps) { steps = []; exchange.Properties[TransportStepsKey] = steps; } steps.Add((key, action)); } /// The block's body: the transport steps register their actions first, then the rest of the route runs. private static IProcessor WithTransportSteps(IProcessor inner) => new DelegateProcessor(async (ex, ct) => { if (ex.Properties.TryGetValue(TransportStepsKey, out var raw) && raw is List<(string Key, ITransactedAction Action)> steps) { foreach (var (key, action) in steps) TransactedActions.Register(ex, key, action, "test-transport"); } await inner.Process(ex, ct); }); // ── Constructor ── [Fact] public void Ctor_ThrowsOnNullInner() { var act = () => new TransactedProcessor(null!, TransactionPolicy.Default); act.Should().Throw(); } [Fact] public void Ctor_ThrowsOnNullPolicy() { var inner = Substitute.For(); var act = () => new TransactedProcessor(WithTransportSteps(inner), null!); act.Should().Throw(); } // ── Success path ── [Fact] public async Task Process_CallsInnerProcessor() { var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); await processor.Process(exchange); await inner.Received(1).Process(exchange, Arg.Any()); } [Fact] public async Task Process_CommitsActionsOnSuccess() { var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); var action = RegisterAction(exchange); await processor.Process(exchange); action.Committed.Should().BeTrue(); action.RolledBack.Should().BeFalse(); } [Fact] public async Task Process_CommitsMultipleActionsOnSuccess() { var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); var action1 = RegisterAction(exchange, "kafka-topic-1"); var action2 = RegisterAction(exchange, "redis-stream-1"); await processor.Process(exchange); action1.Committed.Should().BeTrue(); action2.Committed.Should().BeTrue(); } [Fact] public async Task Process_OpensTransactActionsDictionaryForTheBlockOnly() { object? inside = null; var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(ci => { ci.Arg().Properties.TryGetValue(TransactedProcessor.TransactActionPropertyKey, out inside); return Task.CompletedTask; }); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); // No TRANSACT_ACTION set: the processor creates it for the block and removes it when the block ends, // so a transacted step after the block cannot defer a send nobody would commit. await processor.Process(exchange); inside.Should().BeAssignableTo>(); exchange.Properties.Should().NotContainKey(TransactedProcessor.TransactActionPropertyKey); } // ── Failure path ── [Fact] public async Task Process_RollsBackActionsOnException() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(x => throw new InvalidOperationException("Processing failed.")); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); var action = RegisterAction(exchange); var act = () => processor.Process(exchange); await act.Should().ThrowAsync(); action.RolledBack.Should().BeTrue(); action.Committed.Should().BeFalse(); } [Fact] public async Task Process_RollsBackMultipleActionsOnException() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(x => throw new ApplicationException("Boom")); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); var action1 = RegisterAction(exchange, "action-a"); var action2 = RegisterAction(exchange, "action-b"); var act = () => processor.Process(exchange); await act.Should().ThrowAsync(); action1.RolledBack.Should().BeTrue(); action2.RolledBack.Should().BeTrue(); } [Fact] public async Task Process_RollsBackOnCancellation() { var cts = new CancellationTokenSource(); var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(x => throw new OperationCanceledException()); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); var action = RegisterAction(exchange); var act = () => processor.Process(exchange, cts.Token); await act.Should().ThrowAsync(); action.RolledBack.Should().BeTrue(); action.Committed.Should().BeFalse(); } // ── Rollback failure suppression ── [Fact] public async Task Process_SuppressesRollbackFailure_PropagatesOriginalException() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(x => throw new InvalidOperationException("Original")); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); // Register a failing rollback action RegisterInBlock(exchange, "failing-rollback", new FailingRollbackAction()); var act = () => processor.Process(exchange); // The original exception should propagate, not the rollback failure await act.Should().ThrowAsync() .WithMessage("Original"); } // ── Transport-registered actions during processing ── [Fact] public async Task Process_CommitsActionsRegisteredDuringProcessing() { // Simulate a transport that registers an action during processing var trackingAction = new TrackingTransactedAction(); var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { var ex = callInfo.Arg(); var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["kafka://orders"] = trackingAction; return Task.CompletedTask; }); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); await processor.Process(exchange); trackingAction.Committed.Should().BeTrue(); } // ── No actions registered ── [Fact] public async Task Process_SucceedsWithNoRegisteredActions() { var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Default); var exchange = CreateExchange(); // No actions registered — should still succeed await processor.Process(exchange); await inner.Received(1).Process(exchange, Arg.Any()); } // ── Policy variations ── [Fact] public async Task Process_WorksWithRequiresNewPolicy() { var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.RequiresNew); var exchange = CreateExchange(); var action = RegisterAction(exchange); await processor.Process(exchange); action.Committed.Should().BeTrue(); } [Fact] public async Task Process_WorksWithSuppressPolicy() { var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), TransactionPolicy.Suppress); var exchange = CreateExchange(); var action = RegisterAction(exchange); await processor.Process(exchange); action.Committed.Should().BeTrue(); } [Fact] public async Task Process_WorksWithCustomPolicy() { var policy = new TransactionPolicy { ScopeOption = System.Transactions.TransactionScopeOption.RequiresNew, Timeout = TimeSpan.FromMinutes(1), IsolationLevel = System.Transactions.IsolationLevel.Serializable }; var inner = Substitute.For(); var processor = new TransactedProcessor(WithTransportSteps(inner), policy); var exchange = CreateExchange(); var action = RegisterAction(exchange); await processor.Process(exchange); action.Committed.Should().BeTrue(); } // ── PropertyKey constant ── [Fact] public void TransactActionPropertyKey_IsCorrect() { TransactedProcessor.TransactActionPropertyKey.Should().Be("TRANSACT_ACTION"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedPropagationTests.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/Transactions/TransactedPropagationTests.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// Blocks inside blocks, as in Camel: a Required block inside a running transaction is part of that unit of work, /// so its deferred sends leave with the enclosing commit; a RequiresNew or Suppress block is a unit of work /// of its own and settles only its own sends. The imperative BeginTransaction ... CommitTransaction follows /// the same rules and commits in the same order: the database first, the sends after it. /// public class TransactedPropagationTests { private sealed class LoggedSend(string name, List log) : ITransactedAction { public Task Commit(CancellationToken ct = default) { lock (log) log.Add($"commit:{name}"); return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { lock (log) log.Add($"rollback:{name}"); return Task.CompletedTask; } } /// A database stand-in: a resource enlisted in the ambient transaction that logs its commit. private sealed class LoggedDatabase(List log) : IEnlistmentNotification { public void Prepare(PreparingEnlistment enlistment) => enlistment.Prepared(); public void Commit(Enlistment enlistment) { lock (log) log.Add("db:commit"); enlistment.Done(); } public void Rollback(Enlistment enlistment) { lock (log) log.Add("db:rollback"); enlistment.Done(); } public void InDoubt(Enlistment enlistment) => enlistment.Done(); } private static void Send(IExchange exchange, string name, List log) => TransactedActions.Register(exchange, $"{name}-{Guid.NewGuid():N}", new LoggedSend(name, log), $"broker:{name}"); private static void WriteDatabase(List log) => Transaction.Current!.EnlistVolatile(new LoggedDatabase(log), EnlistmentOptions.None); private static TransactedProcessor Block(TransactionPolicy policy, Func body) => new(new DelegateProcessor(body), policy); private static TransactedProcessor Block(TransactionPolicy policy, Action body) => new(new DelegateProcessor(body), policy); public static TheoryData OwnUnitsOfWork => new() { "RequiresNew", "Suppress" }; // ── .Transacted() inside .Transacted() ── [Fact] public async Task Required_inner_block_leaves_its_sends_to_the_enclosing_block() { var log = new List(); await Block(TransactionPolicy.Default, async (ex, ct) => { Send(ex, "outer", log); await Block(TransactionPolicy.Default, inner => Send(inner, "inner", log)).Process(ex, ct); log.Add("inner block ended"); }).Process(new Exchange(new Message("m"))); log[0].Should().Be("inner block ended", "a joined block commits nothing of its own"); log.Skip(1).Should().BeEquivalentTo("commit:outer", "commit:inner"); } [Fact] public async Task Required_inner_block_commits_its_sends_after_the_enclosing_database_commit() { var log = new List(); await Block(TransactionPolicy.Default, async (ex, ct) => { WriteDatabase(log); await Block(TransactionPolicy.Default, inner => Send(inner, "inner", log)).Process(ex, ct); }).Process(new Exchange(new Message("m"))); log.Should().Equal("db:commit", "commit:inner"); } [Theory] [MemberData(nameof(OwnUnitsOfWork))] public async Task Inner_block_of_its_own_settles_only_its_own_sends(string policy) { var log = new List(); await Block(TransactionPolicy.Default, async (ex, ct) => { Send(ex, "outer", log); await Block(TransactionPolicy.FromName(policy), inner => Send(inner, "inner", log)).Process(ex, ct); log.Add("inner block ended"); }).Process(new Exchange(new Message("m"))); log.Should().Equal("commit:inner", "inner block ended", "commit:outer"); } [Theory] [MemberData(nameof(OwnUnitsOfWork))] public async Task Failed_inner_block_of_its_own_rolls_back_only_its_own_sends(string policy) { var log = new List(); await Block(TransactionPolicy.Default, async (ex, ct) => { Send(ex, "outer", log); var inner = Block(TransactionPolicy.FromName(policy), (inner, _) => { Send(inner, "inner", log); throw new InvalidOperationException("inner unit of work failed"); }); var failed = () => inner.Process(ex, ct); await failed.Should().ThrowAsync(); }).Process(new Exchange(new Message("m"))); log.Should().Equal("rollback:inner", "commit:outer"); } // ── BeginTransaction ... CommitTransaction ── [Fact] public async Task CommitTransaction_commits_the_database_before_the_sends() { var log = new List(); var exchange = new Exchange(new Message("m")); await new BeginTransactionProcessor().Process(exchange); WriteDatabase(log); Send(exchange, "send", log); await new CommitTransactionProcessor().Process(exchange); log.Should().Equal("db:commit", "commit:send"); } [Fact] public async Task CommitTransaction_inside_a_transacted_block_leaves_the_sends_to_the_block() { var log = new List(); await Block(TransactionPolicy.Default, async (ex, ct) => { Send(ex, "outer", log); await new BeginTransactionProcessor().Process(ex, ct); Send(ex, "inner", log); await new CommitTransactionProcessor().Process(ex, ct); log.Add("commitTransaction ran"); }).Process(new Exchange(new Message("m"))); log[0].Should().Be("commitTransaction ran", "a joined imperative block commits nothing of its own"); log.Skip(1).Should().BeEquivalentTo("commit:outer", "commit:inner"); } [Fact] public async Task RequiresNew_imperative_block_inside_a_transacted_block_settles_only_its_own_sends() { var log = new List(); await Block(TransactionPolicy.Default, async (ex, ct) => { Send(ex, "outer", log); await new BeginTransactionProcessor(TransactionPolicy.RequiresNew).Process(ex, ct); Send(ex, "inner", log); await new CommitTransactionProcessor().Process(ex, ct); log.Add("commitTransaction ran"); }).Process(new Exchange(new Message("m"))); log.Should().Equal("commit:inner", "commitTransaction ran", "commit:outer"); } // ── The order the deferred sends leave in ── [Fact] public async Task Deferred_sends_commit_in_the_order_the_route_registered_them() { var log = new List(); var expected = Enumerable.Range(1, 20).Select(i => $"commit:send-{i:D2}").ToList(); await Block(TransactionPolicy.Default, ex => { for (var i = 1; i <= 20; i++) TransactedActions.Register(ex, $"key-{Guid.NewGuid():N}", new LoggedSend($"send-{i:D2}", log), "broker"); }).Process(new Exchange(new Message("m"))); log.Should().Equal(expected, "two sends to one queue must not arrive swapped"); } // ── The transacted parameter of a producer ── [Fact] public async Task Unset_transacted_defers_inside_a_block_and_sends_at_once_outside() { var exchange = new Exchange(new Message("m")); bool? inside = null; await Block(TransactionPolicy.Default, ex => inside = TransactedActions.Defers(ex, transacted: null)) .Process(exchange); inside.Should().BeTrue(); TransactedActions.Defers(exchange, transacted: null).Should().BeFalse(); } [Fact] public async Task Transacted_false_sends_at_once_even_inside_a_block() { bool? inside = null; await Block(TransactionPolicy.Default, ex => inside = TransactedActions.Defers(ex, transacted: false)) .Process(new Exchange(new Message("m"))); inside.Should().BeFalse(); } [Fact] public void Transacted_true_always_defers_so_that_outside_a_block_registration_refuses_it() { TransactedActions.Defers(new Exchange(new Message("m")), transacted: true).Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedRetryOutsideTests.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/Transactions/TransactedRetryOutsideTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; using Xunit; namespace redb.Route.Tests.Transactions; /// /// Retry wraps the transaction, it does not live inside it. One attempt is one unit of work: a failed attempt /// rolls its own database work and its own outgoing sends back, and the transaction never stays open across the /// retry delays (a long-lived transaction on a broker connection is exactly what the deferred design tried to avoid). /// public class TransactedRetryOutsideTests { private sealed class TrackingAction : ITransactedAction { public int Commits; public int Rollbacks; public Task Commit(CancellationToken ct = default) { Commits++; return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { Rollbacks++; return Task.CompletedTask; } } [Fact] public async Task A_failed_attempt_does_not_leave_its_send_for_the_successful_one() { var attempts = 0; var perAttempt = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://tx-retry-in") .RouteId("tx-retry") .Transacted() .Retry(3, TimeSpan.FromMilliseconds(1)) .Process((ex, _) => { attempts++; var action = new TrackingAction(); perAttempt.Add(action); var bag = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; bag[$"send-{attempts}"] = action; if (attempts < 3) throw new InvalidOperationException($"attempt {attempts} fails"); return Task.CompletedTask; }) .End()); await context.Start(); var producer = context.GetEndpoint("direct://tx-retry-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); attempts.Should().Be(3); perAttempt.Should().HaveCount(3); perAttempt[0].Rollbacks.Should().Be(1, "a failed attempt rolls its own send back"); perAttempt[0].Commits.Should().Be(0, "a failed attempt must never be sent by the attempt that succeeded"); perAttempt[1].Rollbacks.Should().Be(1); perAttempt[1].Commits.Should().Be(0); perAttempt[2].Commits.Should().Be(1, "the attempt that succeeded sends its own message"); perAttempt[2].Rollbacks.Should().Be(0); } [Fact] public async Task Every_attempt_runs_in_a_transaction_of_its_own() { var ambientPerAttempt = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://tx-retry-scope-in") .RouteId("tx-retry-scope") .Transacted() .Retry(2, TimeSpan.FromMilliseconds(1)) .Process((ex, _) => { ambientPerAttempt.Add( System.Transactions.Transaction.Current?.TransactionInformation.LocalIdentifier); if (ambientPerAttempt.Count == 1) throw new InvalidOperationException("first attempt fails"); return Task.CompletedTask; }) .End()); await context.Start(); var producer = context.GetEndpoint("direct://tx-retry-scope-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); ambientPerAttempt.Should().HaveCount(2); ambientPerAttempt[0].Should().NotBeNull("a transacted block runs in a transaction"); ambientPerAttempt[1].Should().NotBeNull(); ambientPerAttempt[1].Should().NotBe(ambientPerAttempt[0], "the second attempt gets a transaction of its own, so a retry never holds one open across its delay"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedRollbackOnlyTests.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/Transactions/TransactedRollbackOnlyTests.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// .RollbackAll() is Camel's markRollbackOnly(): the route stops, the unit of work is rolled back without an /// exception (the database and the deferred sends), and the consumer does not acknowledge the message, so the broker /// delivers it again. /// public class TransactedRollbackOnlyTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private sealed class LoggedSend(string name, List log) : ITransactedAction { public Task Commit(CancellationToken ct = default) { lock (log) log.Add($"commit:{name}"); return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { lock (log) log.Add($"rollback:{name}"); return Task.CompletedTask; } } /// A database stand-in: a resource enlisted in the ambient transaction that logs how it ends. private sealed class LoggedDatabase(List log) : IEnlistmentNotification { public void Prepare(PreparingEnlistment enlistment) => enlistment.Prepared(); public void Commit(Enlistment enlistment) { lock (log) log.Add("db:commit"); enlistment.Done(); } public void Rollback(Enlistment enlistment) { lock (log) log.Add("db:rollback"); enlistment.Done(); } public void InDoubt(Enlistment enlistment) => enlistment.Done(); } private static void Work(IExchange exchange, List log) { Transaction.Current!.EnlistVolatile(new LoggedDatabase(log), EnlistmentOptions.None); TransactedActions.Register(exchange, $"send-{Guid.NewGuid():N}", new LoggedSend("send", log), "broker:send"); } private async Task Run(string uri) { await _context.Start(); var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); // no exception: a rollback-only exchange is not an error } [Fact] public async Task RollbackAll_inside_a_block_rolls_back_the_database_and_the_sends_and_stops_the_route() { var log = new List(); _context.AddRoutes(r => r.From("direct://rb-block") .Transacted() .Process(ex => Work(ex, log)) .RollbackAll() .Process(_ => log.Add("step after rollbackAll")) .End() .Process(_ => log.Add("step after the block"))); await Run("direct://rb-block"); log.Should().Contain("db:rollback").And.Contain("rollback:send"); log.Should().NotContain("db:commit").And.NotContain("commit:send"); log.Should().NotContain("step after rollbackAll").And.NotContain("step after the block", "the route stops"); } [Fact] public async Task RollbackAll_in_a_joined_inner_block_rolls_back_the_whole_unit_of_work() { var log = new List(); _context.AddRoutes(r => r.From("direct://rb-joined") .Transacted() .Process(ex => Work(ex, log)) .Transacted() .RollbackAll() .End() .End()); await Run("direct://rb-joined"); log.Should().Contain("db:rollback").And.Contain("rollback:send"); log.Should().NotContain("db:commit").And.NotContain("commit:send"); } [Fact] public async Task RollbackAll_after_BeginTransaction_rolls_that_transaction_back() { var log = new List(); _context.AddRoutes(r => r.From("direct://rb-imperative") .BeginTransaction() .Process(ex => Work(ex, log)) .RollbackAll() .CommitTransaction()); await Run("direct://rb-imperative"); log.Should().Contain("db:rollback").And.Contain("rollback:send"); log.Should().NotContain("db:commit").And.NotContain("commit:send"); } [Fact] public void Consumer_treats_a_rollback_only_exchange_as_a_failed_unit_of_work() { var exchange = new Exchange(new Message("m")); exchange.Properties["RollbackOnly"] = true; // what .RollbackAll() leaves on the exchange var settle = () => exchange.ThrowIfUnhandledFailure(); settle.Should().Throw("the consumer must not acknowledge a rolled-back unit of work") .WithMessage("*rollback*"); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedRouteIntegrationTests.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/Transactions/TransactedRouteIntegrationTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// Integration tests that verify the DSL → OldRouteCompiler → TransactedProcessor pipeline. /// Uses real RouteContext with direct:// components to test the full compilation flow. /// public class TransactedRouteIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private sealed class TrackingTransactedAction : ITransactedAction { public bool Committed { get; private set; } public bool RolledBack { get; private set; } public Task Commit(CancellationToken ct = default) { Committed = true; return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { RolledBack = true; return Task.CompletedTask; } } // ── DSL records TransactedStep ── [Fact] public void Transacted_SetsIsTransactedFlag() { var def = new RouteDefinition(); def.From("direct://in").Transacted(); def.IsTransacted.Should().BeTrue(); } [Fact] public void Transacted_WithPolicy_RecordsPolicy() { var def = new RouteDefinition(); def.From("direct://in").Transacted(TransactionPolicy.RequiresNew); var txDef = def.Outputs.OfType().FirstOrDefault(); txDef.Should().NotBeNull(); txDef!.Policy.Should().BeSameAs(TransactionPolicy.RequiresNew); } [Fact] public void Transacted_WithName_ParsesPolicy() { var def = new RouteDefinition(); def.From("direct://in").Transacted("RequiresNew"); var txDef = def.Outputs.OfType().FirstOrDefault(); txDef.Should().NotBeNull(); txDef!.Policy!.ScopeOption.Should().Be(System.Transactions.TransactionScopeOption.RequiresNew); } [Fact] public void Transacted_WithInvalidName_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://in").Transacted("Bogus"); act.Should().Throw().WithMessage("*Unknown transaction policy*"); } [Fact] public void Transacted_WithNullPolicy_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://in").Transacted((TransactionPolicy)null!); act.Should().Throw(); } [Fact] public void Transacted_WithNullName_Throws() { var def = new RouteDefinition(); var act = () => def.From("direct://in").Transacted((string)null!); act.Should().Throw(); } // ── Compiler integrates TransactedProcessor ── [Fact] public async Task Transacted_Route_CommitsActionsOnSuccess() { IExchange? captured = null; var trackingAction = new TrackingTransactedAction(); _context.AddRoutes(r => { r.From("direct://tx-in") .Transacted() .Process((ex, _) => { // Simulate a transport registering a deferred action var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["test-transport"] = trackingAction; return Task.CompletedTask; }) .To("direct://tx-out"); }); _context.AddRoutes(r => { r.From("direct://tx-out") .Process(ex => captured = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = "transacted-payload" }); await producer.Process(exchange); captured.Should().NotBeNull(); trackingAction.Committed.Should().BeTrue(); trackingAction.RolledBack.Should().BeFalse(); } [Fact] public async Task Transacted_Route_RollsBackOnFailure() { var trackingAction = new TrackingTransactedAction(); _context.AddRoutes(r => { r.From("direct://tx-fail-in") .Transacted() .Process((ex, _) => { var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["test-transport"] = trackingAction; throw new InvalidOperationException("Simulated failure"); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-fail-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = "will-fail" }); var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("Simulated failure"); trackingAction.RolledBack.Should().BeTrue(); trackingAction.Committed.Should().BeFalse(); } [Fact] public async Task Transacted_WithRequiresNewPolicy_Works() { IExchange? captured = null; var trackingAction = new TrackingTransactedAction(); _context.AddRoutes(r => { r.From("direct://tx-rn-in") .Transacted(TransactionPolicy.RequiresNew) .Process((ex, _) => { var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["transport"] = trackingAction; return Task.CompletedTask; }) .To("direct://tx-rn-out"); }); _context.AddRoutes(r => { r.From("direct://tx-rn-out") .Process(ex => captured = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-rn-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "rn" })); captured.Should().NotBeNull(); trackingAction.Committed.Should().BeTrue(); } [Fact] public async Task Transacted_WithStringPolicy_Works() { var trackingAction = new TrackingTransactedAction(); _context.AddRoutes(r => { r.From("direct://tx-str-in") .Transacted("Required") .Process((ex, _) => { var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["transport"] = trackingAction; return Task.CompletedTask; }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-str-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "str-policy" })); trackingAction.Committed.Should().BeTrue(); } // ── Transacted + Retry combination ── [Fact] public async Task Transacted_WithRetry_RetriesThenTransacts() { var callCount = 0; var trackingAction = new TrackingTransactedAction(); _context.AddRoutes(r => { r.From("direct://tx-retry-in") .Transacted() .Retry(2, TimeSpan.FromMilliseconds(10)) .Process((ex, _) => { var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["transport"] = trackingAction; callCount++; if (callCount < 2) throw new InvalidOperationException("Transient failure"); return Task.CompletedTask; }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-retry-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "retry-tx" })); callCount.Should().Be(2); // After retry succeeds, transaction commits trackingAction.Committed.Should().BeTrue(); } // ── Transacted + DeadLetterChannel combination ── [Fact] public async Task Transacted_WithDLC_SendsToDeadLetterOnFailure() { IExchange? deadLettered = null; var trackingAction = new TrackingTransactedAction(); _context.AddRoutes(r => { r.From("direct://tx-dlc-in") .Transacted() .DeadLetterChannel("direct://tx-dlc-dead") .Process((ex, _) => { var dict = (ConcurrentDictionary) ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["transport"] = trackingAction; throw new InvalidOperationException("Fatal"); }); }); _context.AddRoutes(r => { r.From("direct://tx-dlc-dead") .Process(ex => deadLettered = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-dlc-in").CreateProducer(); await producer.Start(); // DLC should catch the exception, so no throw expected await producer.Process(new Exchange(new Message { Body = "dlc-tx" })); deadLettered.Should().NotBeNull(); // Transaction rolls back because the inner processing failed trackingAction.RolledBack.Should().BeTrue(); } // ── Exchange property key ── [Fact] public async Task Transacted_Route_SetsTransactActionProperty() { object? propertyValue = null; _context.AddRoutes(r => { r.From("direct://tx-prop-in") .Transacted() .Process(ex => { ex.Properties.TryGetValue(TransactedProcessor.TransactActionPropertyKey, out propertyValue); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://tx-prop-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "check-prop" })); propertyValue.Should().NotBeNull(); propertyValue.Should().BeAssignableTo>(); } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactedRouteTerminalStateTests.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/Transactions/TransactedRouteTerminalStateTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; using Xunit; namespace redb.Route.Tests.Transactions; /// /// End-to-end: a failure that an OnException without Handled(true) leaves on the exchange /// must still roll the enclosing .Transacted() block back, whichever way it reaches the transaction. /// public class TransactedRouteTerminalStateTests { private sealed class TrackingAction : ITransactedAction { public bool Committed { get; private set; } public bool RolledBack { get; private set; } public Task Commit(CancellationToken ct = default) { Committed = true; return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { RolledBack = true; return Task.CompletedTask; } } private static void Register(IExchange ex, ITransactedAction action) { var dict = (ConcurrentDictionary)ex.Properties[TransactedProcessor.TransactActionPropertyKey]!; dict["send-1"] = action; } /// /// The in-route OnException is hoisted outside the transaction: the throw reaches TransactedProcessor directly. /// [Fact] public async Task OnExceptionWithoutHandled_InsideTransacted_RollsBack() { var context = new RouteContext(); var action = new TrackingAction(); context.AddRoutes(r => { r.From("direct://tx-oe-in") .Transacted() .OnException() // no Handled(): failure stays on the exchange .Log("seen") .End() .Process((ex, _) => { Register(ex, action); throw new InvalidOperationException("boom"); }) .End(); }); await AssertRolledBack(context, "direct://tx-oe-in", action); } /// /// A sub-route called from the transacted body handles the failure (handled:false) and returns normally — /// the caller's exchange carries the exception without a throw. /// [Fact] public async Task SubRouteOnExceptionWithoutHandled_InsideTransacted_RollsBack() { var context = new RouteContext(); var action = new TrackingAction(); context.AddRoutes(r => { r.From("direct://tx-sub-in") .Transacted() .To("direct://tx-sub-work") .End(); r.From("direct://tx-sub-work") .OnException() // no Handled(): the sub-route returns normally .Log("seen") .End() .Process((ex, _) => { Register(ex, action); throw new InvalidOperationException("boom"); }); }); await AssertRolledBack(context, "direct://tx-sub-in", action); } private static async Task AssertRolledBack(RouteContext context, string uri, TrackingAction action) { await context.Start(); try { var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = "x" }); await producer.Process(exchange); // returns normally: handled:false keeps the failure on the exchange exchange.Exception.Should().NotBeNull("handled:false keeps the failure on the exchange"); exchange.ExceptionHandled.Should().BeFalse(); action.RolledBack.Should().BeTrue("an unhandled failure must roll the transaction back"); action.Committed.Should().BeFalse(); } finally { await context.DisposeAsync(); } } } Path: redb-route/tests/redb.Route.Tests/Transactions/TransactionPolicyTests.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/Transactions/TransactionPolicyTests.cs ---- using System.Transactions; using redb.Route.Transactions; namespace redb.Route.Tests.Transactions; /// /// Tests for . /// public class TransactionPolicyTests { // ── Defaults ── [Fact] public void Default_HasRequiredScopeOption() { var policy = TransactionPolicy.Default; policy.ScopeOption.Should().Be(TransactionScopeOption.Required); } [Fact] public void Default_Has30SecondTimeout() { TransactionPolicy.Default.Timeout.Should().Be(TimeSpan.FromSeconds(30)); } [Fact] public void Default_HasReadCommittedIsolation() { TransactionPolicy.Default.IsolationLevel.Should().Be(IsolationLevel.ReadCommitted); } // ── Static policies ── [Fact] public void RequiresNew_HasCorrectScopeOption() { TransactionPolicy.RequiresNew.ScopeOption.Should().Be(TransactionScopeOption.RequiresNew); } [Fact] public void Suppress_HasCorrectScopeOption() { TransactionPolicy.Suppress.ScopeOption.Should().Be(TransactionScopeOption.Suppress); } // ── Init syntax ── [Fact] public void Init_AllowsCustomValues() { var policy = new TransactionPolicy { ScopeOption = TransactionScopeOption.RequiresNew, Timeout = TimeSpan.FromMinutes(5), IsolationLevel = IsolationLevel.Serializable }; policy.ScopeOption.Should().Be(TransactionScopeOption.RequiresNew); policy.Timeout.Should().Be(TimeSpan.FromMinutes(5)); policy.IsolationLevel.Should().Be(IsolationLevel.Serializable); } // ── FromName ── [Theory] [InlineData("Required", TransactionScopeOption.Required)] [InlineData("REQUIRED", TransactionScopeOption.Required)] [InlineData("required", TransactionScopeOption.Required)] [InlineData(" Required ", TransactionScopeOption.Required)] [InlineData("RequiresNew", TransactionScopeOption.RequiresNew)] [InlineData("REQUIRESNEW", TransactionScopeOption.RequiresNew)] [InlineData("Suppress", TransactionScopeOption.Suppress)] [InlineData("SUPPRESS", TransactionScopeOption.Suppress)] public void FromName_ParsesKnownPolicies(string name, TransactionScopeOption expected) { var policy = TransactionPolicy.FromName(name); policy.ScopeOption.Should().Be(expected); } [Fact] public void FromName_ThrowsForUnknownName() { var act = () => TransactionPolicy.FromName("NotAPolicy"); act.Should().Throw() .WithMessage("*Unknown transaction policy*NotAPolicy*"); } [Fact] public void FromName_ThrowsForNullName() { var act = () => TransactionPolicy.FromName(null!); act.Should().Throw(); } // ── Mandatory (R-16) ── [Theory] [InlineData("Mandatory")] [InlineData("MANDATORY")] [InlineData(" mandatory ")] public void FromName_ParsesMandatory(string name) { var policy = TransactionPolicy.FromName(name); policy.Should().BeSameAs(TransactionPolicy.Mandatory); } [Fact] public void Mandatory_CreateScope_ThrowsWhenNoAmbientTransaction() { // Sanity guard: ensure no ambient transaction leaked from another test. Transaction.Current.Should().BeNull(); var act = () => TransactionPolicy.Mandatory.CreateScope(); act.Should().Throw() .WithMessage("*Mandatory*ambient*"); } [Fact] public void Mandatory_CreateScope_JoinsExistingAmbientTransaction() { using var outer = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); Transaction.Current.Should().NotBeNull(); var ambientId = Transaction.Current!.TransactionInformation.LocalIdentifier; using (var inner = TransactionPolicy.Mandatory.CreateScope()) { // Inside the Mandatory scope we must still see the same ambient transaction. Transaction.Current.Should().NotBeNull(); Transaction.Current!.TransactionInformation.LocalIdentifier.Should().Be(ambientId); inner.Complete(); } outer.Complete(); } } Path: redb-route/tests/redb.Route.Tests/Validation/RouteResourceResolverTests.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/Validation/RouteResourceResolverTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Validation; /// /// Resource resolution for file-reading endpoint components. The default chain is /// absolute path → ResourceRoot → AppContext.BaseDirectory → working directory /// (last, preserving the pre-resolver behaviour), and a miss names every probed location. /// public class RouteResourceResolverTests : IDisposable { private readonly string _root = Directory.CreateTempSubdirectory("route-res-").FullName; public void Dispose() => Directory.Delete(_root, recursive: true); [Fact] public void AbsolutePath_IsReturnedAsIs_WhenTheFileExists() { var file = Path.Combine(_root, "abs.json"); File.WriteAllText(file, "{}"); new RouteResourceResolver().Resolve(file).Should().Be(file); } [Fact] public void AbsolutePath_Missing_ResolvesToNull_AndSearchNamesOnlyThatPath() { var file = Path.Combine(_root, "missing.json"); var resolver = new RouteResourceResolver(); resolver.Resolve(file).Should().BeNull(); resolver.DescribeSearch(file).Should().Be(file); } [Fact] public void Relative_ResourceRoot_WinsOverBaseDirectory() { var name = $"probe-{Guid.NewGuid():N}.json"; var inRoot = Path.Combine(_root, name); var inBase = Path.Combine(AppContext.BaseDirectory, name); File.WriteAllText(inRoot, "{}"); File.WriteAllText(inBase, "{}"); try { var resolver = new RouteResourceResolver { ResourceRoot = _root }; resolver.Resolve(name).Should().Be(inRoot); } finally { File.Delete(inBase); } } [Fact] public void Relative_FallsBackToBaseDirectory_WhenNotUnderResourceRoot() { var name = $"probe-{Guid.NewGuid():N}.json"; var inBase = Path.Combine(AppContext.BaseDirectory, name); File.WriteAllText(inBase, "{}"); try { var resolver = new RouteResourceResolver { ResourceRoot = _root }; resolver.Resolve(name).Should().Be(Path.GetFullPath(inBase)); } finally { File.Delete(inBase); } } [Fact] public void NotFound_DescribeSearch_ListsEveryProbedLocation() { var name = $"no-such-{Guid.NewGuid():N}.json"; var resolver = new RouteResourceResolver { ResourceRoot = _root }; resolver.Resolve(name).Should().BeNull(); var search = resolver.DescribeSearch(name); search.Should().Contain(Path.GetFullPath(Path.Combine(_root, name))); search.Should().Contain(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, name))); search.Should().Contain(Path.GetFullPath(name)); } [Fact] public async Task ValidatorEndpoint_FindsSchema_ThroughTheRegisteredResolver() { File.WriteAllText(Path.Combine(_root, "order.schema.json"), """{"type":"object"}"""); await using var context = new RouteContext(); context.AddComponent(new redb.Route.Validation.ValidatorComponent()); context.AddService(typeof(IRouteResourceResolver), new RouteResourceResolver { ResourceRoot = _root }); var endpoint = context.GetEndpoint("validator:order.schema.json"); endpoint.Should().NotBeNull(); } [Fact] public async Task ValidatorEndpoint_MissingSchema_ErrorNamesEverySearchedPlace() { await using var context = new RouteContext(); context.AddComponent(new redb.Route.Validation.ValidatorComponent()); context.AddService(typeof(IRouteResourceResolver), new RouteResourceResolver { ResourceRoot = _root }); var act = () => context.GetEndpoint($"validator:absent-{Guid.NewGuid():N}.json"); act.Should().Throw() .WithMessage("*Schema file not found*Searched:*"); } } Path: redb-route/tests/redb.Route.Tests/Validation/ValidationSeverityTests.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/Validation/ValidationSeverityTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Validation; using Xunit; namespace redb.Route.Tests.Validation; public class ValidationSeverityTests { private sealed class StubValidator : IMessageValidator { private readonly ValidationResult _result; public StubValidator(ValidationResult result) => _result = result; public ValidationResult Validate(IExchange exchange) => _result; } private static IExchange CreateExchange() => new Exchange(new Message("body")); [Fact] public async Task Warning_AppendsToHeader_AndDoesNotThrow() { var validator = new StubValidator( ValidationResult.Failure(new[] { "field 'x' is suspicious" }, ValidationSeverity.Warning)); var processor = new ValidateProcessor(validator, throwOnFailure: true); var exchange = CreateExchange(); var act = async () => await processor.Process(exchange); await act.Should().NotThrowAsync(); exchange.In.Headers.Should().ContainKey(ValidateProcessor.ValidationWarningsHeader); exchange.In.Headers[ValidateProcessor.ValidationWarningsHeader] .Should().Be("field 'x' is suspicious"); } [Fact] public async Task Warning_MultipleInvocations_AppendedWithSemicolon() { var v1 = new StubValidator(ValidationResult.Failure(new[] { "warn-1" }, ValidationSeverity.Warning)); var v2 = new StubValidator(ValidationResult.Failure(new[] { "warn-2", "warn-3" }, ValidationSeverity.Warning)); var p1 = new ValidateProcessor(v1); var p2 = new ValidateProcessor(v2); var exchange = CreateExchange(); await p1.Process(exchange); await p2.Process(exchange); exchange.In.Headers[ValidateProcessor.ValidationWarningsHeader] .Should().Be("warn-1; warn-2; warn-3"); } [Fact] public async Task Error_PreservesThrowBehavior_WhenThrowOnFailureTrue() { var validator = new StubValidator( ValidationResult.Failure(new[] { "boom" }, ValidationSeverity.Error)); var processor = new ValidateProcessor(validator, throwOnFailure: true); await Assert.ThrowsAsync(() => processor.Process(CreateExchange())); } [Fact] public async Task Error_DoesNotThrow_WhenThrowOnFailureFalse_ButSetsProperties() { var validator = new StubValidator( ValidationResult.Failure(new[] { "boom" }, ValidationSeverity.Error)); var processor = new ValidateProcessor(validator, throwOnFailure: false); var exchange = CreateExchange(); await processor.Process(exchange); exchange.Properties[ValidateProcessor.ValidationResultProperty].Should().Be(false); exchange.Properties[ValidateProcessor.ValidationErrorsProperty].Should().Be("boom"); exchange.In.Headers.Should().NotContainKey(ValidateProcessor.ValidationWarningsHeader); } [Fact] public void DefaultFailureFactory_IsErrorSeverity() { var result = ValidationResult.Failure(new[] { "x" }); result.Severity.Should().Be(ValidationSeverity.Error); } [Fact] public void Failure_WithExplicitSeverity_PropagatesSeverity() { var result = ValidationResult.Failure(new[] { "x" }, ValidationSeverity.Warning); result.Severity.Should().Be(ValidationSeverity.Warning); result.IsValid.Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests/Validation/ValidatorTests.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/Validation/ValidatorTests.cs ---- using System.Text.Json; using System.Xml.Linq; using System.Xml.Schema; using AwesomeAssertions; using Json.Schema; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Validation; using Xunit; namespace redb.Route.Tests.Validation; public class ValidatorTests { // ═══════════════════════════════════════════════════════════════════ // Sample data // ═══════════════════════════════════════════════════════════════════ private const string PersonJsonSchema = """ { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer", "minimum": 0 } }, "required": ["name", "age"] } """; private const string ValidPersonJson = """{"name":"John","age":30}"""; private const string InvalidPersonJson_MissingAge = """{"name":"John"}"""; private const string InvalidPersonJson_WrongType = """{"name":"John","age":"thirty"}"""; private const string NotJson = "this is not json"; private const string PersonXsd = """ """; private const string ValidPersonXml = "John30"; private const string InvalidPersonXml_MissingAge = "John"; private const string InvalidPersonXml_WrongType = "Johnthirty"; private const string NotXml = "this is not xml"; private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ═══════════════════════════════════════════════════════════════════ // JsonSchemaValidator // ═══════════════════════════════════════════════════════════════════ [Fact] public void JsonSchemaValidator_ValidJson_ReturnsSuccess() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(ValidPersonJson); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); result.Errors.Should().BeEmpty(); } [Fact] public void JsonSchemaValidator_MissingRequiredField_ReturnsFailure() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(InvalidPersonJson_MissingAge); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().NotBeEmpty(); } [Fact] public void JsonSchemaValidator_WrongType_ReturnsFailure() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(InvalidPersonJson_WrongType); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().NotBeEmpty(); } [Fact] public void JsonSchemaValidator_NotJson_ReturnsFailure() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(NotJson); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("Invalid JSON")); } [Fact] public void JsonSchemaValidator_NullBody_ReturnsFailure() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(null); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain("Message body is null"); } [Fact] public void JsonSchemaValidator_JsonDocumentBody_ValidatesDirectly() { var validator = new JsonSchemaValidator(PersonJsonSchema); var doc = JsonDocument.Parse(ValidPersonJson); var exchange = CreateExchange(doc); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void JsonSchemaValidator_PocoBody_SerializesAndValidates() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(new { name = "John", age = 30 }); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void JsonSchemaValidator_PocoBody_Invalid_ReturnsFailure() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(new { name = "John" }); // missing age var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); } [Fact] public void JsonSchemaValidator_FromSchemaObject_Works() { var schema = JsonSchema.FromText(PersonJsonSchema); var validator = new JsonSchemaValidator(schema); var exchange = CreateExchange(ValidPersonJson); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void JsonSchemaValidator_NullSchema_Throws() { var act = () => new JsonSchemaValidator((JsonSchema)null!); act.Should().Throw(); } [Fact] public void JsonSchemaValidator_NullSchemaString_Throws() { var act = () => new JsonSchemaValidator((string)null!); act.Should().Throw(); } // ═══════════════════════════════════════════════════════════════════ // XsdValidator // ═══════════════════════════════════════════════════════════════════ [Fact] public void XsdValidator_ASchemaWithItsOwnDoctype_Loads() { // W3C's xmldsig-core-schema.xsd starts with a decorative internal DTD; the schema's DOCTYPE is skipped. const string withDoctype = """ ]> """; var validator = new XsdValidator(withDoctype); validator.Validate(CreateExchange("5")).IsValid.Should().BeTrue(); validator.Validate(CreateExchange("x")).IsValid.Should().BeFalse(); } [Fact] public void XsdValidator_ASchemaWhoseContentUsesAnEntity_FailsNamingIt() { const string usesEntity = """ ]> """; var act = () => new XsdValidator(usesEntity); act.Should().Throw().WithMessage("*ns*"); } [Fact] public void XsdValidator_AMessageWithADoctype_IsStillRefused() { var validator = new XsdValidator(PersonXsd); var result = validator.Validate(CreateExchange("""]>&e;""")); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("DTD is prohibited")); } [Fact] public void XsdValidator_ValidXml_ReturnsSuccess() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(ValidPersonXml); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); result.Errors.Should().BeEmpty(); } [Fact] public void XsdValidator_MissingRequiredElement_ReturnsFailure() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(InvalidPersonXml_MissingAge); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().NotBeEmpty(); } [Fact] public void XsdValidator_WrongType_ReturnsFailure() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(InvalidPersonXml_WrongType); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().NotBeEmpty(); } [Fact] public void XsdValidator_NotXml_ReturnsFailure() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(NotXml); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); } [Fact] public void XsdValidator_RootWithoutNamespace_ReturnsFailure() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(""); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("not declared")); } [Fact] public void XsdValidator_RootInForeignNamespace_ReturnsFailure() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange("John30"); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("not declared")); } [Fact] public void XsdValidator_NullBody_ReturnsFailure() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(null); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain("Message body is null"); } [Fact] public void XsdValidator_XDocumentBody_Validates() { var validator = new XsdValidator(PersonXsd); var doc = XDocument.Parse(ValidPersonXml); var exchange = CreateExchange(doc); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void XsdValidator_XElementBody_Validates() { var validator = new XsdValidator(PersonXsd); var el = XElement.Parse(ValidPersonXml); var exchange = CreateExchange(el); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void XsdValidator_FromSchemaSet_Works() { var schemaSet = new XmlSchemaSet(); using var reader = new StringReader(PersonXsd); schemaSet.Add("", System.Xml.XmlReader.Create(reader)); schemaSet.Compile(); var validator = new XsdValidator(schemaSet); var exchange = CreateExchange(ValidPersonXml); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void XsdValidator_WithTargetNamespace_Works() { const string nsXsd = """ """; const string nsXml = """John"""; var validator = new XsdValidator("http://example.com/person", nsXsd); var exchange = CreateExchange(nsXml); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } // Row 50: without the targetNamespace option the schema's own target namespace is taken, as the xml doc says; // the namespace used to be passed as "" (no namespace), so a namespaced schema failed to load. private const string NamespacedXsd = """ """; [Fact] public void XsdValidator_NamespacedSchema_WithoutTheOption_TakesTheSchemasNamespace() { var validator = new XsdValidator(NamespacedXsd); validator.Validate(CreateExchange("""John""")) .IsValid.Should().BeTrue(); validator.Validate(CreateExchange("""1""")) .IsValid.Should().BeFalse(); } [Fact] public void XsdValidator_NamespacedSchema_WithANullOption_TakesTheSchemasNamespace() { var validator = new XsdValidator(null, NamespacedXsd); validator.Validate(CreateExchange("""John""")) .IsValid.Should().BeTrue(); } [Fact] public void ValidateXsd_NamespacedSchemaString_BuildsItsProcessor() { var act = () => new ValidateXsdStringDefinition(NamespacedXsd).CreateProcessor(new RouteContext()); act.Should().NotThrow(); } [Fact] public void XsdValidator_NullSchemaSet_Throws() { var act = () => new XsdValidator((XmlSchemaSet)null!); act.Should().Throw(); } [Fact] public void XsdValidator_NullXsdString_Throws() { var act = () => new XsdValidator((string)null!); act.Should().Throw(); } // ═══════════════════════════════════════════════════════════════════ // PredicateValidator // ═══════════════════════════════════════════════════════════════════ [Fact] public void PredicateValidator_PredicateTrue_ReturnsSuccess() { var validator = new PredicateValidator(e => e.In.Body != null); var exchange = CreateExchange("data"); var result = validator.Validate(exchange); result.IsValid.Should().BeTrue(); } [Fact] public void PredicateValidator_PredicateFalse_ReturnsFailure() { var validator = new PredicateValidator(e => e.In.Body != null, "Body must not be null"); var exchange = CreateExchange(null); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain("Body must not be null"); } [Fact] public void PredicateValidator_DynamicErrorMessage_UsesFactory() { var validator = new PredicateValidator( e => e.In.Body is string s && s.Length > 5, e => $"Body too short: {((string?)e.In.Body)?.Length ?? 0} chars"); var exchange = CreateExchange("abc"); var result = validator.Validate(exchange); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain(e => e.Contains("3 chars")); } [Fact] public void PredicateValidator_NullPredicate_Throws() { // The cast only picks the overload: both the predicate and the delegate constructors reject null. var act = () => new PredicateValidator((redb.Route.Abstractions.IPredicate)null!); act.Should().Throw(); } // ═══════════════════════════════════════════════════════════════════ // ValidateProcessor // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task ValidateProcessor_Valid_SetsProperties() { var validator = new JsonSchemaValidator(PersonJsonSchema); var processor = new ValidateProcessor(validator); var exchange = CreateExchange(ValidPersonJson); await processor.Process(exchange); exchange.Properties[ValidateProcessor.ValidationResultProperty].Should().Be(true); exchange.Properties[ValidateProcessor.ValidationErrorsProperty].Should().BeNull(); } [Fact] public async Task ValidateProcessor_Invalid_ThrowsByDefault() { var validator = new JsonSchemaValidator(PersonJsonSchema); var processor = new ValidateProcessor(validator); var exchange = CreateExchange(InvalidPersonJson_MissingAge); var act = () => processor.Process(exchange); await act.Should().ThrowAsync(); exchange.Properties[ValidateProcessor.ValidationResultProperty].Should().Be(false); exchange.Properties[ValidateProcessor.ValidationErrorsProperty].Should().NotBeNull(); } [Fact] public async Task ValidateProcessor_Invalid_SoftMode_DoesNotThrow() { var validator = new JsonSchemaValidator(PersonJsonSchema); var processor = new ValidateProcessor(validator, throwOnFailure: false); var exchange = CreateExchange(InvalidPersonJson_MissingAge); await processor.Process(exchange); exchange.Properties[ValidateProcessor.ValidationResultProperty].Should().Be(false); var errors = (string?)exchange.Properties[ValidateProcessor.ValidationErrorsProperty]; errors.Should().NotBeNullOrEmpty(); } [Fact] public void ValidateProcessor_NullValidator_Throws() { var act = () => new ValidateProcessor(null!); act.Should().Throw(); } // ═══════════════════════════════════════════════════════════════════ // ValidationException // ═══════════════════════════════════════════════════════════════════ [Fact] public void ValidationException_ContainsErrors() { var errors = new List { "err1", "err2" }; var ex = new ValidationException(errors); ex.Errors.Should().BeEquivalentTo(new[] { "err1", "err2" }); ex.Message.Should().Contain("err1"); ex.Message.Should().Contain("err2"); } // ═══════════════════════════════════════════════════════════════════ // ValidationResult // ═══════════════════════════════════════════════════════════════════ [Fact] public void ValidationResult_Success_IsValid() { var result = ValidationResult.Success(); result.IsValid.Should().BeTrue(); result.Errors.Should().BeEmpty(); } [Fact] public void ValidationResult_Failure_SingleError() { var result = ValidationResult.Failure("bad"); result.IsValid.Should().BeFalse(); result.Errors.Should().ContainSingle().Which.Should().Be("bad"); } [Fact] public void ValidationResult_Failure_MultipleErrors() { var result = ValidationResult.Failure(new[] { "err1", "err2" }); result.IsValid.Should().BeFalse(); result.Errors.Should().HaveCount(2); } // ═══════════════════════════════════════════════════════════════════ // DSL Integration — .Validate() step // ═══════════════════════════════════════════════════════════════════ [Fact] public void DSL_Validate_WithInstance_RecordsStep() { var def = new RouteDefinition(); var validator = new JsonSchemaValidator(PersonJsonSchema); def.Validate(validator).To("direct://output"); def.Outputs.Should().ContainSingle(s => s is ValidateInstanceDefinition); } [Fact] public void DSL_Validate_WithPredicate_RecordsStep() { var def = new RouteDefinition(); def.Validate(e => e.In.Body != null, "Body required").To("direct://output"); def.Outputs.Should().ContainSingle(s => s is ValidatePredicateDefinition); } [Fact] public void DSL_Validate_WithJsonSchemaValidator_RecordsCorrectStep() { var def = new RouteDefinition(); var validator = new JsonSchemaValidator(PersonJsonSchema); def.Validate(validator).To("mock://result"); var node = def.Outputs.OfType().Single(); node.Validator.Should().BeSameAs(validator); node.ThrowOnFailure.Should().BeTrue(); } [Fact] public void DSL_Validate_WithXsdValidator_RecordsCorrectStep() { var def = new RouteDefinition(); var validator = new XsdValidator(PersonXsd); def.Validate(validator).To("mock://result"); var node = def.Outputs.OfType().Single(); node.Validator.Should().BeSameAs(validator); } [Fact] public void DSL_Validate_WithPredicate_RecordsCorrectStep() { var def = new RouteDefinition(); def.Validate(e => e.In.Body != null, "Body required").To("mock://result"); var node = def.Outputs.OfType().Single(); node.ErrorMessage.Should().Be("Body required"); node.ThrowOnFailure.Should().BeTrue(); } [Fact] public void DSL_Validate_SoftMode_NoThrow() { var def = new RouteDefinition(); var validator = new JsonSchemaValidator(PersonJsonSchema); def.Validate(validator, throwOnFailure: false).To("mock://result"); def.Outputs.OfType().Single().ThrowOnFailure.Should().BeFalse(); } // ═══════════════════════════════════════════════════════════════════ // End-to-end pipeline validation // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Pipeline_JsonValidation_Valid_PassesThrough() { var validator = new JsonSchemaValidator(PersonJsonSchema); var processor = new ValidateProcessor(validator); var exchange = CreateExchange(ValidPersonJson); await processor.Process(exchange); // No exception, body untouched exchange.In.Body.Should().Be(ValidPersonJson); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task Pipeline_XsdValidation_Valid_PassesThrough() { var validator = new XsdValidator(PersonXsd); var processor = new ValidateProcessor(validator); var exchange = CreateExchange(ValidPersonXml); await processor.Process(exchange); exchange.In.Body.Should().Be(ValidPersonXml); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task Pipeline_JsonValidation_Invalid_Throws() { var validator = new JsonSchemaValidator(PersonJsonSchema); var processor = new ValidateProcessor(validator); var exchange = CreateExchange(InvalidPersonJson_MissingAge); var act = () => processor.Process(exchange); var ex = (await act.Should().ThrowAsync()).Which; ex.Errors.Should().NotBeEmpty(); } [Fact] public async Task Pipeline_XsdValidation_Invalid_Throws() { var validator = new XsdValidator(PersonXsd); var processor = new ValidateProcessor(validator); var exchange = CreateExchange(InvalidPersonXml_MissingAge); var act = () => processor.Process(exchange); var ex = (await act.Should().ThrowAsync()).Which; ex.Errors.Should().NotBeEmpty(); } [Fact] public async Task Pipeline_SoftValidation_Invalid_SetsPropertyOnly() { var validator = new XsdValidator(PersonXsd); var processor = new ValidateProcessor(validator, throwOnFailure: false); var exchange = CreateExchange(InvalidPersonXml_MissingAge); await processor.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeFalse(); var errors = (string?)exchange.Properties[ValidateProcessor.ValidationErrorsProperty]; errors.Should().NotBeNullOrEmpty(); // Body untouched exchange.In.Body.Should().Be(InvalidPersonXml_MissingAge); } // ═══════════════════════════════════════════════════════════════════ // Mix: validate JSON then transform, validate XML then transform // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Pipeline_ValidateJson_ThenTransform() { var validator = new JsonSchemaValidator(PersonJsonSchema); var exchange = CreateExchange(ValidPersonJson); // Validate var proc = new ValidateProcessor(validator); await proc.Process(exchange); // Transform after valid exchange.In.Body = $"Validated: {exchange.In.Body}"; exchange.In.Body.Should().Be("Validated: {\"name\":\"John\",\"age\":30}"); } [Fact] public async Task Pipeline_ValidateXsd_ThenTransform() { var validator = new XsdValidator(PersonXsd); var exchange = CreateExchange(ValidPersonXml); var proc = new ValidateProcessor(validator); await proc.Process(exchange); exchange.In.Body = $"Validated: {exchange.In.Body}"; ((string)exchange.In.Body!).Should().StartWith("Validated:"); } // ═══════════════════════════════════════════════════════════════════ // ValidatorComponent (URI-based) // ═══════════════════════════════════════════════════════════════════ [Fact] public void ValidatorComponent_Scheme_IsValidator() { var component = new ValidatorComponent(); component.Scheme.Should().Be("validator"); } [Fact] public void ValidatorComponent_JsonSchema_CreatesEndpoint() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".json"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}", new Dictionary()); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); endpoint.Should().BeOfType(); } finally { File.Delete(schemaFile); } } [Fact] public void ValidatorComponent_XsdSchema_CreatesEndpoint() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonXsd, ".xsd"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}", new Dictionary()); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); } finally { File.Delete(schemaFile); } } [Fact] public void ValidatorComponent_MissingFile_Throws() { var component = new ValidatorComponent(); var uri = new EndpointUri("validator", "nonexistent.json", "validator://nonexistent.json", new Dictionary()); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } [Fact] public void ValidatorComponent_FormatOverride_ForcesJson() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".txt"); // .txt extension, but format=json try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}?format=json", new Dictionary { { "format", "json" } }); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); } finally { File.Delete(schemaFile); } } [Fact] public async Task ValidatorComponent_ProducerValidatesJson() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".json"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(ValidPersonJson); await producer.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } finally { File.Delete(schemaFile); } } [Fact] public async Task ValidatorComponent_ProducerThrowsOnInvalidJson() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".json"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(InvalidPersonJson_MissingAge); var act = () => producer.Process(exchange); await act.Should().ThrowAsync(); } finally { File.Delete(schemaFile); } } [Fact] public async Task ValidatorComponent_SoftMode_DoesNotThrow() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".json"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}?throwOnFailure=false", new Dictionary { { "throwOnFailure", "false" } }); var endpoint = component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(InvalidPersonJson_MissingAge); await producer.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeFalse(); } finally { File.Delete(schemaFile); } } [Fact] public void ValidatorComponent_ConsumerNotSupported() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".json"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } finally { File.Delete(schemaFile); } } [Fact] public void ValidatorComponent_InvalidFormatParameter_Throws() { var component = new ValidatorComponent(); var schemaFile = CreateTempFile(PersonJsonSchema, ".json"); try { var uri = new EndpointUri("validator", schemaFile, $"validator://{schemaFile}?format=yaml", new Dictionary { { "format", "yaml" } }); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*yaml*"); } finally { File.Delete(schemaFile); } } // ═══════════════════════════════════════════════════════════════════ // DSL: Explicit format-forcing methods // ═══════════════════════════════════════════════════════════════════ [Fact] public void ValidateJsonSchema_String_Records_Step() { var def = new RouteDefinition(); def.ValidateJsonSchema(PersonJsonSchema); def.Outputs.Should().ContainSingle(s => s is ValidateJsonSchemaStringDefinition) .Which.Should().BeOfType() .Which.SchemaJson.Should().Be(PersonJsonSchema); } [Fact] public void ValidateJsonSchema_String_ThrowOnFailure_Default_True() { var def = new RouteDefinition(); def.ValidateJsonSchema(PersonJsonSchema); def.Outputs.OfType().Single() .ThrowOnFailure.Should().BeTrue(); } [Fact] public void ValidateJsonSchema_String_SoftMode() { var def = new RouteDefinition(); def.ValidateJsonSchema(PersonJsonSchema, throwOnFailure: false); def.Outputs.OfType().Single() .ThrowOnFailure.Should().BeFalse(); } [Fact] public void ValidateJsonSchema_Object_Records_Step() { var schema = JsonSchema.FromText(PersonJsonSchema); var def = new RouteDefinition(); def.ValidateJsonSchema(schema); def.Outputs.Should().ContainSingle(s => s is ValidateJsonSchemaObjectDefinition) .Which.Should().BeOfType(); } [Fact] public void ValidateJsonSchema_NullString_Throws() { var def = new RouteDefinition(); var act = () => def.ValidateJsonSchema((string)null!); act.Should().Throw(); } [Fact] public void ValidateJsonSchema_NullObject_Throws() { var def = new RouteDefinition(); var act = () => def.ValidateJsonSchema((JsonSchema)null!); act.Should().Throw(); } [Fact] public void ValidateXsd_String_Records_Step() { var def = new RouteDefinition(); def.ValidateXsd(PersonXsd); def.Outputs.Should().ContainSingle(s => s is ValidateXsdStringDefinition) .Which.Should().BeOfType() .Which.XsdContent.Should().Be(PersonXsd); } [Fact] public void ValidateXsd_String_ThrowOnFailure_Default_True() { var def = new RouteDefinition(); def.ValidateXsd(PersonXsd); def.Outputs.OfType().Single() .ThrowOnFailure.Should().BeTrue(); } [Fact] public void ValidateXsd_String_SoftMode() { var def = new RouteDefinition(); def.ValidateXsd(PersonXsd, throwOnFailure: false); def.Outputs.OfType().Single() .ThrowOnFailure.Should().BeFalse(); } [Fact] public void ValidateXsd_Namespace_Records_Step() { var def = new RouteDefinition(); def.ValidateXsd("http://example.com", PersonXsd); def.Outputs.Should().ContainSingle(s => s is ValidateXsdNamespaceDefinition) .Which.Should().BeOfType(); var node = def.Outputs.OfType().Single(); node.TargetNamespace.Should().Be("http://example.com"); node.XsdContent.Should().Be(PersonXsd); } [Fact] public void ValidateXsd_SchemaSet_Records_Step() { var schemaSet = new XmlSchemaSet(); using var reader = new StringReader(PersonXsd); schemaSet.Add("", System.Xml.XmlReader.Create(reader)); schemaSet.Compile(); var def = new RouteDefinition(); def.ValidateXsd(schemaSet); def.Outputs.Should().ContainSingle(s => s is ValidateXsdSchemaSetDefinition) .Which.Should().BeOfType(); } [Fact] public void ValidateXsd_NullString_Throws() { var def = new RouteDefinition(); var act = () => def.ValidateXsd((string)null!); act.Should().Throw(); } [Fact] public void ValidateXsd_NullSchemaSet_Throws() { var def = new RouteDefinition(); var act = () => def.ValidateXsd((XmlSchemaSet)null!); act.Should().Throw(); } // ── E2E: Forced-format pipeline tests ── [Fact] public async Task ValidateJsonSchema_Pipeline_Valid_PassesThrough() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateJsonSchema(PersonJsonSchema); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(ValidPersonJson); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task ValidateJsonSchema_Pipeline_Invalid_Throws() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateJsonSchema(PersonJsonSchema); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(InvalidPersonJson_MissingAge); var act = async () => await compiled.Process(exchange); await act.Should().ThrowAsync(); } [Fact] public async Task ValidateJsonSchema_Object_Pipeline_Valid() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var schema = JsonSchema.FromText(PersonJsonSchema); var route = new RouteDefinition(); route.From("direct:validated") .ValidateJsonSchema(schema); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(ValidPersonJson); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task ValidateXsd_Pipeline_Valid_PassesThrough() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateXsd(PersonXsd); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(ValidPersonXml); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task ValidateXsd_Pipeline_Invalid_Throws() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateXsd(PersonXsd); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(InvalidPersonXml_MissingAge); var act = async () => await compiled.Process(exchange); await act.Should().ThrowAsync(); } [Fact] public async Task ValidateXsd_Namespace_Pipeline_Valid() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateXsd(null, PersonXsd); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(ValidPersonXml); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task ValidateXsd_SchemaSet_Pipeline_Valid() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var schemaSet = new XmlSchemaSet(); using var reader = new StringReader(PersonXsd); schemaSet.Add("", System.Xml.XmlReader.Create(reader)); schemaSet.Compile(); var route = new RouteDefinition(); route.From("direct:validated") .ValidateXsd(schemaSet); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(ValidPersonXml); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeTrue(); } [Fact] public async Task ValidateJsonSchema_SoftMode_Pipeline_Invalid_NoThrow() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateJsonSchema(PersonJsonSchema, throwOnFailure: false); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(InvalidPersonJson_MissingAge); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeFalse(); exchange.Properties[ValidateProcessor.ValidationErrorsProperty].Should().NotBeNull(); } [Fact] public async Task ValidateXsd_SoftMode_Pipeline_Invalid_NoThrow() { var context = new RouteContext(); context.AddComponent(new Route.Components.DirectComponent()); var route = new RouteDefinition(); route.From("direct:validated") .ValidateXsd(PersonXsd, throwOnFailure: false); var compiled = route.CreateProcessor(context); var exchange = CreateExchange(InvalidPersonXml_MissingAge); await compiled.Process(exchange); ((bool)exchange.Properties[ValidateProcessor.ValidationResultProperty]!).Should().BeFalse(); exchange.Properties[ValidateProcessor.ValidationErrorsProperty].Should().NotBeNull(); } // ═══════════════════════════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════════════════════════ private static string CreateTempFile(string content, string extension) { var path = Path.Combine(Path.GetTempPath(), $"redb_test_{Guid.NewGuid()}{extension}"); File.WriteAllText(path, content); return path; } } Path: redb-route/tests/redb.Route.Tests/Validation/XsdMultiFileTests.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/Validation/XsdMultiFileTests.cs ---- using System.Xml.Schema; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Validation; using Xunit; namespace redb.Route.Tests.Validation; /// /// Row 37: an XSD read from its file resolves its xs:import and xs:include relative to it, from under /// one root only. A reference that is not found, lies outside the root or points to the network is an error naming it; /// so is anything else the schema compiler reports. Before, every form read the file as text and lost its location, /// so multi-file schemas (UBL, ebMS3) could not be validated at all. /// public sealed class XsdMultiFileTests : IAsyncLifetime { private readonly string _dir = Path.Combine(Path.GetTempPath(), "xsd-multi-" + Guid.NewGuid().ToString("N")[..8]); private readonly RouteContext _context = new(); private static string Fixtures => Path.Combine(AppContext.BaseDirectory, "Fixtures", "xsd"); public Task InitializeAsync() { Directory.CreateDirectory(_dir); return Task.CompletedTask; } public async Task DisposeAsync() { await _context.DisposeAsync(); Directory.Delete(_dir, recursive: true); } private string Write(string relative, string content) { var path = Path.Combine(_dir, relative); Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllText(path, content); return path; } private static IExchange Body(string xml) => new Exchange(new Message(xml)); private const string Common = """ """; private const string Part = """ """; private static string Main(string importLocation, bool useImported = true) => $""" """; private const string Valid = """1EUR"""; // ── import and include in nested directories ── [Fact] public void ImportAndInclude_InNestedDirectories_Load() { Write("schemas/common/common.xsd", Common); Write("schemas/order/parts/id.xsd", Part); var main = Write("schemas/order/order.xsd", Main("../common/common.xsd")); var validator = XsdValidator.FromFile(main, schemaRoot: ".."); validator.Validate(Body(Valid)).IsValid.Should().BeTrue(); validator.Validate(Body("""1euro""")) .IsValid.Should().BeFalse("the imported type's pattern applies"); } [Fact] public void AnImportOutsideTheRoot_IsAnError_EvenWhenUnused() { Write("common/common.xsd", Common); Write("order/parts/id.xsd", Part); var main = Write("order/order.xsd", Main("../common/common.xsd", useImported: false)); var act = () => XsdValidator.FromFile(main); act.Should().Throw() .WithMessage("validateXsd: the schema refers to '*common.xsd', outside '*order*'; imports and includes stay inside the package."); } [Fact] public void ANetworkImport_IsAnError_EvenWhenUnused() { Write("parts/id.xsd", Part); var main = Write("order.xsd", Main("http://127.0.0.1:9/common.xsd", useImported: false)); var act = () => XsdValidator.FromFile(main); act.Should().Throw() .WithMessage("validateXsd: the schema refers to 'http://127.0.0.1:9/common.xsd'; a schema and its imports are read from the package only, not the network."); } [Fact] public void AMissingImport_IsAnError_NamingTheSchema() { Write("parts/id.xsd", Part); var main = Write("order.xsd", Main("common.xsd", useImported: false)); var act = () => XsdValidator.FromFile(main); act.Should().Throw().WithMessage($"validateXsd: schema '{main}': *"); } [Fact] public void ADoctypeInAnImportedFile_IsSkipped() { Write("common.xsd", """ ]> """ + Common); Write("parts/id.xsd", Part); var main = Write("order.xsd", Main("common.xsd")); XsdValidator.FromFile(main).Validate(Body(Valid)).IsValid.Should().BeTrue(); } // ── the root element across an imported namespace ── [Fact] public void TheRootElementCheck_KnowsTheGlobalElementsOfImportedSchemas() { Write("common.xsd", Common); Write("parts/id.xsd", Part); var validator = XsdValidator.FromFile(Write("order.xsd", Main("common.xsd"))); validator.Validate(Body("""hello""")).IsValid .Should().BeTrue("a global element of an imported schema is a root of the set"); validator.Validate(Body("""hello""")).Errors .Should().ContainSingle().Which.Should().Be("Root element '{urn:other}note' is not declared in the schema (cvc-elt.1.a)"); } [Fact] public void ALaxWildcardOverAnImportedNamespace_IsValidatedOnceTheImportLoads() { Write("common.xsd", Common); Write("parts/id.xsd", Part); var validator = XsdValidator.FromFile(Write("order.xsd", Main("common.xsd"))); validator.Validate(Body("""1EUR7""")) .IsValid.Should().BeTrue(); validator.Validate(Body("""1EURseven""")) .IsValid.Should().BeFalse("the element has a declaration now, so lax content is validated against it"); } // ── standard multi-file schemas ── [Fact] public void Ubl21Invoice_ValidatesItsExample_WithTheRootAboveMaindoc() { var validator = XsdValidator.FromFile(Path.Combine(Fixtures, "ubl", "maindoc", "UBL-Invoice-2.1.xsd"), schemaRoot: ".."); validator.Validate(Body(File.ReadAllText(Path.Combine(Fixtures, "ubl", "xml", "UBL-Invoice-2.1-Example.xml")))) .IsValid.Should().BeTrue(); } [Fact] public void Ubl21Invoice_WithoutTheRoot_RefusesItsCommonImports() { var act = () => XsdValidator.FromFile(Path.Combine(Fixtures, "ubl", "maindoc", "UBL-Invoice-2.1.xsd")); act.Should().Throw().WithMessage("validateXsd: the schema refers to '*common*', outside '*maindoc*'*"); } [Fact] public void WsSecurity_LoadsXmldsigWithItsDoctype() { var act = () => XsdValidator.FromFile(Path.Combine(Fixtures, "ebms", "oasis-200401-wss-wssecurity-secext-1.0.xsd")); act.Should().NotThrow(); } // ── the route forms ── private sealed class PackageResolver(string root) : IRouteResourceResolver { public string? Resolve(string reference) { var candidate = Path.Combine(root, reference); return File.Exists(candidate) ? candidate : null; } public string DescribeSearch(string reference) => Path.Combine(root, reference); } [Fact] public async Task ValidateXsdFile_ResolvesThroughTheResourceResolver_AndReadsTheImports() { Write("resources/schemas/common.xsd", Common); Write("resources/schemas/parts/id.xsd", Part); Write("resources/schemas/order.xsd", Main("common.xsd")); _context.AddService(typeof(IRouteResourceResolver), new PackageResolver(_dir)); _context.AddRoutes(r => r.From("direct://xsd-file-in").ValidateXsdFile("resources/schemas/order.xsd")); await _context.Start(); var producer = _context.GetEndpoint("direct://xsd-file-in").CreateProducer(); await producer.Start(); var good = new Exchange(new Message(Valid)); await producer.Process(good); var bad = () => producer.Process(new Exchange(new Message("""1euro"""))); good.Exception.Should().BeNull(); await bad.Should().ThrowAsync().WithMessage("*'urn:common:Code'*Pattern*"); } [Fact] public async Task ValidatorEndpoint_ReadsTheImportsUnderSchemaRoot() { Write("schemas/common/common.xsd", Common); Write("schemas/order/parts/id.xsd", Part); var main = Write("schemas/order/order.xsd", Main("../common/common.xsd")); var uri = $"validator:{main.Replace('\\', '/')}?schemaRoot=.."; _context.AddComponent(new ValidatorComponent()); _context.AddRoutes(r => r.From("direct://xsd-endpoint-in").To(uri)); await _context.Start(); var producer = _context.GetEndpoint("direct://xsd-endpoint-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(Valid)); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } [Fact] public void ValidatorEndpoint_WithSchemaRootOnAJsonSchema_IsRefused() { var json = Write("schema.json", """{"type":"object"}"""); var component = new ValidatorComponent(); var act = () => component.CreateEndpoint(new EndpointUri("validator", json, "validator:" + json, new Dictionary { ["schemaRoot"] = ".." })); act.Should().Throw().WithMessage("schemaRoot applies to XSD schemas*"); } } Path: redb-route/tests/redb.Route.Tests/Xslt/XsltEngineSubstitutionTests.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/Xslt/XsltEngineSubstitutionTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xslt; namespace redb.Route.Tests.Xslt; /// /// has been an interface since 3.5.0, and its documentation said another /// engine could be plugged in. It could not: the DSL verbs and the component each named /// directly, so there was no seam behind the interface. /// /// Substitution now goes through — the factory rather than the /// engine, because a stylesheet has to be compiled, and compiling is exactly what a different /// processor does differently. These tests cover all three places a stylesheet gets compiled, plus /// the default staying the default. /// /// public class XsltEngineSubstitutionTests : IAsyncLifetime { private const string Stylesheet = """ """; private const string Input = "world"; private const string BclResult = "world"; private readonly string _stylesheetFile; public XsltEngineSubstitutionTests() { _stylesheetFile = Path.Combine(Path.GetTempPath(), $"redb-xslt-sub-{Guid.NewGuid():N}.xsl"); File.WriteAllText(_stylesheetFile, Stylesheet); } public Task InitializeAsync() => Task.CompletedTask; public Task DisposeAsync() { try { File.Delete(_stylesheetFile); } catch (IOException) { /* the temp file outlives the test at worst */ } GC.SuppressFinalize(this); return Task.CompletedTask; } // ── A stand-in processor ── /// An engine that ignores the stylesheet and reports what it was handed. private sealed class StubEngine(string origin) : IXsltEngine { public object Transform(object? body, XsltOutput output, IReadOnlyDictionary? parameters) => $"stub[{origin}]:{body}"; } private sealed class StubFactory : IXsltEngineFactory { public int FileCompilations { get; private set; } public int ContentCompilations { get; private set; } public IXsltEngine FromFile(string stylesheetPath) { FileCompilations++; return new StubEngine("file"); } public IXsltEngine FromContent(string stylesheetXml) { ContentCompilations++; return new StubEngine("content"); } } // ── Harness ── private static async Task RunRoute(RouteContext context, string from, Action configure) { object? result = null; context.AddRoutes(r => configure(r.From(from).Process(_ => { }))); await context.Start(); var producer = context.GetEndpoint(from).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(Input)); await producer.Process(exchange); result = exchange.In.Body; return result; } // ── The default is unchanged ── [Fact] public async Task Without_a_registration_the_built_in_engine_still_runs() { await using var context = new RouteContext(); var result = await RunRoute(context, "direct://xslt-default", r => r.XsltContent(Stylesheet)); result.Should().Be(BclResult); } [Fact] public void The_default_factory_is_the_answer_when_nothing_is_registered() { var context = new RouteContext(); context.GetXsltEngineFactory().Should().BeSameAs(XslCompiledTransformEngineFactory.Instance); } // ── Substitution reaches every place a stylesheet is compiled ── [Fact] public async Task A_registered_factory_compiles_the_inline_stylesheet_verb() { var factory = new StubFactory(); await using var context = new RouteContext(); context.UseXsltEngine(factory); var result = await RunRoute(context, "direct://xslt-sub-content", r => r.XsltContent(Stylesheet)); result.Should().Be($"stub[content]:{Input}"); factory.ContentCompilations.Should().Be(1); } [Fact] public async Task A_registered_factory_compiles_the_file_stylesheet_verb() { var factory = new StubFactory(); await using var context = new RouteContext(); context.UseXsltEngine(factory); var result = await RunRoute(context, "direct://xslt-sub-file", r => r.Xslt(_stylesheetFile)); result.Should().Be($"stub[file]:{Input}"); factory.FileCompilations.Should().Be(1); } [Fact] public async Task A_registered_factory_compiles_the_component_stylesheet() { var factory = new StubFactory(); await using var context = new RouteContext(); context.UseXsltEngine(factory); var result = await RunRoute(context, "direct://xslt-sub-comp", r => r.To($"xslt:{_stylesheetFile}")); result.Should().Be($"stub[file]:{Input}"); factory.FileCompilations.Should().Be(1); } // ── Both registration surfaces ── [Fact] public void A_factory_registered_through_DI_is_found_too() { var factory = new StubFactory(); var services = new ServiceCollection(); services.AddXsltEngine(factory); var context = new RouteContext(services.BuildServiceProvider()); context.GetXsltEngineFactory().Should().BeSameAs(factory); } [Fact] public void What_the_context_was_told_wins_over_the_container() { var fromContainer = new StubFactory(); var fromContext = new StubFactory(); var services = new ServiceCollection(); services.AddXsltEngine(fromContainer); var context = new RouteContext(services.BuildServiceProvider()); context.UseXsltEngine(fromContext); context.GetXsltEngineFactory().Should().BeSameAs(fromContext, "the order is the same as for every other pluggable service here"); } } Path: redb-route/tests/redb.Route.Tests/Xslt/XsltEngineTests.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/Xslt/XsltEngineTests.cs ---- using System.Text; using System.Xml; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Xslt; namespace redb.Route.Tests.Xslt; /// Tests for and . public class XsltEngineTests { // Maps X → X. private const string Stylesheet = """ """; private const string Input = "world"; [Fact] public void FromContent_TransformsXml_ToString() { var engine = XslCompiledTransformEngine.FromContent(Stylesheet); var result = engine.Transform(Input, XsltOutput.String, null); result.Should().BeOfType().Which.Should().Be("world"); } [Fact] public void Transform_BytesOutput_ReturnsEncodedXml() { var engine = XslCompiledTransformEngine.FromContent(Stylesheet); var result = engine.Transform(Input, XsltOutput.Bytes, null); result.Should().BeOfType(); Encoding.UTF8.GetString((byte[])result).Should().Contain("world"); } [Fact] public void Transform_DomOutput_ReturnsXmlDocument() { var engine = XslCompiledTransformEngine.FromContent(Stylesheet); var result = engine.Transform(Input, XsltOutput.Dom, null); var doc = result.Should().BeOfType().Which; doc.DocumentElement!.Name.Should().Be("hello"); doc.DocumentElement.InnerText.Should().Be("world"); } [Fact] public void Transform_ByteArrayInput_Works() { var engine = XslCompiledTransformEngine.FromContent(Stylesheet); var result = engine.Transform(Encoding.UTF8.GetBytes(Input), XsltOutput.String, null); result.Should().Be("world"); } [Fact] public void Transform_XDocumentInput_Works() { var engine = XslCompiledTransformEngine.FromContent(Stylesheet); var result = engine.Transform(XDocument.Parse(Input), XsltOutput.String, null); result.Should().Be("world"); } [Fact] public void Transform_WithParameters_PassesToStylesheet() { const string paramStyle = """ Hello """; var engine = XslCompiledTransformEngine.FromContent(paramStyle); var result = engine.Transform("", XsltOutput.String, new Dictionary { ["who"] = "world" }); result.Should().Be("Hello world"); } [Fact] public void Transform_UnsupportedBodyType_Throws() { var engine = XslCompiledTransformEngine.FromContent(Stylesheet); var act = () => engine.Transform(42, XsltOutput.String, null); act.Should().Throw(); } [Fact] public void FromContent_InvalidStylesheet_Throws() { var act = () => XslCompiledTransformEngine.FromContent(""); act.Should().Throw(); } [Fact] public void FromContent_NullOrEmpty_Throws() { var act = () => XslCompiledTransformEngine.FromContent(""); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Xslt/XsltFileResolutionTests.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/Xslt/XsltFileResolutionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Xslt; /// /// The .Xslt(file) step (<xslt file="…"/> in markup) finds its stylesheet through the context's resource /// resolver, as the xslt: endpoint does: a package keeps its stylesheet where only the resolver knows. Before, the /// path was opened relative to the working directory, and a module on the Tsak worker failed with "Could not find a part /// of the path '/app/resources/…'". /// public sealed class XsltFileResolutionTests : IAsyncLifetime { private const string Stylesheet = """ invoice: """; private readonly string _dir = Path.Combine(Path.GetTempPath(), "xslt-res-" + Guid.NewGuid().ToString("N")); private readonly RouteContext _context = new(); public Task InitializeAsync() { Directory.CreateDirectory(Path.Combine(_dir, "resources")); File.WriteAllText(Path.Combine(_dir, "resources", "order-to-invoice.xslt"), Stylesheet); return Task.CompletedTask; } public async Task DisposeAsync() { await _context.DisposeAsync(); Directory.Delete(_dir, recursive: true); } /// Resolves references under one directory only, as a package's resolver does. private sealed class PackageResolver(string root) : IRouteResourceResolver { public string? Resolve(string reference) { var candidate = Path.Combine(root, reference); return File.Exists(candidate) ? candidate : null; } public string DescribeSearch(string reference) => Path.Combine(root, reference); } [Fact] public async Task The_stylesheet_of_an_xslt_step_is_found_through_the_resource_resolver() { _context.AddService(typeof(IRouteResourceResolver), new PackageResolver(_dir)); object? result = null; _context.AddRoutes(r => r.From("direct://xslt-in") .Xslt("resources/order-to-invoice.xslt") .Process(e => result = e.In.Body)); await _context.Start(); var producer = _context.GetEndpoint("direct://xslt-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(""))); result.Should().Be("invoice:o-1"); } [Fact] public async Task A_stylesheet_nobody_can_find_fails_the_start_naming_where_it_was_looked_for() { _context.AddService(typeof(IRouteResourceResolver), new PackageResolver(_dir)); _context.AddRoutes(r => r.From("direct://xslt-missing").Xslt("resources/missing.xslt")); var start = () => _context.Start(); (await start.Should().ThrowAsync()).Which.ToString().Should().Contain("missing.xslt"); } } Path: redb-route/tests/redb.Route.Tests/Xslt/XsltIntegrationTests.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/Xslt/XsltIntegrationTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xslt; namespace redb.Route.Tests.Xslt; /// /// Integration tests for XSLT through the DSL → Compiler → Engine pipeline, covering the inline /// .XsltContent(...) and file-based .Xslt(...) leaf forms and the xslt: component. /// public class XsltIntegrationTests : IAsyncLifetime { private const string Stylesheet = """ """; // Alternate stylesheet used for the dynamic (from-header) test: greeting → . private const string AltStylesheet = """ """; // Stylesheet that reads a parameter fed from a message header. private const string ParamStylesheet = """ region= """; private const string Input = "world"; private const string Expected = "world"; private readonly RouteContext _context = new(); private readonly string _stylesheetFile; private readonly string _altStylesheetFile; public XsltIntegrationTests() { _stylesheetFile = Path.Combine(Path.GetTempPath(), $"redb-xslt-{Guid.NewGuid():N}.xsl"); File.WriteAllText(_stylesheetFile, Stylesheet); _altStylesheetFile = Path.Combine(Path.GetTempPath(), $"redb-xslt-alt-{Guid.NewGuid():N}.xsl"); File.WriteAllText(_altStylesheetFile, AltStylesheet); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); try { File.Delete(_stylesheetFile); } catch { /* best-effort */ } try { File.Delete(_altStylesheetFile); } catch { /* best-effort */ } GC.SuppressFinalize(this); } private async Task StartAndGetProducer(string fromUri) { await _context.Start(); var producer = _context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task Xslt_InlineContent_TransformsBody() { object? result = null; _context.AddRoutes(r => r.From("direct://xslt-content") .XsltContent(Stylesheet) .Process(e => result = e.In.Body)); var producer = await StartAndGetProducer("direct://xslt-content"); await producer.Process(new Exchange(new Message(Input))); result.Should().Be(Expected); } [Fact] public async Task Xslt_FromFile_TransformsBody() { object? result = null; _context.AddRoutes(r => r.From("direct://xslt-file") .Xslt(_stylesheetFile) .Process(e => result = e.In.Body)); var producer = await StartAndGetProducer("direct://xslt-file"); await producer.Process(new Exchange(new Message(Input))); result.Should().Be(Expected); } [Fact] public async Task Xslt_Component_ViaTo_TransformsBody() { // The xslt: component is registered out of the box — no AddComponent needed. object? result = null; _context.AddRoutes(r => r.From("direct://xslt-comp") .To($"xslt:{_stylesheetFile}") .Process(e => result = e.In.Body)); var producer = await StartAndGetProducer("direct://xslt-comp"); await producer.Process(new Exchange(new Message(Input))); result.Should().Be(Expected); } [Fact] public async Task Xslt_Component_BytesOutput() { object? result = null; _context.AddRoutes(r => r.From("direct://xslt-bytes") .To($"xslt:{_stylesheetFile}?output=bytes") .Process(e => result = e.In.Body)); var producer = await StartAndGetProducer("direct://xslt-bytes"); await producer.Process(new Exchange(new Message(Input))); result.Should().BeOfType(); System.Text.Encoding.UTF8.GetString((byte[])result!).Should().Contain(Expected); } [Fact] public async Task Xslt_PassesHeadersAsParameters() { object? result = null; _context.AddRoutes(r => r.From("direct://xslt-param") .XsltContent(ParamStylesheet) .Process(e => result = e.In.Body)); var producer = await StartAndGetProducer("direct://xslt-param"); var exchange = new Exchange(new Message("")); exchange.In.Headers["region"] = "EU"; // fed to await producer.Process(exchange); result.Should().Be("region=EU"); } [Fact] public async Task Xslt_AllowTemplateFromHeader_OverridesStylesheetPerMessage() { object? result = null; _context.AddRoutes(r => r.From("direct://xslt-dyn") .Xslt(_stylesheetFile, allowTemplateFromHeader: true) // default → .Process(e => result = e.In.Body)); var producer = await StartAndGetProducer("direct://xslt-dyn"); var exchange = new Exchange(new Message(Input)); exchange.In.Headers[XsltHeaders.ResourceUri] = _altStylesheetFile; // override → await producer.Process(exchange); result.Should().Be("world"); } } Path: redb-route/tests/redb.Route.Tests/Xslt/XsltProcessorTests.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/Xslt/XsltProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xslt; namespace redb.Route.Tests.Xslt; /// Tests for body/null handling. public class XsltProcessorTests { private const string Stylesheet = """ """; private static XsltProcessor NewProcessor(bool failOnNullBody = true) => new(XslCompiledTransformEngine.FromContent(Stylesheet), XsltOutput.String, failOnNullBody); [Fact] public async Task Process_TransformsBody_InPlace() { var exchange = new Exchange(new Message("world")); await NewProcessor().Process(exchange); exchange.In.Body.Should().Be("world"); } [Fact] public async Task Process_NullBody_ThrowsWhenFailOnNull() { var exchange = new Exchange(new Message(null)); var act = () => NewProcessor(failOnNullBody: true).Process(exchange); await act.Should().ThrowAsync(); } [Fact] public async Task Process_NullBody_PassesThroughWhenNotFailOnNull() { var exchange = new Exchange(new Message(null)); await NewProcessor(failOnNullBody: false).Process(exchange); exchange.In.Body.Should().BeNull(); } [Fact] public void Constructor_NullEngine_Throws() { var act = () => new XsltProcessor(null!); act.Should().Throw().WithParameterName("engine"); } } Path: redb-route/tests/redb.Route.Tests/redb.Route.Tests.csproj 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/redb.Route.Tests.csproj ----