Bundle: redb-route / tests/redb.Route.Tests.Kafka (tests.redb.Route.Tests.Kafka.txt), 32 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/tests/redb.Route.Tests.Kafka/AckModeOptionsTests.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/AckModeOptionsTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// ackMode, the one option that says when a consumer settles what it received (manual: after the route,
/// auto: on receipt). The connector's former option is refused with its replacement named.
///
public class AckModeOptionsTests
{
private static KafkaEndpointOptions Bind(params (string Key, string Value)[] parameters)
{
var options = new KafkaEndpointOptions();
options.BindFromUri(parameters.ToDictionary(p => p.Key, p => p.Value));
return options;
}
[Fact]
public void The_default_is_manual() => new KafkaEndpointOptions().AckMode.Should().Be(AckMode.Manual);
[Fact]
public void Auto_binds_from_the_uri() => Bind(("ackMode", "auto")).AckMode.Should().Be(AckMode.Auto);
[Fact]
public void The_former_option_is_refused_with_its_replacement()
{
var act = () => Bind(("enableAutoCommit", "false"));
act.Should().Throw().WithMessage("*'enableAutoCommit' is replaced by 'ackMode'*");
}
[Fact]
public void Auto_with_breakOnFirstError_is_refused()
{
var options = Bind(("brokers", "localhost:9092"), ("ackMode", "auto"), ("breakOnFirstError", "true"));
var act = () => options.Validate();
act.Should().Throw().WithMessage("*ackMode=auto*breakOnFirstError*");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/CapturingLoggerProvider.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/CapturingLoggerProvider.cs
----
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
namespace redb.Route.Tests.Kafka;
/// Test-only logger provider that keeps every entry in memory, for assertions on what the connector says.
internal sealed class CapturingLoggerProvider : ILoggerProvider
{
public ConcurrentQueue Entries { get; } = new();
public ILogger CreateLogger(string categoryName) => new Logger(this);
public void Dispose() { }
internal sealed record LogEntry(LogLevel Level, string Message);
private sealed class Logger(CapturingLoggerProvider owner) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state,
Exception? exception, Func formatter) =>
owner.Entries.Enqueue(new LogEntry(logLevel, formatter(state, exception)));
}
}
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");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaBuilderTests.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/KafkaBuilderTests.cs
----
using redb.Route.Core;
using redb.Route.Expressions;
using KafkaDsl = redb.Route.Kafka.Kafka;
namespace redb.Route.Tests.Kafka;
public class KafkaBuilderTests
{
private static ConstantExpression C(string s) => new(s);
// ── Factory ─────────────────────────────────────────────────────
[Fact]
public void Topic_StartsWithKafkaScheme()
{
var uri = KafkaDsl.Topic("orders").Build();
uri.Should().StartWith("kafka:orders");
}
[Fact]
public void NullTopic_Throws()
{
var act = () => KafkaDsl.Topic(null!);
act.Should().Throw();
}
[Fact]
public void EmptyTopic_Throws()
{
var act = () => KafkaDsl.Topic("");
act.Should().Throw();
}
// ── Connection ──────────────────────────────────────────────────
[Fact]
public void Brokers_SetsParam()
{
var uri = KafkaDsl.Topic("t").Brokers(C("broker1:9092")).Build();
uri.Should().Contain("brokers=broker1%3A9092");
}
[Fact]
public void SecurityProtocol_SetsParam()
{
var uri = KafkaDsl.Topic("t").SecurityProtocol("SaslSsl").Build();
uri.Should().Contain("securityProtocol=SaslSsl");
}
[Fact]
public void Sasl_SetsParams()
{
var uri = KafkaDsl.Topic("t").Sasl("PLAIN", C("user"), C("pass")).Build();
uri.Should().Contain("saslMechanism=PLAIN");
uri.Should().Contain("saslUsername=user");
uri.Should().Contain("saslPassword=pass");
}
[Fact]
public void SslCa_SetsParam()
{
var uri = KafkaDsl.Topic("t").SslCa(C("/certs/ca.pem")).Build();
uri.Should().Contain("sslCaLocation=");
}
[Fact]
public void ConnectionFactory_SetsParam()
{
var uri = KafkaDsl.Topic("t").ConnectionFactory(C("myFactory")).Build();
uri.Should().Contain("connectionFactory=myFactory");
}
// ── Consumer ────────────────────────────────────────────────────
[Fact]
public void GroupId_SetsParam()
{
var uri = KafkaDsl.Topic("t").GroupId(C("grp1")).Build();
uri.Should().Contain("groupId=grp1");
}
[Fact]
public void AutoOffsetReset_SetsParam()
{
var uri = KafkaDsl.Topic("t").AutoOffsetReset("Earliest").Build();
uri.Should().Contain("autoOffsetReset=Earliest");
}
[Fact]
public void Batching_SetsTheBatchOptions()
{
var uri = KafkaDsl.Topic("t").Batching().MaxBatchMessages(100).BatchingIntervalMs(2000).Build();
uri.Should().Contain("batching=true").And.Contain("maxBatchMessages=100").And.Contain("batchingIntervalMs=2000");
KafkaDsl.Topic("t").Build().Should().NotContain("batching");
}
[Fact]
public void BreakOnFirstError_SetsParam()
{
var uri = KafkaDsl.Topic("t").BreakOnFirstError().Build();
uri.Should().Contain("breakOnFirstError=true");
}
[Fact]
public void SeekTo_SetsParam()
{
var uri = KafkaDsl.Topic("t").SeekTo("beginning").Build();
uri.Should().Contain("seekTo=beginning");
}
[Fact]
public void TopicIsPattern_SetsParam()
{
var uri = KafkaDsl.Topic("order.*").TopicIsPattern().Build();
uri.Should().Contain("topicIsPattern=true");
}
[Fact]
public void IsolationLevel_SetsParam()
{
var uri = KafkaDsl.Topic("t").IsolationLevel("ReadCommitted").Build();
uri.Should().Contain("isolationLevel=ReadCommitted");
}
// ── Producer ────────────────────────────────────────────────────
[Fact]
public void Acks_SetsParam()
{
var uri = KafkaDsl.Topic("t").Acks("All").Build();
uri.Should().Contain("acks=All");
}
[Fact]
public void Retries_SetsParam()
{
var uri = KafkaDsl.Topic("t").Retries(5).Build();
uri.Should().Contain("retries=5");
}
[Fact]
public void RecordMetadata_SetsParam()
{
var uri = KafkaDsl.Topic("t").RecordMetadata().Build();
uri.Should().Contain("recordMetadata=true");
}
[Fact]
public void SslVerifyHostname_SetsTheIdentificationAlgorithm()
{
KafkaDsl.Topic("t").SslVerifyHostname(false).Build().Should().Contain("sslEndpointIdentificationAlgorithm=none");
KafkaDsl.Topic("t").SslVerifyHostname().Build().Should().Contain("sslEndpointIdentificationAlgorithm=https");
KafkaDsl.Topic("t").Build().Should().NotContain("sslEndpointIdentificationAlgorithm");
}
[Fact]
public void Key_SetsParam()
{
var uri = KafkaDsl.Topic("t").Key(C("userId")).Build();
uri.Should().Contain("key=userId");
}
[Fact]
public void Compression_SetsParam()
{
var uri = KafkaDsl.Topic("t").Compression("snappy").Build();
uri.Should().Contain("compressionType=snappy");
}
[Fact]
public void Transacted_SetsParam()
{
var uri = KafkaDsl.Topic("t").Transacted().Build();
uri.Should().Contain("transacted=true");
}
[Fact]
public void Transacted_false_is_written_out_to_send_at_once_inside_a_block()
{
var uri = KafkaDsl.Topic("t").Transacted(false).Build();
uri.Should().Contain("transacted=false");
}
[Fact]
public void EnableIdempotence_IsWrittenOutBothWays()
{
KafkaDsl.Topic("t").EnableIdempotence().Build().Should().Contain("enableIdempotence=true");
KafkaDsl.Topic("t").EnableIdempotence(false).Build().Should().Contain("enableIdempotence=false");
KafkaDsl.Topic("t").Build().Should().NotContain("enableIdempotence", "unset, it follows acks");
}
[Fact]
public void Transacted_left_unset_is_not_written_so_the_producer_follows_the_block()
{
var uri = KafkaDsl.Topic("t").Build();
uri.Should().NotContain("transacted");
}
// ── Conversion ──────────────────────────────────────────────────
[Fact]
public void ImplicitConversion_ReturnsUri()
{
string uri = KafkaDsl.Topic("orders").Brokers(C("b:9092")).GroupId(C("g"));
uri.Should().StartWith("kafka:orders?");
}
[Fact]
public void ToString_ReturnsSameAsBuild()
{
var builder = KafkaDsl.Topic("t").Brokers(C("b:9092")).Acks("All");
builder.ToString().Should().Be(builder.Build());
}
// ── Full chain ──────────────────────────────────────────────────
[Fact]
public void FullChain_Consumer_BuildsCorrectUri()
{
var uri = KafkaDsl.Topic("orders")
.Brokers(C("broker1:9092,broker2:9092"))
.GroupId(C("order-group"))
.AutoOffsetReset("Earliest")
.Batching()
.MaxBatchMessages(500)
.BreakOnFirstError()
.IsolationLevel("ReadCommitted")
.Build();
uri.Should().StartWith("kafka:orders?");
uri.Should().Contain("groupId=order-group");
uri.Should().Contain("autoOffsetReset=Earliest");
uri.Should().Contain("batching=true").And.Contain("maxBatchMessages=500");
uri.Should().Contain("breakOnFirstError=true");
}
[Fact]
public void FullChain_Producer_BuildsCorrectUri()
{
var uri = KafkaDsl.Topic("notifications")
.Brokers(C("broker1:9092"))
.Acks("All")
.Retries(3)
.Key(C("userId"))
.Compression("snappy")
.Build();
uri.Should().StartWith("kafka:notifications?");
uri.Should().Contain("acks=All");
uri.Should().Contain("retries=3");
uri.Should().Contain("key=userId");
uri.Should().Contain("compressionType=snappy");
}
// ── Round-trip ──────────────────────────────────────────────────
[Fact]
public void RoundTrip_ParseAndReconstruct()
{
var original = KafkaDsl.Topic("orders").GroupId(C("g1")).Acks("All").Build();
var parsed = EndpointUriParser.Parse(original);
parsed.Scheme.Should().Be("kafka");
parsed.Path.Should().Be("orders");
parsed.RawParameters["groupId"].Should().Be("g1");
parsed.RawParameters["acks"].Should().Be("All");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaComponentTests.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/KafkaComponentTests.cs
----
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
public sealed class KafkaComponentTests
{
private readonly KafkaComponent _sut = new();
[Fact]
public void Scheme_ReturnsKafka()
{
_sut.Scheme.Should().Be("kafka");
}
[Fact]
public void CreateEndpoint_ValidUri_ReturnsKafkaEndpoint()
{
var uri = EndpointUriParser.Parse("kafka://my-topic?brokers=localhost:9092&groupId=grp1");
var endpoint = _sut.CreateEndpoint(uri);
endpoint.Should().BeOfType();
var kafka = (KafkaEndpoint)endpoint;
kafka.TopicName.Should().Be("my-topic");
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var act = () => _sut.CreateEndpoint(null!);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_MissingBrokers_Throws()
{
var uri = EndpointUriParser.Parse("kafka://my-topic");
var act = () => _sut.CreateEndpoint(uri);
act.Should().Throw().WithMessage("*brokers*");
}
[Fact]
public void CreateEndpoint_WithAllConsumerOptions_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"kafka://events?brokers=b1:9092,b2:9092&groupId=g1&autoOffsetReset=Earliest&batching=true&maxBatchMessages=50&pollTimeoutMs=2000&breakOnFirstError=true&seekTo=beginning&topicIsPattern=true");
var endpoint = (KafkaEndpoint)_sut.CreateEndpoint(uri);
endpoint.TopicName.Should().Be("events");
}
[Fact]
public void CreateEndpoint_WithProducerOptions_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"kafka://orders?brokers=localhost:9092&acks=All&retries=5&recordMetadata=true&key=OrderId&transacted=true");
var endpoint = (KafkaEndpoint)_sut.CreateEndpoint(uri);
endpoint.TopicName.Should().Be("orders");
}
[Fact]
public void CreateEndpoint_WithSecurityOptions_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"kafka://secure-topic?brokers=kafka:9093&securityProtocol=SaslSsl&saslMechanism=Plain&saslUsername=user&saslPassword=pass");
var endpoint = (KafkaEndpoint)_sut.CreateEndpoint(uri);
endpoint.TopicName.Should().Be("secure-topic");
}
[Theory]
[InlineData("maxBatchMessages=10", "maxBatchMessages")]
[InlineData("batchingIntervalMs=1000", "batchingIntervalMs")]
public void A_batch_option_without_batching_fails_the_start(string option, string named)
{
var act = () => _sut.CreateEndpoint(EndpointUriParser.Parse($"kafka://orders?brokers=localhost:9092&{option}"));
act.Should().Throw().WithMessage($"*kafka://orders*{named}*batching=true*");
}
[Theory]
[InlineData("maxBatchMessages=0", "maxBatchMessages")]
[InlineData("pollTimeoutMs=0", "pollTimeoutMs")]
[InlineData("batchingIntervalMs=0", "batchingIntervalMs")]
public void A_batch_value_out_of_range_fails_the_start(string option, string named)
{
var act = () => _sut.CreateEndpoint(
EndpointUriParser.Parse($"kafka://orders?brokers=localhost:9092&batching=true&{option}"));
act.Should().Throw().WithMessage($"*kafka://orders*{named}*");
}
[Fact]
public void MaxPollRecords_is_refused_naming_its_replacement()
{
var act = () => _sut.CreateEndpoint(EndpointUriParser.Parse("kafka://orders?brokers=localhost:9092&maxPollRecords=10"));
act.Should().Throw().WithMessage("*maxPollRecords*maxBatchMessages*batching=true*");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaConformanceTests.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/KafkaConformanceTests.cs
----
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using redb.Route.Abstractions;
using redb.Route.Kafka;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.Kafka;
///
/// The Kafka connector against , on (one KRaft
/// node at localhost:39092). A "queue" is a topic with one partition, read by the group
/// : Kafka keeps the records, so a record is "off the queue" once that group committed
/// it, and the stand drains as that group. A failed record is read again with breakOnFirstError=true (Kafka has no
/// redelivery count: it is read until it succeeds). Not applicable here, and passing without running:
/// the dead letter cases (Kafka has no dead letter queue), the concurrency bound (one poll loop per consumer, no option for
/// more), and the start while the broker is down (after the bootstrap the client goes to the address the broker announces,
/// past the late port). Runs alone: the restart case breaks the broker for every connection of the suite; it and every other
/// case need the stand, so the class runs only in a fault run (run-fault-suite.sh --broker kafka ).
///
[Trait("Category", "Integration")]
[Collection(KafkaBrokerRestartCollection.Name)]
public sealed class KafkaConformanceTests : ConnectorConformance
{
protected override KafkaFaultStand Stand => KafkaFaultStand.Instance;
protected override ConnectorTraits Traits { get; } = new()
{
AckOnReceipt = true, Transactions = true, DeadLetter = false, Concurrency = false, Batch = true, LateBroker = false,
};
protected override int BrokerPort => 39092;
protected override IComponent CreateComponent() => new KafkaComponent();
protected override async Task CreateQueueAsync(bool deadLetter)
=> new(await KafkaFaultStand.CreateTopicAsync("conformance"), null);
protected override async Task DeleteQueueAsync(ConformanceQueue queue)
{
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = KafkaFaultStand.Brokers }).Build();
try
{
await admin.DeleteTopicsAsync([queue.Name]);
}
catch (DeleteTopicsException)
{
// Gone already, or the broker is still coming back after the restart case: the topic is the test's own.
}
}
protected override string ConsumerUri(ConformanceQueue queue, ConsumerSettings settings)
{
var uri = $"kafka://{queue.Name}?brokers=localhost:{settings.Port ?? BrokerPort}"
+ $"&groupId={KafkaFaultStand.GroupOf(queue.Name)}&autoOffsetReset=Earliest";
uri += settings.AckOnReceipt ? "&ackMode=auto" : "&breakOnFirstError=true";
if (settings.BatchSize is { } size)
uri += $"&batching=true&maxBatchMessages={size}&pollTimeoutMs={(int)settings.BatchWait.TotalMilliseconds}";
return uri;
}
protected override string ProducerUri(ConformanceQueue queue, bool transacted)
=> $"kafka://{queue.Name}?brokers=localhost:{BrokerPort}"
+ (transacted ? $"&transactionalIdPrefix=conformance-{Guid.NewGuid():N}" : "");
// The data folder of the stand's broker survives a restart: the topic is there as soon as the broker is.
protected override Task QueueIsBackAsync(ConformanceQueue queue) => Task.Run(() =>
{
try
{
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = KafkaFaultStand.Brokers }).Build();
var topic = admin.GetMetadata(queue.Name, TimeSpan.FromSeconds(5)).Topics.SingleOrDefault();
return topic is { Error.IsError: false } && topic.Partitions.All(p => p.Leader >= 0);
}
catch (KafkaException)
{
return false;
}
});
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaConnectionFactoryLoudTests.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/KafkaConnectionFactoryLoudTests.cs
----
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// A set-but-unknown connectionFactory name must fail loud —
/// never silently fall back to URI parameters.
///
public sealed class KafkaConnectionFactoryLoudTests
{
[Fact]
public async Task ConnectionFactoryTypo_FailsLoud()
{
await using var ctx = new RouteContext();
ctx.AddComponent(new KafkaComponent());
var act = () => ctx.GetEndpoint("kafka://orders?connectionFactory=typo-name&brokers=localhost:9092");
act.Should().Throw()
.Which.Message.Should().Contain("typo-name");
}
[Fact]
public async Task ConnectionFactoryRegistered_Resolves()
{
await using var ctx = new RouteContext();
ctx.AddComponent(new KafkaComponent());
ctx.AddToRegistry("real", new KafkaConnectionFactory { Brokers = "broker:9092" });
var endpoint = ctx.GetEndpoint("kafka://orders?connectionFactory=real");
endpoint.Should().NotBeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaConsumerTests.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/KafkaConsumerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
public sealed class KafkaConsumerTests
{
private readonly KafkaComponent _component = new();
private KafkaEndpoint CreateEndpoint(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
return (KafkaEndpoint)_component.CreateEndpoint(uri);
}
[Fact]
public void Ctor_NullEndpoint_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", GroupId = "g" };
var proc = Substitute.For();
var act = () => new KafkaConsumer(null!, proc, opts);
act.Should().Throw();
}
[Fact]
public void Ctor_NullProcessor_Throws()
{
var ep = CreateEndpoint("kafka://t?brokers=x:9092&groupId=g");
var opts = new KafkaEndpointOptions { Brokers = "x:9092", GroupId = "g" };
var act = () => new KafkaConsumer(ep, null!, opts);
act.Should().Throw();
}
[Fact]
public void Ctor_NullOptions_Throws()
{
var ep = CreateEndpoint("kafka://t?brokers=x:9092&groupId=g");
var proc = Substitute.For();
var act = () => new KafkaConsumer(ep, proc, null!);
act.Should().Throw();
}
[Fact]
public void ProcessedCount_InitiallyZero()
{
var ep = CreateEndpoint("kafka://t?brokers=x:9092&groupId=g");
var proc = Substitute.For();
var opts = new KafkaEndpointOptions { Brokers = "x:9092", GroupId = "g" };
var consumer = new KafkaConsumer(ep, proc, opts);
consumer.ProcessedCount.Should().Be(0);
}
[Fact]
public async Task Stop_BeforeStart_DoesNotThrow()
{
var ep = CreateEndpoint("kafka://t?brokers=x:9092&groupId=g");
var proc = Substitute.For();
var opts = new KafkaEndpointOptions { Brokers = "x:9092", GroupId = "g" };
var consumer = new KafkaConsumer(ep, proc, opts);
var act = () => consumer.Stop();
await act.Should().NotThrowAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaEndpointOptionsTests.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/KafkaEndpointOptionsTests.cs
----
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
public sealed class KafkaEndpointOptionsTests
{
[Fact]
public void Defaults_AreReasonable()
{
var opts = new KafkaEndpointOptions();
opts.Brokers.Should().BeEmpty();
opts.SecurityProtocol.Should().Be("Plaintext");
opts.AutoOffsetReset.Should().Be("Latest");
opts.Batching.Should().BeFalse();
opts.MaxBatchMessages.Should().BeNull();
opts.BatchingIntervalMs.Should().BeNull();
opts.PollTimeoutMs.Should().Be(1000);
opts.BreakOnFirstError.Should().BeFalse();
opts.TopicIsPattern.Should().BeFalse();
opts.Acks.Should().Be("All", "as in the Kafka 3 client and Camel 4");
opts.EnableIdempotence.Should().BeNull("unset, idempotence follows acks");
opts.Retries.Should().Be(3);
opts.RecordMetadata.Should().BeFalse();
opts.Transacted.Should().BeNull("unset, a producer follows the enclosing .Transacted() block");
// TransactionIdPrefix removed: transactional.id is deliberately never set, the value was discarded
}
[Fact]
public void Validate_NoBrokers_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "" };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*brokers*");
}
[Fact]
public void ResolveBatch_ZeroMaxBatchMessages_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", Batching = true, MaxBatchMessages = 0 };
var act = () => opts.ResolveBatch("kafka://t");
act.Should().Throw().WithMessage("*kafka://t*maxBatchMessages*");
}
[Fact]
public void ResolveBatch_DefaultsTo500_IdleTimeoutFromPollTimeoutMs()
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", Batching = true, PollTimeoutMs = 300 };
opts.ResolveBatch("kafka://t");
opts.Batch!.MaxMessages.Should().Be(500);
opts.Batch.PollTimeout.Should().Be(TimeSpan.FromMilliseconds(300));
opts.Batch.Interval.Should().BeNull();
}
[Fact]
public void ResolveBatch_SingleRecordMode_IsNull()
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092" };
opts.ResolveBatch("kafka://t");
opts.Batch.Should().BeNull();
}
[Fact]
public void Validate_NegativePollTimeoutMs_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", PollTimeoutMs = -1 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_NegativeRetries_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", Retries = -1 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_ValidOptions_DoesNotThrow()
{
var opts = new KafkaEndpointOptions
{
Brokers = "localhost:9092",
GroupId = "test-group",
Batching = true,
MaxBatchMessages = 100,
PollTimeoutMs = 500,
Retries = 5
};
var act = () => opts.Validate();
act.Should().NotThrow();
}
[Fact]
public void BuildConsumerConfig_SetsBootstrapServers()
{
var opts = new KafkaEndpointOptions { Brokers = "b1:9092,b2:9092", GroupId = "grp1" };
var config = opts.BuildConsumerConfig();
config.BootstrapServers.Should().Be("b1:9092,b2:9092");
config.GroupId.Should().Be("grp1");
config.EnableAutoCommit.Should().BeFalse();
}
[Fact]
public void BuildConsumerConfig_ParsesAutoOffsetReset()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", GroupId = "g", AutoOffsetReset = "Earliest" };
var config = opts.BuildConsumerConfig();
config.AutoOffsetReset.Should().Be(Confluent.Kafka.AutoOffsetReset.Earliest);
}
[Fact]
public void BuildProducerConfig_SetsAcksAndRetries()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", Acks = "All", Retries = 10 };
var config = opts.BuildProducerConfig();
config.Acks.Should().Be(Confluent.Kafka.Acks.All);
config.MessageSendMaxRetries.Should().Be(10);
}
// ── acks=all and an idempotent producer by default, as in the Kafka 3 client and Camel 4 ──
[Fact]
public void BuildProducerConfig_Default_IsAcksAllAndIdempotent()
{
var config = new KafkaEndpointOptions { Brokers = "x:9092" }.BuildProducerConfig();
config.Acks.Should().Be(Confluent.Kafka.Acks.All);
config.EnableIdempotence.Should().BeTrue();
}
[Fact]
public void BuildProducerConfig_AcksLeader_IsNotIdempotent()
{
var config = new KafkaEndpointOptions { Brokers = "x:9092", Acks = "leader" }.BuildProducerConfig();
config.Acks.Should().Be(Confluent.Kafka.Acks.Leader);
config.EnableIdempotence.Should().BeFalse("an idempotent producer needs acks=all");
}
[Fact]
public void BuildProducerConfig_IdempotenceOff_KeepsAcksAll()
{
var config = new KafkaEndpointOptions { Brokers = "x:9092", EnableIdempotence = false }.BuildProducerConfig();
config.Acks.Should().Be(Confluent.Kafka.Acks.All);
config.EnableIdempotence.Should().BeFalse();
}
[Fact]
public void Validate_IdempotenceWithoutAcksAll_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", Acks = "leader", EnableIdempotence = true };
var act = opts.Validate;
act.Should().Throw().WithMessage("*enableIdempotence*acks*all*");
}
[Fact]
public void Validate_TransactedWithAcksLeader_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", Acks = "leader", Transacted = true };
var act = opts.Validate;
act.Should().Throw("the explicit acks would be overridden without a word")
.WithMessage("*transacted*acks*all*");
}
[Fact]
public void Factory_DefaultsToAcksAll()
{
new KafkaConnectionFactory().Acks.Should().Be("All");
}
[Fact]
public void BuildProducerConfig_Transacted_EnablesIdempotence()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", Transacted = true };
var config = opts.BuildProducerConfig();
// `transacted=true` is deferred-idempotent, NOT Kafka EOS: BuildProducerConfig deliberately
// enables idempotence + Acks.All but does NOT set transactional.id — configuring one would put
// librdkafka into transactional mode requiring BeginTransaction/Commit around every Produce,
// which the connector does not implement (a deferred Produce would throw "Local: Erroneous
// state"). See redb.Route.Kafka/KafkaEndpointOptions.BuildProducerConfig; Kafka transactions are the
// separate transactionalIdPrefix option.
config.EnableIdempotence.Should().BeTrue();
config.Acks.Should().Be(Confluent.Kafka.Acks.All);
config.TransactionalId.Should().BeNull("transactional.id must stay unset in deferred-idempotent mode");
}
[Theory]
[InlineData("earliest", Confluent.Kafka.AutoOffsetReset.Earliest)]
[InlineData("latest", Confluent.Kafka.AutoOffsetReset.Latest)]
[InlineData("error", Confluent.Kafka.AutoOffsetReset.Error)]
// "unknown" -> Latest was the silent fallback; a typo now throws (KafkaLoudConfigTests)
public void BuildConsumerConfig_AutoOffsetReset_AllValues(string input, Confluent.Kafka.AutoOffsetReset expected)
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", GroupId = "g", AutoOffsetReset = input };
var config = opts.BuildConsumerConfig();
config.AutoOffsetReset.Should().Be(expected);
}
[Theory]
[InlineData("none", Confluent.Kafka.Acks.None)]
[InlineData("0", Confluent.Kafka.Acks.None)]
[InlineData("leader", Confluent.Kafka.Acks.Leader)]
[InlineData("1", Confluent.Kafka.Acks.Leader)]
[InlineData("all", Confluent.Kafka.Acks.All)]
[InlineData("-1", Confluent.Kafka.Acks.All)]
// "unknown" -> Leader was the silent fallback; a typo now throws (KafkaLoudConfigTests)
public void BuildProducerConfig_Acks_AllValues(string input, Confluent.Kafka.Acks expected)
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092", Acks = input };
var config = opts.BuildProducerConfig();
config.Acks.Should().Be(expected);
}
[Fact]
public void BuildConsumerConfig_WithSaslSecurity_AppliesCredentials()
{
var opts = new KafkaEndpointOptions
{
Brokers = "kafka:9093",
SecurityProtocol = "SaslPlaintext",
SaslMechanism = "Plain",
SaslUsername = "user",
SaslPassword = "pass",
GroupId = "g"
};
var config = opts.BuildConsumerConfig();
config.SecurityProtocol.Should().Be(Confluent.Kafka.SecurityProtocol.SaslPlaintext);
config.SaslMechanism.Should().Be(Confluent.Kafka.SaslMechanism.Plain);
config.SaslUsername.Should().Be("user");
config.SaslPassword.Should().Be("pass");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaEndpointTests.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/KafkaEndpointTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
public sealed class KafkaEndpointTests
{
private readonly KafkaComponent _component = new();
private KafkaEndpoint CreateEndpoint(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
return (KafkaEndpoint)_component.CreateEndpoint(uri);
}
[Fact]
public void TopicName_ExtractedFromPath()
{
var ep = CreateEndpoint("kafka://order-events?brokers=localhost:9092");
ep.TopicName.Should().Be("order-events");
}
[Fact]
public void CreateProducer_ReturnsKafkaProducer()
{
var ep = CreateEndpoint("kafka://topic1?brokers=localhost:9092");
var producer = ep.CreateProducer();
producer.Should().BeOfType();
}
[Fact]
public void CreateConsumer_WithGroupId_ReturnsKafkaConsumer()
{
var ep = CreateEndpoint("kafka://topic1?brokers=localhost:9092&groupId=test-group");
var processor = Substitute.For();
var consumer = ep.CreateConsumer(processor);
consumer.Should().BeOfType();
}
[Fact]
public void CreateConsumer_WithoutGroupId_Throws()
{
var ep = CreateEndpoint("kafka://topic1?brokers=localhost:9092");
var processor = Substitute.For();
var act = () => ep.CreateConsumer(processor);
act.Should().Throw().WithMessage("*groupId*");
}
[Fact]
public void Uri_PreservesOriginalUri()
{
var ep = CreateEndpoint("kafka://my-topic?brokers=b:9092");
ep.Uri.Scheme.Should().Be("kafka");
ep.Uri.Path.Should().Be("my-topic");
}
[Fact]
public void Component_IsKafkaComponent()
{
var ep = CreateEndpoint("kafka://t?brokers=b:9092");
ep.Component.Should().BeSameAs(_component);
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaErrorHandlingTests.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/KafkaErrorHandlingTests.cs
----
using System.Collections.Concurrent;
using Confluent.Kafka;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// The options sweep, end to end against a live cluster.
/// A message whose processing throws used to be LOST with nothing but a log line: its offset was
/// never committed, but the next successful message's commit covered it (a Kafka commit is a
/// position, not a per-record mark), so a restart resumed past it. The connector's own family
/// contract is different - RabbitMQ nacks with requeue. And the option that exists exactly for
/// this scenario, breakOnFirstError, was declared, documented, exposed in the DSL and read by
/// nothing.
///
[Trait("Category", "Integration")]
public sealed class KafkaErrorHandlingTests : IAsyncLifetime
{
private const string BootstrapServers = "localhost:29092,localhost:29094,localhost:29096";
private readonly List _consumers = [];
public Task InitializeAsync() => KafkaReadiness.GroupCoordinatorAsync();
public async Task DisposeAsync()
{
foreach (var c in _consumers) await c.Stop();
}
private KafkaEndpoint CreateEndpoint(string topic, string extraParams)
{
var uri = EndpointUriParser.Parse($"kafka://{topic}?brokers={BootstrapServers}&{extraParams}");
return (KafkaEndpoint)new KafkaComponent().CreateEndpoint(uri);
}
private static async Task Produce(string topic, params string[] values)
{
var config = new ProducerConfig { BootstrapServers = BootstrapServers };
using var producer = new ProducerBuilder(config).Build();
foreach (var v in values)
await producer.ProduceAsync(topic, new Message { Key = "", Value = v });
producer.Flush(TimeSpan.FromSeconds(10));
}
///
/// Waits for the observed condition. The bound only keeps a broken run from hanging: a passing run
/// returns as soon as the condition holds, so it is generous for a slow shared stand.
///
private static async Task WaitUntil(Func condition, int timeoutMs = 60000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(200);
}
[Fact]
public async Task BreakOnFirstError_FailedMessage_IsRetriedNotLost()
{
// One partition: "after" is behind the poisoned record, so it can only arrive once the retry passed.
var topic = await KafkaReadiness.CreateSinglePartitionTopicAsync("a2-break");
await Produce(topic, "poison-once", "after");
var attempts = new ConcurrentQueue();
var failedOnce = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(ci =>
{
var body = System.Text.Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!);
attempts.Enqueue(body);
if (body == "poison-once" && Interlocked.Exchange(ref failedOnce, 1) == 0)
throw new InvalidOperationException("transient failure");
return Task.CompletedTask;
});
var endpoint = CreateEndpoint(topic,
$"groupId=g-{Guid.NewGuid():N}&autoOffsetReset=earliest&breakOnFirstError=true");
var consumer = (KafkaConsumer)endpoint.CreateConsumer(processor);
_consumers.Add(consumer);
await consumer.Start();
await WaitUntil(() => attempts.Count(a => a == "poison-once") >= 2 && attempts.Contains("after"));
attempts.Count(a => a == "poison-once").Should().BeGreaterThanOrEqualTo(2,
"breakOnFirstError must redeliver the failed message, not skip it");
attempts.Should().Contain("after", "after a successful retry the flow goes on");
}
[Fact]
public async Task Default_FailedMessage_IsSkippedExplicitly_AndCountedByTheRoute()
{
// One partition: the poisoned record is consumed before "after". With the cluster's three partitions and
// an empty key the two landed on random partitions, and "after" could finish before the failure was counted.
var topic = await KafkaReadiness.CreateSinglePartitionTopicAsync("a2-skip");
await Produce(topic, "poison-always", "after");
// The PRODUCT path: a real route. Pipeline statistics belong to the core's
// StatisticsProcessor wrapping the consumer's processor - the connector deliberately does
// not record the escaping exception itself, that would double-count.
var processed = new ConcurrentQueue();
var uri = $"kafka://{topic}?brokers={BootstrapServers}&groupId=g-{Guid.NewGuid():N}&autoOffsetReset=earliest";
await using var context = new RouteContext();
context.AddComponent(new KafkaComponent());
context.AddRoutes(r => r.From(uri).Process(e =>
{
var body = System.Text.Encoding.UTF8.GetString((byte[])e.In.Body!);
if (body == "poison-always") throw new InvalidOperationException("permanent failure");
processed.Enqueue(body);
}));
await context.Start();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
await WaitUntil(() => processed.Contains("after") && statistics.Errors >= 1);
// The default stays "move on" (Camel's default too), but it is visible:
// the escaping exception lands in the endpoint statistics via the core wrapper.
processed.Should().Contain("after");
statistics.Errors.Should().BeGreaterThanOrEqualTo(1,
"a skipped poison message must be visible in the endpoint statistics");
}
[Fact]
public async Task BatchAcrossPartitions_CommitsEveryPartition_BeforeShutdown()
{
// The batch used to commit only batch[^1] - ONE partition; the others rode on
// the revoked-handler at CLEAN shutdown (verified by the review's probe), so kill -9
// replayed far more than needed. Committed offsets must be right while running.
var topic = $"a6-batch-{Guid.NewGuid():N}"[..30];
using (var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = BootstrapServers }).Build())
{
await admin.CreateTopicsAsync([new Confluent.Kafka.Admin.TopicSpecification
{ Name = topic, NumPartitions = 3, ReplicationFactor = 1 }]);
await KafkaReadiness.WaitForLeaders(admin, topic, partitions: 3);
}
var config = new ProducerConfig { BootstrapServers = BootstrapServers };
using (var producer = new ProducerBuilder(config).Build())
{
for (var i = 0; i < 30; i++)
await producer.ProduceAsync(new TopicPartition(topic, new Partition(i % 3)),
new Message { Key = "", Value = $"m{i}" });
producer.Flush(TimeSpan.FromSeconds(10));
}
var processedTotal = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(ci =>
{
var messages = (List)ci.Arg().In.Body!;
Interlocked.Add(ref processedTotal, messages.Count);
return Task.CompletedTask;
});
var groupId = $"g-{Guid.NewGuid():N}";
var endpoint = CreateEndpoint(topic,
$"groupId={groupId}&autoOffsetReset=earliest&batching=true&maxBatchMessages=30&pollTimeoutMs=4000");
var consumer = (KafkaConsumer)endpoint.CreateConsumer(processor);
_consumers.Add(consumer);
await consumer.Start();
await WaitUntil(() => Volatile.Read(ref processedTotal) >= 30);
// The consumer is STILL RUNNING - no revoked-handler safety net involved. The inline commit lands
// after the processor returns: read the committed offsets until they settle on the end of each partition.
using var check = new ConsumerBuilder(new ConsumerConfig
{ BootstrapServers = BootstrapServers, GroupId = groupId }).Build();
var tps = Enumerable.Range(0, 3).Select(i => new TopicPartition(topic, new Partition(i))).ToList();
List committed = [];
await WaitUntil(() =>
{
committed = check.Committed(tps, TimeSpan.FromSeconds(10));
return committed.All(c => c.Offset.Value == 10);
});
check.Close();
committed.Should().OnlyContain(c => c.Offset.Value == 10,
"a batch must commit the last offset of EVERY partition, not of the last record only");
}
[Fact]
public async Task Producer_RecordsWireBytesOut()
{
var topic = $"a5-bytes-{Guid.NewGuid():N}"[..30];
var endpoint = CreateEndpoint(topic, "acks=all");
var producer = (KafkaProducer)endpoint.CreateProducer();
await producer.Start();
try
{
await producer.Process(new Exchange(new Message("12345")));
}
finally
{
await producer.Stop();
}
// ToProcessor counts MessagesOut for a routed producer, but only the connector knows the
// payload size on the wire.
((IEndpointStatistics)endpoint).BytesOut.Should().Be(5);
}
[Fact]
public async Task TopicIsPattern_SubscribesByRegex()
{
var suffix = Guid.NewGuid().ToString("N")[..8];
var actualTopic = $"a2-pat-{suffix}-eu";
await Produce(actualTopic, "matched");
var received = new ConcurrentQueue();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(ci =>
{
received.Enqueue(System.Text.Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!));
return Task.CompletedTask;
});
// The topic in the URI is a regex WITHOUT the ^ prefix - the flag must supply it.
var endpoint = CreateEndpoint($"a2-pat-{suffix}-.*",
$"groupId=g-{Guid.NewGuid():N}&autoOffsetReset=earliest&topicIsPattern=true");
var consumer = (KafkaConsumer)endpoint.CreateConsumer(processor);
_consumers.Add(consumer);
await consumer.Start();
await WaitUntil(() => received.Contains("matched"), 30000);
received.Should().Contain("matched",
"topicIsPattern=true must turn on the regex subscription, not be a dead flag");
}
[Fact]
public void TopicIsPattern_WithExplicitPartition_IsRefused()
{
var act = () => CreateEndpoint("orders-.*",
"groupId=g&topicIsPattern=true&partitionNumber=0");
act.Should().Throw().WithMessage("*topicIsPattern*",
"a regex subscription and an explicit partition assignment contradict each other");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaFactoryPrecedenceTests.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/KafkaFactoryPrecedenceTests.cs
----
using NSubstitute;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// The options sweep. The factory path used to resolve
/// configuration asymmetrically: brokers from the URI were honored, SASL/SSL from the URI were
/// silently swallowed, the endpoint's DEFAULTS for autoOffsetReset/retries stomped the factory's
/// explicit settings. The family rule (TcpConnectionFactory, WsConnectionFactory,
/// HttpConnectionFactory) is one sentence: a parameter the URI actually supplies wins, everything
/// else comes from the factory.
///
public sealed class KafkaFactoryPrecedenceTests
{
private static KafkaEndpointOptions BindOptions(string query, out Dictionary supplied)
{
supplied = query.Split('&', StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split('=', 2))
.ToDictionary(p => p[0], p => p[1], StringComparer.OrdinalIgnoreCase);
var options = new KafkaEndpointOptions();
options.BindFromUri(supplied);
return options;
}
private static KafkaConnectionFactory Factory() => new()
{
Brokers = "factory:9092",
SecurityProtocol = "SaslSsl",
SaslMechanism = "ScramSha256",
SaslUsername = "factory-user",
SaslPassword = "factory-pass",
AutoOffsetReset = "Earliest",
Retries = 7,
Acks = "All",
};
[Fact]
public void UriSasl_OverridesTheFactory()
{
var options = BindOptions("saslUsername=uri-user&saslPassword=uri-pass", out var supplied);
var config = options.BuildConsumerConfig(Factory(), supplied);
config.SaslUsername.Should().Be("uri-user",
"SASL from the URI was silently swallowed by the factory, though brokers from the same URI was taken");
config.SaslPassword.Should().Be("uri-pass");
config.SaslMechanism.Should().Be(Confluent.Kafka.SaslMechanism.ScramSha256,
"what the URI does not set stays the factory's");
}
[Fact]
public void FactoryAutoOffsetReset_SurvivesTheEndpointDefault()
{
var options = BindOptions("groupId=g", out var supplied);
var config = options.BuildConsumerConfig(Factory(), supplied);
config.AutoOffsetReset.Should().Be(Confluent.Kafka.AutoOffsetReset.Earliest,
"the endpoint default (Latest) overwrote the factory's explicit setting");
}
[Fact]
public void FactoryRetries_SurviveTheEndpointDefault()
{
var options = BindOptions("", out var supplied);
var config = options.BuildProducerConfig(Factory(), supplied);
config.MessageSendMaxRetries.Should().Be(7,
"the endpoint default (3) overwrote the factory's explicit setting");
}
[Fact]
public void UriAcks_OverridesTheFactory()
{
var options = BindOptions("acks=leader", out var supplied);
var config = options.BuildProducerConfig(Factory(), supplied);
config.Acks.Should().Be(Confluent.Kafka.Acks.Leader,
"acks from the URI was not applied at all on the factory path");
}
[Fact]
public void FactoryAcks_SurviveWhenUriIsSilent()
{
var options = BindOptions("", out var supplied);
var config = options.BuildProducerConfig(Factory(), supplied);
config.Acks.Should().Be(Confluent.Kafka.Acks.All);
}
// ── Hybrid configurations through the component ──────────
[Fact]
public void FactorySaslCredentials_SatisfyAUriMechanism()
{
// The RequireSaslCredentials error text offers "inline or via a named connectionFactory",
// but the component used to copy only Brokers from the factory before Validate() - so the
// second path it advertised was a lie: URI mechanism + factory credentials always threw.
var ctx = new RouteContext();
ctx.AddComponent(new KafkaComponent());
ctx.AddToRegistry("cf", Factory());
var act = () => ctx.GetEndpoint(
"kafka://orders?connectionFactory=cf&saslMechanism=ScramSha512&securityProtocol=SaslSsl&groupId=g");
act.Should().NotThrow("the factory's credentials are the second legal path from the error text");
}
[Fact]
public void FactoryGroupId_IsUsed_WhenTheUriHasNone()
{
// KafkaConnectionFactory.GroupId documented "Default consumer group ID", but nothing ever
// read it: the endpoint demanded a URI groupId before the factory value could apply -
// a dead option left behind by the dead-options sweep itself.
var ctx = new RouteContext();
ctx.AddComponent(new KafkaComponent());
var factory = Factory();
factory.GroupId = "cf-group";
ctx.AddToRegistry("cf", factory);
var endpoint = ctx.GetEndpoint("kafka://orders?connectionFactory=cf");
var act = () => endpoint.CreateConsumer(Substitute.For());
act.Should().NotThrow("the factory's GroupId must work as the default");
}
[Fact]
public void UriIdempotence_WithFactoryAcksLeader_FailsInTheConnectorsWords()
{
// Validate() checked enableIdempotence against the endpoint's
// acks only, so a factory's acks=leader reached librdkafka, which refused the client with its own error.
var options = BindOptions("connectionFactory=cf&enableIdempotence=true", out var supplied);
var factory = Factory();
factory.Acks = "Leader";
var act = () => options.BuildProducerConfig(factory, supplied);
act.Should().Throw()
.WithMessage("*'enableIdempotence=true' requires 'acks=all'*connection factory 'cf'*Leader*");
}
[Fact]
public void FactoryAcksLeader_WithoutExplicitIdempotence_StaysNonIdempotent()
{
// The check above is for an explicit enableIdempotence=true only: unset, idempotence follows the effective acks.
var options = BindOptions("connectionFactory=cf", out var supplied);
var factory = Factory();
factory.Acks = "Leader";
var config = options.BuildProducerConfig(factory, supplied);
config.Acks.Should().Be(Confluent.Kafka.Acks.Leader);
config.EnableIdempotence.Should().BeFalse();
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaFaultStand.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/KafkaFaultStand.cs
----
using System.Text;
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.Kafka;
///
/// The Kafka stand of the fault runs: one KRaft node (controller and broker) at localhost:39092 with host networking,
/// started by tests/docker/run-fault-suite.sh --broker kafka , reached through Confluent.Kafka directly, not
/// through the connector. Its data stays in the container, so topics and committed offsets outlive a stop and a start.
/// The three-node cluster of the compose file does not fit: stopping one node of three tests a leader change, not a
/// lost connection. Its container, when names it, is broken with ;
/// the broker is ready when it answers an API versions request.
///
public sealed class KafkaFaultStand : IConnectorStand
{
/// The variable that names the Kafka container a test may stop and restart.
public const string ContainerVariable = "REDB_TEST_KAFKA_CONTAINER";
/// The bootstrap server of the stand.
public const string Brokers = "localhost:39092";
/// The stand of this process.
public static KafkaFaultStand Instance { get; } = new();
private KafkaFaultStand()
{
}
///
public BrokerFault? Fault { get; } = BrokerFault.FromEnvironment(ContainerVariable,
"/opt/kafka/bin/kafka-broker-api-versions.sh", "--bootstrap-server", Brokers);
///
public TimeSpan Wait { get; } = BrokerFault.DefaultWait;
/// Creates a topic with one partition and waits until it has a leader.
public static async Task CreateTopicAsync(string prefix)
{
var topic = $"{prefix}-{Guid.NewGuid():N}";
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = Brokers }).Build();
await admin.CreateTopicsAsync([new TopicSpecification { Name = topic, NumPartitions = 1, ReplicationFactor = 1 }]);
var deadline = DateTime.UtcNow + BrokerFault.DefaultWait;
while (true)
{
var metadata = admin.GetMetadata(topic, TimeSpan.FromSeconds(10)).Topics.SingleOrDefault(t => t.Topic == topic);
if (metadata is { Error.IsError: false } && metadata.Partitions.Count == 1 && metadata.Partitions[0].Leader >= 0)
return topic;
if (DateTime.UtcNow > deadline)
throw new TimeoutException($"topic {topic} has no leader after {BrokerFault.DefaultWait}.");
await Task.Delay(200);
}
}
///
public async Task PutAsync(string destination, string body, CancellationToken ct = default)
{
using var producer = new ProducerBuilder(new ProducerConfig
{
BootstrapServers = Brokers, MessageTimeoutMs = 60000,
}).Build();
await producer.ProduceAsync(destination, new Message { Value = body }, ct);
}
///
/// The consumer group a route on reads with in the conformance cases: Kafka keeps the records,
/// so "taken off the queue" is "committed by this group", and reads as this group too.
///
public static string GroupOf(string topic) => $"conformance-{topic}";
///
///
/// Reads as the group of from its committed offsets (the start of the topic when it has none),
/// committed transactions only, and commits what it read.
///
public Task> DrainAsync(string destination, TimeSpan wait, CancellationToken ct = default)
=> Task.Run>(() =>
{
using var consumer = new ConsumerBuilder(new ConsumerConfig
{
BootstrapServers = Brokers, GroupId = GroupOf(destination),
AutoOffsetReset = AutoOffsetReset.Earliest, IsolationLevel = IsolationLevel.ReadCommitted,
EnableAutoCommit = false,
}).Build();
consumer.Subscribe(destination);
var bodies = new List();
var deadline = DateTime.UtcNow + wait;
while (DateTime.UtcNow < deadline && !ct.IsCancellationRequested)
{
var result = consumer.Consume(TimeSpan.FromMilliseconds(200));
if (result?.Message is null)
{
if (bodies.Count > 0) break;
continue;
}
bodies.Add(result.Message.Value is null ? "" : Encoding.UTF8.GetString(result.Message.Value));
consumer.Commit(result);
}
consumer.Close();
return bodies;
}, ct);
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaHeaderFilterStrategyTests.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/KafkaHeaderFilterStrategyTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// headerFilterStrategy=#name on Kafka endpoints: on a producer it decides which exchange headers go into the
/// record, on a consumer which record headers come into the exchange; the record's content type and the consumer's
/// CamelKafka* metadata are set whatever the strategy says.
///
[Trait("Category", "Integration")]
public sealed class KafkaHeaderFilterStrategyTests
{
private const string Brokers = "localhost:29092";
private static async Task> RoundTrip(string producerOptions, string consumerOptions)
{
var topic = $"hdr-strategy-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new KafkaComponent());
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false });
ctx.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["Authorization"] });
ctx.AddRoutes(r => r
.From($"kafka://{topic}?brokers={Brokers}&groupId=grp-{Guid.NewGuid():N}&autoOffsetReset=Earliest{consumerOptions}")
.Process(e => received.TrySetResult(e)));
await ctx.Start();
var exchange = new Exchange(new Message("body") { ContentType = "application/json" });
exchange.In.Headers["Correlation-ID"] = "c-42";
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["Authorization"] = "Bearer secret";
var producer = ctx.GetEndpoint($"kafka://{topic}?brokers={Brokers}{producerOptions}").CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
var arrived = await received.Task.WaitAsync(TimeSpan.FromSeconds(30));
arrived.In.ContentType.Should().Be("application/json", "the content type crosses whatever the strategy says");
return new Dictionary(arrived.In.Headers);
}
[Fact]
public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader()
{
var headers = await RoundTrip("&headerFilterStrategy=#correlationOnly", "");
headers["Correlation-ID"].Should().Be("c-42");
headers.Should().NotContainKey("X-Corr");
headers.Should().NotContainKey("Authorization");
headers.Should().ContainKey(KafkaHeaders.Topic, "the consumer's own metadata is set whatever the strategy says");
}
[Fact]
public async Task OnAConsumer_TheStrategyDecidesWhatComesIn()
{
var headers = await RoundTrip("", "&headerFilterStrategy=#noSecrets");
headers["X-Corr"].Should().Be("c1");
headers.Should().NotContainKey("Authorization", "the consumer's strategy drops it on the way in");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaHeaderMappingCharacterizationTests.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/KafkaHeaderMappingCharacterizationTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// What crosses a Kafka record today, producer to consumer: pinned before the header filter strategy
/// takes the rule over, so the transport's default keeps it exactly.
/// The producer sends every exchange header but the Camel* and kafka.* ones (Camel's strategy), as text; the consumer takes every record
/// header back, as text. A control header of another transport (redbHttp.Method ) and a credential cross too.
///
[Trait("Category", "Integration")]
public sealed class KafkaHeaderMappingCharacterizationTests
{
private const string Brokers = "localhost:29092";
[Fact]
public async Task ProducerToConsumer_TheHeadersThatCrossTheRecord()
{
var topic = $"hdr-char-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new KafkaComponent());
ctx.AddRoutes(r => r
.From($"kafka://{topic}?brokers={Brokers}&groupId=grp-{Guid.NewGuid():N}&autoOffsetReset=Earliest")
.Process(e => received.TrySetResult(e)));
await ctx.Start();
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["X-Int"] = 42;
exchange.In.Headers["X-Null"] = null;
exchange.In.Headers["Authorization"] = "Bearer secret";
exchange.In.Headers["redbHttp.Method"] = "DELETE";
exchange.In.Headers["CamelCustom"] = "camel";
exchange.In.Headers["kafka.custom"] = "kafka";
exchange.In.Headers[KafkaHeaders.PartitionKey] = 0;
var producer = ctx.GetEndpoint($"kafka://{topic}?brokers={Brokers}").CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
var headers = (await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers;
headers["X-Corr"].Should().Be("c1");
headers["X-Int"].Should().Be("42", "a value crosses as its text");
headers["X-Null"].Should().Be("", "a null value crosses as an empty value, it is not skipped");
headers["Authorization"].Should().Be("Bearer secret", "nothing filters a credential");
headers["redbHttp.Method"].Should().Be("DELETE", "a control header of another transport crosses (finding 3.1)");
headers.Should().NotContainKey("CamelCustom", "Camel* headers stay off the record, as Camel's strategy keeps them");
headers.Should().NotContainKey("kafka.custom", "kafka.* headers stay off the record too");
headers.Should().NotContainKey(KafkaHeaders.PartitionKey, "the producer's own CamelKafka* headers never reach the next hop");
headers[KafkaHeaders.Topic].Should().Be(topic, "the consumer adds its own metadata");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaIntegrationTests.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/KafkaIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using Confluent.Kafka;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Transactions;
using redb.Route.Processors;
using redb.Route.Kafka;
using Xunit.Abstractions;
namespace redb.Route.Tests.Kafka;
///
/// Integration tests against a real Kafka cluster (3-node KRaft).
/// Expects brokers at localhost:29092,localhost:29094,localhost:29096.
///
[Trait("Category", "Integration")]
public sealed class KafkaIntegrationTests
{
private const string BootstrapServers = "localhost:29092,localhost:29094,localhost:29096";
private readonly ITestOutputHelper _output;
public KafkaIntegrationTests(ITestOutputHelper output) => _output = output;
// ───── Helpers ─────
private KafkaEndpoint CreateEndpoint(string topic, string? extraParams = null)
{
var qs = $"brokers={BootstrapServers}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"kafka://{topic}?{qs}");
var component = new KafkaComponent();
return (KafkaEndpoint)component.CreateEndpoint(uri);
}
private async Task ConsumeOneMessage(string topic, string groupId, int timeoutMs = 15000)
{
var config = new ConsumerConfig
{
BootstrapServers = BootstrapServers,
GroupId = groupId,
AutoOffsetReset = Confluent.Kafka.AutoOffsetReset.Earliest,
EnableAutoCommit = true
};
using var consumer = new ConsumerBuilder(config).Build();
consumer.Subscribe(topic);
using var cts = new CancellationTokenSource(timeoutMs);
try
{
// Retry loop: topic may not be available immediately after auto-creation
while (!cts.Token.IsCancellationRequested)
{
try
{
var result = consumer.Consume(cts.Token);
return result?.Message?.Value;
}
catch (ConsumeException ex) when (ex.Error.Code == ErrorCode.UnknownTopicOrPart)
{
await Task.Delay(500, cts.Token);
}
}
return null;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
consumer.Close();
}
}
private async Task ProduceMessage(string topic, string value, string? key = null)
{
var config = new ProducerConfig { BootstrapServers = BootstrapServers };
using var producer = new ProducerBuilder(config).Build();
await producer.ProduceAsync(topic, new Message { Key = key ?? "", Value = value });
producer.Flush(TimeSpan.FromSeconds(5));
}
// ───── Tests ─────
[Fact]
public async Task Producer_SendsMessage_ConsumerReceives()
{
var topic = $"test-produce-consume-{Guid.NewGuid():N}";
_output.WriteLine($"Topic: {topic}");
var ep = CreateEndpoint(topic);
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("Hello Kafka Cluster"));
await producer.Process(exchange);
await producer.Stop();
var received = await ConsumeOneMessage(topic, $"verify-{Guid.NewGuid():N}");
received.Should().Be("Hello Kafka Cluster");
}
[Fact]
public async Task Producer_WithRecordMetadata_SetsHeaders()
{
var topic = $"test-metadata-{Guid.NewGuid():N}";
var ep = CreateEndpoint(topic, "recordMetadata=true");
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("meta-test"));
await producer.Process(exchange);
await producer.Stop();
var meta = exchange.In.Headers[KafkaHeaders.RecordMeta].Should().BeOfType>().Subject;
meta.Should().ContainSingle();
meta[0].Topic.Should().Be(topic);
meta[0].Offset.Should().BeGreaterThanOrEqualTo(0);
}
[Fact]
public async Task Producer_ForwardsMessageHeaders()
{
var topic = $"test-headers-{Guid.NewGuid():N}";
var ep = CreateEndpoint(topic);
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var msg = new Message("data");
msg.Headers["custom-header"] = "custom-value";
var exchange = new Exchange(msg);
await producer.Process(exchange);
await producer.Stop();
var config = new ConsumerConfig
{
BootstrapServers = BootstrapServers,
GroupId = $"hdr-verify-{Guid.NewGuid():N}",
AutoOffsetReset = Confluent.Kafka.AutoOffsetReset.Earliest,
EnableAutoCommit = true
};
using var consumer = new ConsumerBuilder(config).Build();
consumer.Subscribe(topic);
using var cts = new CancellationTokenSource(15000);
var result = consumer.Consume(cts.Token);
consumer.Close();
result.Message.Headers.TryGetLastBytes("custom-header", out var bytes).Should().BeTrue();
System.Text.Encoding.UTF8.GetString(bytes!).Should().Be("custom-value");
}
[Fact]
public async Task Consumer_PollsMessages_InvokesProcessor()
{
var topic = $"test-consumer-{Guid.NewGuid():N}";
await ProduceMessage(topic, "consumer-test-msg");
var ep = CreateEndpoint(topic, $"groupId=grp-{Guid.NewGuid():N}&autoOffsetReset=Earliest");
var received = new ConcurrentBag();
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var ex = callInfo.Arg();
received.Add(Encoding.UTF8.GetString((byte[])ex.In.Body!));
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)ep.CreateConsumer(processor);
await consumer.Start();
var completed = await Task.WhenAny(tcs.Task, Task.Delay(30_000));
await consumer.Stop();
completed.Should().Be(tcs.Task, "consumer should receive the message within timeout");
received.Should().Contain("consumer-test-msg");
consumer.ProcessedCount.Should().BeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task Consumer_SetsKafkaMetadataHeaders()
{
var topic = $"test-meta-headers-{Guid.NewGuid():N}";
await ProduceMessage(topic, "meta-test", key: "myKey");
var ep = CreateEndpoint(topic, $"groupId=grp-{Guid.NewGuid():N}&autoOffsetReset=Earliest");
IExchange? capturedExchange = null;
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
capturedExchange = callInfo.Arg();
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)ep.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(30_000));
await consumer.Stop();
capturedExchange.Should().NotBeNull();
capturedExchange!.In.Headers.Should().ContainKey(KafkaHeaders.Topic);
capturedExchange.In.Headers[KafkaHeaders.Topic].Should().Be(topic);
capturedExchange.In.Headers.Should().ContainKey(KafkaHeaders.Partition);
capturedExchange.In.Headers.Should().ContainKey(KafkaHeaders.Offset);
capturedExchange.In.Headers.Should().ContainKey(KafkaHeaders.Key);
capturedExchange.In.Headers[KafkaHeaders.Key].Should().Be("myKey");
capturedExchange.Pattern.Should().Be(ExchangePattern.InOnly);
}
[Fact]
public async Task Consumer_BatchMode_CollectsMultipleMessages()
{
var topic = $"test-batch-{Guid.NewGuid():N}";
for (int i = 0; i < 5; i++)
await ProduceMessage(topic, $"batch-{i}");
var ep = CreateEndpoint(topic,
$"groupId=grp-{Guid.NewGuid():N}&autoOffsetReset=Earliest&batching=true&maxBatchMessages=10&pollTimeoutMs=5000");
var processedMessages = new ConcurrentBag();
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var ex = callInfo.Arg();
processedMessages.Add(ex.In.Body);
if (ex.In.Body is List)
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)ep.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(30_000));
await consumer.Stop();
processedMessages.Should().NotBeEmpty();
}
/// Starts a consumer on and returns the first exchange it hands the route.
private async Task FirstExchange(string topic, string consumerParams)
{
var ep = CreateEndpoint(topic, $"groupId=grp-{Guid.NewGuid():N}&autoOffsetReset=Earliest&{consumerParams}");
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
first.TrySetResult(callInfo.Arg());
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)ep.CreateConsumer(processor);
await consumer.Start();
try
{
return await first.Task.WaitAsync(TimeSpan.FromSeconds(30));
}
finally
{
await consumer.Stop();
}
}
/// Reads the first record of as it is on the wire: key, value, headers.
private static Message? ReadOneRecord(string topic)
{
var config = new ConsumerConfig
{
BootstrapServers = BootstrapServers,
GroupId = $"verify-{Guid.NewGuid():N}",
AutoOffsetReset = Confluent.Kafka.AutoOffsetReset.Earliest,
};
using var consumer = new ConsumerBuilder(config).Build();
consumer.Subscribe(topic);
try
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20);
while (DateTime.UtcNow < deadline)
{
try
{
if (consumer.Consume(TimeSpan.FromMilliseconds(250))?.Message is { } message)
return message;
}
catch (ConsumeException ex) when (ex.Error.Code == ErrorCode.UnknownTopicOrPart)
{
}
}
return null;
}
finally
{
consumer.Close();
}
}
/// Sends one exchange as a consumed record would reach the producer: with the headers the consumer set.
private async Task?> PassOn(string topic, string? producerParams, Action consumed)
{
var producer = (KafkaProducer)CreateEndpoint(topic, producerParams).CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("passed-on"));
consumed(exchange.In);
await producer.Process(exchange);
await producer.Stop();
return ReadOneRecord(topic);
}
[Fact]
public async Task Producer_PassingARecordOn_KeepsItsKey()
{
// The consumer put the record's key on the exchange and the
// producer dropped it with its own metadata headers: a passthrough changed partition and compaction.
var topic = $"test-key-carry-{Guid.NewGuid():N}";
var record = await PassOn(topic, null, m => m.Headers[KafkaHeaders.Key] = "order-7");
record.Should().NotBeNull();
record!.Key.Should().Be("order-7");
}
[Fact]
public async Task Producer_KeyOption_WinsOverTheConsumedKey()
{
var topic = $"test-key-option-{Guid.NewGuid():N}";
var record = await PassOn(topic, "key=explicit", m => m.Headers[KafkaHeaders.Key] = "order-7");
record!.Key.Should().Be("explicit");
}
[Fact]
public async Task Producer_WithoutTheKeyHeader_SendsWithoutAKey()
{
var topic = $"test-key-off-{Guid.NewGuid():N}";
var record = await PassOn(topic, null, m => m.Headers.Remove(KafkaHeaders.Key));
record.Should().NotBeNull();
record!.Key.Should().BeNull();
}
[Fact]
public async Task Producer_PassingARecordOn_SendsOneContentType()
{
// Review R7: the consumer keeps the record's content-type header next to ContentType; the producer wrote both.
var topic = $"test-content-type-{Guid.NewGuid():N}";
var record = await PassOn(topic, null, m =>
{
m.ContentType = "application/json";
m.Headers["content-type"] = "application/json";
});
record.Should().NotBeNull();
record!.Headers.Where(h => h.Key == "content-type").Should().ContainSingle()
.Which.GetValueBytes().Should().Equal(Encoding.UTF8.GetBytes("application/json"));
}
[Fact]
public async Task Consumer_BatchMode_GivesARecordTheSameHeadersAsSingleMode()
{
// The batch path left out the key and the timestamp headers,
// so a route reading the key worked record by record and got null once batch mode was on.
var topic = $"test-batch-shape-{Guid.NewGuid():N}";
await ProduceMessage(topic, "shape-test", key: "order-42");
var single = (await FirstExchange(topic, "pollTimeoutMs=5000")).In;
var batch = await FirstExchange(topic, "batching=true&maxBatchMessages=10&pollTimeoutMs=5000");
var inBatch = batch.In.Body.Should().BeAssignableTo>().Subject[0];
inBatch.Headers.Keys.Should().BeEquivalentTo(single.Headers.Keys);
inBatch.Headers[KafkaHeaders.Key].Should().Be("order-42");
inBatch.Headers[KafkaHeaders.Timestamp].Should().Be(single.Headers[KafkaHeaders.Timestamp]);
}
/// Runs inside a transacted block, as .Transacted() on a route does.
private static Task InTransaction(IExchange exchange, Func body) =>
new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
[Fact]
public async Task TransactedProducer_DeferredCommit_Delivers()
{
// Regression for the "Local: Erroneous state" bug: with transacted=true, committing the
// deferred KafkaSendAction (what a .Transacted() boundary does) must actually deliver the
// message. Before the fix this threw because transactional.id + InitTransactions put
// librdkafka into transactional mode, where Produce without BeginTransaction is rejected.
var topic = $"test-tx-deliver-{Guid.NewGuid():N}";
var ep = CreateEndpoint(topic, "transacted=true");
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("tx-real-msg"));
// The block commits the deferred KafkaSendAction, i.e. the deferred ProduceAsync; it must NOT throw.
await InTransaction(exchange, (ex, ct) => producer.Process(ex, ct));
await producer.Stop();
var received = await ConsumeOneMessage(topic, $"verify-{Guid.NewGuid():N}");
received.Should().Be("tx-real-msg");
}
[Fact]
public async Task TransactedProducer_DeferredCommit_RecordsTheSameMetadataAsAnImmediateSend()
{
// The deferred send recorded less metadata than the immediate one.
var topic = $"test-tx-metadata-{Guid.NewGuid():N}";
var ep = CreateEndpoint(topic, "transacted=true&recordMetadata=true");
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("tx-meta"));
await InTransaction(exchange, (ex, ct) => producer.Process(ex, ct));
await producer.Stop();
var meta = exchange.In.Headers[KafkaHeaders.RecordMeta].Should().BeOfType>().Subject;
meta.Should().ContainSingle().Which.Topic.Should().Be(topic, "a deferred send records its metadata as an immediate one");
meta[0].Timestamp.Should().BePositive();
}
[Fact]
public async Task TransactedProducer_OutsideTransactedBlock_Refuses()
{
var topic = $"test-transact-{Guid.NewGuid():N}";
var ep = CreateEndpoint(topic, "transacted=true");
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
// Nothing would ever commit a send deferred outside .Transacted(), so the producer refuses it.
var act = () => producer.Process(new Exchange(new Message("transacted-msg")));
await act.Should().ThrowAsync().WithMessage("*Transacted()*");
await producer.Stop();
}
/// Sends one message from inside a .Transacted() block that then fails.
private async Task SendFromAFailedBlock(string topic, string? producerParams)
{
var ep = CreateEndpoint(topic, producerParams);
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var failed = () => InTransaction(new Exchange(new Message("sent-from-a-failed-block")), async (ex, ct) =>
{
await producer.Process(ex, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync();
await producer.Stop();
}
[Fact]
public async Task Producer_without_transacted_joins_the_block_and_sends_nothing_when_it_fails()
{
var topic = $"test-join-{Guid.NewGuid():N}";
await SendFromAFailedBlock(topic, producerParams: null);
(await ConsumeOneMessage(topic, $"verify-{Guid.NewGuid():N}", timeoutMs: 8000))
.Should().BeNull("inside .Transacted() a send joins the transaction unless transacted=false opts out");
}
[Fact]
public async Task Producer_with_transacted_false_sends_at_once_even_from_a_failed_block()
{
var topic = $"test-optout-{Guid.NewGuid():N}";
await SendFromAFailedBlock(topic, "transacted=false");
(await ConsumeOneMessage(topic, $"verify-{Guid.NewGuid():N}")).Should().Be("sent-from-a-failed-block");
}
[Fact]
public async Task Roundtrip_ProduceAndConsume_MultipleMessages()
{
var topic = $"test-roundtrip-{Guid.NewGuid():N}";
const int messageCount = 10;
var epProd = CreateEndpoint(topic);
var producer = (KafkaProducer)epProd.CreateProducer();
await producer.Start();
for (int i = 0; i < messageCount; i++)
{
var exchange = new Exchange(new Message($"msg-{i}"));
await producer.Process(exchange);
}
await producer.Stop();
var epCons = CreateEndpoint(topic, $"groupId=rt-{Guid.NewGuid():N}&autoOffsetReset=Earliest");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var ex = callInfo.Arg();
received.Add(Encoding.UTF8.GetString((byte[])ex.In.Body!));
if (received.Count >= messageCount)
allReceived.TrySetResult();
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allReceived.Task, Task.Delay(30_000));
await consumer.Stop();
received.Count.Should().BeGreaterThanOrEqualTo(messageCount);
for (int i = 0; i < messageCount; i++)
received.Should().Contain($"msg-{i}");
}
[Fact]
public async Task Producer_WithKey_PartitioningWorks()
{
var topic = $"test-key-partition-{Guid.NewGuid():N}";
var ep = CreateEndpoint(topic, "key=${header.orderId}");
var producer = (KafkaProducer)ep.CreateProducer();
await producer.Start();
var msg = new Message("order-data");
msg.Headers["orderId"] = "ORD-12345";
var exchange = new Exchange(msg);
await producer.Process(exchange);
await producer.Stop();
var config = new ConsumerConfig
{
BootstrapServers = BootstrapServers,
GroupId = $"key-verify-{Guid.NewGuid():N}",
AutoOffsetReset = Confluent.Kafka.AutoOffsetReset.Earliest,
EnableAutoCommit = true
};
using var consumer = new ConsumerBuilder(config).Build();
consumer.Subscribe(topic);
// Same UnknownTopicOrPart retry the file's own ConsumeOneMessage helper uses: the topic is
// auto-created by the produce above, and its metadata may lag under cluster load.
using var cts = new CancellationTokenSource(15000);
ConsumeResult? result = null;
while (result is null && !cts.Token.IsCancellationRequested)
{
try
{
result = consumer.Consume(cts.Token);
}
catch (ConsumeException ex) when (ex.Error.Code == ErrorCode.UnknownTopicOrPart)
{
await Task.Delay(500, cts.Token);
}
}
consumer.Close();
result.Should().NotBeNull();
result!.Message.Key.Should().Be("ORD-12345");
result.Message.Value.Should().Be("order-data");
}
[Fact]
public async Task MultiNode_ProduceConsume_AcrossCluster()
{
var topic = $"test-cluster-{Guid.NewGuid():N}";
_output.WriteLine($"Cluster test: {topic}");
// Produce 20 messages with acks=all — replicated across brokers
var epProd = CreateEndpoint(topic, "acks=all");
var producer = (KafkaProducer)epProd.CreateProducer();
await producer.Start();
for (int i = 0; i < 20; i++)
{
var exchange = new Exchange(new Message($"cluster-msg-{i}"));
await producer.Process(exchange);
}
await producer.Stop();
// Consume all 20
var epCons = CreateEndpoint(topic, $"groupId=cluster-{Guid.NewGuid():N}&autoOffsetReset=Earliest");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
received.Add(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
if (received.Count >= 20)
allReceived.TrySetResult();
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allReceived.Task, Task.Delay(30_000));
await consumer.Stop();
received.Count.Should().Be(20);
}
// ───── ackMode (framework-level offset commit) ─────
///
/// Reads the total committed offset for a group across all partitions of a topic via the
/// group coordinator. Uses a non-subscribing probe consumer (never joins the group → no
/// rebalance), so it can be called while another consumer in the same group is running.
///
private long GetCommittedTotal(string topic, string groupId)
{
using var admin = new AdminClientBuilder(
new AdminClientConfig { BootstrapServers = BootstrapServers }).Build();
var meta = admin.GetMetadata(topic, TimeSpan.FromSeconds(10));
var tps = meta.Topics[0].Partitions
.Select(p => new TopicPartition(topic, new Partition(p.PartitionId)))
.ToList();
using var probe = new ConsumerBuilder(new ConsumerConfig
{
BootstrapServers = BootstrapServers,
GroupId = groupId,
EnableAutoCommit = false
}).Build();
var committed = probe.Committed(tps, TimeSpan.FromSeconds(10));
return committed.Where(c => c.Offset != Offset.Unset).Sum(c => c.Offset.Value);
}
[Fact]
public async Task Consumer_AutoCommitDefault_CommitsOffsetInline_BeforeStop()
{
// Default ackMode=manual: the consumer must commit the offset inline right after a
// successful Process — i.e. BEFORE any graceful stop (the PartitionsRevokedHandler that
// commits on stop is intentionally not exercised here, so a committed offset can only come
// from the inline auto-commit path).
var topic = $"test-autocommit-on-{Guid.NewGuid():N}";
var groupId = $"ac-on-{Guid.NewGuid():N}";
const int n = 3;
for (int i = 0; i < n; i++) await ProduceMessage(topic, $"msg-{i}");
var ep = CreateEndpoint(topic, $"groupId={groupId}&autoOffsetReset=Earliest");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci =>
{
received.Add(Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!));
if (received.Count >= n) allReceived.TrySetResult();
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)ep.CreateConsumer(processor);
await consumer.Start();
try
{
await Task.WhenAny(allReceived.Task, Task.Delay(30_000));
received.Count.Should().BeGreaterThanOrEqualTo(n);
// Poll the committed offset WHILE the consumer is still running (no stop → no revoke commit).
long committed = 0;
for (int i = 0; i < 20 && committed < n; i++)
{
await Task.Delay(500);
committed = GetCommittedTotal(topic, groupId);
}
committed.Should().BeGreaterThanOrEqualTo(n,
"ackMode=manual must commit the offset inline after Process, before any stop");
}
finally
{
await consumer.Stop();
}
}
[Fact]
public async Task Consumer_AckModeAuto_CommitsOnReceipt_EvenWhenTheRouteFails()
{
// ackMode=auto (at-most-once): the offset is committed before the route runs, so records whose route
// failed are not read again. The committed offset advances while the consumer still runs.
var topic = $"test-ackmode-auto-{Guid.NewGuid():N}";
var groupId = $"ack-auto-{Guid.NewGuid():N}";
const int n = 3;
for (int i = 0; i < n; i++) await ProduceMessage(topic, $"msg-{i}");
var ep = CreateEndpoint(topic, $"groupId={groupId}&autoOffsetReset=Earliest&ackMode=auto");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci =>
{
received.Add(Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!));
if (received.Count >= n) allReceived.TrySetResult();
throw new InvalidOperationException("the route fails");
});
var consumer = (KafkaConsumer)ep.CreateConsumer(processor);
await consumer.Start();
try
{
await Task.WhenAny(allReceived.Task, Task.Delay(30_000));
received.Count.Should().BeGreaterThanOrEqualTo(n);
long committed = 0;
for (int i = 0; i < 20 && committed < n; i++)
{
await Task.Delay(500);
committed = GetCommittedTotal(topic, groupId);
}
committed.Should().BeGreaterThanOrEqualTo(n,
"ackMode=auto commits on receipt, whatever the route then does");
}
finally
{
await consumer.Stop();
}
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaListSendTests.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/KafkaListSendTests.cs
----
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;
///
/// A list body at the Kafka producer, as camel-kafka sends an Iterable body: each element of a list of IMessage is its
/// own record with its own value, headers and key, none of the exchange's headers; each element of a plain list is a
/// record with the exchange's headers and key; a failure in the middle stops the list and the records sent stay.
///
[Trait("Category", "Integration")]
public sealed class KafkaListSendTests : 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, int partitions = 1)
{
var topic = $"{name}-{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)
{
var uri = EndpointUriParser.Parse($"kafka://{topic}?brokers={BootstrapServers}");
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,
};
using var consumer = new ConsumerBuilder(config).Build();
consumer.Subscribe(topic);
var records = new List>();
var deadline = DateTime.UtcNow + (expected == 0 ? TimeSpan.FromSeconds(5) : TimeSpan.FromSeconds(60));
while (DateTime.UtcNow < deadline && (expected == 0 || 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? Header(ConsumeResult record, string name)
=> record.Message.Headers.TryGetLastBytes(name, out var bytes) ? Encoding.UTF8.GetString(bytes) : null;
private static string Value(ConsumeResult record) => Encoding.UTF8.GetString(record.Message.Value);
[Fact]
public async Task Each_message_of_a_list_is_its_own_record_with_its_own_value_headers_and_key()
{
var topic = await CreateTopic("list-messages", partitions: 3);
var producer = await StartProducer(topic);
var parent = new Exchange(new Message(new List
{
Element("a", "key-a", "rec-a"),
Element("b", "key-b", "rec-b"),
Element("c", "key-a", "rec-c"),
}));
parent.In.Headers["X-Parent"] = "must-not-travel";
await producer.Process(parent);
await producer.Stop();
var records = Read(topic, 3).OrderBy(r => Value(r)).ToList();
records.Select(Value).Should().Equal("a", "b", "c");
records.Select(r => r.Message.Key).Should().Equal("key-a", "key-b", "key-a");
records.Select(r => Header(r, "X-Record")).Should().Equal("rec-a", "rec-b", "rec-c");
records.Should().AllSatisfy(r => Header(r, "X-Parent").Should().BeNull());
records[0].Partition.Should().Be(records[2].Partition, "the same key goes to the same partition");
}
[Fact]
public async Task Each_value_of_a_plain_list_is_a_record_with_the_exchanges_headers_and_key()
{
var topic = await CreateTopic("list-plain");
var producer = await StartProducer(topic);
var parent = new Exchange(new Message(new List { "x", "y" }));
parent.In.Headers["X-Parent"] = "p";
parent.In.Headers[KafkaHeaders.Key] = "parent-key";
await producer.Process(parent);
await producer.Stop();
var records = Read(topic, 2);
records.Select(Value).Should().Equal("x", "y");
records.Should().AllSatisfy(r =>
{
r.Message.Key.Should().Be("parent-key");
Header(r, "X-Parent").Should().Be("p");
});
}
[Fact]
public async Task A_failure_in_the_middle_stops_the_list_and_the_records_sent_stay()
{
var topic = await CreateTopic("list-fail");
var producer = await StartProducer(topic);
var tooLarge = new Message(new byte[2_000_000]);
var parent = new Exchange(new Message(new List { new Message("first"), tooLarge, new Message("third") }));
var act = () => producer.Process(parent);
await act.Should().ThrowAsync();
await producer.Stop();
Read(topic, 0).Select(Value).Should().Equal("first");
}
private static Message Element(string value, string key, string header)
{
var message = new Message(value);
message.Headers[KafkaHeaders.Key] = key;
message.Headers["X-Record"] = header;
return message;
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaLoudConfigTests.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/KafkaLoudConfigTests.cs
----
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// The options sweep: a typo in an enum-valued option must
/// fail endpoint creation, not silently fall back to a default. The worst case was security:
/// securityProtocol=SaslSSL (typo) used to yield a PLAINTEXT connection with no
/// credentials, because both TryParse branches quietly skipped the assignment. The rest are the
/// same disease with milder symptoms: acks=quorum silently became Leader, isolationLevel typo
/// silently read uncommitted, autoOffsetReset typo silently skipped history.
///
public sealed class KafkaLoudConfigTests
{
private static KafkaEndpoint CreateEndpoint(string parameters)
{
var uri = EndpointUriParser.Parse($"kafka://orders?brokers=localhost:9092&{parameters}");
return (KafkaEndpoint)new KafkaComponent().CreateEndpoint(uri);
}
// ── A typo must fail ──
[Theory]
[InlineData("securityProtocol=SaslSSLx")]
[InlineData("securityProtocol=SASLL_SSL")]
[InlineData("saslMechanism=Plane&saslUsername=u&saslPassword=p&securityProtocol=SaslSsl")]
[InlineData("acks=quorum")]
[InlineData("isolationLevel=readcommited")]
[InlineData("autoOffsetReset=earlist")]
[InlineData("compressionType=gzipp")]
[InlineData("partitionAssignmentStrategy=sticky")]
[InlineData("seekTo=start")]
public void Typo_FailsEndpointCreation_NamingTheOption(string parameters)
{
var act = () => CreateEndpoint(parameters);
var optionName = parameters.Split('=')[0];
act.Should().Throw(
$"a typo in '{optionName}' silently gave the default value")
.WithMessage($"*{optionName}*", "the error must name the option");
}
[Fact]
public void SecurityProtocolTypo_MessageListsTheValidValues()
{
var act = () => CreateEndpoint("securityProtocol=SaslSSLx");
act.Should().Throw().WithMessage("*SaslSsl*",
"the admin must see the allowed values, not go to the sources");
}
[Fact]
public void FactoryWithTypo_FailsOnBuild()
{
var factory = new KafkaConnectionFactory { SecurityProtocol = "SaslSSLx" };
var act = () => factory.BuildConsumerConfig("g");
act.Should().Throw().WithMessage("*securityProtocol*");
}
// ── Legitimate forms must work, including the canonical Kafka spellings ──
[Theory]
[InlineData("SaslSsl", SecurityProtocol.SaslSsl)]
[InlineData("SASL_SSL", SecurityProtocol.SaslSsl)] // librdkafka canon
[InlineData("sasl_plaintext", SecurityProtocol.SaslPlaintext)]
[InlineData("Plaintext", SecurityProtocol.Plaintext)]
public void SecurityProtocol_AcceptsBothCSharpAndKafkaForms(string value, SecurityProtocol expected)
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", SecurityProtocol = value };
opts.BuildConsumerConfig().SecurityProtocol.Should().Be(expected);
}
[Theory]
[InlineData("ScramSha256", SaslMechanism.ScramSha256)]
[InlineData("SCRAM-SHA-256", SaslMechanism.ScramSha256)] // Kafka canon
[InlineData("PLAIN", SaslMechanism.Plain)]
public void SaslMechanism_AcceptsBothForms(string value, SaslMechanism expected)
{
var opts = new KafkaEndpointOptions
{
Brokers = "localhost:9092", SecurityProtocol = "SaslSsl",
SaslMechanism = value, SaslUsername = "u", SaslPassword = "p",
};
opts.BuildConsumerConfig().SaslMechanism.Should().Be(expected);
}
[Theory]
[InlineData("all", Acks.All)]
[InlineData("-1", Acks.All)]
[InlineData("1", Acks.Leader)]
[InlineData("none", Acks.None)]
public void Acks_KeepsItsHistoricalSynonyms(string value, Acks expected)
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", Acks = value };
opts.BuildProducerConfig().Acks.Should().Be(expected);
}
[Theory]
[InlineData("read_committed", IsolationLevel.ReadCommitted)]
[InlineData("ReadCommitted", IsolationLevel.ReadCommitted)]
[InlineData("readuncommitted", IsolationLevel.ReadUncommitted)]
public void IsolationLevel_KeepsItsHistoricalSynonyms(string value, IsolationLevel expected)
{
var opts = new KafkaEndpointOptions { Brokers = "localhost:9092", IsolationLevel = value };
opts.BuildConsumerConfig().IsolationLevel.Should().Be(expected);
}
// ── A mechanism without credentials is loud too ──
[Fact]
public void SaslMechanismWithoutCredentials_Fails()
{
var act = () => CreateEndpoint("securityProtocol=SaslSsl&saslMechanism=Plain");
act.Should().Throw().WithMessage("*saslUsername*");
}
// ── additionalProperties: both sources, one list of refused properties ──
private static KafkaEndpointOptions WithProperty(string name, string value, string? transactionalIdPrefix = null) =>
new()
{
Brokers = "localhost:9092",
TransactionalIdPrefix = transactionalIdPrefix,
AdditionalProperties = { [name] = value },
};
/// Creates an endpoint through a context whose registry holds connection factory 'cf'.
private static IEndpoint EndpointWithFactory(KafkaConnectionFactory factory, string parameters)
{
var context = new RouteContext();
context.AddComponent(new KafkaComponent());
context.AddToRegistry("cf", factory);
return context.GetEndpoint($"kafka://orders?connectionFactory=cf&{parameters}");
}
[Fact]
public void AutoCommit_InAdditionalProperties_IsRefused()
{
// Applied last, it overrode the connector's enable.auto.commit=false: records read but not processed were
// committed on a timer, whatever ackMode said.
var act = () => WithProperty("enable.auto.commit", "true").Validate();
act.Should().Throw().WithMessage("*enable.auto.commit=true*additionalProperties*ackMode*");
}
[Fact]
public void AutoCommit_InTheFactorysAdditionalProperties_IsRefused()
{
var factory = new KafkaConnectionFactory { Brokers = "localhost:9092", AdditionalProperties = { ["enable.auto.commit"] = "true" } };
var act = () => EndpointWithFactory(factory, "groupId=g");
act.Should().Throw().WithMessage("*enable.auto.commit=true*connection factory 'cf'*");
}
[Fact]
public void TransactionalId_InTheFactorysAdditionalProperties_IsRefused()
{
// The endpoint's own additionalProperties refused it; the factory's were a way round.
var factory = new KafkaConnectionFactory { Brokers = "localhost:9092", AdditionalProperties = { ["transactional.id"] = "orders" } };
var act = () => EndpointWithFactory(factory, "acks=all");
act.Should().Throw().WithMessage("*transactional.id*connection factory 'cf'*transactionalIdPrefix*");
}
[Theory]
[InlineData("enable.idempotence", "false")]
[InlineData("acks", "1")]
[InlineData("acks", "leader")]
public void A_property_contradicting_a_transactional_producer_is_refused(string name, string value)
{
var act = () => WithProperty(name, value, transactionalIdPrefix: "orders").Validate();
act.Should().Throw().WithMessage($"*'{name}={value}'*transactionalIdPrefix*");
}
// ── TLS options ──
[Theory]
[InlineData("none", Confluent.Kafka.SslEndpointIdentificationAlgorithm.None)]
[InlineData("", Confluent.Kafka.SslEndpointIdentificationAlgorithm.None)]
[InlineData("HTTPS", Confluent.Kafka.SslEndpointIdentificationAlgorithm.Https)]
public void HostnameVerification_IsParsedByValue(string value, Confluent.Kafka.SslEndpointIdentificationAlgorithm expected)
{
// "none" used to mean https: only the empty string turned the check off.
var options = new KafkaEndpointOptions { Brokers = "localhost:9092", SslEndpointIdentificationAlgorithm = value };
options.BuildProducerConfig().SslEndpointIdentificationAlgorithm.Should().Be(expected);
}
[Theory]
[InlineData("kafka://orders?brokers=localhost:9092&sslEndpointIdentificationAlgorithm=nope")]
[InlineData("kafka://orders?brokers=localhost:9092&sslEndpointIdentificationAlgorithm=off")]
public void HostnameVerification_Typo_FailsEndpointCreation(string uri)
{
var act = () => new KafkaComponent().CreateEndpoint(EndpointUriParser.Parse(uri));
act.Should().Throw().WithMessage("*sslEndpointIdentificationAlgorithm*https*none*");
}
[Fact]
public void HostnameVerification_Typo_InTheFactory_FailsTheBuild()
{
var factory = new KafkaConnectionFactory { Brokers = "localhost:9092", SslEndpointIdentificationAlgorithm = "nope" };
var act = () => factory.BuildProducerConfig();
act.Should().Throw().WithMessage("*sslEndpointIdentificationAlgorithm*");
}
[Theory]
[InlineData("securityProtocol=SaslPlaintext&saslMechanism=Plain&saslUsername=u&saslPassword=p", true)]
[InlineData("securityProtocol=SaslSsl&saslMechanism=Plain&saslUsername=u&saslPassword=p", false)]
[InlineData("securityProtocol=SaslPlaintext&saslMechanism=ScramSha512&saslUsername=u&saslPassword=p", false)]
public async Task SaslPlain_OverPlaintext_WarnsThatThePasswordGoesUnencrypted(string parameters, bool warned)
{
var capture = new CapturingLoggerProvider();
await using var context = new RouteContext(loggerFactory: Microsoft.Extensions.Logging.LoggerFactory.Create(
b => b.AddProvider(capture)));
var component = new KafkaComponent();
context.AddComponent(component);
var endpoint = (KafkaEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse($"kafka://orders?brokers=localhost:1&{parameters}"));
// A plain producer builds its client on start without reaching a broker.
var producer = (KafkaProducer)endpoint.CreateProducer();
await producer.Start();
await producer.Stop();
capture.Entries.Any(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Warning
&& e.Message.Contains("sends the password unencrypted"))
.Should().Be(warned);
}
[Theory]
[InlineData("enable.auto.commit", "false", null)]
[InlineData("enable.idempotence", "true", "orders")]
[InlineData("acks", "all", "orders")]
[InlineData("acks", "-1", "orders")]
[InlineData("acks", "1", null)]
public void A_property_that_agrees_with_the_connector_is_left_alone(string name, string value, string? prefix)
{
var act = () => WithProperty(name, value, prefix).Validate();
act.Should().NotThrow();
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaOverrideHeadersIntegrationTests.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/KafkaOverrideHeadersIntegrationTests.cs
----
using System.Text;
using Confluent.Kafka;
using Confluent.Kafka.Admin;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
using redb.Route.Processors;
using redb.Route.Transactions;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.Tests.Kafka;
///
/// and against the three-broker
/// stand: a record lands in the overriding topic with the overriding timestamp, at once, deferred to a
/// .Transacted() block and inside a Kafka transaction; a list follows camel-kafka's createRecordIterable
/// (the exchange's topic once for every element, an element's own override first); a bad value sends nothing.
///
[Trait("Category", "Integration")]
public sealed class KafkaOverrideHeadersIntegrationTests : IAsyncLifetime
{
private const string BootstrapServers = "localhost:29092,localhost:29094,localhost:29096";
// A recent stamp: a record older than the topic's retention.ms (7 days by default) is deleted by the broker's next
// retention check, before the test reads it.
private static readonly long Stamp = DateTimeOffset.UtcNow.AddMinutes(-5).ToUnixTimeMilliseconds();
public Task InitializeAsync() => KafkaReadiness.GroupCoordinatorAsync();
public Task DisposeAsync() => Task.CompletedTask;
private static async Task CreateTopic(string name)
{
var topic = $"override-{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 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;
}
/// Reads from the start until records or the wait ends.
private static List> Read(string topic, int expected, int seconds = 60)
{
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(seconds);
while (DateTime.UtcNow < deadline && records.Count < expected)
{
try
{
var result = consumer.Consume(TimeSpan.FromMilliseconds(250));
if (result?.Message is not null) records.Add(result);
}
catch (ConsumeException ex) when (ex.Error.Code == ErrorCode.UnknownTopicOrPart)
{
// A topic just created, and not written to, may not be known yet to the broker the consumer asks.
}
}
consumer.Close();
return records;
}
/// Reads for a few seconds and expects nothing: the topic stayed empty.
private static List> ReadNothing(string topic) => Read(topic, expected: 1, seconds: 8);
private static string Body(ConsumeResult record) => Encoding.UTF8.GetString(record.Message.Value);
private static Exchange Overridden(string body, string topic, object? timestamp = null)
{
var exchange = new Exchange(new RouteMessage(body));
exchange.In.Headers[KafkaHeaders.OverrideTopic] = topic;
if (timestamp is not null) exchange.In.Headers[KafkaHeaders.OverrideTimestamp] = timestamp;
return exchange;
}
private static void ShouldBeTheOverride(ConsumeResult record, string body)
{
Body(record).Should().Be(body);
record.Message.Timestamp.UnixTimestampMs.Should().Be(Stamp);
record.Message.Timestamp.Type.Should().Be(TimestampType.CreateTime);
record.Message.Headers.Should().NotContain(h => h.Key.StartsWith("CamelKafkaOverride"), "the headers never go on the wire");
}
[Fact]
public async Task A_record_lands_in_the_overriding_topic_with_the_overriding_timestamp()
{
var configured = await CreateTopic("configured");
var other = await CreateTopic("other");
var producer = await StartProducer(configured);
var exchange = Overridden("moved", other, Stamp);
try
{
await producer.Process(exchange);
}
finally
{
await producer.Stop();
}
ShouldBeTheOverride(Read(other, 1).Single(), "moved");
ReadNothing(configured).Should().BeEmpty();
exchange.In.Headers.Should().NotContainKey(KafkaHeaders.OverrideTopic).And.NotContainKey(KafkaHeaders.OverrideTimestamp);
}
[Fact]
public async Task A_send_deferred_to_a_transacted_block_keeps_the_overrides()
{
var configured = await CreateTopic("configured");
var other = await CreateTopic("other");
var producer = await StartProducer(configured, "transacted=true");
try
{
await new TransactedProcessor(new DelegateProcessor((ex, ct) => producer.Process(ex, ct)), new TransactionPolicy())
.Process(Overridden("deferred", other, Stamp));
}
finally
{
await producer.Stop();
}
ShouldBeTheOverride(Read(other, 1).Single(), "deferred");
ReadNothing(configured).Should().BeEmpty();
}
[Fact]
public async Task A_Kafka_transaction_sends_to_the_overriding_topic_with_the_overriding_timestamp()
{
var configured = await CreateTopic("configured");
var other = await CreateTopic("other");
var producer = await StartProducer(configured, "transactionalIdPrefix=override-topic");
try
{
await producer.Process(Overridden("in-tx", other, Stamp));
await producer.Process(new Exchange(new RouteMessage("stays")));
}
finally
{
await producer.Stop();
}
ShouldBeTheOverride(Read(other, 1).Single(), "in-tx");
Body(Read(configured, 1).Single()).Should().Be("stays", "the override is per message; the producer's topic is unchanged");
}
[Fact]
public async Task A_list_of_IMessage_takes_each_element_s_override_and_the_exchange_s_topic_for_the_rest()
{
var configured = await CreateTopic("configured");
var listTopic = await CreateTopic("list");
var own = await CreateTopic("own");
var producer = await StartProducer(configured);
var first = new RouteMessage("own") { Headers = { [KafkaHeaders.OverrideTopic] = own, [KafkaHeaders.OverrideTimestamp] = Stamp } };
var elements = new List { first, new RouteMessage("list") };
var parent = new Exchange(new RouteMessage(elements));
parent.In.Headers[KafkaHeaders.OverrideTopic] = listTopic;
parent.In.Headers[KafkaHeaders.OverrideTimestamp] = Stamp + 1; // camel-kafka does not read it for a list
try
{
await producer.Process(parent);
}
finally
{
await producer.Stop();
}
ShouldBeTheOverride(Read(own, 1).Single(), "own");
var fallback = Read(listTopic, 1).Single();
Body(fallback).Should().Be("list");
fallback.Message.Timestamp.UnixTimestampMs.Should().NotBe(Stamp + 1);
ReadNothing(configured).Should().BeEmpty();
first.Headers.Should().NotContainKey(KafkaHeaders.OverrideTopic, "Camel removes it from the element");
parent.In.Headers.Should().NotContainKey(KafkaHeaders.OverrideTopic);
}
[Fact]
public async Task A_plain_list_sends_every_element_to_the_exchange_s_overriding_topic()
{
var configured = await CreateTopic("configured");
var other = await CreateTopic("other");
var producer = await StartProducer(configured);
var exchange = new Exchange(new RouteMessage(new List { "a", "b", "c" }));
exchange.In.Headers[KafkaHeaders.OverrideTopic] = other;
try
{
await producer.Process(exchange);
}
finally
{
await producer.Stop();
}
Read(other, 3).Select(Body).Should().Equal("a", "b", "c");
ReadNothing(configured).Should().BeEmpty();
}
[Fact]
public async Task A_bad_override_sends_nothing()
{
var configured = await CreateTopic("configured");
var producer = await StartProducer(configured);
try
{
var badTopic = () => producer.Process(Overridden("bad-topic", ""));
var badStamp = () => producer.Process(Overridden("bad-stamp", configured, "yesterday"));
await badTopic.Should().ThrowAsync().WithMessage($"The {KafkaHeaders.OverrideTopic} header*");
await badStamp.Should().ThrowAsync().WithMessage($"The {KafkaHeaders.OverrideTimestamp} header*");
}
finally
{
await producer.Stop();
}
ReadNothing(configured).Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaOverrideHeadersTests.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/KafkaOverrideHeadersTests.cs
----
using Confluent.Kafka;
using redb.Route.Core;
using redb.Route.Kafka;
using Message = redb.Route.Core.Message;
namespace redb.Route.Tests.Kafka;
///
/// The producer's per-message topic and timestamp, read as camel-kafka's createRecord reads them:
/// wins over the endpoint's topic,
/// becomes the record's timestamp in milliseconds since the Unix epoch, both are removed from the message, and a value
/// that is neither is refused before anything is sent.
///
public sealed class KafkaOverrideHeadersTests
{
private static KafkaProducer Producer(string query = "acks=all")
=> (KafkaProducer)new KafkaComponent()
.CreateEndpoint(EndpointUriParser.Parse($"kafka://orders?brokers=x:9092&{query}"))
.CreateProducer();
private static Message Record() => new() { Value = [1], Headers = new Headers() };
[Fact]
public void The_override_topic_wins_over_the_endpoint_topic_and_is_removed()
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers[KafkaHeaders.OverrideTopic] = "audit";
var target = Producer().ResolveTarget(exchange, Record());
target.Topic.Should().Be("audit");
exchange.In.Headers.Should().NotContainKey(KafkaHeaders.OverrideTopic, "Camel removes it so it does not travel further");
}
[Fact]
public void Without_the_override_the_endpoint_topic_is_used_and_the_record_keeps_no_timestamp()
{
var record = Record();
var target = Producer().ResolveTarget(new Exchange(new Message("x")), record);
target.Topic.Should().Be("orders");
record.Timestamp.Type.Should().Be(TimestampType.NotAvailable, "the client stamps it at send time");
}
[Fact]
public void The_override_topic_and_the_partition_key_go_together()
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers[KafkaHeaders.OverrideTopic] = "audit";
exchange.In.Headers[KafkaHeaders.PartitionKey] = 2;
Producer().ResolveTarget(exchange, Record()).Should().Be(new KafkaTarget("audit", 2));
}
[Fact]
public void The_override_timestamp_becomes_the_record_timestamp_and_is_removed()
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers[KafkaHeaders.OverrideTimestamp] = 1_700_000_000_123L;
var record = Record();
Producer().ResolveTarget(exchange, record);
record.Timestamp.UnixTimestampMs.Should().Be(1_700_000_000_123L);
record.Timestamp.Type.Should().Be(TimestampType.CreateTime);
exchange.In.Headers.Should().NotContainKey(KafkaHeaders.OverrideTimestamp);
}
[Fact]
public void A_null_override_is_absent_and_is_removed()
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers[KafkaHeaders.OverrideTopic] = null;
exchange.In.Headers[KafkaHeaders.OverrideTimestamp] = null;
var record = Record();
Producer().ResolveTarget(exchange, record).Topic.Should().Be("orders");
record.Timestamp.Type.Should().Be(TimestampType.NotAvailable);
exchange.In.Headers.Should().NotContainKey(KafkaHeaders.OverrideTopic).And.NotContainKey(KafkaHeaders.OverrideTimestamp);
}
[Theory]
[InlineData(42)]
[InlineData("")]
[InlineData(" ")]
public void An_override_topic_that_is_not_a_topic_name_is_refused_naming_the_header(object value)
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers[KafkaHeaders.OverrideTopic] = value;
var act = () => Producer().ResolveTarget(exchange, Record());
act.Should().Throw()
.WithMessage($"The {KafkaHeaders.OverrideTopic} header must be a topic name*Nothing was sent.*");
}
public static TheoryData Timestamps => new()
{
{ 1_700_000_000_123L, 1_700_000_000_123L },
{ 5, 5L },
{ " 1700000000123 ", 1_700_000_000_123L },
{ new DateTimeOffset(2026, 11, 19, 12, 0, 0, TimeSpan.FromHours(3)), new DateTimeOffset(2026, 11, 19, 9, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds() },
{ new DateTime(2026, 11, 19, 9, 0, 0, DateTimeKind.Utc), new DateTimeOffset(2026, 11, 19, 9, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds() },
};
[Theory]
[MemberData(nameof(Timestamps))]
public void The_override_timestamp_takes_epoch_milliseconds_or_a_date(object value, long expected)
=> KafkaPartitions.TimestampFromHeader(value).Should().Be(expected);
[Fact]
public void A_local_date_is_read_as_local_time()
{
var local = new DateTime(2026, 11, 19, 12, 0, 0, DateTimeKind.Local);
KafkaPartitions.TimestampFromHeader(local).Should().Be(new DateTimeOffset(local).ToUnixTimeMilliseconds());
}
[Theory]
[InlineData(-1L)]
[InlineData("-5")]
[InlineData("yesterday")]
[InlineData("1.5")]
[InlineData(1.5)]
[InlineData("")]
public void An_override_timestamp_that_is_not_one_is_refused_naming_the_header(object value)
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers[KafkaHeaders.OverrideTimestamp] = value;
var act = () => Producer().ResolveTarget(exchange, Record());
act.Should().Throw()
.WithMessage($"The {KafkaHeaders.OverrideTimestamp} header must be milliseconds since the Unix epoch or a date*Nothing was sent.*");
}
[Fact]
public void A_record_kept_for_a_later_send_keeps_its_timestamp()
{
// The deferred and the Kafka-transaction paths send a copy of the record at commit.
var record = Record();
record.Timestamp = new Timestamp(1_700_000_000_123L, TimestampType.CreateTime);
KafkaSendAction.CloneMessage(record).Timestamp.Should().Be(record.Timestamp);
}
[Fact]
public void The_override_headers_have_camels_names()
{
KafkaHeaders.OverrideTopic.Should().Be("CamelKafkaOverrideTopic");
KafkaHeaders.OverrideTimestamp.Should().Be("CamelKafkaOverrideTimestamp");
}
}
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();
}
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaPartitionKeyTests.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/KafkaPartitionKeyTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// The partition of a sent record, by Apache Camel's rule: the endpoint's partitionKey takes precedence over the
/// per-message header; without either Kafka's partitioner places the record by its
/// key. A value that is not a partition number is refused; one name for each thing (partitionKey for a producer,
/// partitionNumber for a consumer).
///
public sealed class KafkaPartitionKeyTests
{
private static KafkaEndpoint Endpoint(string query)
=> (KafkaEndpoint)new KafkaComponent().CreateEndpoint(EndpointUriParser.Parse($"kafka://orders?brokers=x:9092&{query}"));
private static int? Resolve(string query, object? header = null, bool withHeader = true)
{
var endpoint = Endpoint(query);
var producer = (KafkaProducer)endpoint.CreateProducer();
var exchange = new Exchange(new Message("x"));
if (withHeader)
exchange.In.Headers[KafkaHeaders.PartitionKey] = header;
return producer.ResolvePartition(exchange);
}
[Fact]
public void The_endpoint_option_takes_precedence_over_the_header_as_in_camel()
=> Resolve("partitionKey=1", header: 4).Should().Be(1);
[Fact]
public void Without_the_option_the_header_decides()
=> Resolve("acks=all", header: 4).Should().Be(4);
[Fact]
public void Without_either_there_is_no_partition_and_the_partitioner_decides_by_key()
=> Resolve("acks=all", withHeader: false).Should().BeNull();
[Theory]
[InlineData("partitionKey=2", null, 2)]
[InlineData("partitionKey=2", 3, 2)]
[InlineData("acks=all", 3, 3)]
public void A_plain_list_element_takes_the_endpoint_option_else_the_exchange_header_unlike_camel(
string query, object? header, int expected)
{
// camel-kafka sends a plain (non-Message) element with no partition; ours keeps the endpoint's or the exchange's
// (owner's decision 2026-11-19): an endpoint that names a partition means it for every record.
var producer = (KafkaProducer)Endpoint(query).CreateProducer();
var exchange = new Exchange(new Message(new List { "a", "b" }));
if (header is not null)
exchange.In.Headers[KafkaHeaders.PartitionKey] = header;
producer.ResolvePartition(ListBody.ElementExchange(exchange, "a")).Should().Be(expected);
}
[Theory]
[InlineData(3, 3)]
[InlineData(3L, 3)]
[InlineData((short)2, 2)]
[InlineData((byte)1, 1)]
[InlineData("5", 5)]
[InlineData(" 0 ", 0)]
public void The_header_takes_an_integer_or_a_whole_number_text(object value, int partition)
=> KafkaPartitions.FromHeader(value).Should().Be(partition);
[Theory]
[InlineData(-1)]
[InlineData("-2")]
[InlineData("two")]
[InlineData("1.5")]
[InlineData(1.5)]
[InlineData("")]
[InlineData(null)]
[InlineData(3_000_000_000L)]
public void A_header_that_is_not_a_partition_number_is_refused_naming_it(object? value)
{
var act = () => KafkaPartitions.FromHeader(value);
act.Should().Throw()
.WithMessage($"The {KafkaHeaders.PartitionKey} header must be a partition number, 0 or more*Nothing was sent.*");
}
[Fact]
public void A_negative_partitionKey_option_is_refused()
{
var act = () => Endpoint("partitionKey=-1");
act.Should().Throw().WithMessage("*partitionKey must be a partition number, 0 or more*");
}
[Fact]
public void A_producer_refuses_partitionNumber_naming_partitionKey()
{
var act = () => Endpoint("partitionNumber=2").CreateProducer();
act.Should().Throw().WithMessage("*'partitionNumber' names the partition a consumer reads*'partitionKey'*");
}
[Fact]
public void A_consumer_refuses_partitionKey_naming_partitionNumber()
{
var act = () => Endpoint("groupId=g&partitionKey=2").CreateConsumer(Substitute.For());
act.Should().Throw().WithMessage("*'partitionKey' names the partition a producer sends to*'partitionNumber'*");
}
[Fact]
public void The_builder_writes_partitionKey_for_a_producer_and_partitionNumber_for_a_consumer()
{
redb.Route.Kafka.Kafka.Topic("orders").PartitionKey(2).Build().Should().Contain("partitionKey=2").And.NotContain("partitionNumber");
redb.Route.Kafka.Kafka.Topic("orders").PartitionNumber(1).Build().Should().Contain("partitionNumber=1");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaProducerTests.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/KafkaProducerTests.cs
----
using System.Collections.Concurrent;
using System.Reflection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
public sealed class KafkaProducerTests
{
private readonly KafkaComponent _component = new();
private KafkaEndpoint CreateEndpoint(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
return (KafkaEndpoint)_component.CreateEndpoint(uri);
}
[Fact]
public void Ctor_NullEndpoint_Throws()
{
var opts = new KafkaEndpointOptions { Brokers = "x:9092" };
var act = () => new KafkaProducer(null!, opts);
act.Should().Throw();
}
[Fact]
public void Ctor_NullOptions_Throws()
{
var ep = CreateEndpoint("kafka://t?brokers=x:9092");
var act = () => new KafkaProducer(ep, null!);
act.Should().Throw();
}
[Fact]
public async Task Process_BeforeStart_Throws()
{
var ep = CreateEndpoint("kafka://t?brokers=x:9092");
var producer = new KafkaProducer(ep, new KafkaEndpointOptions { Brokers = "x:9092" });
var exchange = new Exchange(new Message("test"));
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*not been started*");
}
[Fact]
public void CreateProducer_ReturnsExpectedType()
{
var ep = CreateEndpoint("kafka://topic?brokers=localhost:9092");
ep.CreateProducer().Should().BeOfType();
}
// ── Commit of a Kafka transaction ──
private static readonly BindingFlags Private = BindingFlags.NonPublic | BindingFlags.Instance;
/// A transactional producer whose librdkafka client is : no broker involved.
private KafkaProducer TransactionalProducerOver(Confluent.Kafka.IProducer client)
{
var producer = (KafkaProducer)CreateEndpoint("kafka://t?brokers=x:9092&transactionalIdPrefix=tx").CreateProducer();
typeof(KafkaProducer).GetField("_producer", Private)!.SetValue(producer, client);
typeof(KafkaProducer).GetField("_transactionalId", Private)!.SetValue(producer, "tx-test");
return producer;
}
private static bool MarkedForRebuild(KafkaProducer producer) =>
(bool)typeof(KafkaProducer).GetField("_rebuild", Private)!.GetValue(producer)!;
private static KafkaTransactionalSend Send() => new(
new Confluent.Kafka.Message { Value = [1], Headers = new Confluent.Kafka.Headers() }, new KafkaTarget("t", null),
new Exchange(new Message("x")));
[Fact]
public async Task A_commit_whose_outcome_is_unknown_is_not_aborted_and_the_producer_is_rebuilt()
{
// A commit that keeps timing out may have reached the coordinator and succeeded; the abort that followed was
// no undo, only a call librdkafka refuses. The next incarnation's InitTransactions settles the outcome.
var client = Substitute.For>();
client.When(c => c.CommitTransaction()).Do(_ =>
throw new Confluent.Kafka.KafkaRetriableException(new Confluent.Kafka.Error(Confluent.Kafka.ErrorCode.Local_TimedOut)));
var producer = TransactionalProducerOver(client);
var commit = () => producer.CommitTransactionAsync([Send()], offsets: null, CancellationToken.None);
await commit.Should().ThrowAsync();
client.Received(3).CommitTransaction();
client.DidNotReceive().AbortTransaction();
client.DidNotReceive().AbortTransaction(Arg.Any());
MarkedForRebuild(producer).Should().BeTrue();
}
[Fact]
public async Task A_commit_that_requires_an_abort_is_aborted_and_neither_call_takes_our_timeout()
{
// librdkafka strongly recommends CommitTransaction/AbortTransaction without a timeout: its API timeouts do not
// match the protocol requests.
var client = Substitute.For>();
client.When(c => c.CommitTransaction()).Do(_ =>
throw new Confluent.Kafka.KafkaTxnRequiresAbortException(new Confluent.Kafka.Error(Confluent.Kafka.ErrorCode.InvalidTxnState)));
var producer = TransactionalProducerOver(client);
var commit = () => producer.CommitTransactionAsync([Send()], offsets: null, CancellationToken.None);
await commit.Should().ThrowAsync();
client.DidNotReceive().CommitTransaction(Arg.Any());
client.Received(1).AbortTransaction();
client.DidNotReceive().AbortTransaction(Arg.Any());
MarkedForRebuild(producer).Should().BeFalse("an aborted transaction leaves the producer usable");
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaReadiness.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/KafkaReadiness.cs
----
using Confluent.Kafka;
using Confluent.Kafka.Admin;
namespace redb.Route.Tests.Kafka;
///
/// Waits, once per test run, until the test cluster can serve what a test is about to use. A freshly started
/// cluster answers metadata requests long before it has loaded its internal topics: a consumer group then joins
/// late (a test's observation window passes before the first record arrives) and InitTransactions fails
/// with "Coordinator load in progress" after its own timeout. Tests await these checks before they start
/// measuring, so their windows time the code under test, not the broker's warm-up.
///
internal static class KafkaReadiness
{
private const string BootstrapServers = "localhost:29092,localhost:29094,localhost:29096";
private static readonly TimeSpan Limit = TimeSpan.FromMinutes(3);
private static readonly Lazy Groups = new(() => Task.Run(WaitForGroupCoordinator));
private static readonly Lazy Transactions = new(() => Task.Run(WaitForTransactionCoordinator));
/// A consumer group can join and get partitions assigned.
public static Task GroupCoordinatorAsync() => Groups.Value;
/// A transactional producer can initialize its transactions.
public static Task TransactionCoordinatorAsync() => Transactions.Value;
///
/// Creates a topic with one partition, so the records a test produces are consumed in the order they were
/// sent, and waits until its leader is known. Replicated like the cluster's auto-created topics.
///
public static async Task CreateSinglePartitionTopicAsync(string prefix)
{
var topic = $"{prefix}-{Guid.NewGuid():N}";
using var admin = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = BootstrapServers }).Build();
await admin.CreateTopicsAsync([new TopicSpecification { Name = topic, NumPartitions = 1, ReplicationFactor = 3 }]);
await WaitForLeaders(admin, topic, partitions: 1);
return topic;
}
/// Waits until the metadata of names a leader for each of its partitions.
public static async Task WaitForLeaders(IAdminClient admin, string topic, int partitions)
{
var deadline = DateTime.UtcNow + Limit;
while (true)
{
var metadata = admin.GetMetadata(topic, TimeSpan.FromSeconds(10)).Topics.SingleOrDefault(t => t.Topic == topic);
if (metadata is { Error.IsError: false } && metadata.Partitions.Count == partitions
&& metadata.Partitions.All(p => p.Leader >= 0))
return;
if (DateTime.UtcNow > deadline)
throw new TimeoutException($"topic {topic} has no leader for each of its {partitions} partitions after {Limit}.");
await Task.Delay(200);
}
}
private static async Task WaitForGroupCoordinator()
{
var topic = await CreateSinglePartitionTopicAsync("ready-group");
using var consumer = new ConsumerBuilder(new ConsumerConfig
{
BootstrapServers = BootstrapServers,
GroupId = $"ready-{Guid.NewGuid():N}",
AutoOffsetReset = AutoOffsetReset.Earliest,
}).Build();
consumer.Subscribe(topic);
var deadline = DateTime.UtcNow + Limit;
try
{
while (consumer.Assignment.Count == 0)
{
if (DateTime.UtcNow > deadline)
throw new TimeoutException($"no consumer group got a partition assigned within {Limit}.");
consumer.Consume(TimeSpan.FromMilliseconds(250));
}
}
finally
{
consumer.Close();
}
}
private static void WaitForTransactionCoordinator()
{
var deadline = DateTime.UtcNow + Limit;
while (true)
{
using var producer = new ProducerBuilder(new ProducerConfig
{
BootstrapServers = BootstrapServers,
TransactionalId = $"ready-{Guid.NewGuid():N}",
}).Build();
try
{
producer.InitTransactions(TimeSpan.FromSeconds(30));
return;
}
catch (KafkaRetriableException) when (DateTime.UtcNow < deadline)
{
// The transaction coordinator is still loading its log; ask again.
}
}
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaReconnectTests.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/KafkaReconnectTests.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using Confluent.Kafka;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Kafka;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.Kafka;
///
/// A Kafka consumer through a lost broker and through a fatal client error, on (one KRaft
/// node). librdkafka reconnects to the broker by itself; what the consumer owes is the truth in health: the endpoint shows
/// the lost broker while it is away (not Healthy, no message errors counted), counts one reconnect when it is back, and the
/// route reads on. A fatal error (a static member fenced by a second member with its group.instance.id ) ends the
/// client instance for good: the consumer must build a new one and read on, not leave the route Started and deaf. The
/// stop and start of the broker are : they run only where REDB_TEST_KAFKA_CONTAINER names
/// the broker's container, elsewhere they are skipped. Run them with tests/docker/run-fault-suite.sh --broker kafka .
///
[Trait("Category", "Integration")]
[Collection(KafkaBrokerRestartCollection.Name)]
public sealed class KafkaReconnectTests
{
private static readonly KafkaFaultStand Stand = KafkaFaultStand.Instance;
[BrokerFaultTheory(KafkaFaultStand.ContainerVariable)]
[InlineData(false)]
[InlineData(true)]
public async Task A_consumer_shows_the_lost_broker_in_health_and_reads_again_once_it_is_back(bool batch)
{
var fault = Stand.Fault!;
var topic = await KafkaFaultStand.CreateTopicAsync("restart");
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = $"kafka://{topic}?brokers={KafkaFaultStand.Brokers}&groupId=g-{Guid.NewGuid():N}&autoOffsetReset=Earliest"
+ (batch ? "&batching=true&maxBatchMessages=10&pollTimeoutMs=500" : "");
context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(topic, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the topic before the outage");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
var errorsBefore = statistics.Errors;
statistics.Reconnects.Should().Be(0, "nothing was lost before the outage");
await fault.StopAsync();
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the endpoint shows that its broker is gone");
statistics.HealthReason.Should().Contain("connection", "the reason names the lost connection");
statistics.Errors.Should().Be(errorsBefore, "a lost connection is not a failed message");
}
finally
{
await fault.StartAsync();
}
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the endpoint counts the reconnect");
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(topic, "after"); return true; }
catch (Exception) { return false; }
}, Stand.Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the broker takes a message once it is back");
(await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was put after the outage");
statistics.Reconnects.Should().Be(1, "one outage is one reconnect");
statistics.Errors.Should().Be(errorsBefore, "a lost connection is not a failed message");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the broker is back");
context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route");
}
[BrokerFaultTheory(KafkaFaultStand.ContainerVariable)]
[InlineData(false)]
[InlineData(true)]
public async Task A_route_stops_in_time_while_its_broker_is_away(bool batch)
{
var fault = Stand.Fault!;
var topic = await KafkaFaultStand.CreateTopicAsync("stop-in-outage");
var received = new ConcurrentQueue();
var context = NewContext();
var uri = $"kafka://{topic}?brokers={KafkaFaultStand.Brokers}&groupId=g-{Guid.NewGuid():N}&autoOffsetReset=Earliest"
+ (batch ? "&batching=true&maxBatchMessages=10&pollTimeoutMs=500" : "");
context.AddRoutes(r => r.From(uri).RouteId("stopped").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(topic, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
await fault.StopAsync();
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the consumer knows its broker is gone");
var watch = Stopwatch.StartNew();
await context.Stop();
await context.DisposeAsync();
watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(30),
"a stop does not wait for the broker or for a probe of it");
}
finally
{
await fault.StartAsync();
}
}
[BrokerFaultTheory(KafkaFaultStand.ContainerVariable)]
[InlineData(false)]
[InlineData(true)]
public async Task A_consumer_fenced_by_a_member_with_its_instance_id_builds_a_new_client_and_reads_on(bool batch)
{
var topic = await KafkaFaultStand.CreateTopicAsync("fenced");
var group = $"g-{Guid.NewGuid():N}";
var instance = $"static-{Guid.NewGuid():N}";
var received = new ConcurrentQueue();
await using var context = NewContext();
// Static membership: a second member with the same group.instance.id fences the first, and librdkafka raises a
// fatal error on it (the instance cannot be used again).
context.AddToRegistry("static", new KafkaConnectionFactory
{
Brokers = KafkaFaultStand.Brokers, AdditionalProperties = { ["group.instance.id"] = instance },
});
var uri = $"kafka://{topic}?connectionFactory=static&groupId={group}&autoOffsetReset=Earliest"
+ (batch ? "&batching=true&maxBatchMessages=10&pollTimeoutMs=500" : "");
context.AddRoutes(r => r.From(uri).RouteId("fenced").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(topic, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the topic before it is fenced");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
using (var intruder = new ConsumerBuilder(new ConsumerConfig
{
BootstrapServers = KafkaFaultStand.Brokers, GroupId = group, GroupInstanceId = instance,
AutoOffsetReset = AutoOffsetReset.Earliest, EnableAutoCommit = false,
}).Build())
{
intruder.Subscribe(topic);
// The intruder joins while it polls; the route's member is fenced at its next heartbeat.
(await Until(() =>
{
intruder.Consume(TimeSpan.FromMilliseconds(200));
return statistics.HealthStatus != EndpointHealthStatus.Healthy;
})).Should().BeTrue("the fenced consumer shows it in health");
intruder.Close();
}
await Stand.PutAsync(topic, "after");
(await Until(() => received.Contains("after"))).Should().BeTrue(
"the consumer builds a new client after the fatal error and reads what was put after it");
statistics.Reconnects.Should().BeGreaterThan(0, "the new client is a reconnect");
context.GetRoute("fenced")!.Status.Should().Be(RouteStatus.Started);
}
private static RouteContext NewContext()
{
var context = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(5) });
context.AddComponent(new KafkaComponent());
return context;
}
private static void Collect(IExchange exchange, ConcurrentQueue into)
{
if (exchange.In.Body is List batch)
{
foreach (var message in batch)
into.Enqueue(Text(message.Body));
return;
}
into.Enqueue(Text(exchange.In.Body));
}
private static string Text(object? body) => body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
null => "",
_ => body.ToString() ?? "",
};
private static async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Stand.Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(100);
}
return true;
}
}
/// A broker stop cuts every connection of the suite, so nothing runs beside the fault tests.
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class KafkaBrokerRestartCollection
{
/// The collection's name.
public const string Name = "Kafka broker restart";
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaSeekToTests.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/KafkaSeekToTests.cs
----
using System.Collections.Concurrent;
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// The options sweep. HandleSeekTo used to read
/// consumer.Assignment right after Subscribe() - the group has not joined yet, the
/// assignment is empty (verified on the live cluster: assignment.Count=0 ), so
/// seekTo=beginning was a silent no-op for every group consumer. It only worked with an
/// explicit partitionNumber . The seek now rides the partitions-assigned handler, once,
/// on the first assignment - which is what "on first start" in the option's doc always meant.
///
[Trait("Category", "Integration")]
public sealed class KafkaSeekToTests : IAsyncLifetime
{
private const string BootstrapServers = "localhost:29092,localhost:29094,localhost:29096";
private readonly List _consumers = [];
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
foreach (var c in _consumers) await c.Stop();
}
private static async Task Produce(string topic, params string[] values)
{
var config = new ProducerConfig { BootstrapServers = BootstrapServers };
using var producer = new ProducerBuilder(config).Build();
foreach (var v in values)
await producer.ProduceAsync(topic, new Message { Key = "", Value = v });
producer.Flush(TimeSpan.FromSeconds(10));
}
private KafkaConsumer StartCollectingConsumer(string uriParams, string topic, ConcurrentQueue sink)
{
var uri = EndpointUriParser.Parse($"kafka://{topic}?brokers={BootstrapServers}&{uriParams}");
var endpoint = (KafkaEndpoint)new KafkaComponent().CreateEndpoint(uri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(ci =>
{
sink.Enqueue(System.Text.Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!));
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)endpoint.CreateConsumer(processor);
_consumers.Add(consumer);
return consumer;
}
[Fact]
public async Task SeekToBeginning_GroupConsumer_ReadsTheBacklog()
{
var topic = $"a4-seek-{Guid.NewGuid():N}"[..30];
await Produce(topic, "old-1", "old-2");
// autoOffsetReset=latest would skip the backlog; seekTo=beginning must win over it.
var received = new ConcurrentQueue();
var consumer = StartCollectingConsumer(
$"groupId=g-{Guid.NewGuid():N}&autoOffsetReset=latest&seekTo=beginning", topic, received);
await consumer.Start();
var deadline = DateTime.UtcNow.AddSeconds(25);
while (received.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(200);
received.Should().Contain(["old-1", "old-2"],
"seekTo=beginning was a silent no-op: Assignment is empty right after Subscribe");
}
[Fact]
public async Task SeekTo_IsAppliedOnce_NotOnEveryRebalance()
{
var topic = $"a4-once-{Guid.NewGuid():N}"[..30];
await Produce(topic, "first");
var received = new ConcurrentQueue();
var groupId = $"g-{Guid.NewGuid():N}";
var consumer = StartCollectingConsumer(
$"groupId={groupId}&autoOffsetReset=latest&seekTo=beginning", topic, received);
await consumer.Start();
var deadline = DateTime.UtcNow.AddSeconds(25);
while (!received.Contains("first") && DateTime.UtcNow < deadline) await Task.Delay(200);
received.Should().Contain("first");
// A second consumer joining the same group forces a rebalance of the first one. The seek
// must NOT re-apply, otherwise every rebalance would replay the topic from the start.
var second = StartCollectingConsumer(
$"groupId={groupId}&autoOffsetReset=latest", topic, new ConcurrentQueue());
await second.Start();
await Task.Delay(6000);
received.Count(v => v == "first").Should().Be(1,
"the seek applies once on the first assignment, not on every rebalance");
}
[Fact]
public async Task SeekTo_SurvivesAnEmptyFirstAssignment()
{
// More consumers than partitions means a member's FIRST assignment
// callback can carry zero partitions. TakeSeekToOnce() used to burn the one-shot flag on
// that empty list - when partitions later arrived on a rebalance, the seek silently never
// happened: the exact "silent no-op" A4 was written to kill, through the side door.
var topic = $"a4-empty-{Guid.NewGuid():N}"[..30];
await Produce(topic, "old-1", "old-2");
var groupId = $"g-{Guid.NewGuid():N}";
// Holder drains the single partition and commits, so the group offset sits at the end.
var holderSink = new ConcurrentQueue();
var holder = StartCollectingConsumer(
$"groupId={groupId}&autoOffsetReset=earliest&partitionAssignmentStrategy=CooperativeSticky", topic, holderSink);
await holder.Start();
var deadline = DateTime.UtcNow.AddSeconds(25);
while (holderSink.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(200);
holderSink.Count.Should().Be(2, "the holder must drain the partition and commit the tail");
// The seeking member joins while the only partition is held: its first assignment is empty.
var received = new ConcurrentQueue();
var seeker = StartLoggedConsumer(
$"groupId={groupId}&autoOffsetReset=latest&seekTo=beginning&partitionAssignmentStrategy=CooperativeSticky", topic, received);
await seeker.Start();
await Task.Delay(6000); // let it join and receive the empty assignment
// Holder leaves; the rebalance finally hands the partition to the seeker.
await holder.Stop();
deadline = DateTime.UtcNow.AddSeconds(25);
while (received.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(200);
received.Should().Contain(["old-1", "old-2"],
$"seekTo must survive an empty first assignment and apply on the first non-empty one; log: {string.Join(" | ", Logs)}");
}
internal static readonly ConcurrentQueue Logs = new();
private sealed class QueueLoggerProvider : Microsoft.Extensions.Logging.ILoggerProvider
{
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new L();
public void Dispose() { }
private sealed class L : Microsoft.Extensions.Logging.ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
TState state, Exception? exception, Func formatter)
=> Logs.Enqueue(formatter(state, exception));
}
}
private KafkaConsumer StartLoggedConsumer(string uriParams, string topic, ConcurrentQueue sink)
{
var lf = Microsoft.Extensions.Logging.LoggerFactory.Create(b => b.AddProvider(new QueueLoggerProvider()));
var ctx = new RouteContext(loggerFactory: lf);
ctx.AddComponent(new KafkaComponent());
var endpoint = (KafkaEndpoint)ctx.GetEndpoint($"kafka://{topic}?brokers={BootstrapServers}&{uriParams}");
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(ci =>
{
sink.Enqueue(System.Text.Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!));
return Task.CompletedTask;
});
var consumer = (KafkaConsumer)endpoint.CreateConsumer(processor);
_consumers.Add(consumer);
return consumer;
}
}
Path: redb-route/tests/redb.Route.Tests.Kafka/KafkaTlsTests.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/KafkaTlsTests.cs
----
using Confluent.Kafka;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Kafka;
namespace redb.Route.Tests.Kafka;
///
/// Encrypted and authenticated connections against the live 3-node cluster: its SECURE listeners (SASL_SSL,
/// SCRAM-SHA-512, user redb) and MTLS listeners (SSL, client certificate required), profile