Path: redb-route/tests/redb.Route.Tests/Batching/BatchDispatcherTests.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/Batching/BatchDispatcherTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Processors;
namespace redb.Route.Tests.Batching;
///
/// The batch exchange and the settle boundary: body a list of (one message too), shared transport
/// headers, the route run once, and exactly one settlement after it.
///
public class BatchDispatcherTests
{
private sealed record Record(string Body, string Topic, int Partition);
private sealed class RecordingSettlement : IBatchSettlement
{
public List Calls { get; } = [];
public Exception? Failure { get; private set; }
public bool ScopeOpenAtSettle { get; private set; }
private bool _scopeOpen;
public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
Calls.Add("before");
_scopeOpen = true;
return ValueTask.FromResult(new Scope(this));
}
public ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
ScopeOpenAtSettle = _scopeOpen;
Calls.Add($"accept:{items.Count}");
return ValueTask.CompletedTask;
}
public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
ScopeOpenAtSettle = _scopeOpen;
Failure = failure;
Calls.Add($"reject:{items.Count}");
return ValueTask.CompletedTask;
}
public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
Calls.Add($"return:{items.Count}");
return ValueTask.CompletedTask;
}
private sealed class Scope(RecordingSettlement owner) : IDisposable
{
public void Dispose()
{
owner._scopeOpen = false;
owner.Calls.Add("scope-closed");
}
}
}
private static IMessage ToMessage(Record record, IExchange _)
{
var message = new Message(record.Body);
message.Headers["topic"] = record.Topic;
message.Headers["partition"] = record.Partition;
return message;
}
private static BatchDispatcher Dispatcher(IProcessor route, IBatchSettlement settlement) =>
new(route, settlement, ToMessage, scopeFactory: null, sharedHeaders: ["topic", "partition"]);
[Fact]
public async Task Dispatch_BodyIsAListOfMessages_RouteRunsOnce_AcceptedOnceAfterTheRoute()
{
var runs = new List();
object? body = null;
var settlement = new RecordingSettlement();
var route = new DelegateProcessor(ex =>
{
runs.Add(ex);
body = ex.In.Body;
settlement.Calls.Add("route");
});
var outcome = await Dispatcher(route, settlement)
.DispatchAsync([new("a", "t", 0), new("b", "t", 1)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Accepted);
runs.Should().ContainSingle().Which.Pattern.Should().Be(ExchangePattern.InOnly);
body.Should().BeOfType>().Which.Select(m => m.Body).Should().Equal("a", "b");
settlement.Calls.Should().Equal("before", "route", "scope-closed", "accept:2");
settlement.ScopeOpenAtSettle.Should().BeFalse();
}
[Fact]
public async Task Dispatch_OneMessage_IsStillAList()
{
object? body = null;
var outcome = await Dispatcher(new DelegateProcessor(ex => body = ex.In.Body), new RecordingSettlement())
.DispatchAsync([new("only", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Accepted);
body.Should().BeOfType>().Which.Should().ContainSingle().Which.Body.Should().Be("only");
}
[Fact]
public async Task Dispatch_SharedHeaders_OnlyWhenEveryMessageAgrees_NoSizeHeader()
{
IMessage? batch = null;
await Dispatcher(new DelegateProcessor(ex => batch = ex.In), new RecordingSettlement())
.DispatchAsync([new("a", "orders", 0), new("b", "orders", 1)], default, CancellationToken.None);
batch!.Headers.Should().ContainKey("topic").WhoseValue.Should().Be("orders");
batch.Headers.Should().NotContainKey("partition", "the messages come from two partitions");
batch.Headers.Should().HaveCount(1, "the size is body.Count, not a header");
}
[Fact]
public async Task Dispatch_FailureLeftOnTheExchange_IsRejectedOnce()
{
var settlement = new RecordingSettlement();
var failure = new InvalidOperationException("boom");
var outcome = await Dispatcher(new DelegateProcessor(ex => ex.Exception = failure), settlement)
.DispatchAsync([new("a", "t", 0), new("b", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Rejected);
settlement.Calls.Should().Equal("before", "scope-closed", "reject:2");
settlement.Failure.Should().BeSameAs(failure);
}
[Fact]
public async Task Dispatch_FailureThrownByTheRoute_IsRejectedOnce()
{
var settlement = new RecordingSettlement();
var outcome = await Dispatcher(new DelegateProcessor(_ => throw new TimeoutException("slow")), settlement)
.DispatchAsync([new("a", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Rejected);
settlement.Calls.Should().Equal("before", "scope-closed", "reject:1");
settlement.Failure.Should().BeOfType();
}
[Fact]
public async Task Dispatch_HandledFailure_IsAccepted()
{
var settlement = new RecordingSettlement();
var route = new DelegateProcessor(ex =>
{
ex.Exception = new InvalidOperationException("handled");
ex.ExceptionHandled = true;
});
var outcome = await Dispatcher(route, settlement).DispatchAsync([new("a", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Accepted);
}
[Fact]
public async Task Dispatch_CancelledWhileTheRouteRuns_IsReturned_AndTheCancellationIsThrown()
{
using var processing = new CancellationTokenSource();
var settlement = new RecordingSettlement();
var route = new DelegateProcessor(async (_, ct) =>
{
await processing.CancelAsync();
ct.ThrowIfCancellationRequested();
});
var act = () => Dispatcher(route, settlement).DispatchAsync([new("a", "t", 0), new("b", "t", 0)], default, processing.Token);
await act.Should().ThrowAsync();
settlement.Calls.Should().Equal("before", "scope-closed", "return:2");
}
[Fact]
public async Task Dispatch_EmptyBatch_IsRefused()
{
var act = () => Dispatcher(new DelegateProcessor(_ => { }), new RecordingSettlement())
.DispatchAsync([], default, CancellationToken.None);
await act.Should().ThrowAsync();
}
}