conreg-client 0.2.0

Conreg is a distributed configuration and registration center similar to Nacos, and conreg client is conreg's client SDK
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
//! # Conreg Client
//!
//! Conreg is a distributed service registry and configuration center designed with reference to Nacos. See details: [conreg](https://github.com/xgpxg/conreg)
//!
//! conreg-client is the client SDK for conreg, used to integrate into your services and communicate with conreg-server.
//!
//! # Features
//!
//! - Configuration Center: Load and manage configurations from conreg-server
//! - Service Discovery: Register and discover service instances
//! - Load Balancing: Multiple load balancing strategies (Random, Round-Robin, Weighted, etc.)
//! - Declarative HTTP Client: Feign-like declarative microservice calling (requires `feign` feature)
//!
//! # Quick Start
//!
//! ## Basic Usage
//!
//! Add a `bootstrap.yaml` configuration file in your project's root directory:
//!
//! ```yaml
//! conreg:
//!   # Service ID is the unique identifier of the service. Service IDs in the same namespace cannot be duplicated.
//!   service-id: test
//!   # Client configuration, this information will be submitted to the registry as basic information of the service instance
//!   client:
//!     # Listening address
//!     address: 127.0.0.1
//!     # Port
//!     port: 8000
//!   # Configuration center configuration
//!   config:
//!   # Configuration center address
//!     server-addr: 127.0.0.1:8000
//!     # Configuration ID
//!     # If there are duplicate configuration keys in multiple configurations, the latter configuration will overwrite the previous one
//!     config-ids:
//!       - test.yaml
//!     auth-token: your_token
//!   # Registry configuration
//!   discovery:
//!     # Registry address
//!     server-addr:
//!       - 127.0.0.1:8000
//!       - 127.0.0.1:8001
//!       - 127.0.0.1:8002
//!     auth-token: your_token
//! ```
//!
//! Then, initialize in the `main` function:
//!
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     // Initialization
//!     init().await;
//!     // Get configuration item
//!     println!("{:?}", AppConfig::get::<String>("name"));
//!     // Get service instances
//!     let instances = AppDiscovery::get_instances("your_service_id").await.unwrap();
//!     println!("service instances: {:?}", instances);
//! }
//! ```
//!
//! ## Namespace
//!
//! Conreg uses namespaces to isolate configurations and services. The default namespace is `public`.
//!
//! ## Configuration Center
//!
//! Load and use configurations from the configuration center. Currently only `yaml` format configurations are supported.
//!
//! ### Initialize and Load Configuration
//!
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     init_with(
//!         ConRegConfigBuilder::default()
//!             .config(
//!                 ConfigConfigBuilder::default()
//!                     .server_addr("127.0.0.1:8000")
//!                     .namespace("public")
//!                     .config_ids(vec!["test.yaml".into()])
//!                     .build()
//!                     .unwrap(),
//!             )
//!             .build()
//!             .unwrap(),
//!     )
//!         .await;
//!     println!("{:?}", AppConfig::get::<String>("name"));
//!     println!("{:?}", AppConfig::get::<u32>("age"));
//! }
//! ```
//!
//! ### Initialize from Configuration File
//!
//! By default, conreg-client loads configurations from the bootstrap.yaml file in the project root directory to initialize configurations, just like SpringCloud.
//! The following is an example of `bootstrap.yaml` configuration:
//!
//! ```yaml
//! conreg:
//!   config:
//!     server-addr: 127.0.0.1:8000
//!     config-ids:
//!       - your_config.yaml
//! ```
//!
//! Then call the `init` method to initialize and get the configuration content.
//!
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     init().await;
//!     // Or specify the configuration file path
//!     // init_from_file("config.yaml").await;
//!     println!("{:?}", AppConfig::get::<String>("name"));
//!     println!("{:?}", AppConfig::get::<u32>("age"));
//! }
//! ```
//!
//! ## Registry Center
//!
//! Used for service registration and discovery.
//!
//! ### Initialize and Load Configuration
//!
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     let config = ConRegConfigBuilder::default()
//!         .service_id("your_service_id")
//!         .client(
//!             ClientConfigBuilder::default()
//!                 .address("127.0.0.1")
//!                 .port(8080)
//!                 .build()
//!                 .unwrap(),
//!         )
//!         .discovery(
//!             DiscoveryConfigBuilder::default()
//!                 .server_addr("127.0.0.1:8000")
//!                 .build()
//!                 .unwrap(),
//!         )
//!         .build()
//!         .unwrap();
//!     let service_id = config.service_id.clone();
//!     init_with(config).await;
//!     let instances = AppDiscovery::get_instances(&service_id).await.unwrap();
//!     println!("service instances: {:?}", instances);
//! }
//! ```
//!
//! ### Initialize from Configuration File
//!
//! By default, configurations are loaded from `bootstrap.yaml`.
//! The following is an example configuration:
//!
//! ```yaml
//! conreg:
//!   service-id: your_service_id
//!   client:
//!     address: 127.0.0.1
//!     port: 8000
//!   discovery:
//!     server-addr:
//!       - 127.0.0.1:8000
//!       - 127.0.0.1:8001
//!       - 127.0.0.1:8002
//! ```
//!
//! ```rust
//! #[tokio::main]
//! async fn main() {
//!     init().await;
//!     // Or specify the configuration file path
//!     // init_from_file("config.yaml").await;
//!     init_with(config).await;
//!     let service_id = "your_service_id";
//!     let instances = AppDiscovery::get_instances(service_id).await.unwrap();
//!     println!("service instances: {:?}", instances);
//! }
//! ```
//!
//! # Load Balancing
//!
//! conreg-client provides a load balancing client based on `reqwest`, supporting custom protocol requests in the format `lb://service_id`.
//! Reference: [lb](https://docs.rs/conreg-client/latest/conreg_client/lb/index.html)
//!
//! # Listen for Configuration Changes
//!
//! Add a handler function for the specified config_id, which will be called when the configuration changes.
//!
//! ```rust
//! AppConfig::add_listener("test.yaml", |config| {
//! println!("Config changed, new config: {:?}", config);
//! });
//! ```
//!
//! # Feign-like Component
//! [conreg-feign-macro](https://docs.rs/conreg-feign-macro) provides a macro that implements functionality similar to Java's Feign, enabling remote procedure calls across microservices.
//!
//! Example:
//! ```rust
//! #[feign_client(service_id = "user-service", base_path = "/api")]
//! trait UserService{
//!   #[get("/api/users/{id}")]
//!   async fn get_user(&self, id: i32) -> Result<String, FeignError>;
//!
//!   // ... other methods
//! }
//!
//! // Then, you can use the generated client like this:
//! let client = UserServiceImpl::default();
//! let user = client.get_user(1).await?;
//! ```

use crate::conf::{ConRegConfig, ConRegConfigWrapper};
use crate::config::Configs;
use crate::discovery::{Discovery, DiscoveryClient};
pub use crate::protocol::Instance;
use anyhow::bail;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::exit;
use std::sync::{Arc, OnceLock, RwLock};

pub mod conf;
mod config;
mod discovery;
pub mod lb;
mod network;
mod protocol;
mod utils;

#[cfg(feature = "feign")]
pub use conreg_feign_macro::{delete, feign_client, get, patch, post, put};

/// Feign client error types
#[derive(Debug)]
pub enum FeignError {
    /// HTTP request error
    RequestError(String),
    /// Response deserialization error
    DeserializationError(String),
    /// Service instance not found
    InstanceNotFound(String),
    /// Load balance error
    LoadBalanceError(String),
}

impl std::fmt::Display for FeignError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FeignError::RequestError(msg) => write!(f, "Request error: {}", msg),
            FeignError::DeserializationError(msg) => {
                write!(f, "Deserialization error: {}", msg)
            }
            FeignError::InstanceNotFound(msg) => write!(f, "Instance not found: {}", msg),
            FeignError::LoadBalanceError(msg) => write!(f, "Load balance error: {}", msg),
        }
    }
}

impl std::error::Error for FeignError {}

impl From<crate::lb::LoadBalanceError> for FeignError {
    fn from(err: crate::lb::LoadBalanceError) -> Self {
        FeignError::LoadBalanceError(err.to_string())
    }
}

struct Conreg;

/// Store configuration content
static CONFIGS: OnceLock<Arc<RwLock<Configs>>> = OnceLock::new();
/// Global instance for service discovery
static DISCOVERY: OnceLock<Discovery> = OnceLock::new();
/// Request header for namespace authentication
const NS_TOKEN_HEADER: &str = "X-NS-Token";

impl Conreg {
    /// Initialize configuration center and registry center
    async fn init(file: Option<PathBuf>) -> anyhow::Result<()> {
        #[cfg(feature = "tracing")]
        utils::init_log();

        let mut file = file.unwrap_or("bootstrap.yaml".into());
        if !file.exists() {
            file = "bootstrap.yml".into();
        }
        let s = match std::fs::read_to_string(&file) {
            Ok(s) => s,
            Err(e) => {
                log::error!("no bootstrap.yaml found, {}", e);
                exit(1);
            }
        };

        log::info!("loaded bootstrap config from {}", file.display());

        let config = match serde_yaml::from_str::<ConRegConfigWrapper>(&s) {
            Ok(config) => config,
            Err(e) => {
                log::error!("parse bootstrap.yaml failed, {}", e);
                exit(1);
            }
        };

        Self::init_with(&config.conreg).await?;

        log::info!("conreg init completed");
        Ok(())
    }

    async fn init_with(config: &ConRegConfig) -> anyhow::Result<()> {
        #[cfg(feature = "tracing")]
        utils::init_log();

        if config.config.is_some() {
            let config_client = config::ConfigClient::new(config);
            let configs = config_client.load().await?;
            CONFIGS.set(Arc::new(RwLock::new(configs))).map_err(|_| {
                anyhow::anyhow!(
                    "config has already been initialized, please do not initialize repeatedly"
                )
            })?;
        }

        if config.discovery.is_some() {
            let discovery_client = DiscoveryClient::new(config);
            discovery_client.register().await?;
            let discovery = Discovery::new(discovery_client).await;
            DISCOVERY.set(discovery).map_err(|_| {
                anyhow::anyhow!(
                    "discovery has already been initialized, please do not initialize repeatedly"
                )
            })?;
        }

        Ok(())
    }
}

/// Initialize configuration center and registry center
pub async fn init() {
    match Conreg::init(None).await {
        Ok(_) => {}
        Err(e) => {
            log::error!("conreg init failed: {}", e);
            exit(1);
        }
    };
}

/// Initialize configuration center and registry center from configuration file
pub async fn init_from_file(path: impl Into<PathBuf>) {
    match Conreg::init(Some(path.into())).await {
        Ok(_) => {}
        Err(e) => {
            log::error!("conreg init failed: {}", e);
            exit(1);
        }
    };
}

/// Initialize from custom configuration
pub async fn init_with(config: ConRegConfig) {
    match Conreg::init_with(&config).await {
        Ok(_) => {}
        Err(e) => {
            log::error!("conreg init failed: {}", e);
            exit(1);
        }
    };
}

/// Application Configuration
pub struct AppConfig;
impl AppConfig {
    fn reload(configs: Configs) {
        match CONFIGS.get() {
            None => {
                log::error!("config not init");
            }
            Some(config) => {
                *config.write().unwrap() = configs;
            }
        }
    }

    /// Get configuration value
    ///
    /// `key` is the key of the configuration item, such as `app.name`.
    ///
    /// Note: The type of the obtained value needs to be consistent with the type of the value in the configuration.
    /// If they are inconsistent, it may cause conversion failure. When conversion fails, `None` will be returned.
    ///
    /// This method retrieves from the flattened configuration. To retrieve the raw configuration, use `get_raw`.
    pub fn get<V: DeserializeOwned>(key: &str) -> Option<V> {
        match CONFIGS.get() {
            None => {
                log::error!("config not init");
                None
            }
            Some(config) => match config.read().expect("read lock error").get(key) {
                None => None,
                Some(value) => match serde_yaml::from_value::<V>(value.clone()) {
                    Ok(value) => Some(value),
                    Err(e) => {
                        log::error!("parse config failed, {}", e);
                        None
                    }
                },
            },
        }
    }

    /// Get raw configuration value
    pub fn get_raw<V: DeserializeOwned>(key: &str) -> Option<V> {
        match CONFIGS.get() {
            None => {
                log::error!("config not init");
                None
            }
            Some(config) => match config.read().expect("read lock error").get_raw(key) {
                None => None,
                Some(value) => match serde_yaml::from_value::<V>(value.clone()) {
                    Ok(value) => Some(value),
                    Err(e) => {
                        log::error!("parse config failed, {}", e);
                        None
                    }
                },
            },
        }
    }

    /// Add configuration listener
    ///
    /// - `config_id`: Configuration ID
    /// - `handler`: Configuration listener function, parameter is the changed, merged and flattened configuration content
    pub fn add_listener(config_id: &str, handler: fn(&HashMap<String, serde_yaml::Value>)) {
        Configs::add_listener(config_id, handler);
    }
}

/// Service Discovery
pub struct AppDiscovery;
impl AppDiscovery {
    /// Get available service instances for the specified service
    pub async fn get_instances(service_id: &str) -> anyhow::Result<Vec<Instance>> {
        match DISCOVERY.get() {
            Some(discovery) => {
                let instances = discovery.get_instances(service_id).await;
                Ok(instances)
            }
            None => {
                bail!("discovery not initialized")
            }
        }
    }
}

#[cfg(test)]
#[allow(unused)]
mod tests {
    use crate::conf::{ClientConfigBuilder, ConRegConfigBuilder, DiscoveryConfigBuilder};
    use crate::{AppConfig, AppDiscovery, init};
    use reqwest::StatusCode;
    use reqwest::multipart::{Form, Part};
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use std::collections::HashMap;

    #[tokio::test]
    async fn test_config() {
        //init_log();
        init().await;
        //init_from_file("bootstrap.yaml").await;
        /*init_with(
            ConRegConfigBuilder::default()
                .config(
                    ConfigConfigBuilder::default()
                        .server_addr("127.0.0.1:8000")
                        .namespace("public")
                        .config_ids(vec!["test.yaml".into()])
                        .auth_token(Some("2cTtsBUpor".to_string()))
                        .build()
                        .unwrap(),
                )
                .build()
                .unwrap(),
        )
        .await;*/
        println!("{:?}", AppConfig::get::<String>("name"));
        println!("{:?}", AppConfig::get::<u32>("age"));

        AppConfig::add_listener("test.yaml", |config| {
            println!("Listen config change1: {:?}", config);
        });
        AppConfig::add_listener("test2.yml", |config| {
            println!("Listen config change2: {:?}", config);
        });
        let h = tokio::spawn(async move {
            loop {
                println!("{:?}", AppConfig::get::<String>("name"));
                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            }
        });
        tokio::join!(h);
    }

    #[tokio::test]
    async fn test_discovery() {
        //init_log();
        init().await;
        // let config = ConRegConfigBuilder::default()
        //     .service_id("your_service_id")
        //     .client(
        //         ClientConfigBuilder::default()
        //             .address("127.0.0.1")
        //             .port(8080)
        //             .build()
        //             .unwrap(),
        //     )
        //     .discovery(
        //         DiscoveryConfigBuilder::default()
        //             .server_addr(vec!["127.0.0.1:8000", "127.0.0.1:8001"])
        //             .build()
        //             .unwrap(),
        //     )
        //     .build()
        //     .unwrap();
        // // println!("config: {:?}", config);
        // let service_id = config.service_id.clone();
        // init_with(config).await;
        let h = tokio::spawn(async move {
            loop {
                println!("{:?}", AppConfig::get::<String>("name"));
                let instances =
                    AppDiscovery::get_instances(crate::utils::current_process_name().as_str())
                        .await
                        .unwrap();
                println!("current: {:?}", instances);
                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            }
        });
        tokio::join!(h);
    }
}