nacos_sdk/api/
props.rs

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
use std::collections::HashMap;

use crate::api::constants::*;
use crate::properties::{get_value, get_value_bool, get_value_option, get_value_u32};

/// Configures settings for Client.
#[derive(Debug, Clone)]
pub struct ClientProps {
    /// server_addr e.g: 127.0.0.1:8848; 192.168.0.1
    server_addr: String,
    /// grpc port
    grpc_port: Option<u32>,
    /// public is "", Should define a more meaningful namespace
    namespace: String,
    /// app_name
    app_name: String,
    /// naming push_empty_protection, default true
    naming_push_empty_protection: bool,
    /// naming load_cache_at_start, default false
    naming_load_cache_at_start: bool,
    /// env_first when get props, default true
    env_first: bool,
    /// metadata
    labels: HashMap<String, String>,
    /// client_version
    client_version: String,
    /// auth context
    auth_context: HashMap<String, String>,
    /// max retries
    max_retries: Option<u32>,
}

impl ClientProps {
    pub(crate) fn get_server_addr(&self) -> String {
        if self.env_first {
            get_value(
                ENV_NACOS_CLIENT_COMMON_SERVER_ADDRESS,
                self.server_addr.clone(),
            )
        } else {
            self.server_addr.clone()
        }
    }

    pub(crate) fn get_remote_grpc_port(&self) -> Option<u32> {
        self.grpc_port
    }

    pub(crate) fn get_namespace(&self) -> String {
        if self.env_first {
            get_value(ENV_NACOS_CLIENT_COMMON_NAMESPACE, self.namespace.clone())
        } else {
            self.namespace.clone()
        }
    }

    pub(crate) fn get_app_name(&self) -> String {
        if self.env_first {
            get_value(ENV_NACOS_CLIENT_COMMON_APP_NAME, self.app_name.clone())
        } else {
            self.app_name.clone()
        }
    }

    pub(crate) fn get_naming_push_empty_protection(&self) -> bool {
        if self.env_first {
            get_value_bool(
                ENV_NACOS_CLIENT_NAMING_PUSH_EMPTY_PROTECTION,
                self.naming_push_empty_protection,
            )
        } else {
            self.naming_push_empty_protection
        }
    }

    pub(crate) fn get_naming_load_cache_at_start(&self) -> bool {
        if self.env_first {
            get_value_bool(
                ENV_NACOS_CLIENT_NAMING_LOAD_CACHE_AT_START,
                self.naming_load_cache_at_start,
            )
        } else {
            self.naming_load_cache_at_start
        }
    }

    pub(crate) fn get_labels(&self) -> HashMap<String, String> {
        let mut labels = self.labels.clone();
        labels.insert(KEY_LABEL_APP_NAME.to_string(), self.get_app_name());
        labels
    }

    pub(crate) fn get_client_version(&self) -> String {
        self.client_version.clone()
    }

    pub(crate) fn get_auth_context(&self) -> HashMap<String, String> {
        let mut auth_context = self.auth_context.clone();
        if self.env_first {
            #[cfg(feature = "auth-by-http")]
            self.get_http_auth_context(&mut auth_context);
            #[cfg(feature = "auth-by-aliyun")]
            self.get_aliyun_auth_context(&mut auth_context);
        }
        auth_context
    }

    #[cfg(feature = "auth-by-http")]
    fn get_http_auth_context(&self, context: &mut HashMap<String, String>) {
        if let Some(u) = get_value_option(ENV_NACOS_CLIENT_AUTH_USERNAME) {
            context.insert(crate::api::plugin::USERNAME.into(), u);
        }
        if let Some(p) = get_value_option(ENV_NACOS_CLIENT_AUTH_PASSWORD) {
            context.insert(crate::api::plugin::PASSWORD.into(), p);
        }
    }

    #[cfg(feature = "auth-by-aliyun")]
    fn get_aliyun_auth_context(&self, context: &mut HashMap<String, String>) {
        if let Some(ak) = get_value_option(ENV_NACOS_CLIENT_AUTH_ACCESS_KEY) {
            context.insert(crate::api::plugin::ACCESS_KEY.into(), ak);
        }
        if let Some(sk) = get_value_option(ENV_NACOS_CLIENT_AUTH_ACCESS_SECRET) {
            context.insert(crate::api::plugin::ACCESS_SECRET.into(), sk);
        }
        if let Some(sign_region_id) = get_value_option(ENV_NACOS_CLIENT_SIGN_REGION_ID) {
            context.insert(crate::api::plugin::SIGN_REGION_ID.into(), sign_region_id);
        }
    }

    pub(crate) fn get_server_list(&self) -> crate::api::error::Result<Vec<String>> {
        let server_addr = self.get_server_addr();
        if server_addr.trim().is_empty() {
            return Err(crate::api::error::Error::WrongServerAddress(String::from(
                "Server address is empty",
            )));
        }
        let hosts: Vec<&str> = server_addr.trim().split(',').collect::<Vec<&str>>();
        let mut result = vec![];
        for host in hosts {
            let host_port = host.split(':').collect::<Vec<&str>>();
            if host_port.len() == 1 {
                result.push(format!(
                    "{}:{}",
                    host,
                    get_value_u32(ENV_NACOS_CLIENT_COMMON_SERVER_PORT, DEFAULT_SERVER_PORT,)
                ));
                continue;
            }
            result.push(host.to_string());
        }

        Ok(result)
    }

    pub(crate) fn get_max_retries(&self) -> Option<u32> {
        self.max_retries
    }
}

#[allow(clippy::new_without_default)]
impl ClientProps {
    /// Creates a new `ClientConfig`.
    pub fn new() -> Self {
        let env_project_version = env!("CARGO_PKG_VERSION");
        let client_version = format!("Nacos-Rust-Client:{}", env_project_version);

        ClientProps {
            server_addr: String::from(DEFAULT_SERVER_ADDR),
            namespace: String::from(""),
            app_name: UNKNOWN.to_string(),
            naming_push_empty_protection: true,
            naming_load_cache_at_start: false,
            env_first: true,
            labels: HashMap::default(),
            client_version,
            auth_context: HashMap::default(),
            grpc_port: None,
            max_retries: None,
        }
    }

    /// Sets the server addr.
    pub fn server_addr(mut self, server_addr: impl Into<String>) -> Self {
        self.server_addr = server_addr.into();
        self
    }

    /// Sets the grpc port
    pub fn remote_grpc_port(mut self, grpc_port: u32) -> Self {
        self.grpc_port = Some(grpc_port);
        self
    }

    /// Sets the namespace.
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = namespace.into();
        self
    }

    /// Sets the app_name.
    pub fn app_name(mut self, app_name: impl Into<String>) -> Self {
        self.app_name = app_name.into();
        self
    }

    /// Sets the naming_push_empty_protection.
    pub fn naming_push_empty_protection(mut self, naming_push_empty_protection: bool) -> Self {
        self.naming_push_empty_protection = naming_push_empty_protection;
        self
    }

    /// Sets the naming_load_cache_at_start.
    pub fn naming_load_cache_at_start(mut self, naming_load_cache_at_start: bool) -> Self {
        self.naming_load_cache_at_start = naming_load_cache_at_start;
        self
    }

    /// Sets the env_first.
    pub fn env_first(mut self, env_first: bool) -> Self {
        self.env_first = env_first;
        self
    }

    /// Sets the labels.
    pub fn labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels.extend(labels);
        self
    }

    /// Add auth username.
    #[cfg(feature = "auth-by-http")]
    pub fn auth_username(mut self, username: impl Into<String>) -> Self {
        self.auth_context
            .insert(crate::api::plugin::USERNAME.into(), username.into());
        self
    }

    /// Add auth password.
    #[cfg(feature = "auth-by-http")]
    pub fn auth_password(mut self, password: impl Into<String>) -> Self {
        self.auth_context
            .insert(crate::api::plugin::PASSWORD.into(), password.into());
        self
    }

    /// Add access-key
    #[cfg(feature = "auth-by-aliyun")]
    pub fn auth_access_key(mut self, access_key: impl Into<String>) -> Self {
        self.auth_context
            .insert(crate::api::plugin::ACCESS_KEY.into(), access_key.into());
        self
    }

    /// Add access-secret
    #[cfg(feature = "auth-by-aliyun")]
    pub fn auth_access_secret(mut self, access_secret: impl Into<String>) -> Self {
        self.auth_context.insert(
            crate::api::plugin::ACCESS_SECRET.into(),
            access_secret.into(),
        );
        self
    }

    /// Add signature region id
    #[cfg(feature = "auth-by-aliyun")]
    pub fn auth_signature_region_id(mut self, signature_region_id: impl Into<String>) -> Self {
        self.auth_context.insert(
            crate::api::plugin::SIGN_REGION_ID.into(),
            signature_region_id.into(),
        );
        self
    }

    /// Add auth ext params.
    pub fn auth_ext(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
        self.auth_context.insert(key.into(), val.into());
        self
    }

    /// Sets the max retries.
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }
}

#[cfg(test)]
mod tests {
    use crate::api::error::Error;

    use super::*;

    #[test]
    fn test_get_server_list() {
        let client_props = ClientProps {
            server_addr: "127.0.0.1:8848,192.168.0.1".to_string(),
            grpc_port: Some(8888),
            namespace: "test_namespace".to_string(),
            app_name: "test_app".to_string(),
            naming_push_empty_protection: true,
            naming_load_cache_at_start: false,
            env_first: true,
            labels: HashMap::new(),
            client_version: "test_version".to_string(),
            auth_context: HashMap::new(),
            max_retries: None,
        };

        let result = client_props.get_server_list();
        assert!(result.is_ok());
        match result {
            Ok(ref vec) => {
                assert!(vec.contains(&"127.0.0.1:8848".to_string()));
                assert!(vec.contains(&"192.168.0.1:8848".to_string()));
            }
            Err(_) => {}
        }
        let client_props = client_props.server_addr(String::from("     "));
        let result1 = client_props.get_server_list();
        assert!(result1.is_err());
        assert_eq!(
            format!("{}", result1.err().unwrap()),
            format!(
                "{}",
                Error::WrongServerAddress("Server address is empty".to_string())
            )
        );
    }
}