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)ex.In.Body!) .Process(ex => { parts.Enqueue((Encoding.UTF8.GetString((byte[])ex.In.Body!), ex.In.GetHeader("X-Record"), ex.GetProperty(ExchangePropertyKeys.SplitIndex), ex.GetProperty(ExchangePropertyKeys.SplitComplete), ex.In.Headers.ContainsKey("batch-level"))); if (parts.Count == 3) done.TrySetResult(); }) .EndSplit()); await done.Task.WaitAsync(TimeSpan.FromSeconds(30)); parts.Should().Equal(("a", "rec-a", 0, false, false), ("b", "rec-b", 1, false, false), ("c", "rec-c", 2, true, false)); } [Fact] public async Task The_batch_is_committed_once_after_the_route() { var topic = await CreateTopic("batch-commit"); await Produce(topic, "a", "b", "c"); var group = $"g-{Guid.NewGuid():N}"; long? committedDuringRoute = null; var runs = 0; var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (var context = await Start(r => r .From(From(topic, group, "batching=true&maxBatchMessages=3&pollTimeoutMs=3000")) .Process(async (_, _) => { Interlocked.Increment(ref runs); committedDuringRoute = await CommittedOffset(group, topic); done.TrySetResult(); }))) { await done.Task.WaitAsync(TimeSpan.FromSeconds(30)); var deadline = DateTime.UtcNow.AddSeconds(15); while (await CommittedOffset(group, topic) != 3 && DateTime.UtcNow < deadline) await Task.Delay(200); } runs.Should().Be(1); committedDuringRoute.Should().Be(Offset.Unset.Value, "nothing is committed while the route runs"); (await CommittedOffset(group, topic)).Should().Be(3); } [Fact] public async Task A_failed_batch_with_breakOnFirstError_comes_again_whole() { var topic = await CreateTopic("batch-break"); await Produce(topic, "a", "b"); var deliveries = new ConcurrentQueue>(); var second = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = await Start(r => r .From(From(topic, $"g-{Guid.NewGuid():N}", "batching=true&maxBatchMessages=2&pollTimeoutMs=3000&breakOnFirstError=true")) .Process(ex => { deliveries.Enqueue(Records(ex).Select(Text).ToList()); if (deliveries.Count == 1) throw new InvalidOperationException("the first delivery fails"); second.TrySetResult(); })); await second.Task.WaitAsync(TimeSpan.FromSeconds(60)); deliveries.Should().HaveCount(2); deliveries.Should().AllSatisfy(d => d.Should().Equal("a", "b")); } [Fact] public async Task A_failed_batch_without_breakOnFirstError_is_passed_and_the_next_commit_covers_it() { var topic = await CreateTopic("batch-move-on"); await Produce(topic, "a", "b"); var group = $"g-{Guid.NewGuid():N}"; var deliveries = 0; var next = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (var context = await Start(r => r .From(From(topic, group, "batching=true&maxBatchMessages=2&pollTimeoutMs=3000")) .Process(ex => { if (Interlocked.Increment(ref deliveries) == 1) throw new InvalidOperationException("the batch fails"); next.TrySetResult(); }))) { await Task.Delay(TimeSpan.FromSeconds(3)); (await CommittedOffset(group, topic)).Should().Be(Offset.Unset.Value, "the failed batch is not committed"); await Produce(topic, "c"); await next.Task.WaitAsync(TimeSpan.FromSeconds(30)); var deadline = DateTime.UtcNow.AddSeconds(15); while (await CommittedOffset(group, topic) != 3 && DateTime.UtcNow < deadline) await Task.Delay(200); } deliveries.Should().Be(2, "the failed batch is not delivered again"); (await CommittedOffset(group, topic)).Should().Be(3); } [Fact] public async Task A_batch_half_collected_at_stop_is_not_run_and_its_records_come_again() { var topic = await CreateTopic("batch-stop"); await Produce(topic, "a", "b"); var group = $"g-{Guid.NewGuid():N}"; var runsBeforeStop = 0; // A long idle timeout and a size it never reaches: the batch is still being collected when the context stops. await using (var context = await Start(r => r .From(From(topic, group, "batching=true&maxBatchMessages=100&pollTimeoutMs=60000")) .Process(_ => Interlocked.Increment(ref runsBeforeStop)))) { await Task.Delay(TimeSpan.FromSeconds(8)); await context.Stop(); } runsBeforeStop.Should().Be(0); (await CommittedOffset(group, topic)).Should().Be(Offset.Unset.Value); var again = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); await using var restarted = await Start(r => r .From(From(topic, group, "batching=true&maxBatchMessages=100&pollTimeoutMs=500")) .Process(ex => again.TrySetResult(Records(ex).Select(Text).ToList()))); (await again.Task.WaitAsync(TimeSpan.FromSeconds(60))).Should().Equal("a", "b"); } }