Skip to main content

rocketmq_common/common/controller/
controller_config.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::env;
17use std::fmt;
18use std::net::SocketAddr;
19use std::path::PathBuf;
20
21use rocketmq_error::RocketMQError;
22use rocketmq_error::RocketMQResult;
23use serde::Deserialize;
24use serde::Serialize;
25use tokio::sync::RwLock;
26
27use crate::common::metrics::MetricsExporterType;
28use crate::common::mix_all::ROCKETMQ_HOME_ENV;
29use crate::utils::env_utils::EnvUtils;
30
31/// Controller type constant
32pub const RAFT_CONTROLLER: &str = "Raft";
33
34/// Controller configuration
35///
36/// This configuration defines the behavior and parameters of the RocketMQ controller.
37/// It manages broker election, state synchronization, and cluster coordination.
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct RaftPeer {
41    /// Node ID
42    pub id: u64,
43
44    /// Peer address
45    pub addr: SocketAddr,
46}
47
48/// Storage backend type
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50pub enum StorageBackendType {
51    /// RocksDB storage
52    RocksDB,
53
54    /// File-based storage
55    File,
56
57    /// In-memory storage (for testing)
58    Memory,
59}
60
61impl fmt::Display for StorageBackendType {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::RocksDB => write!(f, "rocks_db"),
65            Self::File => write!(f, "file"),
66            Self::Memory => write!(f, "memory"),
67        }
68    }
69}
70
71#[derive(Debug, Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73pub struct ControllerConfig {
74    // --- shared Controller fields (existing) ---
75    /// RocketMQ home directory
76    ///
77    /// Defaults to ROCKETMQ_HOME environment variable or current directory
78    pub rocketmq_home: String,
79
80    /// Configuration file storage path
81    ///
82    /// Defaults to $HOME/controller/controller.properties
83    pub config_store_path: PathBuf,
84
85    /// Controller type: "Raft"
86    ///
87    /// Default: Raft
88    /// Note: In Rust implementation, "Raft" uses OpenRaft.
89    pub controller_type: String,
90
91    /// Interval of periodic scanning for non-active broker (milliseconds)
92    ///
93    /// Default: 5000 (5 seconds)
94    pub scan_not_active_broker_interval: u64,
95
96    /// Number of threads to handle broker or operation requests (like REGISTER_BROKER)
97    ///
98    /// Default: 16
99    pub controller_thread_pool_nums: usize,
100
101    /// Capacity of queue to hold client requests
102    ///
103    /// Default: 50000
104    pub controller_request_thread_pool_queue_capacity: usize,
105
106    /// Mapped file size for controller storage
107    ///
108    /// Default: 1GB (1024 * 1024 * 1024)
109    pub mapped_file_size: usize,
110
111    /// Controller storage path
112    ///
113    /// Default: empty string (will be set based on rocketmq_home)
114    pub controller_store_path: String,
115
116    /// Max retry count for electing master when failed because of network or system error
117    ///
118    /// Default: 3
119    pub elect_master_max_retry_count: u32,
120
121    /// Whether the controller can elect a master which is not in the syncStateSet
122    ///
123    /// Default: false
124    pub enable_elect_unclean_master: bool,
125
126    /// Whether process read event
127    ///
128    /// Default: false
129    pub is_process_read_event: bool,
130
131    /// Whether notify broker when its role changed
132    ///
133    /// Default: true
134    pub notify_broker_role_changed: bool,
135
136    /// Interval of periodic scanning for non-active master in each broker-set (milliseconds)
137    ///
138    /// Default: 5000 (5 seconds)
139    pub scan_inactive_master_interval: u64,
140
141    /// Wait time after the first broker heartbeat before OpenRaft inactive scanning starts.
142    ///
143    /// Default: 1000 (1 second), matching Java jRaftScanWaitTimeoutMs.
144    pub raft_scan_wait_timeout_ms: u64,
145
146    /// Metrics exporter type
147    ///
148    /// Default: Disable
149    pub metrics_exporter_type: MetricsExporterType,
150
151    /// Metrics gRPC exporter target address
152    pub metrics_grpc_exporter_target: String,
153
154    /// Metrics gRPC exporter header
155    pub metrics_grpc_exporter_header: String,
156
157    /// Metric gRPC exporter timeout (milliseconds)
158    ///
159    /// Default: 3000 (3 seconds)
160    pub metric_grpc_exporter_time_out_in_mills: u64,
161
162    /// Metric gRPC exporter interval (milliseconds)
163    ///
164    /// Default: 60000 (60 seconds)
165    pub metric_grpc_exporter_interval_in_mills: u64,
166
167    /// Metric logging exporter interval (milliseconds)
168    ///
169    /// Default: 10000 (10 seconds)
170    pub metric_logging_exporter_interval_in_mills: u64,
171
172    /// Metrics Prometheus exporter port
173    ///
174    /// Default: 5557
175    pub metrics_prom_exporter_port: u16,
176
177    /// Metrics Prometheus exporter host
178    pub metrics_prom_exporter_host: String,
179
180    /// Metrics label (CSV format: Key:Value,Key:Value)
181    ///
182    /// Example: "instance_id:xxx,uid:xxx"
183    pub metrics_label: String,
184
185    /// Whether metrics are in delta mode
186    ///
187    /// Default: false
188    pub metrics_in_delta: bool,
189
190    /// Configuration blacklist (configs that cannot be updated via command)
191    ///
192    /// These configs can only be changed by restarting the process.
193    /// Default: "configBlackList;configStorePath"
194    pub config_black_list: String,
195
196    // --- node-specific fields (added for controller usage) ---
197    /// Node id for this controller process (optional in shared config)
198    pub node_id: u64,
199
200    /// Listen address for RPC/raft on this node
201    pub listen_addr: SocketAddr,
202
203    /// Peer list used for raft bootstrapping
204    pub raft_peers: Vec<RaftPeer>,
205
206    /// Controller remoting peer list used for broker-facing leader discovery
207    pub controller_peers: Vec<RaftPeer>,
208
209    /// Election timeout (ms) used by Raft
210    pub election_timeout_ms: u64,
211
212    /// Heartbeat interval (ms) used by Raft
213    pub heartbeat_interval_ms: u64,
214
215    /// Local storage path for controller artifacts
216    pub storage_path: String,
217
218    /// Storage backend to use for local controller artifacts
219    pub storage_backend: StorageBackendType,
220
221    /// Whether the controller may elect an unclean master on this node
222    pub enable_elect_unclean_master_local: bool,
223    #[serde(skip)]
224    rw_lock: RwLock<()>,
225}
226impl Clone for ControllerConfig {
227    fn clone(&self) -> Self {
228        Self {
229            rocketmq_home: self.rocketmq_home.clone(),
230            config_store_path: self.config_store_path.clone(),
231            controller_type: self.controller_type.clone(),
232            scan_not_active_broker_interval: self.scan_not_active_broker_interval,
233            controller_thread_pool_nums: self.controller_thread_pool_nums,
234            controller_request_thread_pool_queue_capacity: self.controller_request_thread_pool_queue_capacity,
235            mapped_file_size: self.mapped_file_size,
236            controller_store_path: self.controller_store_path.clone(),
237            elect_master_max_retry_count: self.elect_master_max_retry_count,
238            enable_elect_unclean_master: self.enable_elect_unclean_master,
239            is_process_read_event: self.is_process_read_event,
240            notify_broker_role_changed: self.notify_broker_role_changed,
241            scan_inactive_master_interval: self.scan_inactive_master_interval,
242            raft_scan_wait_timeout_ms: self.raft_scan_wait_timeout_ms,
243            metrics_exporter_type: self.metrics_exporter_type,
244            metrics_grpc_exporter_target: self.metrics_grpc_exporter_target.clone(),
245            metrics_grpc_exporter_header: self.metrics_grpc_exporter_header.clone(),
246            metric_grpc_exporter_time_out_in_mills: self.metric_grpc_exporter_time_out_in_mills,
247            metric_grpc_exporter_interval_in_mills: self.metric_grpc_exporter_interval_in_mills,
248            metric_logging_exporter_interval_in_mills: self.metric_logging_exporter_interval_in_mills,
249            metrics_prom_exporter_port: self.metrics_prom_exporter_port,
250            metrics_prom_exporter_host: self.metrics_prom_exporter_host.clone(),
251            metrics_label: self.metrics_label.clone(),
252            metrics_in_delta: self.metrics_in_delta,
253            config_black_list: self.config_black_list.clone(),
254            node_id: self.node_id,
255            listen_addr: self.listen_addr,
256            raft_peers: self.raft_peers.clone(),
257            controller_peers: self.controller_peers.clone(),
258            election_timeout_ms: self.election_timeout_ms,
259            heartbeat_interval_ms: self.heartbeat_interval_ms,
260            storage_path: self.storage_path.clone(),
261            storage_backend: self.storage_backend.clone(),
262            enable_elect_unclean_master_local: self.enable_elect_unclean_master_local,
263            rw_lock: RwLock::new(()),
264        }
265    }
266}
267
268impl Default for ControllerConfig {
269    fn default() -> Self {
270        // Get ROCKETMQ_HOME from environment variable or use current directory
271        let rocketmq_home = env::var(ROCKETMQ_HOME_ENV)
272            .ok()
273            .or_else(|| env::var("rocketmq.home.dir").ok())
274            .unwrap_or_else(EnvUtils::get_rocketmq_home);
275
276        // Get user home directory
277        let user_home = dirs::home_dir()
278            .unwrap_or_else(|| PathBuf::from("."))
279            .to_string_lossy()
280            .to_string();
281
282        Self {
283            rocketmq_home,
284            config_store_path: PathBuf::from(&user_home)
285                .join("controller")
286                .join("controller.properties"),
287            controller_type: RAFT_CONTROLLER.to_string(),
288            scan_not_active_broker_interval: 5 * 1000,
289            controller_thread_pool_nums: 16,
290            controller_request_thread_pool_queue_capacity: 50000,
291            mapped_file_size: 1024 * 1024 * 1024,
292            controller_store_path: String::new(),
293            elect_master_max_retry_count: 3,
294            enable_elect_unclean_master: false,
295            is_process_read_event: false,
296            notify_broker_role_changed: true,
297            scan_inactive_master_interval: 5 * 1000,
298            raft_scan_wait_timeout_ms: 1000,
299            metrics_exporter_type: MetricsExporterType::Disable,
300            metrics_grpc_exporter_target: String::new(),
301            metrics_grpc_exporter_header: String::new(),
302            metric_grpc_exporter_time_out_in_mills: 3 * 1000,
303            metric_grpc_exporter_interval_in_mills: 60 * 1000,
304            metric_logging_exporter_interval_in_mills: 10 * 1000,
305            metrics_prom_exporter_port: 5557,
306            metrics_prom_exporter_host: String::new(),
307            metrics_label: String::new(),
308            metrics_in_delta: false,
309            config_black_list: "configBlackList;configStorePath".to_string(),
310            node_id: 1,
311            listen_addr: SocketAddr::from(([127, 0, 0, 1], 60109)),
312            raft_peers: Vec::new(),
313            controller_peers: Vec::new(),
314            election_timeout_ms: 1000,
315            heartbeat_interval_ms: 300,
316            storage_path: String::new(),
317            storage_backend: StorageBackendType::Memory,
318            enable_elect_unclean_master_local: false,
319            rw_lock: RwLock::new(()),
320        }
321    }
322}
323
324impl ControllerConfig {
325    /// Create a new ControllerConfig with default values
326    pub fn new() -> Self {
327        Self::default()
328    }
329
330    /// Set RocketMQ home directory
331    pub fn with_rocketmq_home(mut self, path: impl Into<String>) -> Self {
332        self.rocketmq_home = path.into();
333        self
334    }
335
336    /// Set configuration store path
337    pub fn with_config_store_path(mut self, path: PathBuf) -> Self {
338        self.config_store_path = path;
339        self
340    }
341
342    /// Set controller type
343    pub fn with_controller_type(mut self, controller_type: impl Into<String>) -> Self {
344        self.controller_type = controller_type.into();
345        self
346    }
347
348    /// Set scan not active broker interval
349    pub fn with_scan_not_active_broker_interval(mut self, interval_ms: u64) -> Self {
350        self.scan_not_active_broker_interval = interval_ms;
351        self
352    }
353
354    /// Set controller thread pool size
355    pub fn with_controller_thread_pool_nums(mut self, nums: usize) -> Self {
356        self.controller_thread_pool_nums = nums;
357        self
358    }
359
360    /// Set controller request queue capacity
361    pub fn with_controller_request_queue_capacity(mut self, capacity: usize) -> Self {
362        self.controller_request_thread_pool_queue_capacity = capacity;
363        self
364    }
365
366    /// Set controller storage path
367    pub fn with_controller_store_path(mut self, path: impl Into<String>) -> Self {
368        self.controller_store_path = path.into();
369        self
370    }
371
372    /// Set mapped file size
373    pub fn with_mapped_file_size(mut self, size: usize) -> Self {
374        self.mapped_file_size = size;
375        self
376    }
377
378    /// Set elect master max retry count
379    pub fn with_elect_master_max_retry_count(mut self, count: u32) -> Self {
380        self.elect_master_max_retry_count = count;
381        self
382    }
383
384    /// Enable or disable elect unclean master
385    pub fn with_enable_elect_unclean_master(mut self, enable: bool) -> Self {
386        self.enable_elect_unclean_master = enable;
387        self
388    }
389
390    /// Enable or disable process read event
391    pub fn with_process_read_event(mut self, enable: bool) -> Self {
392        self.is_process_read_event = enable;
393        self
394    }
395
396    /// Enable or disable notify broker role changed
397    pub fn with_notify_broker_role_changed(mut self, enable: bool) -> Self {
398        self.notify_broker_role_changed = enable;
399        self
400    }
401
402    /// Set scan inactive master interval
403    pub fn with_scan_inactive_master_interval(mut self, interval_ms: u64) -> Self {
404        self.scan_inactive_master_interval = interval_ms;
405        self
406    }
407
408    /// Set OpenRaft inactive-scan wait timeout.
409    pub fn with_raft_scan_wait_timeout_ms(mut self, timeout_ms: u64) -> Self {
410        self.raft_scan_wait_timeout_ms = timeout_ms;
411        self
412    }
413
414    /// Set metrics exporter type
415    pub fn with_metrics_exporter_type(mut self, exporter_type: MetricsExporterType) -> Self {
416        self.metrics_exporter_type = exporter_type;
417        self
418    }
419
420    /// Set metrics gRPC exporter configuration
421    pub fn with_metrics_grpc_exporter(mut self, target: impl Into<String>, header: impl Into<String>) -> Self {
422        self.metrics_grpc_exporter_target = target.into();
423        self.metrics_grpc_exporter_header = header.into();
424        self
425    }
426
427    /// Set metrics Prometheus exporter configuration
428    pub fn with_metrics_prom_exporter(mut self, host: impl Into<String>, port: u16) -> Self {
429        self.metrics_prom_exporter_host = host.into();
430        self.metrics_prom_exporter_port = port;
431        self
432    }
433
434    /// Set metrics label
435    pub fn with_metrics_label(mut self, label: impl Into<String>) -> Self {
436        self.metrics_label = label.into();
437        self
438    }
439
440    /// Set node id and listen address for node-specific usage
441    pub fn with_node_info(mut self, node_id: u64, listen_addr: SocketAddr) -> Self {
442        self.node_id = node_id;
443        self.listen_addr = listen_addr;
444        self
445    }
446
447    /// Set raft peers for bootstrapping
448    pub fn with_raft_peers(mut self, peers: Vec<RaftPeer>) -> Self {
449        self.raft_peers = peers;
450        self
451    }
452
453    /// Set controller remoting peers used for broker-facing metadata responses.
454    pub fn with_controller_peers(mut self, peers: Vec<RaftPeer>) -> Self {
455        self.controller_peers = peers;
456        self
457    }
458
459    /// Set election timeout (ms)
460    pub fn with_election_timeout_ms(mut self, ms: u64) -> Self {
461        self.election_timeout_ms = ms;
462        self
463    }
464
465    /// Set heartbeat interval (ms)
466    pub fn with_heartbeat_interval_ms(mut self, ms: u64) -> Self {
467        self.heartbeat_interval_ms = ms;
468        self
469    }
470
471    /// Set local storage path for this node
472    pub fn with_storage_path(mut self, path: impl Into<String>) -> Self {
473        self.storage_path = path.into();
474        self
475    }
476
477    /// Set whether to enable elect unclean master locally
478    pub fn with_enable_elect_unclean_master_local(mut self, enable: bool) -> Self {
479        self.enable_elect_unclean_master_local = enable;
480        self
481    }
482
483    /// Set storage backend for this node
484    pub fn with_storage_backend(mut self, backend: StorageBackendType) -> Self {
485        self.storage_backend = backend;
486        self
487    }
488
489    /// Set configuration blacklist
490    pub fn with_config_black_list(mut self, blacklist: impl Into<String>) -> Self {
491        self.config_black_list = blacklist.into();
492        self
493    }
494
495    /// Convenience constructor for a node-specific config (node id + listen addr)
496    pub fn new_node(node_id: u64, listen_addr: SocketAddr) -> Self {
497        Self::default().with_node_info(node_id, listen_addr)
498    }
499
500    /// Test config helper
501    pub fn test_config() -> Self {
502        Self::default().with_node_info(1, SocketAddr::from(([127, 0, 0, 1], 60109)))
503    }
504
505    /// Resolve the Raft RPC address for a node.
506    pub fn raft_addr_for(&self, node_id: u64) -> Option<SocketAddr> {
507        self.raft_peers
508            .iter()
509            .find(|peer| peer.id == node_id)
510            .map(|peer| peer.addr)
511    }
512
513    /// Resolve the local Raft RPC address, falling back to the remoting address for legacy configs.
514    pub fn local_raft_addr(&self) -> SocketAddr {
515        self.raft_addr_for(self.node_id).unwrap_or(self.listen_addr)
516    }
517
518    /// Resolve the broker-facing controller remoting address for a node.
519    pub fn controller_addr_for(&self, node_id: u64) -> Option<SocketAddr> {
520        if node_id == self.node_id {
521            return Some(self.listen_addr);
522        }
523
524        self.controller_peers
525            .iter()
526            .find(|peer| peer.id == node_id)
527            .map(|peer| peer.addr)
528    }
529
530    /// Return the broker-facing controller remoting addresses that should be advertised.
531    pub fn controller_peer_addrs(&self) -> Vec<SocketAddr> {
532        if self.controller_peers.is_empty() {
533            return vec![self.listen_addr];
534        }
535
536        let mut addrs = Vec::with_capacity(self.controller_peers.len() + 1);
537        addrs.push(self.listen_addr);
538        for peer in &self.controller_peers {
539            if !addrs.contains(&peer.addr) {
540                addrs.push(peer.addr);
541            }
542        }
543        addrs
544    }
545
546    /// Check if a configuration key is in the blacklist
547    pub fn is_config_in_blacklist(&self, key: &str) -> bool {
548        self.config_black_list.split(';').any(|item| item.trim() == key)
549    }
550
551    /// Validate the configuration
552    pub fn validate(&self) -> Result<(), String> {
553        if self.controller_type != RAFT_CONTROLLER {
554            return Err(format!(
555                "Invalid controller type: {}. Must be '{}'",
556                self.controller_type, RAFT_CONTROLLER
557            ));
558        }
559
560        if self.controller_thread_pool_nums == 0 {
561            return Err("controller_thread_pool_nums must be greater than 0".to_string());
562        }
563
564        if self.controller_request_thread_pool_queue_capacity == 0 {
565            return Err("controller_request_thread_pool_queue_capacity must be greater than 0".to_string());
566        }
567
568        if self.mapped_file_size == 0 {
569            return Err("mapped_file_size must be greater than 0".to_string());
570        }
571
572        if self.elect_master_max_retry_count == 0 {
573            return Err("elect_master_max_retry_count must be greater than 0".to_string());
574        }
575
576        Ok(())
577    }
578
579    /// Convert configuration to properties string format
580    ///
581    /// Returns a string in properties format (key=value\n) using camelCase naming
582    pub fn to_properties_string(&self) -> String {
583        use std::fmt::Write;
584
585        let mut result = String::with_capacity(2048);
586        macro_rules! write_property {
587            ($($arg:tt)*) => {
588                let _ = writeln!(result, $($arg)*);
589            };
590        }
591
592        write_property!("rocketmqHome={}", self.rocketmq_home);
593        write_property!("configStorePath={}", self.config_store_path.display());
594        write_property!("controllerType={}", self.controller_type);
595        write_property!("scanNotActiveBrokerInterval={}", self.scan_not_active_broker_interval);
596        write_property!("controllerThreadPoolNums={}", self.controller_thread_pool_nums);
597        write_property!(
598            "controllerRequestThreadPoolQueueCapacity={}",
599            self.controller_request_thread_pool_queue_capacity
600        );
601        write_property!("mappedFileSize={}", self.mapped_file_size);
602        write_property!("controllerStorePath={}", self.controller_store_path);
603        write_property!("electMasterMaxRetryCount={}", self.elect_master_max_retry_count);
604        write_property!("enableElectUncleanMaster={}", self.enable_elect_unclean_master);
605        write_property!("isProcessReadEvent={}", self.is_process_read_event);
606        write_property!("notifyBrokerRoleChanged={}", self.notify_broker_role_changed);
607        write_property!("scanInactiveMasterInterval={}", self.scan_inactive_master_interval);
608        write_property!("raftScanWaitTimeoutMs={}", self.raft_scan_wait_timeout_ms);
609        write_property!("metricsExporterType={}", self.metrics_exporter_type);
610        write_property!("metricsGrpcExporterTarget={}", self.metrics_grpc_exporter_target);
611        write_property!("metricsGrpcExporterHeader={}", self.metrics_grpc_exporter_header);
612        write_property!(
613            "metricGrpcExporterTimeOutInMills={}",
614            self.metric_grpc_exporter_time_out_in_mills
615        );
616        write_property!(
617            "metricGrpcExporterIntervalInMills={}",
618            self.metric_grpc_exporter_interval_in_mills
619        );
620        write_property!(
621            "metricLoggingExporterIntervalInMills={}",
622            self.metric_logging_exporter_interval_in_mills
623        );
624        write_property!("metricsPromExporterPort={}", self.metrics_prom_exporter_port);
625        write_property!("metricsPromExporterHost={}", self.metrics_prom_exporter_host);
626        write_property!("metricsLabel={}", self.metrics_label);
627        write_property!("metricsInDelta={}", self.metrics_in_delta);
628        write_property!("configBlackList={}", self.config_black_list);
629        write_property!("nodeId={}", self.node_id);
630        write_property!("listenAddr={}", self.listen_addr);
631
632        let peers: Vec<String> = self
633            .raft_peers
634            .iter()
635            .map(|peer| format!("{}-{}", peer.id, peer.addr))
636            .collect();
637        write_property!("raftPeers={}", peers.join(";"));
638
639        let controller_peers: Vec<String> = self
640            .controller_peers
641            .iter()
642            .map(|peer| format!("{}-{}", peer.id, peer.addr))
643            .collect();
644        write_property!("controllerPeers={}", controller_peers.join(";"));
645
646        write_property!("electionTimeoutMs={}", self.election_timeout_ms);
647        write_property!("heartbeatIntervalMs={}", self.heartbeat_interval_ms);
648        write_property!("storagePath={}", self.storage_path);
649        write_property!("storageBackend={}", self.storage_backend);
650        write_property!(
651            "enableElectUncleanMasterLocal={}",
652            self.enable_elect_unclean_master_local
653        );
654
655        result
656    }
657    pub async fn update(&mut self, properties: HashMap<String, String>) -> RocketMQResult<()> {
658        let lock = self.rw_lock.write().await;
659        for (key, value) in &properties {
660            match key.as_str() {
661                "rocketmqHome" => {
662                    self.rocketmq_home = value.clone();
663                }
664
665                "configStorePath" => {
666                    self.config_store_path =
667                        serde_json::from_str::<PathBuf>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
668                }
669
670                "controllerType" => {
671                    self.controller_type = value.clone();
672                }
673
674                "scanNotActiveBrokerInterval" => {
675                    self.scan_not_active_broker_interval =
676                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
677                }
678
679                "controllerThreadPoolNums" => {
680                    self.controller_thread_pool_nums =
681                        serde_json::from_str::<usize>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
682                }
683
684                "controllerRequestThreadPoolQueueCapacity" => {
685                    self.controller_request_thread_pool_queue_capacity =
686                        serde_json::from_str::<usize>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
687                }
688
689                "mappedFileSize" => {
690                    self.mapped_file_size =
691                        serde_json::from_str::<usize>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
692                }
693
694                "controllerStorePath" => {
695                    self.controller_store_path = value.clone();
696                }
697
698                "electMasterMaxRetryCount" => {
699                    self.elect_master_max_retry_count =
700                        serde_json::from_str::<u32>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
701                }
702
703                "enableElectUncleanMaster" => {
704                    self.enable_elect_unclean_master =
705                        serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
706                }
707
708                "isProcessReadEvent" => {
709                    self.is_process_read_event =
710                        serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
711                }
712
713                "notifyBrokerRoleChanged" => {
714                    self.notify_broker_role_changed =
715                        serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
716                }
717
718                "scanInactiveMasterInterval" => {
719                    self.scan_inactive_master_interval =
720                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
721                }
722
723                "raftScanWaitTimeoutMs" | "jRaftScanWaitTimeoutMs" => {
724                    self.raft_scan_wait_timeout_ms =
725                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
726                }
727
728                "metricsExporterType" => {
729                    self.metrics_exporter_type = serde_json::from_str::<MetricsExporterType>(value)
730                        .map_err(|e| RocketMQError::Internal(e.to_string()))?;
731                }
732
733                "metricsGrpcExporterTarget" => {
734                    self.metrics_grpc_exporter_target = value.clone();
735                }
736
737                "metricsGrpcExporterHeader" => {
738                    self.metrics_grpc_exporter_header = value.clone();
739                }
740
741                "metricGrpcExporterTimeOutInMills" => {
742                    self.metric_grpc_exporter_time_out_in_mills =
743                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
744                }
745
746                "metricGrpcExporterIntervalInMills" => {
747                    self.metric_grpc_exporter_interval_in_mills =
748                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
749                }
750
751                "metricLoggingExporterIntervalInMills" => {
752                    self.metric_logging_exporter_interval_in_mills =
753                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
754                }
755
756                "metricsPromExporterPort" => {
757                    self.metrics_prom_exporter_port =
758                        serde_json::from_str::<u16>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
759                }
760
761                "metricsPromExporterHost" => {
762                    self.metrics_prom_exporter_host = value.clone();
763                }
764
765                "metricsLabel" => {
766                    self.metrics_label = value.clone();
767                }
768
769                "metricsInDelta" => {
770                    self.metrics_in_delta =
771                        serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
772                }
773
774                "configBlackList" => {
775                    self.config_black_list = value.clone();
776                }
777
778                "nodeId" => {
779                    self.node_id =
780                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
781                }
782
783                "listenAddr" => {
784                    self.listen_addr = serde_json::from_str::<SocketAddr>(value)
785                        .map_err(|e| RocketMQError::Internal(e.to_string()))?;
786                }
787
788                "raftPeers" => {
789                    self.raft_peers = serde_json::from_str::<Vec<RaftPeer>>(value)
790                        .map_err(|e| RocketMQError::Internal(e.to_string()))?;
791                }
792
793                "controllerPeers" => {
794                    self.controller_peers = serde_json::from_str::<Vec<RaftPeer>>(value)
795                        .map_err(|e| RocketMQError::Internal(e.to_string()))?;
796                }
797
798                "electionTimeoutMs" => {
799                    self.election_timeout_ms =
800                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
801                }
802
803                "heartbeatIntervalMs" => {
804                    self.heartbeat_interval_ms =
805                        serde_json::from_str::<u64>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
806                }
807
808                "storagePath" => {
809                    self.storage_path = value.clone();
810                }
811
812                "storageBackend" => {
813                    self.storage_backend = serde_json::from_str::<StorageBackendType>(value)
814                        .map_err(|e| RocketMQError::Internal(e.to_string()))?;
815                }
816
817                "enableElectUncleanMasterLocal" => {
818                    self.enable_elect_unclean_master_local =
819                        serde_json::from_str::<bool>(value).map_err(|e| RocketMQError::Internal(e.to_string()))?;
820                }
821                _ => {
822                    return Err(RocketMQError::Internal(format!("found unknown property: {}", key)));
823                }
824            }
825        }
826        Ok(())
827    }
828}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833
834    #[test]
835    fn test_controller_config_default() {
836        let config = ControllerConfig::default();
837
838        assert_eq!(config.controller_type, RAFT_CONTROLLER);
839        assert_eq!(config.scan_not_active_broker_interval, 5000);
840        assert_eq!(config.controller_thread_pool_nums, 16);
841        assert_eq!(config.controller_request_thread_pool_queue_capacity, 50000);
842        assert_eq!(config.mapped_file_size, 1024 * 1024 * 1024);
843        assert_eq!(config.elect_master_max_retry_count, 3);
844        assert!(!config.enable_elect_unclean_master);
845        assert!(!config.is_process_read_event);
846        assert!(config.notify_broker_role_changed);
847        assert_eq!(config.metrics_prom_exporter_port, 5557);
848    }
849
850    #[test]
851    fn test_controller_config_builder() {
852        let config = ControllerConfig::new()
853            .with_controller_type(RAFT_CONTROLLER)
854            .with_scan_not_active_broker_interval(10000)
855            .with_controller_thread_pool_nums(32)
856            .with_enable_elect_unclean_master(true);
857
858        assert_eq!(config.controller_type, RAFT_CONTROLLER);
859        assert_eq!(config.scan_not_active_broker_interval, 10000);
860        assert_eq!(config.controller_thread_pool_nums, 32);
861        assert!(config.enable_elect_unclean_master);
862    }
863
864    #[test]
865    fn test_config_validation_invalid_type() {
866        let config = ControllerConfig {
867            controller_type: "InvalidType".to_string(),
868            ..Default::default()
869        };
870
871        assert!(config.validate().is_err());
872    }
873
874    #[test]
875    fn test_config_validation_success() {
876        let config = ControllerConfig::new();
877
878        assert!(config.validate().is_ok());
879    }
880
881    #[test]
882    fn test_config_blacklist() {
883        let config = ControllerConfig::default();
884
885        assert!(config.is_config_in_blacklist("configBlackList"));
886        assert!(config.is_config_in_blacklist("configStorePath"));
887        assert!(!config.is_config_in_blacklist("controllerType"));
888    }
889
890    #[test]
891    fn test_metrics_config() {
892        let config = ControllerConfig::new()
893            .with_metrics_exporter_type(MetricsExporterType::Prom)
894            .with_metrics_prom_exporter("localhost", 9090)
895            .with_metrics_label("instance_id:test,uid:123");
896
897        assert_eq!(config.metrics_exporter_type, MetricsExporterType::Prom);
898        assert_eq!(config.metrics_prom_exporter_host, "localhost");
899        assert_eq!(config.metrics_prom_exporter_port, 9090);
900        assert_eq!(config.metrics_label, "instance_id:test,uid:123");
901    }
902
903    #[test]
904    fn test_to_properties_string_basic() {
905        let config = ControllerConfig::default();
906        let result = config.to_properties_string();
907
908        assert!(result.contains("rocketmqHome="));
909        assert!(result.contains("controllerType=Raft"));
910        assert!(result.contains("scanNotActiveBrokerInterval=5000"));
911        assert!(result.contains("controllerThreadPoolNums=16"));
912        assert!(result.contains("notifyBrokerRoleChanged=true"));
913        assert!(result.contains("enableElectUncleanMaster=false"));
914    }
915
916    #[test]
917    fn test_to_properties_string_format() {
918        let config = ControllerConfig::default();
919        let result = config.to_properties_string();
920
921        let lines: Vec<&str> = result.lines().collect();
922        assert!(!lines.is_empty());
923
924        for line in lines {
925            assert!(line.contains('='), "Each line should contain '=': {}", line);
926            let parts: Vec<&str> = line.split('=').collect();
927            assert_eq!(parts.len(), 2, "Each line should have exactly one '=': {}", line);
928        }
929    }
930
931    #[test]
932    fn test_to_properties_string_with_custom_config() {
933        let config = ControllerConfig::new()
934            .with_controller_type(RAFT_CONTROLLER)
935            .with_scan_not_active_broker_interval(10000)
936            .with_controller_thread_pool_nums(32)
937            .with_enable_elect_unclean_master(true)
938            .with_storage_backend(StorageBackendType::RocksDB);
939
940        let result = config.to_properties_string();
941
942        assert!(result.contains("controllerType=Raft"));
943        assert!(result.contains("scanNotActiveBrokerInterval=10000"));
944        assert!(result.contains("controllerThreadPoolNums=32"));
945        assert!(result.contains("enableElectUncleanMaster=true"));
946        assert!(result.contains("storageBackend=rocks_db"));
947    }
948
949    #[test]
950    fn test_to_properties_string_with_raft_peers() {
951        let config = ControllerConfig::new().with_raft_peers(vec![
952            RaftPeer {
953                id: 1,
954                addr: "127.0.0.1:9877".parse().unwrap(),
955            },
956            RaftPeer {
957                id: 2,
958                addr: "127.0.0.1:9878".parse().unwrap(),
959            },
960        ]);
961
962        let result = config.to_properties_string();
963
964        assert!(result.contains("raftPeers=1-127.0.0.1:9877;2-127.0.0.1:9878"));
965    }
966}