batata_client/common/
utils.rs

1use std::collections::HashMap;
2use uuid::Uuid;
3
4/// Generate a unique request ID
5pub fn generate_request_id() -> String {
6    Uuid::new_v4().to_string()
7}
8
9/// Calculate MD5 hash of content
10pub fn md5_hash(content: &str) -> String {
11    format!("{:x}", md5::compute(content.as_bytes()))
12}
13
14/// Build group key for configuration
15pub fn build_config_key(data_id: &str, group: &str, namespace: &str) -> String {
16    if namespace.is_empty() {
17        format!("{}+{}", data_id, group)
18    } else {
19        format!("{}+{}+{}", data_id, group, namespace)
20    }
21}
22
23/// Build service key for naming
24pub fn build_service_key(service_name: &str, group_name: &str, namespace: &str) -> String {
25    format!("{}@@{}@@{}", namespace, group_name, service_name)
26}
27
28/// Parse server address to host and port
29pub fn parse_server_address(address: &str) -> (String, u16) {
30    if let Some((host, port_str)) = address.rsplit_once(':')
31        && let Ok(port) = port_str.parse::<u16>()
32    {
33        return (host.to_string(), port);
34    }
35    (address.to_string(), super::constants::DEFAULT_SERVER_PORT)
36}
37
38/// Get current timestamp in milliseconds
39pub fn current_time_millis() -> i64 {
40    chrono::Utc::now().timestamp_millis()
41}
42
43/// Merge two HashMaps
44pub fn merge_maps(
45    base: &HashMap<String, String>,
46    override_map: &HashMap<String, String>,
47) -> HashMap<String, String> {
48    let mut result = base.clone();
49    for (k, v) in override_map {
50        result.insert(k.clone(), v.clone());
51    }
52    result
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_generate_request_id() {
61        let id1 = generate_request_id();
62        let id2 = generate_request_id();
63        assert_ne!(id1, id2);
64        assert!(!id1.is_empty());
65    }
66
67    #[test]
68    fn test_md5_hash() {
69        let hash = md5_hash("test content");
70        assert_eq!(hash.len(), 32);
71    }
72
73    #[test]
74    fn test_build_config_key() {
75        assert_eq!(
76            build_config_key("dataId", "group", "namespace"),
77            "dataId+group+namespace"
78        );
79        assert_eq!(build_config_key("dataId", "group", ""), "dataId+group");
80    }
81
82    #[test]
83    fn test_parse_server_address() {
84        assert_eq!(
85            parse_server_address("localhost:8848"),
86            ("localhost".to_string(), 8848)
87        );
88        assert_eq!(
89            parse_server_address("localhost"),
90            ("localhost".to_string(), 8848)
91        );
92    }
93}