Path: redb-route/redb.Route.Kafka/Fluent/KafkaDsl.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/Fluent/KafkaDsl.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Kafka; /// /// Fluent API for Kafka endpoints. /// /// .From(Kafka.Topic("orders").Brokers("broker1:9092").GroupId("order-group").AutoOffsetReset("Earliest")) /// .To(Kafka.Topic("notifications").Brokers("broker1:9092").Acks("All")) /// /// public static class Kafka { /// Creates a Kafka endpoint for the given topic name. public static KafkaBuilder Topic(string name) => new(name); } /// /// Fluent builder for Kafka endpoint URIs. /// public sealed class KafkaBuilder { private readonly string _topic; // Connection private string? _brokers; private string? _securityProtocol; private string? _saslMechanism; private string? _saslUsername; private string? _saslPassword; private string? _sslCaLocation; private string? _sslCertificateLocation; private string? _sslKeyLocation; private string? _sslKeyPassword; private string? _sslEndpointIdentification; private string? _connectionFactory; // Consumer private string? _groupId; private string? _autoOffsetReset; private AckMode? _ackMode; private bool _batching; private string? _maxBatchMessages; private string? _batchingIntervalMs; private string? _pollTimeoutMs; private bool _breakOnFirstError; private string? _seekTo; private bool _topicIsPattern; private string? _groupInstanceId; private string? _sessionTimeoutMs; private string? _heartbeatIntervalMs; private string? _maxPollIntervalMs; private string? _partitionAssignmentStrategy; private string? _isolationLevel; // Producer private string? _acks; private string? _retries; private bool _recordMetadata; private string? _key; private string? _partitionNumber; private string? _partitionKey; private bool? _transacted; private bool? _enableIdempotence; private string? _transactionalIdPrefix; private string? _lingerMs; private string? _batchSize; private string? _compressionType; private string? _messageTimeoutMs; internal KafkaBuilder(string topic) { ArgumentException.ThrowIfNullOrWhiteSpace(topic); _topic = topic; } // ── Connection ──────────────────────────────────────────────────── /// Bootstrap servers (comma-separated host:port). e.g. "broker1:9092,broker2:9092". public KafkaBuilder Brokers(IExpression brokers) { _brokers = brokers.ToTemplateString(); return this; } /// Bootstrap servers (template string, supports ${...}). e.g. "broker1:9092,broker2:9092". public KafkaBuilder Brokers(string brokers) { _brokers = brokers; return this; } /// Security protocol: Plaintext, Ssl, SaslPlaintext, SaslSsl. public KafkaBuilder SecurityProtocol(string protocol) { _securityProtocol = protocol; return this; } /// SASL authentication: mechanism + credentials. public KafkaBuilder Sasl(string mechanism, IExpression username, IExpression password) { _saslMechanism = mechanism; _saslUsername = username.ToTemplateString(); _saslPassword = password.ToTemplateString(); return this; } /// Path to CA certificate file for SSL. public KafkaBuilder SslCa(IExpression path) { _sslCaLocation = path.ToTemplateString(); return this; } /// Path to CA certificate file for SSL (template string, supports ${...}). public KafkaBuilder SslCa(string path) { _sslCaLocation = path; return this; } /// Client certificate for mutual TLS. public KafkaBuilder SslCert(IExpression certPath, IExpression? keyPath = null, IExpression? keyPassword = null) { _sslCertificateLocation = certPath.ToTemplateString(); _sslKeyLocation = keyPath?.ToTemplateString(); _sslKeyPassword = keyPassword?.ToTemplateString(); return this; } /// Client certificate for mutual TLS (template strings, support ${...}). public KafkaBuilder SslCert(string certPath, string? keyPath = null, string? keyPassword = null) { _sslCertificateLocation = certPath; _sslKeyLocation = keyPath; _sslKeyPassword = keyPassword; return this; } /// /// Whether the broker's hostname is verified against its certificate (sslEndpointIdentificationAlgorithm /// https / none). Unset, librdkafka verifies it. /// public KafkaBuilder SslVerifyHostname(bool verify = true) { _sslEndpointIdentification = verify ? "https" : "none"; return this; } /// Use a named connection factory registered in DI. public KafkaBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; } /// Use a named connection factory registered in DI (template string, supports ${...}). public KafkaBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } // ── Consumer ────────────────────────────────────────────────────── /// Consumer group ID. public KafkaBuilder GroupId(IExpression groupId) { _groupId = groupId.ToTemplateString(); return this; } /// Consumer group ID (template string, supports ${...}). public KafkaBuilder GroupId(string groupId) { _groupId = groupId; return this; } /// Auto offset reset: Latest, Earliest, Error. public KafkaBuilder AutoOffsetReset(string reset) { _autoOffsetReset = reset; return this; } /// /// When the offset is committed: after the route (, default; a transactional /// route's commit takes precedence) or on receipt (, at-most-once). /// public KafkaBuilder AckMode(AckMode mode) { _ackMode = mode; return this; } /// Batch mode (batching=true): the route gets the records as a List<IMessage>. public KafkaBuilder Batching() { _batching = true; return this; } /// Largest number of records in a batch (maxBatchMessages, default 500). Batch mode only. public KafkaBuilder MaxBatchMessages(int max) { _maxBatchMessages = max.ToString(); return this; } /// Largest number of records in a batch from an expression. public KafkaBuilder MaxBatchMessages(IExpression max) { _maxBatchMessages = max.ToTemplateString(); return this; } /// Hard limit of a batch in milliseconds from its first record (batchingIntervalMs). Batch mode only. public KafkaBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms.ToString(); return this; } /// Hard limit of a batch from an expression. public KafkaBuilder BatchingIntervalMs(IExpression ms) { _batchingIntervalMs = ms.ToTemplateString(); return this; } /// Poll timeout in milliseconds, default 1000; in batch mode the idle timeout of a batch. public KafkaBuilder PollTimeout(int ms) { _pollTimeoutMs = ms.ToString(); return this; } /// Poll timeout from an expression. public KafkaBuilder PollTimeout(IExpression ms) { _pollTimeoutMs = ms.ToTemplateString(); return this; } /// Stop consuming on first error. public KafkaBuilder BreakOnFirstError() { _breakOnFirstError = true; return this; } /// Seek each assigned partition once to a position: "beginning" or "end". public KafkaBuilder SeekTo(string position) { _seekTo = position; return this; } /// Treat topic name as a regex pattern. public KafkaBuilder TopicIsPattern() { _topicIsPattern = true; return this; } /// Consumer: read this one partition (partitionNumber) instead of joining the group's assignment. public KafkaBuilder PartitionNumber(int partition) { _partitionNumber = partition.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// Static group instance ID for cooperative rebalancing. public KafkaBuilder GroupInstanceId(IExpression id) { _groupInstanceId = id.ToTemplateString(); return this; } /// Static group instance ID for cooperative rebalancing (template string, supports ${...}). public KafkaBuilder GroupInstanceId(string id) { _groupInstanceId = id; return this; } /// Session timeout in milliseconds. public KafkaBuilder SessionTimeout(int ms) { _sessionTimeoutMs = ms.ToString(); return this; } /// Session timeout from an expression. public KafkaBuilder SessionTimeout(IExpression ms) { _sessionTimeoutMs = ms.ToTemplateString(); return this; } /// Heartbeat interval in milliseconds. public KafkaBuilder HeartbeatInterval(int ms) { _heartbeatIntervalMs = ms.ToString(); return this; } /// Heartbeat interval from an expression. public KafkaBuilder HeartbeatInterval(IExpression ms) { _heartbeatIntervalMs = ms.ToTemplateString(); return this; } /// Max poll interval in milliseconds. public KafkaBuilder MaxPollInterval(int ms) { _maxPollIntervalMs = ms.ToString(); return this; } /// Max poll interval from an expression. public KafkaBuilder MaxPollInterval(IExpression ms) { _maxPollIntervalMs = ms.ToTemplateString(); return this; } /// Partition assignment strategy. public KafkaBuilder PartitionAssignmentStrategy(string strategy) { _partitionAssignmentStrategy = strategy; return this; } /// Isolation level: ReadUncommitted, ReadCommitted. public KafkaBuilder IsolationLevel(string level) { _isolationLevel = level; return this; } // ── Producer ────────────────────────────────────────────────────── /// Acknowledge level: None, Leader, All. Default "All". public KafkaBuilder Acks(string acks) { _acks = acks; return this; } /// Number of retries. Default 3. public KafkaBuilder Retries(int count) { _retries = count.ToString(); return this; } /// Retries from an expression. public KafkaBuilder Retries(IExpression count) { _retries = count.ToTemplateString(); return this; } /// Include record metadata (partition, offset) in the exchange after produce. public KafkaBuilder RecordMetadata() { _recordMetadata = true; return this; } /// Message key for partitioning. public KafkaBuilder Key(IExpression key) { _key = key.ToTemplateString(); return this; } /// Message key for partitioning (template string, supports ${...}). public KafkaBuilder Key(string key) { _key = key; return this; } /// /// Producer: the partition every record goes to (partitionKey, Apache Camel's name); it takes precedence over /// the per-message header, as in Camel. To choose the partition per message, set /// that header instead. /// public KafkaBuilder PartitionKey(int partition) { _partitionKey = partition.ToString(System.Globalization.CultureInfo.InvariantCulture); return this; } /// /// The send joins the enclosing .Transacted() block (deferred until the database commits) and refuses to run /// outside one; the producer is idempotent. Kafka transactions are a separate switch, /// . /// public KafkaBuilder Transacted() { _transacted = true; return this; } /// /// Sets transacted explicitly. false sends at once even inside a .Transacted() block, outside its /// transaction; left unset, a producer follows the block. /// public KafkaBuilder Transacted(bool value) { _transacted = value; return this; } /// /// Sets enableIdempotence: the broker does not write a retried send twice. Left unset, it follows acks: on /// with all (the default), off otherwise. /// public KafkaBuilder EnableIdempotence(bool value = true) { _enableIdempotence = value; return this; } /// /// Sets transactionalIdPrefix: the producer uses Kafka transactions. The sends it defers in a /// .Transacted() block commit as one Kafka transaction when the block commits, together with the offset of the /// Kafka record the route consumed (exactly-once within Kafka); a send outside a block is a transaction of its own. /// The prefix names the producer: the connector appends the machine, the process and the producer's number, so nodes /// sharing the configuration never fence each other. /// public KafkaBuilder TransactionalIdPrefix(string prefix) { _transactionalIdPrefix = prefix; return this; } /// Linger time in milliseconds (batch delay). public KafkaBuilder Linger(int ms) { _lingerMs = ms.ToString(); return this; } /// Linger from an expression. public KafkaBuilder Linger(IExpression ms) { _lingerMs = ms.ToTemplateString(); return this; } /// Batch size in bytes. public KafkaBuilder BatchSize(int bytes) { _batchSize = bytes.ToString(); return this; } /// Batch size from an expression. public KafkaBuilder BatchSize(IExpression bytes) { _batchSize = bytes.ToTemplateString(); return this; } /// Compression type: none, gzip, snappy, lz4, zstd. public KafkaBuilder Compression(string type) { _compressionType = type; return this; } /// Message delivery timeout in milliseconds. public KafkaBuilder MessageTimeout(int ms) { _messageTimeoutMs = ms.ToString(); return this; } /// Message timeout from an expression. public KafkaBuilder MessageTimeout(IExpression ms) { _messageTimeoutMs = ms.ToTemplateString(); return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the Kafka endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append("kafka:"); sb.Append(_topic); var sep = '?'; void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (value != null) Append(key, value); } void AppendBool(string key, bool value) { if (value) Append(key, "true"); } // Connection AppendIf("brokers", _brokers); AppendIf("securityProtocol", _securityProtocol); AppendIf("saslMechanism", _saslMechanism); AppendIf("saslUsername", _saslUsername); AppendIf("saslPassword", _saslPassword); AppendIf("sslCaLocation", _sslCaLocation); AppendIf("sslCertificateLocation", _sslCertificateLocation); AppendIf("sslKeyLocation", _sslKeyLocation); AppendIf("sslKeyPassword", _sslKeyPassword); AppendIf("sslEndpointIdentificationAlgorithm", _sslEndpointIdentification); AppendIf("connectionFactory", _connectionFactory); // Consumer AppendIf("groupId", _groupId); AppendIf("autoOffsetReset", _autoOffsetReset); AppendIf("ackMode", _ackMode?.ToString().ToLowerInvariant()); if (_batching) Append("batching", "true"); AppendIf("maxBatchMessages", _maxBatchMessages); AppendIf("batchingIntervalMs", _batchingIntervalMs); AppendIf("pollTimeoutMs", _pollTimeoutMs); AppendBool("breakOnFirstError", _breakOnFirstError); AppendIf("seekTo", _seekTo); AppendBool("topicIsPattern", _topicIsPattern); AppendIf("groupInstanceId", _groupInstanceId); AppendIf("sessionTimeoutMs", _sessionTimeoutMs); AppendIf("heartbeatIntervalMs", _heartbeatIntervalMs); AppendIf("maxPollIntervalMs", _maxPollIntervalMs); AppendIf("partitionAssignmentStrategy", _partitionAssignmentStrategy); AppendIf("isolationLevel", _isolationLevel); // Producer AppendIf("acks", _acks); AppendIf("retries", _retries); AppendBool("recordMetadata", _recordMetadata); AppendIf("key", _key); AppendIf("partitionNumber", _partitionNumber); AppendIf("partitionKey", _partitionKey); if (_transacted is { } transacted) Append("transacted", transacted ? "true" : "false"); if (_enableIdempotence is { } idempotence) Append("enableIdempotence", idempotence ? "true" : "false"); AppendIf("transactionalIdPrefix", _transactionalIdPrefix); AppendIf("lingerMs", _lingerMs); AppendIf("batchSize", _batchSize); AppendIf("compressionType", _compressionType); AppendIf("messageTimeoutMs", _messageTimeoutMs); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(KafkaBuilder b) => b.Build(); /// public override string ToString() => Build(); }