Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaBatchContractTests.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.Kafka/KafkaBatchContractTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// The batch contract on the Kafka consumer against the live cluster: a batch is collected by size, by the idle timeout
/// and by the hard interval; the body is a list of messages, one per record, also for one; a Split gives each part its
/// record; the batch is committed once after the route; a failed batch follows breakOnFirstError; a batch half collected
/// at stop is not run and its records come again.
///
[Trait("Category", "Integration")]
public sealed class KafkaBatchContractTests : IAsyncLifetime
{
private const string BootstrapServers = "localhost:29092,localhost:29094,localhost:29096";
public Task InitializeAsync() => KafkaReadiness.GroupCoordinatorAsync();
public Task DisposeAsync() => Task.CompletedTask;
private static async Task CreateTopic(string name)
{
var topic = $"{name}-{Guid.NewGuid():N}";
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = BootstrapServers }).Build();
await admin.CreateTopicsAsync([new TopicSpecification { Name = topic, NumPartitions = 1, ReplicationFactor = 1 }]);
return topic;
}
private static async Task Produce(string topic, params string[] values)
{
using var producer = new ProducerBuilder(new ProducerConfig { BootstrapServers = BootstrapServers }).Build();
foreach (var value in values)
{
var message = new Message { Key = value, Value = value, Headers = [] };
message.Headers.Add("X-Record", Encoding.UTF8.GetBytes("rec-" + value));
await producer.ProduceAsync(topic, message);
}
}
private static async Task CommittedOffset(string group, string topic)
{
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = BootstrapServers }).Build();
var result = await admin.ListConsumerGroupOffsetsAsync(
[new ConsumerGroupTopicPartitions(group, [new TopicPartition(topic, 0)])]);
return result[0].Partitions[0].Offset.Value;
}
private static string From(string topic, string group, string options)
=> $"kafka://{topic}?brokers={BootstrapServers}&groupId={group}&autoOffsetReset=earliest&{options}";
private static async Task Start(Action routes)
{
var context = new RouteContext();
context.AddComponent(new KafkaComponent());
context.AddRoutes(routes);
await context.Start();
return context;
}
private static string Text(IMessage message) => Encoding.UTF8.GetString((byte[])message.Body!);
private static List Records(IExchange exchange) => (List)exchange.In.Body!;
[Fact]
public async Task A_batch_is_collected_up_to_maxBatchMessages_and_the_rest_by_the_idle_timeout()
{
var topic = await CreateTopic("batch-size");
await Produce(topic, "a", "b", "c", "d", "e", "f", "g");
var batches = new ConcurrentQueue>();
var all = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = await Start(r => r
.From(From(topic, $"g-{Guid.NewGuid():N}", "batching=true&maxBatchMessages=3&pollTimeoutMs=2000"))
.Process(ex =>
{
batches.Enqueue(Records(ex).Select(Text).ToList());
if (batches.Sum(b => b.Count) == 7) all.TrySetResult();
}));
await all.Task.WaitAsync(TimeSpan.FromSeconds(60));
batches.Select(b => b.Count).Should().Equal(3, 3, 1);
batches.SelectMany(b => b).Should().Equal("a", "b", "c", "d", "e", "f", "g");
}
[Fact]
public async Task A_partial_batch_is_sent_on_by_the_idle_timeout_not_held_for_the_size()
{
var topic = await CreateTopic("batch-idle");
await Produce(topic, "a", "b");
var arrived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = await Start(r => r
.From(From(topic, $"g-{Guid.NewGuid():N}", "batching=true&maxBatchMessages=1000&pollTimeoutMs=500"))
.Process(ex => arrived.TrySetResult(Records(ex).Count)));
(await arrived.Task.WaitAsync(TimeSpan.FromSeconds(30))).Should().Be(2);
}
[Fact]
public async Task A_steady_stream_is_cut_by_batchingIntervalMs()
{
var topic = await CreateTopic("batch-interval");
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = await Start(r => r
.From(From(topic, $"g-{Guid.NewGuid():N}",
"batching=true&maxBatchMessages=10000&pollTimeoutMs=5000&batchingIntervalMs=1500"))
.Process(ex => first.TrySetResult(Records(ex).Count)));
// A record every 100 ms for 6 s: the idle timeout of 5 s never fires, the interval of 1.5 s does.
using var producing = new CancellationTokenSource();
var produce = Task.Run(async () =>
{
for (var i = 0; i < 60 && !producing.IsCancellationRequested; i++)
{
await Produce(topic, $"r{i}");
await Task.Delay(100);
}
});
var size = await first.Task.WaitAsync(TimeSpan.FromSeconds(30));
await producing.CancelAsync();
await produce;
size.Should().BeInRange(1, 40, "the first batch was cut by the interval, long before the stream ended");
}
[Fact]
public async Task One_record_is_still_a_list_with_its_own_headers_and_the_shared_topic_on_the_batch()
{
var topic = await CreateTopic("batch-shape");
await Produce(topic, "only");
var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = await Start(r => r
.From(From(topic, $"g-{Guid.NewGuid():N}", "batching=true&pollTimeoutMs=500"))
.Process(ex => seen.TrySetResult(ex)));
var batch = await seen.Task.WaitAsync(TimeSpan.FromSeconds(30));
batch.Pattern.Should().Be(ExchangePattern.InOnly);
var record = Records(batch).Should().ContainSingle().Subject;
Text(record).Should().Be("only");
record.Headers["X-Record"].Should().Be("rec-only");
record.Headers[KafkaHeaders.Key].Should().Be("only");
record.Headers.Should().ContainKey(KafkaHeaders.Offset);
batch.In.Headers[KafkaHeaders.Topic].Should().Be(topic);
}
[Fact]
public async Task A_split_part_gets_its_records_body_and_headers_and_the_split_metadata_as_properties()
{
var topic = await CreateTopic("batch-split");
await Produce(topic, "a", "b", "c");
var parts = new ConcurrentQueue<(string Body, string? Header, int Index, bool Complete, bool HeaderLeak)>();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = await Start(r => r
.From(From(topic, $"g-{Guid.NewGuid():N}", "batching=true&maxBatchMessages=3&pollTimeoutMs=3000"))
.SetHeader("batch-level", "parent")
.Split(ex => (IEnumerable