Path: redb-route/tests/redb.Route.Tests/Processors/DetachedPoolTests.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/DetachedPoolTests.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Tests.Processors; /// /// The bounded pool of a detached step (Camel's thread pool profile): a WireTap runs at most /// MaxConcurrency branches and queues at most MaxQueueSize; a branch that finds both full is run by the /// caller (the default), dropped or refused. A caller-run branch is still detached from the caller's transaction. /// public class DetachedPoolTests { private static DetachedExecutor Pool(int concurrency, int queue, ThreadPoolRejectedPolicy policy) => new("test", new ThreadPoolProfile { MaxConcurrency = concurrency, MaxQueueSize = queue, RejectedPolicy = policy }, "wireTap", "pool-route", null); private static Func Blocked(TaskCompletionSource gate, Action? started = null) => async () => { started?.Invoke(); await gate.Task; }; [Fact] public async Task AtMostMaxConcurrencyRun_TheNextWait_AndAllRunOnceSlotsFree() { var pool = Pool(2, 3, ThreadPoolRejectedPolicy.CallerRuns); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var started = 0; var running = 0; var peak = 0; for (var i = 0; i < 5; i++) { (await pool.Execute(async () => { Interlocked.Increment(ref started); var now = Interlocked.Increment(ref running); int seen; while ((seen = Volatile.Read(ref peak)) < now && Interlocked.CompareExchange(ref peak, now, seen) != seen) { } await gate.Task; Interlocked.Decrement(ref running); })).Should().BeTrue(); } await WaitFor(() => Volatile.Read(ref started) == 2); pool.Active.Should().Be(2); pool.Queued.Should().Be(3); gate.SetResult(); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); started.Should().Be(5); peak.Should().Be(2, "never more than MaxConcurrency at a time"); pool.Active.Should().Be(0); pool.Queued.Should().Be(0); } [Fact] public async Task WhenThePoolAndQueueAreFull_TheCallerRunsTheBranch() { var pool = Pool(1, 1, ThreadPoolRejectedPolicy.CallerRuns); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); await pool.Execute(Blocked(gate)); var callerThread = Environment.CurrentManagedThreadId; var ranOn = -1; var third = pool.Execute(() => { ranOn = Environment.CurrentManagedThreadId; return Task.CompletedTask; }); third.IsCompleted.Should().BeTrue("the caller ran the branch before Execute returned"); (await third).Should().BeTrue(); ranOn.Should().Be(callerThread); gate.SetResult(); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); } [Fact] public async Task Discard_DropsTheBranchAndCountsIt() { var pool = Pool(1, 0, ThreadPoolRejectedPolicy.Discard); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); var ran = false; (await pool.Execute(() => { ran = true; return Task.CompletedTask; })).Should().BeFalse(); ran.Should().BeFalse(); pool.Rejected.Should().Be(1); gate.SetResult(); } [Fact] public async Task Abort_RefusesTheBranch() { var pool = Pool(1, 0, ThreadPoolRejectedPolicy.Abort); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); var act = async () => await pool.Execute(() => Task.CompletedTask); await act.Should().ThrowAsync().WithMessage("*pool-route*"); pool.Rejected.Should().Be(1); gate.SetResult(); } [Fact] public async Task Drain_WaitsForWhatRunsAndWaits_AndStopsAtTheToken() { var pool = Pool(1, 5, ThreadPoolRejectedPolicy.CallerRuns); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); await pool.Execute(() => Task.CompletedTask); // The shutdown window runs out: the drain returns and leaves the count behind (logged, not dropped). await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromMilliseconds(200)).Token); (pool.Active + pool.Queued).Should().Be(2); gate.SetResult(); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); (pool.Active + pool.Queued).Should().Be(0, "the branches were not cancelled, they ran to the end"); } [Fact] public async Task AFailingBranch_IsCountedAndDoesNotStopThePool() { var pool = Pool(1, 5, ThreadPoolRejectedPolicy.CallerRuns); var ran = 0; await pool.Execute(() => throw new InvalidOperationException("a branch fails")); await pool.Execute(() => { Interlocked.Increment(ref ran); return Task.CompletedTask; }); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); ran.Should().Be(1); } [Theory] [InlineData(ThreadPoolRejectedPolicy.CallerRuns)] [InlineData(ThreadPoolRejectedPolicy.Discard)] [InlineData(ThreadPoolRejectedPolicy.Abort)] public async Task UnderManyProducers_EveryBranchRunsOnceOrIsCountedAsRejected_AndNothingIsLeftBehind( ThreadPoolRejectedPolicy policy) { const int producers = 16; const int perProducer = 2_000; const int offered = producers * perProducer; var pool = Pool(2, 3, policy); var runs = new int[offered]; var accepted = new bool[offered]; var discarded = 0; var aborted = 0; await Task.WhenAll(Enumerable.Range(0, producers).Select(p => Task.Run(async () => { for (var i = 0; i < perProducer; i++) { var id = p * perProducer + i; try { var taken = await pool.Execute(async () => { Interlocked.Increment(ref runs[id]); if (id % 7 == 0) await Task.Yield(); }); if (taken) accepted[id] = true; else Interlocked.Increment(ref discarded); } catch (RejectedExecutionException) { Interlocked.Increment(ref aborted); } } }))); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token); pool.Active.Should().Be(0); pool.Queued.Should().Be(0, "no branch is left in the queue"); var ran = runs.Count(r => r == 1); runs.Should().OnlyContain(r => r == 0 || r == 1, "no branch runs twice"); Enumerable.Range(0, offered).Where(id => accepted[id]).Should().OnlyContain(id => runs[id] == 1, "every accepted branch ran"); (ran + discarded + aborted).Should().Be(offered, "every branch either ran or was counted as rejected"); pool.Rejected.Should().Be(discarded + aborted); if (policy == ThreadPoolRejectedPolicy.CallerRuns) ran.Should().Be(offered, "nothing is lost under CallerRuns"); } // ── Profiles ── [Fact] public async Task ANamedProfile_RegisteredTwiceWithOtherBounds_Throws_NamingBoth() { await using var context = new RouteContext(); context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 4 }); context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 4 }); var act = () => context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 8 }); act.Should().Throw().WithMessage("*'audit'*MaxConcurrency=4*MaxConcurrency=8*"); } [Fact] public async Task AProfileFromTheOptions_IsKnownToTheContext() { var options = new RouteEngineOptions(); options.ThreadPoolProfiles["audit"] = new ThreadPoolProfile { MaxConcurrency = 3 }; await using var context = new RouteContext(options: options); context.GetThreadPoolProfile("audit").MaxConcurrency.Should().Be(3); context.GetThreadPoolProfile(null).Should().BeSameAs(options.DefaultThreadPoolProfile); } [Fact] public async Task AnUnknownProfile_FailsTheRouteBuild_NamingIt() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://pool-unknown").WireTap("direct://pool-sink", executorService: "no-such-pool")); var act = () => context.Start(); await act.Should().ThrowAsync().Where(e => ContainsMessage(e, "no-such-pool")); } [Fact] public async Task ATap_UsesItsNamedProfile() { await using var context = new RouteContext(); context.AddThreadPoolProfile("tiny", new ThreadPoolProfile { MaxConcurrency = 1, MaxQueueSize = 0 }); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var tapped = 0; context.AddRoutes(r => r.From("direct://pool-sink").Process(async (_, _) => { Interlocked.Increment(ref tapped); await gate.Task; })); context.AddRoutes(r => r.From("direct://pool-named").WireTap("direct://pool-sink", executorService: "tiny")); var producer = await Start(context, "direct://pool-named"); await producer.Process(new Exchange(new Message("first"))); await WaitFor(() => Volatile.Read(ref tapped) == 1); // The one slot is taken and there is no queue: the caller runs the second tap and waits for it. var second = producer.Process(new Exchange(new Message("second"))); await WaitFor(() => Volatile.Read(ref tapped) == 2); second.IsCompleted.Should().BeFalse("the caller is running the tap itself"); gate.SetResult(); await second; } // ── A caller-run tap is still detached ── /// 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(); } private static RouteEngineOptions CallerRunsAlways() => new() { DefaultThreadPoolProfile = new ThreadPoolProfile { MaxConcurrency = 1, MaxQueueSize = 0 }, }; [Theory] [InlineData(true, false)] [InlineData(false, true)] public async Task ACallerRunTap_RunsOutsideTheCallersTransaction_OnACopyWithoutItsSends(bool tapFails, bool mainFails) { var log = new List(); var occupy = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext(options: CallerRunsAlways()); context.AddRoutes(r => r.From("direct://tx-tap-sink").Process(async (e, _) => { if (e.In.Body is "occupy") { await occupy.Task; return; } lock (log) { log.Add(Transaction.Current is null ? "tap:no-transaction" : "tap:in-transaction"); log.Add(e.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey) ? "tap:has-sends" : "tap:no-sends"); } if (tapFails) throw new InvalidOperationException("the tap fails"); })); context.AddRoutes(r => r .From("direct://tx-tap") .Transacted() .Process(_ => { Transaction.Current!.EnlistVolatile(new LoggedDatabase(log), EnlistmentOptions.None); }) .WireTap("direct://tx-tap-sink") .Process(_ => { if (mainFails) throw new InvalidOperationException("the main work fails after the tap"); }) .End()); // The tap's only slot is taken by a branch that waits; with no queue the next tap runs in the caller. var occupier = await Start(context, "direct://tx-tap"); var tapProducer = context.GetEndpoint("direct://tx-tap-sink").CreateProducer(); await tapProducer.Start(); var pool = FindWireTap(context); _ = pool.Executor.Execute(() => tapProducer.Process(new Exchange(new Message("occupy")))); await WaitFor(() => pool.Executor.Active == 1); var send = () => occupier.Process(new Exchange(new Message("work"))); if (mainFails) await send.Should().ThrowAsync().WithMessage("the main work fails after the tap"); else await send.Should().NotThrowAsync("a failing tap never fails the main flow"); occupy.SetResult(); pool.Executor.CallerRuns.Should().Be(1, "the pool was full, so the caller ran the tap before it went on"); lock (log) { log.Should().Contain("tap:no-transaction", "the caller-run tap is detached from the caller's transaction"); log.Should().Contain("tap:no-sends", "the copy does not carry the caller's deferred sends"); log.Should().Contain(mainFails ? "db:rollback" : "db:commit", mainFails ? "the main transaction rolls back although the tap ran" : "the main transaction commits although the tap failed"); } } private static WireTapProcessor FindWireTap(RouteContext context) => context.DisposableProcessors.OfType().Single(); private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } private static bool ContainsMessage(Exception? e, string text) { for (; e is not null; e = e.InnerException) if (e.Message.Contains(text, StringComparison.Ordinal)) return true; return false; } private static async Task WaitFor(Func condition) { var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); while (!condition()) { DateTime.UtcNow.Should().BeBefore(deadline); await Task.Delay(10); } } }