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";
}