Path: redb-route/redb.Route.MqttNet/Fluent/MqttDsl.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.MqttNet/Fluent/MqttDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.MqttNet;
///
/// Entry point for the MQTT Fluent API. Two methods: Subscribe and Publish.
/// Each returns an for fluent configuration.
///
/// The builder generates a URI string equivalent to writing the URI manually.
/// Both paths converge in via URI binding.
///
///
///
/// // Subscribe (consumer):
/// .From(Mqtt.Subscribe("sensors/temperature")
/// .Broker("main").Qos(1).SharedSubscription("group1"))
///
/// // Publish (producer):
/// .To(Mqtt.Publish("sensors/commands")
/// .Broker("main").Qos(1).Retain())
///
/// // URI equivalent:
/// .From("mqtt:sensors/temperature?mode=Subscribe&broker=main&qos=1&sharedSubscription=group1")
///
///
///
public static class Mqtt
{
/// Creates a subscription consumer for the given topic or topic filter (wildcards supported).
/// MQTT topic or topic filter (e.g. sensors/+/temperature, home/#).
public static MqttBuilder Subscribe(string topic) => new(MqttMode.Subscribe, topic);
/// Creates a publisher producer for the given topic.
/// MQTT topic to publish to.
public static MqttBuilder Publish(string topic) => new(MqttMode.Publish, topic);
}
///
/// Fluent builder for MQTT endpoint URIs. Thin sugar over .
/// Call or use implicit conversion to
/// to get the URI for From() / To().
///
public sealed class MqttBuilder
{
private readonly MqttMode _mode;
private readonly string _topic;
// Connection
private string? _broker;
private string? _server;
private string? _port;
private string? _username;
private string? _password;
private string? _connectionFactory;
private string? _clientId;
private bool _useTls;
private string? _keepAlive;
private bool? _cleanSession;
private int? _sessionExpiryInterval;
private int? _maxReconnectDelay;
// Subscribe
private string? _qos;
private string? _sharedSubscription;
private string? _concurrentConsumers;
// Publish
private bool _retain;
private string? _messageExpiryInterval;
private string? _contentType;
private string? _responseTopic;
/// Creates a builder for the given mode and topic.
internal MqttBuilder(MqttMode mode, string topic)
{
ArgumentException.ThrowIfNullOrWhiteSpace(topic);
_mode = mode;
_topic = topic;
}
// ── Connection ────────────────────────────────────────────────────
/// Use a named broker registered via AddBroker().
public MqttBuilder Broker(IExpression name) { _broker = name.ToTemplateString(); return this; }
/// Use a named broker registered via AddBroker() (template string, supports ${...}).
public MqttBuilder Broker(string name) { _broker = name; return this; }
/// Connect directly to this server (hostname or IP).
public MqttBuilder Server(IExpression server) { _server = server.ToTemplateString(); return this; }
/// Connect directly to this server, hostname or IP (template string, supports ${...}).
public MqttBuilder Server(string server) { _server = server; return this; }
/// Server port. Default 1883.
public MqttBuilder Port(int port) { _port = port.ToString(); return this; }
/// Server port from an expression.
public MqttBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
/// Username for broker authentication.
public MqttBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; }
/// Username for broker authentication (template string, supports ${...}).
public MqttBuilder Username(string username) { _username = username; return this; }
/// Password for broker authentication.
public MqttBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; }
/// Password for broker authentication (template string, supports ${...}).
public MqttBuilder Password(string password) { _password = password; return this; }
///
/// References a named from the route registry instead of
/// putting broker credentials in the URI.
///
public MqttBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Client ID for the MQTT connection.
public MqttBuilder ClientId(IExpression clientId) { _clientId = clientId.ToTemplateString(); return this; }
/// Client ID for the MQTT connection (template string, supports ${...}).
public MqttBuilder ClientId(string clientId) { _clientId = clientId; return this; }
/// Enable TLS/SSL.
public MqttBuilder UseTls() { _useTls = true; return this; }
/// Keep-alive interval in seconds.
public MqttBuilder KeepAlive(int seconds) { _keepAlive = seconds.ToString(); return this; }
/// Keep-alive interval from an expression.
public MqttBuilder KeepAlive(IExpression seconds) { _keepAlive = seconds.ToTemplateString(); return this; }
/// Set clean session flag.
public MqttBuilder CleanSession(bool clean = true) { _cleanSession = clean; return this; }
///
/// MQTT 5 Session Expiry Interval in seconds: how long the broker keeps the session after the connection closes.
/// With CleanSession(false) and a value above 0 a failed message is sent again after a reconnect.
///
public MqttBuilder SessionExpiryInterval(int seconds) { _sessionExpiryInterval = seconds; return this; }
/// Longest pause in milliseconds before the consumer reconnects after a failed message. Default 128000.
public MqttBuilder MaxReconnectDelay(int milliseconds) { _maxReconnectDelay = milliseconds; return this; }
// ── QoS ──────────────────────────────────────────────────────────
/// Quality of Service level: 0 (at most once), 1 (at least once), 2 (exactly once).
public MqttBuilder Qos(int level) { _qos = level.ToString(); return this; }
/// QoS from an expression.
public MqttBuilder Qos(IExpression level) { _qos = level.ToTemplateString(); return this; }
// ── Subscribe ────────────────────────────────────────────────────
/// MQTT 5.0 shared subscription group for load-balanced consuming.
public MqttBuilder SharedSubscription(IExpression group) { _sharedSubscription = group.ToTemplateString(); return this; }
/// MQTT 5.0 shared subscription group for load-balanced consuming (template string, supports ${...}).
public MqttBuilder SharedSubscription(string group) { _sharedSubscription = group; return this; }
///
/// Number of concurrent processing workers for received messages (default 1 = serial).
/// When > 1, messages are processed by a pool of N workers and acknowledged only after each
/// worker finishes (manual ack) — parallelism with at-least-once preserved for QoS 1/2.
/// Ordering is not preserved when > 1.
///
public MqttBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; }
/// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)).
public MqttBuilder ConcurrentConsumers(string count) { _concurrentConsumers = count; return this; }
// ── Publish ──────────────────────────────────────────────────────
/// Set retain flag on published messages.
public MqttBuilder Retain() { _retain = true; return this; }
/// Message expiry interval in seconds (MQTT 5.0).
public MqttBuilder MessageExpiryInterval(int seconds) { _messageExpiryInterval = seconds.ToString(); return this; }
/// Message expiry from an expression.
public MqttBuilder MessageExpiryInterval(IExpression seconds) { _messageExpiryInterval = seconds.ToTemplateString(); return this; }
/// Content type for published messages (MQTT 5.0).
public MqttBuilder ContentType(string contentType) { _contentType = contentType; return this; }
/// Content type from an expression.
public MqttBuilder ContentType(IExpression contentType) { _contentType = contentType.ToTemplateString(); return this; }
/// Response topic for request/response pattern (MQTT 5.0).
public MqttBuilder ResponseTopic(IExpression topic) { _responseTopic = topic.ToTemplateString(); return this; }
/// Response topic for request/response pattern, MQTT 5.0 (template string, supports ${...}).
public MqttBuilder ResponseTopic(string topic) { _responseTopic = topic; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the MQTT URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("mqtt:");
sb.Append(_topic);
var separator = '?';
void Append(string key, string value)
{
sb.Append(separator);
sb.Append(key);
sb.Append('=');
sb.Append(Uri.EscapeDataString(value));
separator = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
// Route int-or-expression params to the correct property
void AppendIntOrExpression(string key, string? value)
{
if (value == null) return;
if (value.Contains("${"))
Append(key + "Expression", value);
else
Append(key, value);
}
Append("mode", _mode.ToString());
// Connection
AppendIf("broker", _broker);
AppendIf("server", _server);
AppendIf("port", _port);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("clientId", _clientId);
AppendBool("useTls", _useTls);
AppendIf("keepAlive", _keepAlive);
if (_cleanSession.HasValue)
Append("cleanSession", _cleanSession.Value.ToString().ToLowerInvariant());
if (_sessionExpiryInterval.HasValue)
Append("sessionExpiryInterval", _sessionExpiryInterval.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_maxReconnectDelay.HasValue)
Append("maxReconnectDelay", _maxReconnectDelay.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
// Subscribe/Publish common
AppendIntOrExpression("qos", _qos);
// Subscribe-only
AppendIf("sharedSubscription", _sharedSubscription);
AppendIf("concurrentConsumers", _concurrentConsumers);
// Publish-only
AppendBool("retain", _retain);
AppendIntOrExpression("messageExpiryInterval", _messageExpiryInterval);
AppendIf("contentType", _contentType);
AppendIf("responseTopic", _responseTopic);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(MqttBuilder builder) => builder.Build();
///
public override string ToString() => Build();
}