nacos_sdk/api/
config.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
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
use std::collections::HashMap;
use std::sync::Arc;

use crate::api::{error, plugin, props};

/// Api [`ConfigService`].
///
/// # Examples
///
/// ```ignore
///  let mut config_service = nacos_sdk::api::config::ConfigServiceBuilder::new(
///        nacos_sdk::api::props::ClientProps::new()
///           .server_addr("127.0.0.1:8848")
///           // Attention! "public" is "", it is recommended to customize the namespace with clear meaning.
///           .namespace("")
///           .app_name("todo-your-app-name"),
///   )
///   .build()?;
/// ```
#[doc(alias("config", "sdk", "api"))]
#[async_trait::async_trait]
pub trait ConfigService: Send + Sync {
    /// Get config, return the content.
    ///
    /// Attention to [`error::Error::ConfigNotFound`], [`error::Error::ConfigQueryConflict`]
    async fn get_config(&self, data_id: String, group: String) -> error::Result<ConfigResponse>;

    /// Publish config, return true/false.
    async fn publish_config(
        &self,
        data_id: String,
        group: String,
        content: String,
        content_type: Option<String>,
    ) -> error::Result<bool>;

    /// Cas publish config with cas_md5 (prev content's md5), return true/false.
    async fn publish_config_cas(
        &self,
        data_id: String,
        group: String,
        content: String,
        content_type: Option<String>,
        cas_md5: String,
    ) -> error::Result<bool>;

    /// Beta publish config, return true/false.
    async fn publish_config_beta(
        &self,
        data_id: String,
        group: String,
        content: String,
        content_type: Option<String>,
        beta_ips: String,
    ) -> error::Result<bool>;

    /// Publish config with params (see keys [`constants::*`]), return true/false.
    async fn publish_config_param(
        &self,
        data_id: String,
        group: String,
        content: String,
        content_type: Option<String>,
        cas_md5: Option<String>,
        params: HashMap<String, String>,
    ) -> error::Result<bool>;

    /// Remove config, return true/false.
    async fn remove_config(&self, data_id: String, group: String) -> error::Result<bool>;

    /// Listen the config change.
    async fn add_listener(
        &self,
        data_id: String,
        group: String,
        listener: Arc<dyn ConfigChangeListener>,
    ) -> error::Result<()>;

    /// Remove a Listener.
    async fn remove_listener(
        &self,
        data_id: String,
        group: String,
        listener: Arc<dyn ConfigChangeListener>,
    ) -> error::Result<()>;
}
/// The ConfigChangeListener receive a notify of [`ConfigResponse`].
pub trait ConfigChangeListener: Send + Sync {
    fn notify(&self, config_resp: ConfigResponse);
}

/// ConfigResponse for api.
#[derive(Debug, Clone)]
pub struct ConfigResponse {
    /// Namespace/Tenant
    namespace: String,
    /// DataId
    data_id: String,
    /// Group
    group: String,
    /// Content
    content: String,
    /// Content's Type; e.g. json,properties,xml,html,text,yaml
    content_type: String,
    /// Content's md5
    md5: String,
}

impl std::fmt::Display for ConfigResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut content = self.content.clone();
        if content.len() > 30 {
            content.truncate(30);
            content.push_str("...");
        }
        write!(
            f,
            "ConfigResponse(namespace={n},data_id={d},group={g},md5={m},content={c})",
            n = self.namespace,
            d = self.data_id,
            g = self.group,
            m = self.md5,
            c = content
        )
    }
}

impl ConfigResponse {
    pub fn new(
        data_id: String,
        group: String,
        namespace: String,
        content: String,
        content_type: String,
        md5: String,
    ) -> Self {
        ConfigResponse {
            data_id,
            group,
            namespace,
            content,
            content_type,
            md5,
        }
    }

    pub fn namespace(&self) -> &String {
        &self.namespace
    }
    pub fn data_id(&self) -> &String {
        &self.data_id
    }
    pub fn group(&self) -> &String {
        &self.group
    }
    pub fn content(&self) -> &String {
        &self.content
    }
    pub fn content_type(&self) -> &String {
        &self.content_type
    }
    pub fn md5(&self) -> &String {
        &self.md5
    }
}

pub mod constants {
    /// param type, use for [`crate::api::config::ConfigService::publish_config_param`]
    pub const KEY_PARAM_CONTENT_TYPE: &str = "type";

    /// param betaIps, use for [`crate::api::config::ConfigService::publish_config_param`]
    pub const KEY_PARAM_BETA_IPS: &str = "betaIps";

    /// param appName, use for [`crate::api::config::ConfigService::publish_config_param`]
    pub const KEY_PARAM_APP_NAME: &str = "appName";

    /// param tag, use for [`crate::api::config::ConfigService::publish_config_param`]
    pub const KEY_PARAM_TAG: &str = "tag";

    /// param encryptedDataKey, use inner.
    pub(crate) const KEY_PARAM_ENCRYPTED_DATA_KEY: &str = "encryptedDataKey";
}

/// Builder of api [`ConfigService`].
///
/// # Examples
///
/// ```ignore
///  let mut config_service = nacos_sdk::api::config::ConfigServiceBuilder::new(
///        nacos_sdk::api::props::ClientProps::new()
///           .server_addr("127.0.0.1:8848")
///           // Attention! "public" is "", it is recommended to customize the namespace with clear meaning.
///           .namespace("")
///           .app_name("todo-your-app-name"),
///   )
///   .build()?;
/// ```
#[doc(alias("config", "builder"))]
pub struct ConfigServiceBuilder {
    client_props: props::ClientProps,
    auth_plugin: Option<Arc<dyn plugin::AuthPlugin>>,
    config_filters: Vec<Box<dyn plugin::ConfigFilter>>,
}

impl Default for ConfigServiceBuilder {
    fn default() -> Self {
        ConfigServiceBuilder {
            client_props: props::ClientProps::new(),
            auth_plugin: None,
            config_filters: Vec::new(),
        }
    }
}

impl ConfigServiceBuilder {
    pub fn new(client_props: props::ClientProps) -> Self {
        ConfigServiceBuilder {
            client_props,
            auth_plugin: None,
            config_filters: Vec::new(),
        }
    }

    #[cfg(feature = "auth-by-http")]
    pub fn enable_auth_plugin_http(self) -> Self {
        self.with_auth_plugin(Arc::new(plugin::HttpLoginAuthPlugin::default()))
    }

    #[cfg(feature = "auth-by-aliyun")]
    pub fn enable_auth_plugin_aliyun(self) -> Self {
        self.with_auth_plugin(Arc::new(plugin::AliyunRamAuthPlugin::default()))
    }

    /// Set [`plugin::AuthPlugin`]
    pub fn with_auth_plugin(mut self, auth_plugin: Arc<dyn plugin::AuthPlugin>) -> Self {
        self.auth_plugin = Some(auth_plugin);
        self
    }

    pub fn with_config_filters(
        mut self,
        config_filters: Vec<Box<dyn plugin::ConfigFilter>>,
    ) -> Self {
        self.config_filters = config_filters;
        self
    }

    pub fn add_config_filter(mut self, config_filter: Box<dyn plugin::ConfigFilter>) -> Self {
        self.config_filters.push(config_filter);
        self
    }

    /// Add [`plugin::EncryptionPlugin`], they will wrapper with [`plugin::ConfigEncryptionFilter`] into [`config_filters`]
    pub fn with_encryption_plugins(
        self,
        encryption_plugins: Vec<Box<dyn plugin::EncryptionPlugin>>,
    ) -> Self {
        self.add_config_filter(Box::new(plugin::ConfigEncryptionFilter::new(
            encryption_plugins,
        )))
    }

    /// Builds a new [`ConfigService`].
    pub fn build(self) -> error::Result<impl ConfigService> {
        let auth_plugin = match self.auth_plugin {
            None => Arc::new(plugin::NoopAuthPlugin::default()),
            Some(plugin) => plugin,
        };
        crate::config::NacosConfigService::new(self.client_props, auth_plugin, self.config_filters)
    }
}

#[cfg(test)]
mod tests {
    use crate::api::config::ConfigServiceBuilder;
    use crate::api::config::{ConfigChangeListener, ConfigResponse, ConfigService};
    use std::collections::HashMap;
    use std::time::Duration;
    use tokio::time::sleep;

    struct TestConfigChangeListener;

    impl ConfigChangeListener for TestConfigChangeListener {
        fn notify(&self, config_resp: ConfigResponse) {
            tracing::info!("listen the config={}", config_resp);
        }
    }

    #[tokio::test]
    #[ignore]
    async fn test_api_config_service() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();

        let (data_id, group) = ("test_api_config_service".to_string(), "TEST".to_string());

        let config_service = ConfigServiceBuilder::default().build().unwrap();

        // publish a config
        let _publish_resp = config_service
            .publish_config(
                data_id.clone(),
                group.clone(),
                "test_api_config_service".to_string(),
                Some("text".to_string()),
            )
            .await
            .unwrap();
        // sleep for config sync in server
        sleep(Duration::from_millis(111)).await;

        let config = config_service
            .get_config(data_id.clone(), group.clone())
            .await;
        match config {
            Ok(config) => tracing::info!("get the config {}", config),
            Err(err) => tracing::error!("get the config {:?}", err),
        }

        let _listen = config_service
            .add_listener(
                data_id.clone(),
                group.clone(),
                std::sync::Arc::new(TestConfigChangeListener {}),
            )
            .await;
        match _listen {
            Ok(_) => tracing::info!("listening the config success"),
            Err(err) => tracing::error!("listen config error {:?}", err),
        }

        // publish a config for listener
        let _publish_resp = config_service
            .publish_config(
                data_id.clone(),
                group.clone(),
                "test_api_config_service_for_listener".to_string(),
                Some("text".to_string()),
            )
            .await
            .unwrap();

        // example get a config not exit
        let config_resp = config_service
            .get_config("todo-data-id".to_string(), "todo-group".to_string())
            .await;
        match config_resp {
            Ok(config_resp) => tracing::info!("get the config {}", config_resp),
            Err(err) => tracing::error!("get the config {:?}", err),
        }

        // example add a listener with config not exit
        let _listen = config_service
            .add_listener(
                "todo-data-id".to_string(),
                "todo-group".to_string(),
                std::sync::Arc::new(TestConfigChangeListener {}),
            )
            .await;
        match _listen {
            Ok(_) => tracing::info!("listening the config success"),
            Err(err) => tracing::error!("listen config error {:?}", err),
        }

        // sleep for listener
        sleep(Duration::from_millis(111)).await;
    }

    #[tokio::test]
    #[ignore]
    async fn test_api_config_service_remove_config() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();

        let config_service = ConfigServiceBuilder::default().build().unwrap();

        // remove a config not exit
        let remove_resp = config_service
            .remove_config("todo-data-id".to_string(), "todo-group".to_string())
            .await;
        match remove_resp {
            Ok(result) => tracing::info!("remove a config not exit: {}", result),
            Err(err) => tracing::error!("remove a config not exit: {:?}", err),
        }
    }

    #[tokio::test]
    #[ignore]
    async fn test_api_config_service_publish_config() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();

        let config_service = ConfigServiceBuilder::default().build().unwrap();

        // publish a config
        let publish_resp = config_service
            .publish_config(
                "test_api_config_service_publish_config".to_string(),
                "TEST".to_string(),
                "test_api_config_service_publish_config".to_string(),
                Some("text".to_string()),
            )
            .await
            .unwrap();
        tracing::info!("publish a config: {}", publish_resp);
        assert_eq!(true, publish_resp);
    }

    #[tokio::test]
    #[ignore]
    async fn test_api_config_service_publish_config_param() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();

        let config_service = ConfigServiceBuilder::default().build().unwrap();

        let mut params = HashMap::new();
        params.insert(
            crate::api::config::constants::KEY_PARAM_APP_NAME.into(),
            "test".into(),
        );
        // publish a config with param
        let publish_resp = config_service
            .publish_config_param(
                "test_api_config_service_publish_config_param".to_string(),
                "TEST".to_string(),
                "test_api_config_service_publish_config_param".to_string(),
                None,
                None,
                params,
            )
            .await
            .unwrap();
        tracing::info!("publish a config with param: {}", publish_resp);
        assert_eq!(true, publish_resp);
    }

    #[tokio::test]
    #[ignore]
    async fn test_api_config_service_publish_config_beta() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();

        let config_service = ConfigServiceBuilder::default().build().unwrap();

        // publish a config with beta
        let publish_resp = config_service
            .publish_config_beta(
                "test_api_config_service_publish_config".to_string(),
                "TEST".to_string(),
                "test_api_config_service_publish_config_beta".to_string(),
                None,
                "127.0.0.1,192.168.0.1".to_string(),
            )
            .await
            .unwrap();
        tracing::info!("publish a config with beta: {}", publish_resp);
        assert_eq!(true, publish_resp);
    }

    #[tokio::test]
    #[ignore]
    async fn test_api_config_service_publish_config_cas() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();

        let config_service = ConfigServiceBuilder::default().build().unwrap();

        let data_id = "test_api_config_service_publish_config_cas".to_string();
        let group = "TEST".to_string();
        // publish a config
        let publish_resp = config_service
            .publish_config(
                data_id.clone(),
                group.clone(),
                "test_api_config_service_publish_config_cas".to_string(),
                None,
            )
            .await
            .unwrap();
        assert_eq!(true, publish_resp);

        // sleep for config sync in server
        sleep(Duration::from_millis(111)).await;

        // get a config
        let config_resp = config_service
            .get_config(data_id.clone(), group.clone())
            .await
            .unwrap();

        // publish a config with cas
        let content_cas_md5 =
            "test_api_config_service_publish_config_cas_md5_".to_string() + config_resp.md5();
        let publish_resp = config_service
            .publish_config_cas(
                data_id.clone(),
                group.clone(),
                content_cas_md5.clone(),
                None,
                config_resp.md5().to_string(),
            )
            .await
            .unwrap();
        tracing::info!("publish a config with cas: {}", publish_resp);
        assert_eq!(true, publish_resp);

        // publish a config with cas md5 not right
        let content_cas_md5_not_right = "test_api_config_service_publish_config_cas_md5_not_right";
        let publish_resp = config_service
            .publish_config_cas(
                data_id.clone(),
                group.clone(),
                content_cas_md5_not_right.to_string(),
                None,
                config_resp.md5().to_string(),
            )
            .await;
        match publish_resp {
            Ok(result) => tracing::info!("publish a config with cas: {}", result),
            Err(err) => tracing::error!("publish a config with cas: {:?}", err),
        }
        sleep(Duration::from_millis(111)).await;

        let config_resp = config_service
            .get_config(data_id.clone(), group.clone())
            .await
            .unwrap();
        assert_ne!(content_cas_md5_not_right, config_resp.content().as_str());
        assert_eq!(content_cas_md5.as_str(), config_resp.content().as_str());
    }
}