Path: redb-route/redb.Route.Kafka/KafkaPartitions.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/KafkaPartitions.cs
----
using System.Globalization;
using Confluent.Kafka;
namespace redb.Route.Kafka;
///
/// The partition of a sent record: reading it from the header, and producing to
/// it. A value that is not a partition number, and a partition the topic does not have, are refused with words that name
/// them; nothing goes to partition 0, or to the partitioner, in their place.
///
internal static class KafkaPartitions
{
///
/// The partition a header value names: an integer type, or a whole-number text read without culture. A negative
/// number, a fraction, an empty or other text is refused.
///
public static int FromHeader(object? value)
{
long? number = value switch
{
int i => i,
long l => l,
short s => s,
byte b => b,
sbyte sb => sb,
ushort us => us,
uint ui => ui,
string text when long.TryParse(text.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed)
=> parsed,
_ => null,
};
if (number is null or < 0 or > int.MaxValue)
throw new ArgumentException(
$"The {KafkaHeaders.PartitionKey} header must be a partition number, 0 or more; it is " +
$"{(value is null ? "null" : $"'{value}' ({value.GetType().Name})")}. Nothing was sent.",
KafkaHeaders.PartitionKey);
return (int)number.Value;
}
/// The topic a value names: a non-empty text; anything else is refused.
public static string TopicFromHeader(object value)
=> value is string { Length: > 0 } topic && !string.IsNullOrWhiteSpace(topic)
? topic
: throw new ArgumentException(
$"The {KafkaHeaders.OverrideTopic} header must be a topic name; it is '{value}' ({value.GetType().Name}). Nothing was sent.",
KafkaHeaders.OverrideTopic);
///
/// The record timestamp a value names, in milliseconds since the Unix epoch
/// (Camel converts it to a Long): an integer, a whole-number text, a or a
/// (a local or unspecified one read as local time). A negative number or anything else is refused.
///
public static long TimestampFromHeader(object value)
{
long? ms = value switch
{
long l => l,
int i => i,
string text when long.TryParse(text.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed) => parsed,
DateTimeOffset dto => dto.ToUnixTimeMilliseconds(),
DateTime dt => new DateTimeOffset(dt.Kind == DateTimeKind.Utc ? dt : DateTime.SpecifyKind(dt, DateTimeKind.Local)).ToUnixTimeMilliseconds(),
_ => null,
};
if (ms is null or < 0)
throw new ArgumentException(
$"The {KafkaHeaders.OverrideTimestamp} header must be milliseconds since the Unix epoch or a date; it is '{value}' " +
$"({value.GetType().Name}). Nothing was sent.", KafkaHeaders.OverrideTimestamp);
return ms.Value;
}
///
/// Produces to of , or to the topic
/// (Kafka's partitioner, by the key) when there is no partition. A partition the topic does not have is refused by the
/// client; the refusal is rethrown naming the topic and the partition.
///
public static async Task> ProduceAsync(IProducer producer, string topic,
Message message, int? partition, CancellationToken ct)
{
if (partition is not { } p)
return await producer.ProduceAsync(topic, message, ct).ConfigureAwait(false);
try
{
return await producer.ProduceAsync(new TopicPartition(topic, new Partition(p)), message, ct).ConfigureAwait(false);
}
catch (ProduceException ex) when (ex.Error.Code == ErrorCode.Local_UnknownPartition)
{
throw new InvalidOperationException(
$"Kafka topic '{topic}' has no partition {p}: the record was not sent. Check {KafkaHeaders.PartitionKey} " +
"or the endpoint's partitionKey against the topic's partition count.", ex);
}
}
}