Path: redb-route/tests/redb.Route.Tests/Eip/OnCompletionModeTests.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/Eip/OnCompletionModeTests.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; using redb.Route.Transactions; namespace redb.Route.Tests.Eip; /// /// Where an OnCompletion block runs, as in Apache Camel: in the caller once the route has finished, the caller /// waiting for it, unless ParallelProcessing() or ExecutorService(name) gives it a bounded pool of its /// own. Either way it runs on a copy, detached from the caller's transaction and cancellation, and never changes the /// route's own result. /// public class OnCompletionModeTests { private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task ByDefault_TheCallerWaitsForTheBlock() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-sync") .OnCompletion().Process(async (_, _) => { entered.TrySetResult(); await gate.Task; }).EndOnCompletion() .SetBody("reply")); var producer = await Start(context, "direct://oc-sync"); var send = producer.Process(new Exchange(new Message("in"))); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); await Task.Delay(100); send.IsCompleted.Should().BeFalse("the caller runs the block and waits for it, as in Camel"); gate.SetResult(); await send.WaitAsync(TimeSpan.FromSeconds(5)); } [Fact] public async Task WithParallelProcessing_TheCallerDoesNotWait() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-parallel") .OnCompletion().ParallelProcessing().Process(async (_, _) => { entered.TrySetResult(); await gate.Task; }).EndOnCompletion() .SetBody("reply")); var producer = await Start(context, "direct://oc-parallel"); await producer.Process(new Exchange(new Message("in"))).WaitAsync(TimeSpan.FromSeconds(5)); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); gate.SetResult(); } [Fact] public async Task AFailingBlock_DoesNotChangeTheRoutesResult() { await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-fails") .OnCompletion().ThrowException("the block fails").EndOnCompletion() .SetBody("reply")); await context.Start(); var reply = await context.RequestBody("direct://oc-fails", "in"); reply.Should().Be("reply", "a failing block is logged and counted, never the caller's result"); } [Fact] public async Task AFailingBlock_AfterAFailedRoute_LeavesTheRoutesOwnException() { await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-fails-too") .OnCompletion().OnFailureOnly().ThrowException("the block fails").EndOnCompletion() .ThrowException("the route's own failure")); await context.Start(); var act = () => context.SendBody("direct://oc-fails-too", "in"); await act.Should().ThrowAsync().WithMessage("*the route's own failure*"); } [Fact] public async Task TheCallersCancellation_DoesNotCutTheBlockHalfWay() { // An aborted request (its token cancelled once the route has done its work) must not stop an audit or a // cleanup in the middle: the block after the consumer never gets the caller's token. using var aborted = new CancellationTokenSource(); var finished = false; await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-cancel") .OnCompletion().Process(async (_, ct) => { await Task.Delay(200, ct); finished = true; }).EndOnCompletion() .Process(_ => aborted.Cancel())); var producer = await Start(context, "direct://oc-cancel"); try { await producer.Process(new Exchange(new Message("in")), aborted.Token); } catch (OperationCanceledException) { } finished.Should().BeTrue("the block ran to its end although the caller's token was cancelled"); } /// A database stand-in: a resource enlisted in the ambient transaction that logs its outcome. 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(); } [Theory] [InlineData(true, false)] [InlineData(false, true)] public async Task TheBlock_RunsOutsideTheCallersTransaction_OnACopyWithoutItsSends(bool blockFails, bool mainFails) { // The caller's own transaction (an outer scope, as a transacted route that calls this one) is still open // while the block runs in the caller. var log = new List(); await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-tx") .OnCompletion().Process(e => { lock (log) { log.Add(Transaction.Current is null ? "block:no-transaction" : "block:in-transaction"); log.Add(e.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey) ? "block:has-sends" : "block:no-sends"); } if (blockFails) throw new InvalidOperationException("the block fails"); }).EndOnCompletion() .Transacted() .Process(_ => Transaction.Current!.EnlistVolatile(new LoggedDatabase(log), EnlistmentOptions.None)) .Process(_ => { if (mainFails) throw new InvalidOperationException("the main work fails"); }) .End()); var producer = await Start(context, "direct://oc-tx"); using (var outer = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = new TransactionPolicy().IsolationLevel }, TransactionScopeAsyncFlowOption.Enabled)) { var send = () => producer.Process(new Exchange(new Message("work"))); if (mainFails) await send.Should().ThrowAsync().WithMessage("the main work fails"); else { await send.Should().NotThrowAsync("a failing block never fails the route"); outer.Complete(); } } lock (log) { log.Should().Contain("block:no-transaction", "the block is detached from the caller's transaction"); log.Should().Contain("block:no-sends", "the copy does not carry the caller's deferred sends"); log.Should().Contain(mainFails ? "db:rollback" : "db:commit", mainFails ? "the main work rolls back although the block ran" : "the main work commits although the block failed"); } } [Fact] public async Task AnUnknownExecutorService_FailsTheRouteBuild_NamingIt() { await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-unknown") .OnCompletion().ExecutorService("no-such-pool").To("mock://never").EndOnCompletion() .SetBody("x")); var act = () => context.Start(); await act.Should().ThrowAsync().Where(e => Mentions(e, "no-such-pool")); } [Fact] public async Task AParallelBlock_StillRunning_IsWaitedForWhenTheContextStops() { var finished = false; var context = new RouteContext().AddRoutes(b => b .From("direct://oc-drain") .OnCompletion().ParallelProcessing().Process(async (_, _) => { await Task.Delay(300); finished = true; }).EndOnCompletion() .SetBody("x")); var producer = await Start(context, "direct://oc-drain"); await producer.Process(new Exchange(new Message("in"))); await context.Stop(); finished.Should().BeTrue("the block's pool drains when the consumers have stopped"); await context.DisposeAsync(); } private static bool Mentions(Exception? e, string text) { for (; e is not null; e = e.InnerException) if (e.Message.Contains(text, StringComparison.Ordinal)) return true; return false; } }