Path: redb-route/tests/redb.Route.Tests.Xml/RetryAndScopeKnobsTests.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.Xml/RetryAndScopeKnobsTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Xml;
namespace redb.Route.Tests.Xml;
///
/// The knobs the markup used to leave to C# only: an onException that decides whether it takes
/// the failure at all and how loudly it retries, a transaction with its own retry and dead
/// letter channel, a threads scope with a bounded queue, a metered scope split by tags.
/// Behaviour where the engine can show it, generated C# where the setting only travels.
///
public class RetryAndScopeKnobsTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
private async Task StartAndProducer(string fromUri)
{
await _context.Start();
var producer = _context.GetEndpoint(fromUri).CreateProducer();
await producer.Start();
return producer;
}
private void Load(string xml, string? sourceName = null)
=> _context.AddXmlRoutesFromContent(xml, sourceName ?? "");
private static string CodeOf(string xml)
=> XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Parse(xml), "Knobs", "Tests.Generated",
sourceName: "");
// ── onException: when to take the failure ────────────────────────────────
[Fact]
public async Task OnException_When_TakesTheFailureOnlyWhileTheConditionHolds()
{
Load("""
""");
var producer = await StartAndProducer("direct://knob-onwhen-in");
var matching = new Exchange(new Message("x"));
matching.In.Headers["rescue"] = "yes";
await producer.Process(matching);
matching.Exception.Should().BeNull("the condition holds, so the handler takes the failure");
matching.In.Headers["rescued"].Should().Be("yes");
var other = new Exchange(new Message("x"));
other.In.Headers["rescue"] = "no";
var act = () => producer.Process(other);
await act.Should().ThrowAsync(
"the condition fails, so the handler stands aside and the exception surfaces");
}
[Fact]
public async Task OnException_Continued_ResumesTheRouteAfterTheFailingStep()
{
Load("""
""");
var producer = await StartAndProducer("direct://knob-continued-in");
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.Exception.Should().BeNull("continued suppresses the exception");
exchange.ExceptionHandled.Should().BeTrue();
exchange.In.Headers["noted"].Should().Be("yes");
// Camel's continued(true): the route picks up at the step after the one that failed (implemented 2026-09-21).
exchange.In.Headers["after"].Should().Be("yes", "continued resumes the route after the failing step");
}
///
/// A condition reads a header whose NAME contains dots (the demos namespace their headers,
/// serials.decision). Written with ${…} the same line is a template, and a template
/// in a condition position is truthy whatever it renders — so the spelling matters.
///
[Fact]
public async Task ACondition_ReadsADottedHeaderName()
{
Load("""
""");
var producer = await StartAndProducer("direct://knob-dotted-in");
var accepted = new Exchange(new Message("x"));
accepted.In.Headers["serials.decision"] = "Accepted";
await producer.Process(accepted);
accepted.In.Headers["branch"].Should().Be("accepted");
var rejected = new Exchange(new Message("x"));
rejected.In.Headers["serials.decision"] = "Rejected";
await producer.Process(rejected);
rejected.In.Headers["branch"].Should().Be("other", "the branch is chosen by the value, not by truthiness");
}
// ── onException: the settings that only travel to the engine ─────────────
[Fact]
public void OnException_LoggingAndRetrySettings_ReachTheGeneratedCode()
{
var code = CodeOf("""
""");
code.Should().Contain("UseOriginalBody()");
code.Should().Contain("LogStackTrace(false)");
code.Should().Contain("LogExhausted(true)");
code.Should().Contain("LogHandled(false)");
code.Should().Contain("LogContinued(true)");
code.Should().Contain("RetryAttemptedLogLevel(LogLevel.Debug)");
code.Should().Contain("RetriesExhaustedLogLevel(LogLevel.Critical)");
code.Should().Contain("RetryWhile(\"header.again == 'yes'\")");
}
[Fact]
public void OnException_AnUnknownLogLevel_IsAPositionedError()
{
var act = () => Load("""
""", "bad-level.xml");
act.Should().Throw().WithMessage("*bad-level.xml(4,*Loud*log level*");
}
// ── onException: the three moments a bean can step into ──────────────────
[Fact]
public async Task OnException_CallbackBeans_RunAtTheirMoments()
{
var log = new List();
_context.AddToRegistry("occurred", new MarkProcessor("occurred", log));
_context.AddToRegistry("retry", new MarkProcessor("retry", log));
_context.AddToRegistry("prepare", new MarkProcessor("prepare", log));
Load("""
""");
var producer = await StartAndProducer("direct://knob-callbacks-in");
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.In.Headers["rescued"].Should().Be("yes");
log.Count(m => m == "retry").Should().Be(2, "one call before each of the two redeliveries");
log.Count(m => m == "occurred").Should().Be(3, "the first failure and the two failed retries");
log.Count(m => m == "prepare").Should().Be(1, "once, before the handler takes over for good");
log.Last().Should().Be("prepare", "preparation is the last thing before the handler");
}
[Fact]
public void OnException_ACallbackBeanThatIsNotRegistered_IsAPositionedError()
{
var act = () => Load("""
""", "missing-bean.xml");
act.Should().Throw().WithMessage("*missing-bean.xml(4,*onRedelivery*nowhere*");
}
[Fact]
public void OnException_CallbackBeans_ReachTheGeneratedCode()
{
var code = CodeOf("""
""");
code.Should().Contain("OnExceptionOccurred(Context!.GetFromRegistry(\"occurred\")!)");
code.Should().Contain("OnRedelivery(Context!.GetFromRegistry(\"retry\")!)");
code.Should().Contain("OnPrepareFailure(Context!.GetFromRegistry(\"prepare\")!)");
}
/// A registry bean that only records that it ran.
private sealed class MarkProcessor(string mark, List log) : IProcessor
{
public Task Process(IExchange exchange, CancellationToken ct = default)
{
log.Add(mark);
return Task.CompletedTask;
}
}
// ── transaction: its own retry and dead letter channel ───────────────────
[Fact]
public void Transaction_RetryAndDeadLetterChannel_ReachTheGeneratedCode()
{
var code = CodeOf("""
""");
code.Should().Contain("DeadLetterChannel(\"direct://knob-dlq\")");
code.Should().Contain("Retry(4, TimeSpan.FromSeconds(5))");
}
[Fact]
public void Transaction_RetryAttemptsWithoutADelay_IsRefused()
{
var act = () => Load("""
""", "half-retry.xml");
act.Should().Throw().WithMessage("*half-retry.xml(4,*retryDelay*");
}
// ── threads: a bounded queue in front of the pool ────────────────────────
[Fact]
public void Threads_QueueBounds_ReachTheGeneratedCode()
{
var code = CodeOf("""
""");
code.Should().Contain("Threads(4)");
code.Should().Contain("MaxQueueSize(100)");
code.Should().Contain("EnqueueTimeout(TimeSpan.FromSeconds(3))");
}
// ── metered: the metric split by tags ────────────────────────────────────
[Fact]
public void Metered_Tags_ReachTheGeneratedCode()
{
var code = CodeOf("""
""");
code.Should().Contain("TagFromHeader(\"partner\", \"partnerId\")");
code.Should().Contain("Tag(\"kind\"");
}
[Fact]
public void Metered_ATagWithNoSource_IsRefused()
{
var act = () => Load("""
""", "bad-tag.xml");
act.Should().Throw().WithMessage("*bad-tag.xml(5,*fromHeader*expr*");
}
// ── split: stopOnException=false lets the rest of the batch run ──────────
[Fact]
public async Task Split_StopOnExceptionFalse_ProcessesTheRestAfterAFailure()
{
Load("""
""");
var producer = await StartAndProducer("direct://knob-split-in");
var mock = (MockEndpoint)_context.GetEndpoint("mock://knob-split-out");
// The second of the three elements throws; the third must still be processed.
await producer.Process(new Exchange(new Message("1,2,3")));
mock.ReceivedExchanges.Should().HaveCount(2,
"the failing element is skipped and the elements after it still run");
}
[Fact]
public void Split_StopOnExceptionFalse_ReachesTheGeneratedCode()
{
var code = CodeOf("""
""");
// StopOnException() defaults to true, so the false case has to survive the round trip.
code.Should().Contain("StopOnException(false)");
code.Should().Contain("StopOnException()");
}
}