mqtt5 0.31.2

Complete MQTT v5.0 platform with high-performance async client and full-featured broker supporting TCP, TLS, WebSocket, authentication, bridging, and resource monitoring
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Configuration hot-reload system for the MQTT broker
//!
//! This module provides the ability to reload broker configuration without restarting,
//! which is essential for production deployments and achieving mosquitto-killer status.

use crate::broker::config::BrokerConfig;
use crate::error::{MqttError, Result};
use crate::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::fs;
use tokio::sync::{broadcast, RwLock};
use tracing::{debug, error, info, warn};

fn unix_timestamp_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// Configuration change notification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigChangeEvent {
    /// Timestamp of the change (seconds since UNIX epoch)
    pub timestamp: u64,
    /// Type of configuration change
    pub change_type: ConfigChangeType,
    /// Path to the changed configuration file
    pub config_path: PathBuf,
    /// Previous configuration hash
    pub previous_hash: u64,
    /// New configuration hash
    pub new_hash: u64,
}

/// Types of configuration changes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConfigChangeType {
    /// Complete configuration reload
    FullReload,
    /// Authentication configuration changed
    AuthConfig,
    /// TLS configuration changed
    TlsConfig,
    /// Resource limits changed
    ResourceLimits,
    /// WebSocket configuration changed
    WebSocketConfig,
    /// Bridge configuration changed
    BridgeConfig,
    /// Storage configuration changed
    StorageConfig,
}

/// Hot-reload manager for broker configuration
pub struct HotReloadManager {
    /// Current configuration
    current_config: Arc<RwLock<BrokerConfig>>,
    /// Configuration file path
    config_path: PathBuf,
    /// Change notification sender
    change_sender: broadcast::Sender<ConfigChangeEvent>,
    /// File system watcher handle
    watcher_handle: Option<tokio::task::JoinHandle<()>>,
    /// Last known file modification time
    last_modified: Arc<RwLock<Option<crate::time::SystemTime>>>,
    /// Configuration hash for change detection
    config_hash: Arc<RwLock<u64>>,
}

impl HotReloadManager {
    /// Creates a new hot-reload manager.
    ///
    /// # Errors
    /// This function currently does not return errors but the signature allows for future validation.
    pub fn new(config: BrokerConfig, config_path: PathBuf) -> Result<Self> {
        let (change_sender, _) = broadcast::channel(100);

        let initial_hash = Self::calculate_config_hash(&config);

        let manager = Self {
            current_config: Arc::new(RwLock::new(config)),
            config_path,
            change_sender,
            watcher_handle: None,
            last_modified: Arc::new(RwLock::new(None)),
            config_hash: Arc::new(RwLock::new(initial_hash)),
        };

        Ok(manager)
    }

    /// Starts the hot-reload system.
    ///
    /// # Errors
    /// This function currently does not return errors but the signature allows for future IO errors.
    pub async fn start(&mut self) -> Result<()> {
        info!("Starting configuration hot-reload system");

        // Initialize file modification time
        if let Ok(metadata) = fs::metadata(&self.config_path).await {
            if let Ok(modified) = metadata.modified() {
                *self.last_modified.write().await = Some(modified);
            }
        }

        // Start file system monitoring
        let watcher = self.start_file_watcher();
        self.watcher_handle = Some(watcher);

        info!(
            "Configuration hot-reload system started, monitoring: {:?}",
            self.config_path
        );
        Ok(())
    }

    /// Starts the file system watcher
    fn start_file_watcher(&self) -> tokio::task::JoinHandle<()> {
        let config_path = self.config_path.clone();
        let last_modified = self.last_modified.clone();
        let config_hash = self.config_hash.clone();
        let current_config = self.current_config.clone();
        let change_sender = self.change_sender.clone();

        let handle = tokio::spawn(async move {
            let mut interval = tokio::time::interval(crate::time::Duration::from_secs(5));

            loop {
                interval.tick().await;

                match Self::check_file_changed(&config_path, &last_modified).await {
                    Ok(true) => {
                        info!("Configuration file changed, reloading: {:?}", config_path);

                        match Self::reload_config_file(&config_path).await {
                            Ok(new_config) => {
                                let new_hash = Self::calculate_config_hash(&new_config);
                                let old_hash = *config_hash.read().await;

                                if new_hash == old_hash {
                                    debug!("Configuration file changed but content hash unchanged");
                                } else {
                                    // Validate the new configuration
                                    if let Err(e) = new_config.validate() {
                                        error!(
                                            "Invalid configuration file, ignoring reload: {}",
                                            e
                                        );
                                        continue;
                                    }

                                    // Update stored configuration
                                    *current_config.write().await = new_config;
                                    *config_hash.write().await = new_hash;

                                    // Send change notification
                                    let event = ConfigChangeEvent {
                                        timestamp: unix_timestamp_secs(),
                                        change_type: ConfigChangeType::FullReload,
                                        config_path: config_path.clone(),
                                        previous_hash: old_hash,
                                        new_hash,
                                    };

                                    if let Err(e) = change_sender.send(event) {
                                        warn!("Failed to send config change notification: {e}");
                                    }

                                    info!("Configuration successfully reloaded");
                                }
                            }
                            Err(e) => {
                                error!("Failed to reload configuration: {e}");
                            }
                        }
                    }
                    Ok(false) => {
                        // No change
                    }
                    Err(e) => {
                        warn!("Error checking configuration file: {e}");
                    }
                }
            }
        });

        handle
    }

    /// Checks if the configuration file has been modified
    async fn check_file_changed(
        config_path: &Path,
        last_modified: &Arc<RwLock<Option<crate::time::SystemTime>>>,
    ) -> Result<bool> {
        let metadata = fs::metadata(config_path)
            .await
            .map_err(|e| MqttError::Io(format!("Failed to read config file metadata: {e}")))?;

        let current_modified = metadata
            .modified()
            .map_err(|e| MqttError::Io(format!("Failed to get file modification time: {e}")))?;

        let mut last_mod = last_modified.write().await;

        if let Some(last) = *last_mod {
            if current_modified > last {
                *last_mod = Some(current_modified);
                return Ok(true);
            }
        } else {
            *last_mod = Some(current_modified);
        }

        Ok(false)
    }

    /// Reloads configuration from file.
    ///
    /// # Errors
    /// Returns an error if the file cannot be read or contains invalid JSON/TOML.
    pub async fn reload_config_file(config_path: &Path) -> Result<BrokerConfig> {
        let config_content = fs::read_to_string(config_path)
            .await
            .map_err(|e| MqttError::Io(format!("Failed to read config file: {e}")))?;

        // Support both JSON and TOML formats
        let config = if config_path.extension().and_then(|s| s.to_str()) == Some("toml") {
            toml::from_str(&config_content)
                .map_err(|e| MqttError::Configuration(format!("Invalid TOML config: {e}")))?
        } else {
            serde_json::from_str(&config_content)
                .map_err(|e| MqttError::Configuration(format!("Invalid JSON config: {e}")))?
        };

        Ok(config)
    }

    fn calculate_config_hash(config: &BrokerConfig) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        let json = serde_json::to_string(config).unwrap_or_default();
        json.hash(&mut hasher);
        hasher.finish()
    }

    /// Gets the current configuration
    pub async fn get_config(&self) -> BrokerConfig {
        self.current_config.read().await.clone()
    }

    /// Manually triggers a configuration reload.
    ///
    /// # Errors
    /// Returns an error if the config file cannot be read or the new config is invalid.
    ///
    /// # Panics
    /// Panics if the system time is before the Unix epoch (should not happen).
    pub async fn reload_now(&self) -> Result<bool> {
        info!("Manually triggering configuration reload");

        let new_config = Self::reload_config_file(&self.config_path).await?;
        let new_hash = Self::calculate_config_hash(&new_config);
        let old_hash = *self.config_hash.read().await;

        if new_hash == old_hash {
            info!("Configuration unchanged, no reload needed");
            Ok(false)
        } else {
            // Validate the new configuration
            new_config.validate()?;

            // Update stored configuration
            *self.current_config.write().await = new_config;
            *self.config_hash.write().await = new_hash;

            // Send change notification
            let event = ConfigChangeEvent {
                timestamp: unix_timestamp_secs(),
                change_type: ConfigChangeType::FullReload,
                config_path: self.config_path.clone(),
                previous_hash: old_hash,
                new_hash,
            };

            if let Err(e) = self.change_sender.send(event) {
                warn!("Failed to send config change notification: {e}");
            }

            info!("Configuration manually reloaded successfully");
            Ok(true)
        }
    }

    #[must_use]
    pub fn config_path(&self) -> &Path {
        &self.config_path
    }

    #[must_use]
    pub fn current_config_handle(&self) -> Arc<RwLock<BrokerConfig>> {
        Arc::clone(&self.current_config)
    }

    #[must_use]
    pub fn subscribe_to_changes(&self) -> broadcast::Receiver<ConfigChangeEvent> {
        self.change_sender.subscribe()
    }

    /// Applies specific configuration changes without full reload.
    ///
    /// # Errors
    /// Returns an error if the updated configuration fails validation.
    ///
    /// # Panics
    /// Panics if the system time is before the Unix epoch (should not happen).
    pub async fn apply_partial_config(
        &self,
        change_type: ConfigChangeType,
        update_fn: impl FnOnce(&mut BrokerConfig),
    ) -> Result<()> {
        info!("Applying partial configuration change: {:?}", change_type);

        let mut config = self.current_config.write().await;
        let old_hash = Self::calculate_config_hash(&config);

        // Apply the update
        update_fn(&mut config);

        // Validate the updated configuration
        config.validate()?;

        let new_hash = Self::calculate_config_hash(&config);

        // Send change notification
        let event = ConfigChangeEvent {
            timestamp: unix_timestamp_secs(),
            change_type,
            config_path: self.config_path.clone(),
            previous_hash: old_hash,
            new_hash,
        };

        if let Err(e) = self.change_sender.send(event) {
            warn!("Failed to send config change notification: {e}");
        }

        info!("Partial configuration change applied successfully");
        Ok(())
    }

    #[must_use]
    pub fn get_stats(&self) -> HotReloadStats {
        HotReloadStats {
            config_path: self.config_path.clone(),
            current_hash: futures::executor::block_on(async { *self.config_hash.read().await }),
            subscribers: self.change_sender.receiver_count(),
        }
    }
}

/// Statistics for the hot-reload system
#[derive(Debug, Serialize)]
pub struct HotReloadStats {
    pub config_path: PathBuf,
    pub current_hash: u64,
    pub subscribers: usize,
}

/// Integration helper for broker components
pub struct ConfigSubscriber {
    receiver: broadcast::Receiver<ConfigChangeEvent>,
    component_name: String,
}

impl ConfigSubscriber {
    #[allow(clippy::must_use_candidate)]
    pub fn new(receiver: broadcast::Receiver<ConfigChangeEvent>, component_name: String) -> Self {
        Self {
            receiver,
            component_name,
        }
    }

    /// Waits for the next configuration change.
    ///
    /// # Errors
    /// Returns an error if the change channel is closed.
    pub async fn wait_for_change(&mut self) -> Result<ConfigChangeEvent> {
        loop {
            match self.receiver.recv().await {
                Ok(event) => {
                    debug!(
                        "Component '{}' received config change: {:?}",
                        self.component_name, event.change_type
                    );
                    return Ok(event);
                }
                Err(broadcast::error::RecvError::Closed) => {
                    return Err(MqttError::InvalidState(
                        "Config change channel closed".to_string(),
                    ));
                }
                Err(broadcast::error::RecvError::Lagged(skipped)) => {
                    warn!(
                        "Component '{}' lagged behind, skipped {} config changes",
                        self.component_name, skipped
                    );
                    // Continue loop to try again
                }
            }
        }
    }

    /// Checks for pending configuration changes without blocking
    pub fn try_recv_change(&mut self) -> Option<ConfigChangeEvent> {
        match self.receiver.try_recv() {
            Ok(event) => {
                debug!(
                    "Component '{}' received config change: {:?}",
                    self.component_name, event.change_type
                );
                Some(event)
            }
            Err(_) => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;

    #[tokio::test]
    async fn test_hot_reload_manager() {
        // Create a temporary config file
        let temp_file = NamedTempFile::new().unwrap();
        let initial_config = BrokerConfig::default();
        let config_json = serde_json::to_string_pretty(&initial_config).unwrap();

        tokio::fs::write(temp_file.path(), config_json)
            .await
            .unwrap();

        // Create hot-reload manager
        let mut manager =
            HotReloadManager::new(initial_config.clone(), temp_file.path().to_path_buf()).unwrap();

        // Subscribe to changes
        let mut subscriber =
            ConfigSubscriber::new(manager.subscribe_to_changes(), "test".to_string());

        // Start hot-reload
        manager.start().await.unwrap();

        // Modify the config file
        let mut updated_config = initial_config;
        updated_config.max_clients = 5000;
        let updated_json = serde_json::to_string_pretty(&updated_config).unwrap();

        tokio::fs::write(temp_file.path(), updated_json)
            .await
            .unwrap();

        // Wait for change notification with timeout
        let change_result = tokio::time::timeout(
            crate::time::Duration::from_secs(2),
            subscriber.wait_for_change(),
        )
        .await;

        match change_result {
            Ok(Ok(event)) => {
                assert!(matches!(event.change_type, ConfigChangeType::FullReload));

                // Verify config was updated
                let current_config = manager.get_config().await;
                assert_eq!(current_config.max_clients, 5000);
            }
            Ok(Err(e)) => panic!("Failed to receive config change: {e}"),
            Err(_) => {
                // Timeout - may happen in test environment, just verify manual reload works
                println!("File watcher timeout, testing manual reload");
                let reloaded = manager.reload_now().await.unwrap();
                assert!(reloaded);

                let current_config = manager.get_config().await;
                assert_eq!(current_config.max_clients, 5000);
            }
        }
    }

    #[tokio::test]
    async fn test_partial_config_update() {
        let temp_file = NamedTempFile::new().unwrap();
        let initial_config = BrokerConfig::default();

        let manager =
            HotReloadManager::new(initial_config, temp_file.path().to_path_buf()).unwrap();

        // Apply partial update
        manager
            .apply_partial_config(ConfigChangeType::ResourceLimits, |config| {
                config.max_clients = 10000;
            })
            .await
            .unwrap();

        // Verify update
        let updated_config = manager.get_config().await;
        assert_eq!(updated_config.max_clients, 10000);
    }

    #[tokio::test]
    async fn test_config_validation() {
        let temp_file = NamedTempFile::new().unwrap();
        let initial_config = BrokerConfig::default();

        let manager =
            HotReloadManager::new(initial_config, temp_file.path().to_path_buf()).unwrap();

        // Try to apply invalid config
        let result = manager
            .apply_partial_config(ConfigChangeType::ResourceLimits, |config| {
                // This would make an invalid configuration
                config.max_clients = 0;
            })
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_config_change_event_timestamp() {
        let temp_file = NamedTempFile::new().unwrap();
        let initial_config = BrokerConfig::default();

        let manager =
            HotReloadManager::new(initial_config.clone(), temp_file.path().to_path_buf()).unwrap();

        // Subscribe to changes
        let mut subscriber =
            ConfigSubscriber::new(manager.subscribe_to_changes(), "timestamp_test".to_string());

        // Record time before the operation
        let before_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Apply a config change
        manager
            .apply_partial_config(ConfigChangeType::ResourceLimits, |config| {
                config.max_clients = 3000;
            })
            .await
            .unwrap();

        // Record time after the operation
        let after_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Get the change event
        let event = subscriber.wait_for_change().await.unwrap();

        // Verify timestamp is within reasonable bounds
        assert!(event.timestamp >= before_timestamp);
        assert!(event.timestamp <= after_timestamp);
        assert!(matches!(
            event.change_type,
            ConfigChangeType::ResourceLimits
        ));
    }
}