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
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#![deny(rust_2018_idioms, clippy::disallowed_methods, clippy::disallowed_types)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
//! # Nacos in Rust
//!
//! Thorough examples have been provided in our [repository](https://github.com/nacos-group/nacos-sdk-rust).
//!
//! ## Add Dependency
//!
//! Add the dependency in `Cargo.toml`:
//! - If you need sync API, maybe `futures::executor::block_on(future_fn)`
//! ```toml
//! [dependencies]
//! nacos-sdk = { version = "0.4", features = ["default"] }
//! ```
//!
//! ## General Configurations and Initialization
//!
//! Nacos needs to be initialized. Please see the `api` module.
//!
//! ### Example of Config
//!
//! ```ignore
//! let 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()?;
//! ```
//!
//! ### Example of Naming
//!
//! ```ignore
//! let naming_service = nacos_sdk::api::naming::NamingServiceBuilder::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()?;
//! ```
//!
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::path::Path;
const ENV_NACOS_CLIENT_PROPS_FILE_PATH: &str = "NACOS_CLIENT_PROPS_FILE_PATH";
lazy_static! {
static ref PROPERTIES: HashMap<String, String> = {
let env_file_path = std::env::var(ENV_NACOS_CLIENT_PROPS_FILE_PATH).ok();
let _ = env_file_path.as_ref().map(|file_path| {
dotenvy::from_path(Path::new(file_path)).map_err(|e| {
let _ = dotenvy::dotenv();
e
})
});
dotenvy::dotenv().ok();
dotenvy::vars().collect::<HashMap<String, String>>()
};
}
pub(crate) mod properties {
use crate::PROPERTIES;
pub(crate) fn get_value_option<Key>(key: Key) -> Option<String>
where
Key: AsRef<str>,
{
PROPERTIES.get(key.as_ref()).cloned()
}
pub(crate) fn get_value<Key, Default>(key: Key, default: Default) -> String
where
Key: AsRef<str>,
Default: AsRef<str>,
{
PROPERTIES
.get(key.as_ref())
.map_or(default.as_ref().to_string(), |value| value.to_string())
}
pub(crate) fn get_value_u32<Key>(key: Key, default: u32) -> u32
where
Key: AsRef<str>,
{
PROPERTIES.get(key.as_ref()).map_or(default, |value| {
value.to_string().parse::<u32>().unwrap_or(default)
})
}
pub(crate) fn get_value_bool<Key>(key: Key, default: bool) -> bool
where
Key: AsRef<str>,
{
PROPERTIES.get(key.as_ref()).map_or(default, |value| {
value.to_string().parse::<bool>().unwrap_or(default)
})
}
}
/// Nacos API
pub mod api;
mod common;
#[cfg(feature = "config")]
mod config;
#[cfg(feature = "naming")]
mod naming;
#[allow(dead_code)]
#[path = ""]
mod nacos_proto {
#[path = "_.rs"]
pub mod v2;
}
#[cfg(test)]
mod tests {
use prost_types::Any;
use std::collections::HashMap;
use crate::nacos_proto::v2::Metadata;
use crate::nacos_proto::v2::Payload;
#[test]
fn it_works_nacos_proto() {
let body = Any {
type_url: String::new(),
value: Vec::from("{\"cluster\":\"DEFAULT\",\"healthyOnly\":true}"),
};
let metadata = Metadata {
r#type: String::from("com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest"),
client_ip: String::from("127.0.0.1"),
headers: HashMap::new(),
};
let payload = Payload {
metadata: Some(metadata),
body: Some(body),
};
// println!("{:?}", payload);
assert_eq!(
payload.metadata.unwrap().r#type,
"com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest"
);
assert_eq!(
payload.body.unwrap().value,
Vec::from("{\"cluster\":\"DEFAULT\",\"healthyOnly\":true}")
);
}
}
#[cfg(test)]
mod test_props {
use crate::api::constants::ENV_NACOS_CLIENT_NAMING_PUSH_EMPTY_PROTECTION;
use crate::properties::{get_value, get_value_bool, get_value_u32};
#[test]
fn test_get_value() {
let v = get_value("ENV_TEST", "TEST");
assert_eq!(v, "TEST");
}
#[test]
fn test_get_value_bool() {
let v = get_value_bool(ENV_NACOS_CLIENT_NAMING_PUSH_EMPTY_PROTECTION, true);
assert_eq!(v, true);
}
#[test]
fn test_get_value_u32() {
let not_exist_key = "MUST_NOT_EXIST";
let v = get_value_u32(not_exist_key, 91);
assert_eq!(v, 91);
}
}
#[cfg(test)]
mod test_config {
use std::sync::Once;
use tracing::metadata::LevelFilter;
static LOGGER_INIT: Once = Once::new();
pub(crate) fn setup_log() {
LOGGER_INIT.call_once(|| {
tracing_subscriber::fmt()
.with_thread_names(true)
.with_file(true)
.with_level(true)
.with_line_number(true)
.with_thread_ids(true)
.with_max_level(LevelFilter::DEBUG)
.init()
});
}
}