Path: redb-route/redb.Route.Kafka/KafkaConsumer.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/redb.Route.Kafka/KafkaConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using Confluent.Kafka;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Kafka;
///
/// Kafka consumer. Polls messages from a Kafka topic and delegates to the processor pipeline.
/// Supports single-message and batch modes, with deferred-commit .
///
public sealed class KafkaConsumer : DrainableConsumer
{
private readonly KafkaEndpoint _endpoint;
private readonly KafkaEndpointOptions _options;
private IConsumer? _consumer;
// The cluster id, read on the first offer of consumed offsets (the consumer is connected by then) and kept.
private string? _cluster;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"kafka:{_endpoint.TopicName}";
private long _processedCount;
/// Number of messages successfully processed. Thread-safe.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// Creates a Kafka consumer.
public KafkaConsumer(KafkaEndpoint endpoint, IProcessor processor, KafkaEndpointOptions options)
: base(processor)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly redb.Route.Abstractions.IHeaderFilterStrategy _headerFilter;
///
protected override Task OnStarting(CancellationToken ct)
{
_supervisor = _endpoint.Supervise($"kafka:{_endpoint.TopicName} consumer", Logger);
try
{
_consumer = BuildConsumer();
}
catch
{
_endpoint.Unsupervise(_supervisor);
_supervisor = null;
throw;
}
// Log topic/partition metadata (leaders, replicas, ISR)
LogTopicMetadata();
return Task.CompletedTask;
}
///
/// Builds a client and subscribes it (or assigns its partition): at the start, and again after a fatal error, which
/// leaves a librdkafka instance unusable for good.
///
private IConsumer BuildConsumer()
{
var config = _options.BuildConsumerConfig(_endpoint.ResolvedFactory, _endpoint.Uri.RawParameters);
KafkaOptionParsers.WarnIfPasswordInClear(config, Logger, $"kafka consumer {_endpoint.TopicName}");
var consumer = new ConsumerBuilder(config)
.SetValueDeserializer(Deserializers.ByteArray)
.SetErrorHandler((_, e) =>
{
// Log-only for every error but one: a fatal error also surfaces as a ConsumeException on the poll
// loop's next Consume, which handles it there - recording here too made one fatal event count 2-3
// times. librdkafka reconnects to the brokers by itself; when none is left it reports
// _ALL_BROKERS_DOWN, the loss the supervisor shows in health. The _TRANSPORT of one broker of several
// is not a loss: the others still serve.
if (e.IsFatal)
Logger?.LogError("Kafka consumer fatal error: {Reason} (Code: {Code})", e.Reason, e.Code);
else if (e.Code == ErrorCode.Local_AllBrokersDown)
ReportLost(new KafkaException(e));
else
Logger?.LogWarning("Kafka consumer event: {Reason} (Code: {Code})", e.Reason, e.Code);
})
.SetPartitionsAssignedHandler((c, partitions) =>
{
Logger?.LogInformation("Kafka rebalance: assigned {Count} partitions: [{Partitions}]",
partitions.Count,
string.Join(", ", partitions.Select(p => $"{p.Topic}[{p.Partition}]")));
// seekTo rides the assignment, because right after Subscribe() the
// assignment is empty - the old post-Subscribe seek was a silent no-op for every
// group consumer.
// "Once" is per PARTITION, not per callback. The first callback
// can be empty (more consumers than partitions), and CooperativeSticky delivers
// partitions incrementally across several callbacks - a whole-consumer one-shot
// flag either burned on an empty list or seeked only the first increment. Each
// partition seeks exactly once, on ITS first assignment to this consumer; a
// partition re-assigned by a later rebalance must not replay.
var mapped = partitions
.Select(p => new TopicPartitionOffset(p, SeekOffsetFor(p) ?? Offset.Unset))
.ToList();
var seeked = mapped.Where(m => m.Offset != Offset.Unset).ToList();
if (seeked.Count > 0)
Logger?.LogInformation(
"Kafka consumer: seek to {SeekTo} on first assignment of [{Partitions}]",
_options.SeekTo,
string.Join(", ", seeked.Select(m => $"{m.Topic}[{m.Partition}]")));
return mapped;
})
.SetPartitionsRevokedHandler((c, partitions) =>
{
Logger?.LogInformation("Kafka rebalance: revoked {Count} partitions: [{Partitions}]",
partitions.Count,
string.Join(", ", partitions.Select(p => $"{p.Topic}[{p.Partition}]")));
// NO commit here. Commit(partitions) settles the consumer's
// POSITION, which advances on Consume - not on processing. Rebalance callbacks
// run inside Consume, so during batch collection this handler used to commit
// records that were consumed but never processed: the new owner started past
// them and the record was lost, contradicting the "will be redelivered" log.
// Every processed record is already settled inline (single: per message; batch:
// per partition at batch end), and no Consume happens between processing and
// that settle - so there is nothing legitimate left to commit on revoke.
// Anything consumed-but-unprocessed correctly replays: at-least-once.
})
.SetPartitionsLostHandler((_, partitions) =>
{
Logger?.LogWarning("Kafka rebalance: lost {Count} partitions: [{Partitions}] (involuntary)",
partitions.Count,
string.Join(", ", partitions.Select(p => $"{p.Topic}[{p.Partition}]")));
})
.Build();
try
{
// Subscribe or Assign
if (_options.PartitionNumber.HasValue)
{
var tp = new TopicPartition(_endpoint.TopicName, new Partition(_options.PartitionNumber.Value));
// The assigned handler does not fire for a manual Assign, so the seek offset goes
// directly into the assignment here.
var seek = SeekOffsetFor(tp);
if (seek is null)
consumer.Assign(new[] { tp });
else
consumer.Assign(new[] { new TopicPartitionOffset(tp, seek.Value) });
}
else
{
// librdkafka treats only a "^"-prefixed name as a regex. The flag used
// to be read by nothing, so the only working form was writing the "^" by hand.
var topic = _options.TopicIsPattern && !_endpoint.TopicName.StartsWith('^')
? "^" + _endpoint.TopicName
: _endpoint.TopicName;
consumer.Subscribe(topic);
}
}
catch (Exception ex)
{
Logger?.LogError(ex, "Kafka consumer failed to subscribe to topic {Topic}", _endpoint.TopicName);
consumer.Dispose();
throw;
}
return consumer;
}
///
protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
_pollCt = pollCt;
return Task.Factory.StartNew(
() => PollLoop(pollCt, processingCt),
pollCt,
TaskCreationOptions.LongRunning,
TaskScheduler.Default).Unwrap();
}
///
protected override Task OnStopped()
{
// Under the gate: a probe that is asking the brokers on this client's handle ends (within ProbeTimeout) before
// the client is closed under it.
lock (_clientGate)
{
_consumer?.Close();
_consumer?.Dispose();
_consumer = null;
}
if (_supervisor is { } supervisor)
{
_endpoint.Unsupervise(supervisor);
_supervisor = null;
}
return Task.CompletedTask;
}
// ── Connection supervision ──
// librdkafka reconnects to the brokers by itself and has no "broker back" event, so the supervisor learns of the
// recovery from a probe on its schedule (a metadata request on this client's own connections, never a second
// client) or from the next record, whichever comes first. A fatal error is the one case the consumer rebuilds the
// client: librdkafka cannot use the instance again.
private ConnectionSupervisor? _supervisor;
private readonly object _clientGate = new();
private CancellationToken _pollCt;
private int _probing;
/// How long one probe waits for the brokers' answer.
internal static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(5);
///
/// Reports that no broker is left: the first report shows the loss in health and starts the probe that tells when
/// the brokers answer again. Called on librdkafka's thread, inside Consume: it only starts the probe.
///
private void ReportLost(KafkaException cause)
{
if (_supervisor is not { } supervisor || !supervisor.Lost(cause))
return;
if (Interlocked.CompareExchange(ref _probing, 1, 0) != 0)
return;
var stop = _pollCt;
_ = Task.Run(async () =>
{
try
{
await supervisor.ReconnectAsync(ProbeAsync, stop).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "Kafka consumer on topic {Topic}: the probe of the brokers ended", _endpoint.TopicName);
}
finally
{
Volatile.Write(ref _probing, 0);
}
}, CancellationToken.None);
}
/// Restores the connection on traffic: a record came, so the brokers are there. Cheap while connected.
private void ReportTraffic()
{
if (_supervisor is { State: not ConnectionState.Connected } supervisor)
supervisor.Restored();
}
///
/// One probe: asks the brokers for the metadata of the subscribed topic through this client's own handle, bounded by
/// . Asks nothing once the connection is back (a record restored it meanwhile).
///
private Task ProbeAsync(CancellationToken ct)
{
if (_supervisor is not { State: not ConnectionState.Connected } supervisor)
return Task.CompletedTask;
return supervisor.AttemptAsync(_ => Task.Run(() =>
{
lock (_clientGate)
{
var consumer = _consumer ?? throw new OperationCanceledException("the consumer is stopping");
using var admin = new DependentAdminClientBuilder(consumer.Handle).Build();
// A pattern subscription has no single topic to name: ask for one it was assigned, or for the brokers.
var topic = _options.TopicIsPattern ? consumer.Assignment.FirstOrDefault()?.Topic : _endpoint.TopicName;
var metadata = topic is null ? admin.GetMetadata(ProbeTimeout) : admin.GetMetadata(topic, ProbeTimeout);
if (metadata.Brokers.Count == 0)
throw new KafkaException(ErrorCode.Local_AllBrokersDown);
return true;
}
}, CancellationToken.None), static _ => { }, ct);
}
///
/// Replaces a client a fatal error ended: closes nothing of it (it cannot be used), builds and subscribes a new one,
/// and returns once the brokers answer it. The group then hands it the partitions and their committed offsets; what
/// was read but not committed before the error is delivered again (at least once).
///
private async Task RebuildAsync(CancellationToken ct)
{
lock (_clientGate)
{
var old = _consumer;
_consumer = null;
try { old?.Dispose(); }
catch (Exception ex) { Logger?.LogDebug(ex, "Kafka consumer: error disposing the client a fatal error ended"); }
_consumer = BuildConsumer();
}
await ProbeAsync(ct).ConfigureAwait(false);
}
// ── Poll loop ──
private async Task PollLoop(CancellationToken pollCt, CancellationToken processingCt)
{
while (!pollCt.IsCancellationRequested)
{
try
{
if (_options.Batch is { } batch)
await ProcessBatch(batch, pollCt, processingCt).ConfigureAwait(false);
else
await ProcessSingleMessage(pollCt, processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) { break; }
catch (KafkaException ex) when (ex.Error.IsFatal && _supervisor is { } supervisor)
{
// A fatal librdkafka error ends this client instance for good: retrying Consume on it is noise
//, and leaving the loop left the route Started and deaf. The supervisor shows the loss and
// builds a new client on its schedule; the route reads on once the brokers answer it.
Logger?.LogError(ex, "Kafka consumer on topic {Topic}: fatal client error; building a new client",
_endpoint.TopicName);
supervisor.Lost(ex);
if (!await supervisor.ReconnectAsync(RebuildAsync, pollCt).ConfigureAwait(false))
break;
}
catch (Exception ex)
{
// Transport-level failure (consume error) - invisible to the core's statistics wrappers, so the
// endpoint records it itself.
_endpoint.RecordError(ex);
Logger?.LogError(ex, "Error in Kafka poll loop for topic {Topic}", _endpoint.TopicName);
try { await Task.Delay(1000, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
private async Task ProcessSingleMessage(CancellationToken pollCt, CancellationToken processingCt)
{
var result = _consumer!.Consume(pollCt);
if (result?.Message is null) return;
ReportTraffic();
using var span = StartReceiveSpan(result);
var exchange = CreateExchange(result);
IncrementInflight();
try
{
// The offset is advanced by this consumer after the unit of work ended well, not by the route
// transaction: the transaction owns the database and the outgoing sends.
var commitAction = new KafkaCommitAction(_consumer, result, Logger);
var offered = await OfferOffsetsAsync(exchange, commitAction).ConfigureAwait(false);
// ackMode=auto: the offset is committed on receipt, before the route runs (at-most-once).
if (_options.AckMode == AckMode.Auto)
commitAction.Commit();
try
{
try
{
await Processor.Process(exchange, processingCt).ConfigureAwait(false);
}
finally
{
offered?.Close();
}
exchange.ThrowIfUnhandledFailure();
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
throw; // shutdown, not a processing failure
}
catch (Exception ex)
{
// An unhandled processing failure used to escape to the poll loop, and
// the NEXT successful commit then covered this record's offset - a Kafka commit is
// a position, not a per-record mark - so the message was effectively lost with
// nothing but a log line.
MarkFailed(span, ex);
await HandleProcessingFailure(ex, [result], pollCt).ConfigureAwait(false);
return;
}
Interlocked.Increment(ref _processedCount);
// Auto-commit: settle the offset inline after successful processing — UNLESS a
// transactional route already committed it (commitAction.Committed), in which case
// the transaction owns the commit.
if (_options.AckMode == AckMode.Manual && !commitAction.Committed)
commitAction.Commit();
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
DecrementInflight();
}
}
///
/// The id of the cluster this consumer reads, for a transactional producer to tell whether it may take the offsets.
/// Read once, on the first offer: the consumer has just received a record, so the brokers are there. When it cannot
/// be read, this exchange's offsets are offered without it (a producer then leaves them to the consumer and says so),
/// and the next offer reads again.
///
private async Task ClusterIdAsync()
{
if (_cluster is not null)
return _cluster;
try
{
_cluster = await KafkaConsumedOffsets.ClusterIdOf(_consumer!.Handle, ClusterIdTimeout).ConfigureAwait(false);
}
catch (KafkaException ex)
{
Logger?.LogWarning(ex,
"Kafka consumer on topic {Topic} could not read its cluster id: the offsets of this record cannot ride in a " +
"Kafka transaction (at-least-once for it); it is read again on the next record", _endpoint.TopicName);
}
return _cluster;
}
private static readonly TimeSpan ClusterIdTimeout = TimeSpan.FromSeconds(10);
///
/// Offers the offsets this consumer is about to commit to a Kafka-transactional producer of the same cluster in the
/// route (): committed in its transaction, they leave with its sends. Only with
/// ackMode=manual — with ackMode=auto the offset is already committed on receipt.
///
private async Task OfferOffsetsAsync(IExchange exchange, KafkaCommitAction commitAction)
{
if (_options.AckMode != AckMode.Manual)
return null;
var offered = new KafkaConsumedOffsets(_consumer!, commitAction, await ClusterIdAsync().ConfigureAwait(false), exchange);
exchange.Properties[KafkaConsumedOffsets.PropertyKey] = offered;
return offered;
}
///
/// One place for the two failure policies. breakOnFirstError=true (Camel semantics):
/// seek every partition of the failed delivery back to its first offset, so the same
/// record(s) come again — the route retries instead of losing the message; the poll loop
/// then waits a beat so a permanently poisoned record does not become a hot spin. Default
/// false (also Camel's default): move on, but explicitly — the error lands in
/// endpoint statistics, and the log says the offset will be covered by the next commit.
///
private async Task HandleProcessingFailure(Exception ex, IReadOnlyList> failed, CancellationToken pollCt)
{
// Deliberately NOT RecordError here: in a routed consumer the processor chain is wrapped
// in the core's StatisticsProcessor, which has already recorded this escaping exception
// against the same endpoint - recording again would double-count.
// The connector records only what the core cannot see: transport-level poll errors.
if (_options.BreakOnFirstError)
{
foreach (var group in failed.GroupBy(r => r.TopicPartition))
{
var first = new TopicPartitionOffset(group.Key, group.Min(r => r.Offset.Value));
try
{
_consumer!.Seek(first);
}
catch (KafkaException seekEx)
{
// The partition may have been revoked between consume and seek. The offset is
// not committed, so the record is redelivered to whoever owns the partition now.
Logger?.LogWarning(seekEx,
"Kafka breakOnFirstError: seek back to {Tpo} failed (partition revoked?); " +
"the uncommitted record will be redelivered by the group", first);
}
}
Logger?.LogError(ex,
"Kafka message processing failed: topic={Topic}; breakOnFirstError=true - seeking back and retrying",
_endpoint.TopicName);
// Without a pause a permanently failing record retries in a tight loop.
try { await Task.Delay(1000, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { }
return;
}
Logger?.LogError(ex,
"Kafka message processing failed: topic={Topic}; breakOnFirstError=false - moving on. " +
"The failed record's offset will be covered by the next successful commit " +
"(use a route error handler or breakOnFirstError=true to keep it)",
_endpoint.TopicName);
}
// ── Batch mode (the core contract, redb.Route.Batching) ──
private BatchCollector>? _collector;
private BatchDispatcher>? _dispatcher;
private KafkaBatchSettlement? _settlement;
///
/// One batch: collected by the core's collector over this consumer's poll, run through the route once by the core's
/// dispatcher, settled by . A batch half collected when the consumer stops is not
/// run: its offsets are not committed, so the group delivers its records again.
///
private async Task ProcessBatch(BatchOptions batch, CancellationToken pollCt, CancellationToken processingCt)
{
_settlement ??= new KafkaBatchSettlement(this);
_collector ??= new BatchCollector>(batch, Receive);
_dispatcher ??= new BatchDispatcher>(Processor, _settlement, ToMessage,
_endpoint.ScopeFactory, [KafkaHeaders.Topic, KafkaHeaders.Partition]);
var collected = await _collector.CollectAsync(pollCt).ConfigureAwait(false);
if (collected.Items.Count == 0)
return;
if (collected.Interrupted)
{
await _settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return;
}
var records = collected.Items;
using var span = BatchDispatcher>.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"{records[0].Topic} receive", "kafka",
_endpoint.Uri.NormalizedKey, records[0].Topic,
records.Select(r => RouteTelemetryExtensions.ExtractTraceContext(r.Message.Headers, ReadTraceHeader)),
records.Count);
span.Activity?.SetTag("messaging.kafka.consumer.group", _options.GroupId);
_settlement.PollCt = pollCt;
IncrementInflight();
try
{
var outcome = await _dispatcher.DispatchAsync(records, span, processingCt).ConfigureAwait(false);
if (outcome == BatchOutcome.Accepted)
Interlocked.Add(ref _processedCount, records.Count);
}
finally
{
DecrementInflight();
}
}
///
/// The transport's part of collection: waits up to for one record, in slices short enough to
/// notice the consumer's stop. A consume error that is not fatal is recorded and counts as no record.
///
private ValueTask Receive(List> into, int max, TimeSpan wait, CancellationToken ct)
{
var deadline = DateTime.UtcNow + wait;
while (true)
{
ct.ThrowIfCancellationRequested();
var remaining = deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
return ValueTask.FromResult(0);
try
{
var result = _consumer!.Consume(remaining < PollSlice ? remaining : PollSlice);
if (result?.Message is not null)
{
ReportTraffic();
into.Add(result);
return ValueTask.FromResult(1);
}
}
catch (ConsumeException ex)
{
Logger?.LogError(ex, "Kafka batch consume error: {Reason}", ex.Error.Reason);
// Fatal rethrows into the poll loop, which records it once.
if (ex.Error.IsFatal) throw;
_endpoint.RecordError(ex);
return ValueTask.FromResult(0);
}
}
}
private static readonly TimeSpan PollSlice = TimeSpan.FromMilliseconds(100);
/// One record into a message, built as a single record's: one topic gives one message shape in both modes.
private IMessage ToMessage(ConsumeResult result, IExchange batch)
{
var message = new Message();
Fill(message, result, batch);
return message;
}
///
/// Kafka's settlement of a batch: by position. The offsets of the batch are offered to the route (a transaction may
/// take them) and committed once after the route, the last offset of each partition covering the earlier ones; a
/// failed batch follows breakOnFirstError, the rule of a failed single record.
///
private sealed class KafkaBatchSettlement(KafkaConsumer owner) : IBatchSettlement>
{
private KafkaCommitAction? _commit;
/// The poll loop's stop token, for the pause after a failed batch under breakOnFirstError.
public CancellationToken PollCt { get; set; }
public async ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList> items,
CancellationToken ct)
{
// As in the single-record path: the consumer advances the offset, the transaction does not.
_commit = new KafkaCommitAction(owner._consumer!, items, owner.Logger);
var offered = await owner.OfferOffsetsAsync(batch, _commit).ConfigureAwait(false);
// ackMode=auto: the offsets are committed on receipt, before the route runs (at-most-once).
if (owner._options.AckMode == AckMode.Auto)
_commit.Commit();
return offered is null ? null : new CloseOffered(offered);
}
public ValueTask AcceptAsync(IExchange batch, IReadOnlyList> items, CancellationToken ct)
{
// Unless a transactional route already committed them.
if (owner._options.AckMode == AckMode.Manual && _commit is { Committed: false } commit)
commit.Commit();
return ValueTask.CompletedTask;
}
public async ValueTask RejectAsync(IExchange batch, IReadOnlyList> items,
Exception failure, CancellationToken ct)
=> await owner.HandleProcessingFailure(failure, items, PollCt).ConfigureAwait(false);
public ValueTask ReturnAsync(IReadOnlyList> items, CancellationToken ct)
{
// Nothing to send back: the offsets of these records are not committed, so the group delivers them again.
owner.Logger?.LogDebug("Kafka consumer {Consumer} stopped with {Count} record(s) of a batch not run; " +
"their offsets are not committed", owner.ConsumerName, items.Count);
return ValueTask.CompletedTask;
}
private sealed class CloseOffered(KafkaConsumedOffsets offered) : IDisposable
{
public void Dispose() => offered.Close();
}
}
// ── Tracing ──
///
/// Reads a trace field from Kafka headers the way the connector always has: the name compared without case, the
/// value decoded as UTF-8 (an invalid sequence decodes to replacement characters, which the W3C parser refuses).
///
private static readonly TraceHeaderReader ReadTraceHeader = static (headers, name) =>
headers?.FirstOrDefault(h => string.Equals(h.Key, name, StringComparison.OrdinalIgnoreCase)) is { } header
? Encoding.UTF8.GetString(header.GetValueBytes())
: null;
///
/// The receive span of one record: its parent is the sender's context from the record's headers, a root without
/// one (never the poll thread's ambient activity), and the sender's baggage comes back on it. The core contract
/// (), so it honours EnableTelemetry and carries
/// redb.route.endpoint.
///
private TransportSpan StartReceiveSpan(ConsumeResult result)
{
var span = StartSpan(result.Topic, result.Message.Headers, links: null);
if (span.Activity is { IsAllDataRequested: true } activity)
{
activity.SetTag("messaging.kafka.destination.partition", result.Partition.Value);
activity.SetTag("messaging.kafka.message.offset", result.Offset.Value);
if (!string.IsNullOrEmpty(result.Message.Key))
activity.SetTag("messaging.kafka.message.key", result.Message.Key);
}
return span;
}
///
/// Marks the receive span failed by the route. Only the consumer's own cancellation (its stop) is not a failure,
/// and it never gets here: the processing path rethrows it first. Any other cancellation is one, an HttpClient
/// timeout inside the route (a TaskCanceledException) for one.
///
private static void MarkFailed(TransportSpan span, Exception failure) => span.Activity.RecordFailure(failure);
private TransportSpan StartSpan(string topic, Headers? carrier, IEnumerable? links)
{
var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{topic} receive", ActivityKind.Consumer,
"messaging.system", "kafka", _endpoint.Uri.NormalizedKey,
carrier, ReadTraceHeader,
destination: topic, operation: "receive", links: links);
span.Activity?.SetTag("messaging.kafka.consumer.group", _options.GroupId);
return span;
}
// ── Exchange creation ──
private Exchange CreateExchange(ConsumeResult result)
{
var message = new Message();
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
Fill(message, result, exchange);
return exchange;
}
///
/// One record into a message: its headers as the header filter strategy lets them,
/// from its content-type header, and the CamelKafka* metadata. The single and the batch path both fill it here, so
/// one topic gives one message shape in single and batch mode alike.
///
private void Fill(Message message, ConsumeResult result, IExchange exchange)
{
message.Body = result.Message.Value;
// Kafka headers into the message, as the header filter strategy lets them
if (result.Message.Headers is not null)
{
foreach (var header in result.Message.Headers)
{
try
{
var headerValue = Encoding.UTF8.GetString(header.GetValueBytes());
// The content type is the record's, whatever the strategy says about the header itself.
if (string.Equals(header.Key, "content-type", StringComparison.OrdinalIgnoreCase))
message.ContentType = headerValue;
if (_headerFilter.FilterIncoming(header.Key, headerValue, exchange)) continue;
message.Headers[header.Key] = headerValue;
}
catch (Exception ex) { Logger?.LogDebug(ex, "Kafka: malformed header '{Key}'", header.Key); }
}
}
// Kafka metadata headers, Camel's names and types (KafkaRecordProcessor.setupExchangeMessage)
message.Headers[KafkaHeaders.Topic] = result.Topic;
message.Headers[KafkaHeaders.Partition] = result.Partition.Value;
message.Headers[KafkaHeaders.Offset] = result.Offset.Value;
if (result.Message.Headers is not null)
message.Headers[KafkaHeaders.Headers] = result.Message.Headers;
if (result.Message.Timestamp.Type != TimestampType.NotAvailable)
message.Headers[KafkaHeaders.Timestamp] = result.Message.Timestamp.UnixTimestampMs;
if (!string.IsNullOrEmpty(result.Message.Key))
message.Headers[KafkaHeaders.Key] = result.Message.Key;
}
// ── Seek ──
private readonly HashSet _seekedPartitions = [];
///
/// The seekTo position, handed out exactly once: the first assignment (or the manual Assign)
/// gets it, every later rebalance resumes from committed offsets like any group member.
///
///
/// The seekTo offset for , or null once it has already been
/// seeked. "On first start" is a per-partition promise: each partition seeks exactly once,
/// on its first assignment to this consumer - never again on a later rebalance.
///
private Offset? SeekOffsetFor(TopicPartition partition)
{
if (string.IsNullOrWhiteSpace(_options.SeekTo)) return null;
lock (_seekedPartitions)
{
if (!_seekedPartitions.Add(partition)) return null;
}
return KafkaOptionParsers.ParseSeekTo(_options.SeekTo);
}
private void LogTopicMetadata()
{
// Purely diagnostic - skip the round-trip entirely unless someone will see it.
if (Logger?.IsEnabled(LogLevel.Information) != true) return;
try
{
// The admin client carries the SAME security as the consumer. It used to
// be built from bare brokers, so on a SASL/SSL cluster every consumer start paid a 5s
// timeout for a log line that never appeared - while the factory's ready
// BuildAdminConfig() sat unused.
var adminConfig = _endpoint.ResolvedFactory?.BuildAdminConfig()
?? _options.BuildAdminConfig();
if (!string.IsNullOrWhiteSpace(_options.Brokers))
adminConfig.BootstrapServers = _options.Brokers;
using var adminClient = new AdminClientBuilder(adminConfig).Build();
var metadata = adminClient.GetMetadata(_endpoint.TopicName, TimeSpan.FromSeconds(5));
var topicMeta = metadata.Topics.FirstOrDefault(t => t.Topic == _endpoint.TopicName);
if (topicMeta is null) return;
// One line per consumer start; per-partition leader/ISR detail is Debug - a
// 100-partition topic used to print a hundred Information lines per start.
Logger?.LogInformation("Kafka topic {Topic}: {PartitionCount} partitions, {BrokerCount} brokers",
_endpoint.TopicName, topicMeta.Partitions.Count, metadata.Brokers.Count);
if (Logger?.IsEnabled(LogLevel.Debug) == true)
{
foreach (var p in topicMeta.Partitions)
{
var leader = metadata.Brokers.FirstOrDefault(b => b.BrokerId == p.Leader);
Logger?.LogDebug(
" Partition [{PartitionId}]: leader=broker#{LeaderId} ({Host}:{Port}), replicas=[{Replicas}], ISR=[{ISR}]",
p.PartitionId, p.Leader,
leader?.Host ?? "?", leader?.Port ?? 0,
string.Join(", ", p.Replicas),
string.Join(", ", p.InSyncReplicas));
}
}
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "Kafka: could not fetch topic metadata for {Topic}", _endpoint.TopicName);
}
}
}
///
/// The position a consumer commits for one exchange (a record, or every partition of a batch). The consumer commits it
/// inline, on receipt with ackMode=auto or after the route with ackMode=manual, unless a Kafka transaction already did
/// (, through ). It is not a transacted action: a route's
/// transaction never commits or rolls it back.
///
internal sealed class KafkaCommitAction
{
private readonly IConsumer _consumer;
private readonly ConsumeResult _result;
private readonly IReadOnlyList? _batchOffsets;
private readonly ILogger? _logger;
private int _committed;
public KafkaCommitAction(IConsumer consumer, ConsumeResult result, ILogger? logger)
{
_consumer = consumer;
_result = result;
_logger = logger;
}
///
/// Batch settle: the position of EVERY partition the batch touched. The single
/// "commit the last result" used to settle one partition only, leaving the rest to the
/// revoked-handler at clean shutdown — a kill -9 replayed far more than needed.
/// A committed position is the NEXT offset to read, hence the +1.
///
public KafkaCommitAction(IConsumer consumer,
IReadOnlyList> batch, ILogger? logger)
{
_consumer = consumer;
_result = batch[^1];
_batchOffsets = batch
.GroupBy(r => r.TopicPartition)
.Select(g => new TopicPartitionOffset(g.Key, g.Max(r => r.Offset.Value) + 1))
.ToList();
_logger = logger;
}
/// True once the offset has been committed (by a transactional route or inline auto-commit).
public bool Committed => Volatile.Read(ref _committed) == 1;
/// The positions this action commits: the next offset to read, per partition.
public IReadOnlyList NextOffsets =>
_batchOffsets ?? [new TopicPartitionOffset(_result.TopicPartition, _result.Offset.Value + 1)];
/// A Kafka transaction committed the offsets (SendOffsetsToTransaction): nothing is left to commit.
public void MarkCommitted() => Interlocked.Exchange(ref _committed, 1);
///
/// Commits the position, once. Synchronous: librdkafka's commit waits for the group coordinator and takes no
/// cancellation, so a stop waits for a commit already under way (bounded by the client's own timeouts).
///
public void Commit()
{
// Once: after a Kafka transaction committed the offsets (MarkCommitted), the inline commit is skipped.
if (Interlocked.Exchange(ref _committed, 1) != 0)
return;
if (_batchOffsets is not null)
{
_consumer.Commit(_batchOffsets);
_logger?.LogDebug("Kafka batch offsets committed: [{Offsets}]",
string.Join(", ", _batchOffsets.Select(o => $"{o.Topic}[{o.Partition.Value}]@{o.Offset.Value}")));
}
else
{
_consumer.Commit(_result);
_logger?.LogDebug("Kafka offset committed: topic={Topic}, partition={Partition}, offset={Offset}",
_result.Topic, _result.Partition.Value, _result.Offset.Value);
}
}
}