use std::{collections::BTreeMap, time::Duration};
use serde::Deserialize;
use crate::{
core::{CoreError, CoreResult, LogConfig, LogSection, ServiceConfig, load_config},
mqtt::{
MqttClientAuthConfig, MqttConfig, MqttReconnectConfig, MqttTlsConfig, MqttTopicLabelMode,
},
};
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct MqttServiceConfig {
pub name: String,
pub mode: String,
pub log: LogSection,
pub mqtt: MqttSection,
pub auth: Option<MqttAuthSection>,
}
impl Default for MqttServiceConfig {
fn default() -> Self {
let service = ServiceConfig::default();
Self {
name: service.name,
mode: service.mode,
log: service.log,
mqtt: MqttSection::default(),
auth: None,
}
}
}
impl MqttServiceConfig {
pub fn load(basename: &str, env_prefix: &str) -> Result<Self, config::ConfigError> {
load_config(basename, env_prefix)
}
pub fn log_config(&self) -> LogConfig {
self.log.to_log_config(&self.name)
}
pub fn mqtt_config(&self) -> CoreResult<MqttConfig> {
let broker = self.mqtt.brokers.get(&self.mqtt.broker).ok_or_else(|| {
CoreError::Config(config::ConfigError::Message(format!(
"missing mqtt broker profile: {}",
self.mqtt.broker
)))
})?;
let mut runtime = if !broker.url.trim().is_empty() {
MqttConfig::from_url(self.mqtt.client_id.clone(), &broker.url).map_err(|error| {
CoreError::Config(config::ConfigError::Message(error.to_string()))
})?
} else {
MqttConfig {
client_id: self.mqtt.client_id.clone(),
host: broker.host.clone(),
port: broker.port,
tls: MqttTlsConfig {
enabled: broker.tls.enabled,
..MqttTlsConfig::default()
},
..MqttConfig::default()
}
};
runtime.username = (!broker.username.is_empty()).then(|| broker.username.clone());
runtime.password = (!broker.password.is_empty()).then(|| broker.password.clone());
runtime.keep_alive = Duration::from_secs(broker.keep_alive_secs);
runtime.clean_session = self.mqtt.clean_session;
runtime.inflight = self.mqtt.inflight;
runtime.subscriptions = Vec::new();
runtime.topic_label_mode = self.mqtt.topic_label_mode.into();
runtime.reconnect = MqttReconnectConfig {
initial_delay: Duration::from_millis(self.mqtt.reconnect.initial_delay_ms),
max_delay: Duration::from_millis(self.mqtt.reconnect.max_delay_ms),
};
runtime.handler_timeout = Some(Duration::from_millis(self.mqtt.handler_timeout_ms));
#[cfg(feature = "observability")]
{
runtime.metrics_registry = None;
}
let tls = mqtt_tls_config(&broker.tls)?;
if tls.enabled {
if !runtime.tls.enabled && !broker.tls.enabled {
return Err(CoreError::Config(config::ConfigError::Message(
"mqtt tls file config requires TLS transport via mqtts://, ssl:// or explicit tls.enabled=true"
.to_string(),
)));
}
if !runtime.tls.enabled && !broker.url.trim().is_empty() {
return Err(CoreError::Config(config::ConfigError::Message(
"mqtt broker url scheme must be mqtts or ssl when TLS file config is used with url"
.to_string(),
)));
}
runtime.tls = MqttTlsConfig {
enabled: true,
ca: tls.ca,
client_auth: tls.client_auth,
};
}
Ok(runtime)
}
pub fn jwt_secret(&self) -> Option<String> {
self.auth.as_ref().and_then(MqttAuthSection::jwt_secret)
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct MqttSection {
pub client_id: String,
pub broker: String,
pub handler_timeout_ms: u64,
pub inflight: usize,
pub clean_session: bool,
pub topic_label_mode: MqttTopicLabelModeSection,
pub brokers: BTreeMap<String, MqttBrokerSection>,
pub reconnect: MqttReconnectSection,
}
impl Default for MqttSection {
fn default() -> Self {
Self {
client_id: "rs-zero-mqtt".to_string(),
broker: "default".to_string(),
handler_timeout_ms: 5000,
inflight: 10,
clean_session: true,
topic_label_mode: MqttTopicLabelModeSection::default(),
brokers: BTreeMap::new(),
reconnect: MqttReconnectSection::default(),
}
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct MqttBrokerSection {
pub url: String,
pub host: String,
pub port: u16,
pub username: String,
pub password: String,
pub keep_alive_secs: u64,
pub tls: MqttTlsSection,
}
impl Default for MqttBrokerSection {
fn default() -> Self {
Self {
url: String::new(),
host: "127.0.0.1".to_string(),
port: 1883,
username: String::new(),
password: String::new(),
keep_alive_secs: 30,
tls: MqttTlsSection::default(),
}
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct MqttTlsSection {
pub enabled: bool,
pub ca_file: String,
pub client_cert_file: String,
pub client_key_file: String,
}
impl Default for MqttTlsSection {
fn default() -> Self {
Self {
enabled: false,
ca_file: String::new(),
client_cert_file: String::new(),
client_key_file: String::new(),
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MqttTopicLabelModeSection {
Full,
Subscription,
Disabled,
}
impl Default for MqttTopicLabelModeSection {
fn default() -> Self {
Self::Subscription
}
}
impl From<MqttTopicLabelModeSection> for MqttTopicLabelMode {
fn from(value: MqttTopicLabelModeSection) -> Self {
match value {
MqttTopicLabelModeSection::Full => MqttTopicLabelMode::Full,
MqttTopicLabelModeSection::Subscription => MqttTopicLabelMode::Subscription,
MqttTopicLabelModeSection::Disabled => MqttTopicLabelMode::Disabled,
}
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct MqttReconnectSection {
pub initial_delay_ms: u64,
pub max_delay_ms: u64,
}
impl Default for MqttReconnectSection {
fn default() -> Self {
Self {
initial_delay_ms: 200,
max_delay_ms: 5000,
}
}
}
fn mqtt_tls_config(section: &MqttTlsSection) -> CoreResult<MqttTlsConfig> {
let has_ca = !section.ca_file.trim().is_empty();
let has_cert = !section.client_cert_file.trim().is_empty();
let has_key = !section.client_key_file.trim().is_empty();
if !section.enabled && !has_ca && !has_cert && !has_key {
return Ok(MqttTlsConfig::default());
}
let client_auth = match (has_cert, has_key) {
(false, false) => None,
(true, true) => {
if !has_ca {
return Err(CoreError::Config(config::ConfigError::Message(
"mqtt mTLS requires ca_file when client_cert_file/client_key_file are set"
.to_string(),
)));
}
Some(MqttClientAuthConfig {
cert: read_required_file(§ion.client_cert_file, "mqtt tls client_cert_file")?,
key: read_required_file(§ion.client_key_file, "mqtt tls client_key_file")?,
})
}
_ => {
return Err(CoreError::Config(config::ConfigError::Message(
"mqtt tls client auth requires both client_cert_file and client_key_file"
.to_string(),
)));
}
};
let ca = read_optional_file(§ion.ca_file, "mqtt tls ca_file")?;
Ok(MqttTlsConfig {
enabled: section.enabled || ca.is_some() || client_auth.is_some(),
ca,
client_auth,
})
}
fn read_optional_file(path: &str, label: &str) -> CoreResult<Option<Vec<u8>>> {
if path.trim().is_empty() {
return Ok(None);
}
read_required_file(path, label).map(Some)
}
fn read_required_file(path: &str, label: &str) -> CoreResult<Vec<u8>> {
std::fs::read(path).map_err(|error| {
CoreError::Config(config::ConfigError::Message(format!(
"{label} read failed: {error}"
)))
})
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct MqttAuthSection {
pub jwt_secret: String,
pub jwt_expires: u64,
}
impl Default for MqttAuthSection {
fn default() -> Self {
Self {
jwt_secret: String::new(),
jwt_expires: 7200,
}
}
}
impl MqttAuthSection {
fn jwt_secret(&self) -> Option<String> {
(!self.jwt_secret.is_empty()).then(|| self.jwt_secret.clone())
}
}