Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaPartitionKeyIntegrationTests.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/KafkaPartitionKeyIntegrationTests.cs
----
using System.Text;
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.Tests.Kafka;
///
/// The partition of a sent record against the three-broker stand, on a topic of four partitions: each record lands where
/// its header or the endpoint's partitionKey says (the option first, as in Camel), the key travels with it, list
/// elements land per element, a transacted send keeps the partition, and a partition the topic does not have is refused.
///
[Trait("Category", "Integration")]
public sealed class KafkaPartitionKeyIntegrationTests : 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(int partitions = 4)
{
var topic = $"partition-key-{Guid.NewGuid():N}";
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = BootstrapServers }).Build();
await admin.CreateTopicsAsync([new TopicSpecification { Name = topic, NumPartitions = partitions, ReplicationFactor = 1 }]);
return topic;
}
private static async Task StartProducer(string topic, string? query = null)
{
var uri = EndpointUriParser.Parse($"kafka://{topic}?brokers={BootstrapServers}{(query is null ? "" : "&" + query)}");
var producer = (KafkaProducer)((KafkaEndpoint)new KafkaComponent().CreateEndpoint(uri)).CreateProducer();
await producer.Start();
return producer;
}
private static List> Read(string topic, int expected)
{
var config = new ConsumerConfig
{
BootstrapServers = BootstrapServers, GroupId = $"verify-{Guid.NewGuid():N}", AutoOffsetReset = AutoOffsetReset.Earliest,
IsolationLevel = IsolationLevel.ReadCommitted,
};
using var consumer = new ConsumerBuilder(config).Build();
consumer.Subscribe(topic);
var records = new List>();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(60);
while (DateTime.UtcNow < deadline && records.Count < expected)
{
var result = consumer.Consume(TimeSpan.FromMilliseconds(250));
if (result?.Message is not null) records.Add(result);
}
consumer.Close();
return records;
}
private static string Body(ConsumeResult record) => Encoding.UTF8.GetString(record.Message.Value);
private static Exchange Send(string body, object? partition = null, string? key = null)
{
var exchange = new Exchange(new RouteMessage(body));
if (partition is not null) exchange.In.Headers[KafkaHeaders.PartitionKey] = partition;
if (key is not null) exchange.In.Headers[KafkaHeaders.Key] = key;
return exchange;
}
[Fact]
public async Task Each_record_lands_in_the_partition_its_header_names_with_its_key()
{
var topic = await CreateTopic();
var producer = await StartProducer(topic);
try
{
await producer.Process(Send("p0", 0, "k-a"));
await producer.Process(Send("p3", 3, "k-a"));
await producer.Process(Send("p2", "2", "k-b"));
}
finally
{
await producer.Stop();
}
var records = Read(topic, 3).ToDictionary(Body);
records["p0"].Partition.Value.Should().Be(0);
records["p3"].Partition.Value.Should().Be(3, "the same key k-a goes where the header says, not by its hash");
records["p2"].Partition.Value.Should().Be(2, "a whole-number text is a partition too");
records["p3"].Message.Key.Should().Be("k-a", "the key is sent with the partition, as in Camel");
records.Values.Should().OnlyContain(r => !r.Message.Headers.Any(h => h.Key == KafkaHeaders.PartitionKey),
"the header never goes on the wire");
}
[Fact]
public async Task The_endpoint_option_wins_over_the_header()
{
var topic = await CreateTopic();
var producer = await StartProducer(topic, "partitionKey=1");
try
{
await producer.Process(Send("from-option", 3));
}
finally
{
await producer.Stop();
}
Read(topic, 1).Single().Partition.Value.Should().Be(1);
}
[Fact]
public async Task A_list_of_IMessage_sends_each_element_to_its_own_partition()
{
var topic = await CreateTopic();
var producer = await StartProducer(topic);
var elements = new List
{
new RouteMessage("e1") { Headers = { [KafkaHeaders.PartitionKey] = 1 } },
new RouteMessage("e3") { Headers = { [KafkaHeaders.PartitionKey] = 3 } },
};
var parent = new Exchange(new RouteMessage(elements));
parent.In.Headers[KafkaHeaders.PartitionKey] = 0; // not copied to the elements
try
{
await producer.Process(parent);
}
finally
{
await producer.Stop();
}
var records = Read(topic, 2).ToDictionary(Body);
records["e1"].Partition.Value.Should().Be(1);
records["e3"].Partition.Value.Should().Be(3);
}
[Fact]
public async Task A_transacted_send_keeps_the_partition()
{
var topic = await CreateTopic();
var producer = await StartProducer(topic, "transactionalIdPrefix=partition-key");
try
{
await producer.Process(Send("tx", 2));
}
finally
{
await producer.Stop();
}
Read(topic, 1).Single().Partition.Value.Should().Be(2);
}
[Fact]
public async Task A_partition_the_topic_does_not_have_is_refused_naming_it()
{
var topic = await CreateTopic(partitions: 2);
var producer = await StartProducer(topic);
try
{
var act = () => producer.Process(Send("nowhere", 7));
await act.Should().ThrowAsync().WithMessage($"Kafka topic '{topic}' has no partition 7*");
}
finally
{
await producer.Stop();
}
}
[Fact]
public async Task A_header_that_is_not_a_partition_number_sends_nothing()
{
var topic = await CreateTopic();
var producer = await StartProducer(topic);
try
{
var act = () => producer.Process(Send("bad", "two"));
await act.Should().ThrowAsync().WithMessage($"The {KafkaHeaders.PartitionKey} header*");
}
finally
{
await producer.Stop();
}
}
}