├── examples ├── src │ ├── lib.rs │ ├── proto │ │ └── mod.rs │ ├── gz_encode_decode.rs │ ├── tonic-discover │ │ ├── service.rs │ │ └── client.rs │ ├── config_foreach.rs │ ├── naming_register.rs │ ├── config.rs │ └── naming_only_register.rs ├── build.rs ├── proto │ └── helloworld │ │ └── helloworld.proto └── Cargo.toml ├── .gitignore ├── nacos_rust_client ├── .gitignore ├── src │ ├── client │ │ ├── config_client │ │ │ ├── model.rs │ │ │ ├── inner_grpc_client.rs │ │ │ ├── mod.rs │ │ │ ├── config_key.rs │ │ │ ├── api_model.rs │ │ │ ├── listener.rs │ │ │ ├── client.rs │ │ │ ├── inner.rs │ │ │ └── inner_client.rs │ │ ├── api_model.rs │ │ ├── utils.rs │ │ ├── auth.rs │ │ ├── builder.rs │ │ ├── naming_client │ │ │ ├── request_client.rs │ │ │ ├── udp_actor.rs │ │ │ ├── register.rs │ │ │ ├── api_model.rs │ │ │ ├── mod.rs │ │ │ └── client.rs │ │ └── mod.rs │ ├── conn_manage │ │ ├── endpoint.rs │ │ ├── mod.rs │ │ ├── conn_msg.rs │ │ ├── inner_conn.rs │ │ └── breaker.rs │ ├── grpc │ │ ├── constant.rs │ │ ├── channel.rs │ │ ├── mod.rs │ │ ├── utils.rs │ │ ├── config_request_utils.rs │ │ ├── naming_request_utils.rs │ │ └── api_model.rs │ └── lib.rs ├── Cargo.toml └── proto │ └── nacos_grpc_service.proto ├── Cargo.toml ├── changlog.md ├── .github └── workflows │ └── release.yml ├── nacos-tonic-discover ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── README.md └── LICENSE /examples/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod proto; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | /target 3 | /Cargo.lock 4 | -------------------------------------------------------------------------------- /nacos_rust_client/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /examples/src/proto/mod.rs: -------------------------------------------------------------------------------- 1 | //build from proto file 2 | pub mod helloworld; 3 | /* 4 | pub mod hello{ 5 | tonic::include_proto!("helloworld"); 6 | } 7 | */ 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | 2 | [workspace] 3 | resolver = "2" 4 | members = [ 5 | "nacos_rust_client", 6 | "nacos-tonic-discover", 7 | "examples", 8 | ] 9 | 10 | [workspace.dependencies] 11 | tonic = "0.12" 12 | prost = "0.13" -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/model.rs: -------------------------------------------------------------------------------- 1 | use super::ConfigKey; 2 | 3 | #[derive(Debug, Default, Clone)] 4 | pub struct NotifyConfigItem { 5 | pub key: ConfigKey, 6 | pub content: String, 7 | pub md5: String, 8 | } 9 | -------------------------------------------------------------------------------- /examples/src/gz_encode_decode.rs: -------------------------------------------------------------------------------- 1 | use nacos_rust_client::client::utils::Utils; 2 | 3 | fn main() { 4 | let a=b"abc-gz".to_vec(); 5 | let b=Utils::gz_encode(&a,1); 6 | let c=Utils::gz_decode(&b).unwrap(); 7 | assert_eq!(a,c); 8 | println!("'{}'",&String::from_utf8(c).unwrap()); 9 | } -------------------------------------------------------------------------------- /nacos_rust_client/src/conn_manage/endpoint.rs: -------------------------------------------------------------------------------- 1 | /* 2 | use std::sync::Arc; 3 | 4 | 5 | 6 | #[derive(Default,Debug,Clone)] 7 | pub struct Endpoint { 8 | pub ip: Arc, 9 | pub http_port: u16, 10 | pub grpc_port: u64, 11 | pub support_grpc: bool, 12 | } 13 | 14 | */ 15 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/constant.rs: -------------------------------------------------------------------------------- 1 | pub const LABEL_SOURCE: &str = "source"; 2 | pub const LABEL_SOURCE_SDK: &str = "sdk"; 3 | pub const LABEL_SOURCE_CLUSTER: &str = "cluster"; 4 | pub const LABEL_MODULE: &str = "module"; 5 | pub const LABEL_MODULE_CONFIG: &str = "config"; 6 | pub const LABEL_MODULE_NAMING: &str = "naming"; 7 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/inner_grpc_client.rs: -------------------------------------------------------------------------------- 1 | /* 2 | //use std::sync::Arc; 3 | 4 | use crate::{grpc::nacos_proto::request_client::RequestClient}; 5 | 6 | 7 | 8 | pub struct InnerGrpcClient { 9 | //pub(crate) endpoints: Arc, 10 | pub(crate) request_client: RequestClient, 11 | } 12 | */ 13 | -------------------------------------------------------------------------------- /changlog.md: -------------------------------------------------------------------------------- 1 | ## 0.3.0 2 | 3 | 2023-12-12 4 | 5 | 1. 支持grpc协议 6 | 2. 支持服务异常重连 7 | 8 | ## 0.2.3 9 | 10 | 2023-12-09 11 | 12 | 1. 注册中心支持接受空列表实列的推送。之前是忽略空实现列表推送,以防止空推。 13 | 14 | ## 0.2.2 15 | 16 | 2023-03-28 17 | 18 | 1. 修复创建ConfigClient时没有设置auth_addr导致请求认证失败的问题。 19 | 20 | ## 0.2.1 21 | 22 | 2022-09-03 23 | 24 | 1. 禁用 reqwest 的默认依赖。修改 tokio 使用的 features 25 | 2. 处理编译时的警告 26 | -------------------------------------------------------------------------------- /examples/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | /* 3 | use std::env; 4 | use std::path::PathBuf; 5 | let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); 6 | tonic_build::configure() 7 | .out_dir("src/proto") 8 | .file_descriptor_set_path(out_dir.join("helloworld_descriptor.bin")) 9 | .compile_protos(&["proto/helloworld/helloworld.proto"], &["proto"]) 10 | .unwrap(); 11 | 12 | println!("cargo: rerun-if-changed=proto/helloworld/helloworld.proto"); 13 | */ 14 | } 15 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod api_model; 2 | pub mod client; 3 | pub mod config_key; 4 | pub mod inner; 5 | pub mod inner_client; 6 | pub mod inner_grpc_client; 7 | pub mod listener; 8 | #[warn(unused_imports)] 9 | pub mod model; 10 | 11 | pub type ConfigClient = self::client::ConfigClient; 12 | pub type ConfigInnerActor = self::inner::ConfigInnerActor; 13 | pub type ConfigKey = self::config_key::ConfigKey; 14 | pub type ConfigDefaultListener = self::listener::ConfigDefaultListener; 15 | -------------------------------------------------------------------------------- /nacos_rust_client/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod client; 2 | pub mod conn_manage; 3 | pub mod grpc; 4 | 5 | pub use client::nacos_client::close_global_system_actor as close_current_system; 6 | pub use client::nacos_client::get_last_config_client; 7 | pub use client::nacos_client::get_last_naming_client; 8 | pub use client::nacos_client::init_global_system_actor; 9 | pub use client::nacos_client::ActixSystemCreateAsyncCmd; 10 | pub use client::nacos_client::ActixSystemCreateCmd; 11 | pub use client::nacos_client::ActorCreate; 12 | pub use client::nacos_client::ActorCreateWrap; 13 | -------------------------------------------------------------------------------- /nacos_rust_client/src/conn_manage/mod.rs: -------------------------------------------------------------------------------- 1 | use actix::WeakAddr; 2 | 3 | use crate::client::{ 4 | config_client::inner::ConfigInnerActor, 5 | naming_client::{InnerNamingListener, InnerNamingRegister}, 6 | }; 7 | 8 | pub(crate) mod breaker; 9 | pub mod conn_msg; 10 | pub mod endpoint; 11 | pub(crate) mod inner_conn; 12 | pub mod manage; 13 | 14 | #[derive(Default, Clone)] 15 | pub struct NotifyCallbackAddr { 16 | pub(crate) config_inner_addr: Option>, 17 | pub(crate) naming_listener_addr: Option>, 18 | pub(crate) naming_register_addr: Option>, 19 | } 20 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/api_model.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Clone, Serialize, Deserialize, Default)] 4 | #[serde(rename_all = "camelCase")] 5 | pub struct ConsoleResult 6 | where 7 | T: Sized + Serialize + Clone + Default, 8 | { 9 | pub code: i64, 10 | pub message: Option, 11 | pub data: Option, 12 | } 13 | 14 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] 15 | #[serde(rename_all = "camelCase")] 16 | pub struct NamespaceInfo { 17 | pub namespace: Option, 18 | pub namespace_show_name: Option, 19 | pub namespace_desc: Option, 20 | pub quota: i64, 21 | pub config_count: i64, 22 | pub r#type: i64, 23 | } 24 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | 4 | on: 5 | push: 6 | branches: 7 | - ignore 8 | # - master 9 | tags: [ 'v*' ] 10 | workflow_dispatch: 11 | 12 | permissions: 13 | contents: read 14 | 15 | jobs: 16 | release-crates-io: 17 | name: Release crates.io 18 | runs-on: ubuntu-latest 19 | if: "startsWith(github.ref, 'refs/tags/')" 20 | steps: 21 | - uses: actions/checkout@v3 22 | - uses: dtolnay/rust-toolchain@stable 23 | - name: cargo login 24 | run: cargo login ${{ secrets.CRATES_IO_TOKEN }} 25 | - name: cargo publish 26 | run: | 27 | cd nacos_rust_client 28 | cargo publish 29 | cd ../nacos-tonic-discover 30 | cargo publish 31 | 32 | -------------------------------------------------------------------------------- /nacos-tonic-discover/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nacos-tonic-discover" 3 | version = "0.3.2" 4 | authors = ["heqingpan "] 5 | license = "MIT/Apache-2.0" 6 | description = "nacos tonic discover " 7 | repository = "https://github.com/heqingpan/nacos_rust_client" 8 | readme = "README.md" 9 | keywords = ["nacos", "tonic", "discover"] 10 | edition = "2021" 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [dependencies] 15 | nacos_rust_client = { version = "0.3", path = "../nacos_rust_client" } 16 | tonic = { workspace = true } 17 | tower = "0.4" 18 | actix = "0.12" 19 | log = "0" 20 | tokio = { version = "1", features = ["sync"] } 21 | anyhow = "1" 22 | lazy_static = "1.4" 23 | 24 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/channel.rs: -------------------------------------------------------------------------------- 1 | use std::task::Poll; 2 | 3 | use futures_core::Stream; 4 | 5 | pub struct CloseableChannel { 6 | inner: tokio_stream::wrappers::ReceiverStream>, 7 | } 8 | 9 | impl CloseableChannel { 10 | pub fn new(inner: tokio_stream::wrappers::ReceiverStream>) -> Self { 11 | Self { inner } 12 | } 13 | } 14 | 15 | impl Unpin for CloseableChannel {} 16 | 17 | impl Stream for CloseableChannel { 18 | type Item = T; 19 | 20 | fn poll_next( 21 | mut self: std::pin::Pin<&mut Self>, 22 | cx: &mut std::task::Context<'_>, 23 | ) -> Poll> { 24 | if let Poll::Ready(v) = self.inner.as_mut().poll_recv(cx) { 25 | match v { 26 | Some(v) => Poll::Ready(v), 27 | None => Poll::Ready(None), 28 | } 29 | } else { 30 | Poll::Pending 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/config_key.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, Hash, PartialEq, Eq, Clone, Default)] 2 | pub struct ConfigKey { 3 | pub data_id: String, 4 | pub group: String, 5 | pub tenant: String, 6 | } 7 | 8 | impl ConfigKey { 9 | pub fn new(data_id: &str, group: &str, tenant: &str) -> Self { 10 | Self { 11 | data_id: data_id.to_owned(), 12 | group: group.to_owned(), 13 | tenant: tenant.to_owned(), 14 | } 15 | } 16 | 17 | pub fn build_key(&self) -> String { 18 | if self.tenant.is_empty() { 19 | return format!("{}\x02{}", self.data_id, self.group); 20 | } 21 | format!("{}\x02{}\x02{}", self.data_id, self.group, self.tenant) 22 | } 23 | } 24 | 25 | /* 26 | impl PartialEq for ConfigKey { 27 | fn eq(&self, o: &Self) -> bool { 28 | self.data_id == o.data_id && self.group == o.group && self.tenant == self.tenant 29 | } 30 | } 31 | */ 32 | -------------------------------------------------------------------------------- /nacos_rust_client/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nacos_rust_client" 3 | version = "0.3.2" 4 | authors = ["heqingpan "] 5 | license = "MIT/Apache-2.0" 6 | description = "nacos rust client" 7 | repository = "https://github.com/heqingpan/nacos_rust_client" 8 | readme = "../README.md" 9 | keywords = ["nacos", "client"] 10 | edition = "2021" 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [dependencies] 15 | anyhow = "1" 16 | serde = { version = "1", features = ["derive", "rc"] } 17 | serde_urlencoded = "0.6.1" 18 | serde_json = "1" 19 | tokio = { version = "1", features = ["net", "sync", "signal"] } 20 | reqwest = { version = "0.11", features = ["json"], default-features = false } 21 | actix = "0.12" 22 | log = "0" 23 | local_ipaddress = "0.1.3" 24 | inner-mem-cache = "0.1.3" 25 | rand = "0.8" 26 | flate2 = "1.0" 27 | lazy_static = "1.4" 28 | tonic = { workspace = true } 29 | prost = { workspace = true } 30 | async-stream = "0.3.2" 31 | futures-core = "0.3.7" 32 | tokio-stream = "0.1" 33 | md-5 = "0.10.0" 34 | hex = "0.4" 35 | 36 | [build-dependencies] 37 | tonic-build = "*" 38 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/api_model.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use std::fmt::Debug; 3 | 4 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] 5 | #[serde(rename_all = "camelCase")] 6 | pub struct ConfigSearchPage 7 | where 8 | T: Debug + Sized + Serialize + Clone + Default, 9 | { 10 | pub total_count: Option, 11 | pub page_number: Option, 12 | pub pages_available: Option, 13 | pub page_items: Option>, 14 | } 15 | 16 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] 17 | #[serde(rename_all = "camelCase")] 18 | pub struct ConfigInfoDto { 19 | pub tenant: Option, 20 | pub group: String, 21 | pub data_id: String, 22 | pub content: Option, 23 | pub md5: Option, 24 | } 25 | 26 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] 27 | #[serde(rename_all = "camelCase")] 28 | pub struct ConfigQueryParams { 29 | pub data_id: String, 30 | pub group: String, 31 | pub tenant: Option, 32 | pub desc: Option, 33 | pub r#type: Option, 34 | pub search: Option, //search type 35 | pub page_no: Option, //use at search 36 | pub page_size: Option, //use at search 37 | } 38 | -------------------------------------------------------------------------------- /examples/proto/helloworld/helloworld.proto: -------------------------------------------------------------------------------- 1 | // Copyright 2015 gRPC authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | syntax = "proto3"; 16 | 17 | option java_multiple_files = true; 18 | option java_package = "io.grpc.examples.helloworld"; 19 | option java_outer_classname = "HelloWorldProto"; 20 | 21 | package helloworld; 22 | 23 | // The greeting service definition. 24 | service Greeter { 25 | // Sends a greeting 26 | rpc SayHello (HelloRequest) returns (HelloReply) {} 27 | } 28 | 29 | // The request message containing the user's name. 30 | message HelloRequest { 31 | string name = 1; 32 | } 33 | 34 | // The response message containing the greetings 35 | message HelloReply { 36 | string message = 1; 37 | } -------------------------------------------------------------------------------- /examples/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "examples" 3 | version = "0.1.0" 4 | publish = false 5 | edition = "2021" 6 | 7 | [dependencies] 8 | nacos_rust_client = { path = "../nacos_rust_client" } 9 | nacos-tonic-discover = { path = "../nacos-tonic-discover" } 10 | anyhow = "1" 11 | serde = { version = "1", features = ["derive"] } 12 | serde_urlencoded = "0.6.1" 13 | serde_json = "1" 14 | tokio = { version = "1", features = ["full"] } 15 | reqwest = { version = "0.11", features = ["json"], default-features = false } 16 | actix = "0.12" 17 | log = "0" 18 | env_logger = "0.7" 19 | local_ipaddress = "0.1.3" 20 | ctrlc = "3.4.0" 21 | 22 | tonic = { version = "0.12" } 23 | prost = "0.13" 24 | 25 | [[example]] 26 | name = "config" 27 | path = "src/config.rs" 28 | 29 | [[example]] 30 | name = "config_foreach" 31 | path = "src/config_foreach.rs" 32 | 33 | [[example]] 34 | name = "naming_register" 35 | path = "src/naming_register.rs" 36 | 37 | [[example]] 38 | name = "naming_only_register" 39 | path = "src/naming_only_register.rs" 40 | 41 | [[example]] 42 | name = "tonic_discover_service" 43 | path = "src/tonic-discover/service.rs" 44 | [[example]] 45 | name = "tonic_discover_client" 46 | path = "src/tonic-discover/client.rs" 47 | 48 | 49 | [build-dependencies] 50 | #windows 依赖 cmake 51 | #tonic-build = "0.12" 52 | -------------------------------------------------------------------------------- /nacos_rust_client/proto/nacos_grpc_service.proto: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright 1999-2020 Alibaba Group Holding Ltd. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | syntax = "proto3"; 19 | 20 | 21 | 22 | option java_multiple_files = true; 23 | option java_package = "com.alibaba.nacos.api.grpc.auto"; 24 | 25 | //package _; 26 | 27 | message Any { 28 | string type_url = 1; 29 | bytes value = 2; 30 | } 31 | 32 | message Metadata { 33 | string type = 3; 34 | string clientIp = 8; 35 | map headers = 7; 36 | } 37 | 38 | 39 | message Payload { 40 | Metadata metadata = 2; 41 | Any body = 3; 42 | } 43 | 44 | service RequestStream { 45 | // build a streamRequest 46 | rpc requestStream (Payload) returns (stream Payload) { 47 | } 48 | } 49 | 50 | service Request { 51 | // Sends a commonRequest 52 | rpc request (Payload) returns (Payload) { 53 | } 54 | } 55 | 56 | service BiRequestStream { 57 | // Sends a commonRequest 58 | rpc requestBiStream (stream Payload) returns (stream Payload) { 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /nacos_rust_client/src/conn_manage/conn_msg.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use actix::prelude::*; 4 | 5 | use crate::client::{ 6 | config_client::ConfigKey, 7 | naming_client::{Instance, QueryInstanceListParams, ServiceInstanceKey}, 8 | }; 9 | 10 | #[derive(Debug, Message)] 11 | #[rtype(result = "anyhow::Result")] 12 | pub enum ConfigRequest { 13 | GetConfig(ConfigKey), 14 | SetConfig(ConfigKey, String), 15 | DeleteConfig(ConfigKey), 16 | V1Listen(String), // 兼容v1版本协议 17 | Listen(Vec<(ConfigKey, String)>, bool), //(key,md5) 18 | } 19 | 20 | #[derive(Debug)] 21 | pub enum ConfigResponse { 22 | ConfigValue(String, String), // (content,md5) 23 | ChangeKeys(Vec), 24 | None, 25 | } 26 | 27 | #[derive(Debug, Message)] 28 | #[rtype(result = "anyhow::Result")] 29 | pub enum NamingRequest { 30 | Register(Instance), 31 | Unregister(Instance), 32 | BatchRegister(Vec), 33 | Subscribe(Vec), 34 | Unsubscribe(Vec), 35 | QueryInstance(Box), 36 | V1Heartbeat(Arc), 37 | } 38 | 39 | #[derive(Debug, Default, Clone)] 40 | pub struct ServiceResult { 41 | pub hosts: Vec>, 42 | pub cache_millis: Option, 43 | } 44 | 45 | #[derive(Debug)] 46 | pub enum NamingResponse { 47 | ServiceResult(ServiceResult), 48 | None, 49 | } 50 | 51 | #[derive(Debug, Message)] 52 | #[rtype(result = "anyhow::Result<()>")] 53 | pub enum ConnCallbackMsg { 54 | ConfigChange(ConfigKey, String, String), 55 | InstanceChange(ServiceInstanceKey, ServiceResult), 56 | } 57 | -------------------------------------------------------------------------------- /examples/src/tonic-discover/service.rs: -------------------------------------------------------------------------------- 1 | use nacos_rust_client::client::naming_client::Instance; 2 | use nacos_rust_client::client::naming_client::NamingClient; 3 | use tokio::sync::mpsc; 4 | use tonic::{transport::Server, Request, Response, Status}; 5 | 6 | use examples::proto::helloworld::greeter_server::{Greeter, GreeterServer}; 7 | use examples::proto::helloworld::{HelloReply, HelloRequest}; 8 | 9 | #[derive(Default)] 10 | pub struct MyGreeter {} 11 | 12 | #[tonic::async_trait] 13 | impl Greeter for MyGreeter { 14 | async fn say_hello( 15 | &self, 16 | request: Request, 17 | ) -> Result, Status> { 18 | println!("Got a request from {:?}", request.remote_addr()); 19 | 20 | let reply = HelloReply { 21 | message: format!("Hello {}!", request.into_inner().name), 22 | }; 23 | Ok(Response::new(reply)) 24 | } 25 | } 26 | 27 | #[tokio::main] 28 | async fn main() -> Result<(), Box> { 29 | //let ip="[::]" ; //only use at localhost 30 | let ip = local_ipaddress::get().unwrap(); 31 | let addrs = [(ip.clone(), 10051), (ip.clone(), 10052)]; 32 | let namespace_id = "public".to_owned(); //default teant 33 | let auth_info = None; // Some(AuthInfo::new("nacos","nacos")) 34 | let client = 35 | NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848", namespace_id, auth_info); 36 | 37 | let (tx, mut rx) = mpsc::unbounded_channel(); 38 | 39 | for (_, port) in &addrs { 40 | let addr = format!("{}:{}", "0.0.0.0", port).parse()?; 41 | let tx = tx.clone(); 42 | let greeter = MyGreeter::default(); 43 | let serve = Server::builder() 44 | .add_service(GreeterServer::new(greeter)) 45 | .serve(addr); 46 | 47 | tokio::spawn(async move { 48 | if let Err(e) = serve.await { 49 | eprintln!("Error = {:?}", e); 50 | } 51 | 52 | tx.send(()).unwrap(); 53 | }); 54 | } 55 | 56 | for (ip, port) in &addrs { 57 | let instance = Instance::new_simple(&ip, port.to_owned(), "helloworld", "AppName"); 58 | client.register(instance); 59 | } 60 | 61 | rx.recv().await; 62 | 63 | Ok(()) 64 | } 65 | -------------------------------------------------------------------------------- /examples/src/tonic-discover/client.rs: -------------------------------------------------------------------------------- 1 | use examples::proto::helloworld::greeter_client::GreeterClient; 2 | use examples::proto::helloworld::HelloRequest; 3 | use nacos_rust_client::client::naming_client::NamingClient; 4 | use nacos_rust_client::client::naming_client::{QueryInstanceListParams, ServiceInstanceKey}; 5 | use nacos_tonic_discover::TonicDiscoverFactory; 6 | use std::time::Duration; 7 | 8 | #[tokio::main] 9 | async fn main() -> Result<(), Box> { 10 | let namespace_id = "public".to_owned(); //default teant 11 | let auth_info = None; // Some(AuthInfo::new("nacos","nacos")) 12 | let naming_client = 13 | NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848", namespace_id, auth_info); 14 | 15 | let service_key = ServiceInstanceKey::new("helloworld", "AppName"); 16 | //build client by discover factory 17 | let _ = TonicDiscoverFactory::new(naming_client.clone()); 18 | let discover_factory = nacos_tonic_discover::get_last_factory().unwrap(); 19 | let channel = discover_factory 20 | .build_service_channel(service_key.clone()) 21 | .await?; 22 | let mut client = GreeterClient::new(channel); 23 | 24 | for i in 0..5 { 25 | let request = tonic::Request::new(HelloRequest { 26 | name: format!("Tonic {} [client by discover factory]", i), 27 | }); 28 | let response = client.say_hello(request).await?; 29 | println!("RESPONSE={:?}", response); 30 | tokio::time::sleep(Duration::from_millis(1000)).await; 31 | } 32 | 33 | //build client by naming client select 34 | let param = QueryInstanceListParams::new_by_serivce_key(&service_key); 35 | 36 | for i in 5..10 { 37 | let instance = naming_client.select_instance(param.clone()).await?; 38 | let mut client = 39 | GreeterClient::connect(format!("http://{}:{}", &instance.ip, &instance.port)).await?; 40 | let request = tonic::Request::new(HelloRequest { 41 | name: format!("Tonic {} [client by naming client select]", i), 42 | }); 43 | let response = client.say_hello(request).await?; 44 | println!("RESPONSE={:?}", response); 45 | tokio::time::sleep(Duration::from_millis(1000)).await; 46 | } 47 | Ok(()) 48 | } 49 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/mod.rs: -------------------------------------------------------------------------------- 1 | use self::nacos_proto::request_client::RequestClient; 2 | use crate::client::auth::{get_token_result, AuthActor}; 3 | use crate::client::ClientInfo; 4 | use crate::grpc::nacos_proto::Payload; 5 | use crate::grpc::utils::PayloadUtils; 6 | use actix::Addr; 7 | use serde::Serialize; 8 | use std::collections::HashMap; 9 | use std::sync::Arc; 10 | use std::time::Duration; 11 | use tokio::time::timeout; 12 | use tonic::transport::Channel; 13 | 14 | pub mod api_model; 15 | pub mod channel; 16 | pub mod config_request_utils; 17 | pub mod constant; 18 | pub mod grpc_client; 19 | #[allow(non_camel_case_types)] 20 | pub mod nacos_proto; 21 | pub mod naming_request_utils; 22 | pub mod utils; 23 | 24 | const REQUEST_TIMEOUT: Duration = Duration::from_millis(3000); 25 | 26 | pub const AUTHORIZATION_HEADER: &str = "Authorization"; 27 | pub const ACCESS_TOKEN_HEADER: &str = "accessToken"; 28 | 29 | pub async fn do_timeout_request( 30 | channel: Channel, 31 | payload: nacos_proto::Payload, 32 | ) -> anyhow::Result { 33 | do_timeout_request_with_duration(channel, payload, None).await 34 | } 35 | 36 | pub async fn do_timeout_request_with_duration( 37 | channel: Channel, 38 | payload: Payload, 39 | duration: Option, 40 | ) -> anyhow::Result { 41 | let mut request_client = RequestClient::new(channel); 42 | let duration = if let Some(duration) = duration { 43 | duration 44 | } else { 45 | REQUEST_TIMEOUT 46 | }; 47 | log::debug!( 48 | "grpc request:{}", 49 | &PayloadUtils::get_payload_string(&payload) 50 | ); 51 | let response = timeout( 52 | duration, 53 | request_client.request(tonic::Request::new(payload)), 54 | ) 55 | .await??; 56 | let payload = response.into_inner(); 57 | log::debug!( 58 | "grpc response:{}", 59 | &PayloadUtils::get_payload_string(&payload) 60 | ); 61 | Ok(payload) 62 | } 63 | 64 | pub(crate) async fn build_request_payload( 65 | request_type: &str, 66 | request: &T, 67 | auth_addr: &Addr, 68 | client_info: &Arc, 69 | ) -> anyhow::Result { 70 | let val = serde_json::to_string(request)?; 71 | let mut payload_header = HashMap::new(); 72 | let token = get_token_result(auth_addr).await?; 73 | payload_header.insert(ACCESS_TOKEN_HEADER.to_string(), token.as_ref().to_owned()); 74 | let payload = 75 | PayloadUtils::build_full_payload(request_type, val, &client_info.client_ip, payload_header); 76 | Ok(payload) 77 | } 78 | -------------------------------------------------------------------------------- /nacos_rust_client/src/conn_manage/inner_conn.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use actix::{Actor, Addr, WeakAddr}; 4 | use tonic::transport::Channel; 5 | 6 | use super::{ 7 | breaker::{Breaker, BreakerConfig}, 8 | manage::ConnManage, 9 | }; 10 | use crate::client::auth::AuthActor; 11 | use crate::{ 12 | client::{ 13 | config_client::inner_client::ConfigInnerRequestClient, 14 | naming_client::InnerNamingRequestClient, ClientInfo, HostInfo, 15 | }, 16 | grpc::grpc_client::InnerGrpcClient, 17 | }; 18 | 19 | #[derive(Clone)] 20 | pub(crate) struct InnerConn { 21 | pub id: u32, 22 | pub weight: u64, 23 | pub host_info: HostInfo, 24 | pub breaker: Breaker, 25 | pub support_grpc: bool, 26 | pub channel: Option, 27 | pub _manage_addr: Option>, 28 | pub grpc_client_addr: Option>, 29 | pub config_request_client: Option>, 30 | pub naming_request_client: Option>, 31 | pub(crate) client_info: Arc, 32 | pub(crate) auth_addr: Addr, 33 | } 34 | 35 | impl InnerConn { 36 | pub fn new( 37 | id: u32, 38 | host_info: HostInfo, 39 | support_grpc: bool, 40 | breaker_config: Arc, 41 | client_info: Arc, 42 | auth_addr: Addr, 43 | ) -> Self { 44 | Self { 45 | id, 46 | weight: 1, 47 | host_info, 48 | support_grpc, 49 | breaker: Breaker::new(Default::default(), breaker_config), 50 | channel: None, 51 | grpc_client_addr: None, 52 | _manage_addr: None, 53 | config_request_client: None, 54 | naming_request_client: None, 55 | client_info, 56 | auth_addr, 57 | } 58 | } 59 | 60 | pub fn init_grpc(&mut self, manage_addr: WeakAddr) -> anyhow::Result<()> { 61 | if self.support_grpc { 62 | let addr = format!( 63 | "http://{}:{}", 64 | &self.host_info.ip, &self.host_info.grpc_port 65 | ); 66 | let channel = Channel::from_shared(addr)?.connect_lazy(); 67 | let grpc_client = InnerGrpcClient::new_by_channel( 68 | self.id.to_owned(), 69 | channel.clone(), 70 | manage_addr, 71 | self.client_info.clone(), 72 | self.auth_addr.clone(), 73 | )?; 74 | self.channel = Some(channel); 75 | self.grpc_client_addr = Some(grpc_client.start()); 76 | } 77 | Ok(()) 78 | } 79 | 80 | pub fn close_grpc(&mut self) -> anyhow::Result<()> { 81 | if self.support_grpc { 82 | self.channel = None; 83 | self.grpc_client_addr = None; 84 | } 85 | Ok(()) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /examples/src/config_foreach.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] 2 | use std::sync::Arc; 3 | use std::time::Duration; 4 | 5 | use nacos_rust_client::client::api_model::NamespaceInfo; 6 | use nacos_rust_client::client::config_client::api_model::ConfigQueryParams; 7 | use nacos_rust_client::client::{AuthInfo, ClientBuilder, ConfigClient, HostInfo}; 8 | use serde::{Deserialize, Serialize}; 9 | use serde_json; 10 | 11 | #[tokio::main] 12 | async fn main() -> anyhow::Result<()> { 13 | std::env::set_var("RUST_LOG", "INFO"); 14 | env_logger::init(); 15 | let tenant = "public".to_owned(); //default teant 16 | let auth_info = Some(AuthInfo::new("nacos", "nacos")); 17 | //let auth_info = None; 18 | let config_client = ClientBuilder::new() 19 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 20 | .set_auth_info(auth_info) 21 | .set_tenant(tenant) 22 | .set_use_grpc(false) 23 | .build_config_client(); 24 | tokio::time::sleep(Duration::from_millis(1000)).await; 25 | 26 | let result = config_client.get_namespace_list().await?; 27 | let namespaces = result.data.unwrap_or_default(); 28 | log::info!("namespace count:{}", namespaces.len()); 29 | for item in &namespaces { 30 | log::info!("namespace item: {:?}", item.namespace) 31 | } 32 | log::info!("---- query config list ----\n\n"); 33 | for item in &namespaces { 34 | print_config_list(&config_client, item).await?; 35 | } 36 | nacos_rust_client::close_current_system(); 37 | Ok(()) 38 | } 39 | 40 | async fn print_config_list( 41 | config_client: &ConfigClient, 42 | namespace_info: &NamespaceInfo, 43 | ) -> anyhow::Result<()> { 44 | let namespace_id = if let Some(namespace_id) = namespace_info.namespace.as_ref() { 45 | namespace_id 46 | } else { 47 | return Err(anyhow::anyhow!("namespace_id is none")); 48 | }; 49 | let mut current_page = 0; 50 | let mut total_page = 1; 51 | let mut total_count = 0; 52 | let mut params = ConfigQueryParams { 53 | tenant: Some(namespace_id.to_owned()), 54 | page_no: Some(1), 55 | page_size: Some(100), 56 | ..Default::default() 57 | }; 58 | while current_page < total_page { 59 | current_page += 1; 60 | params.page_no = Some(current_page); 61 | let res = config_client 62 | .query_accurate_config_page(params.clone()) 63 | .await?; 64 | total_page = res.pages_available.unwrap_or_default(); 65 | total_count = res.total_count.unwrap_or_default(); 66 | let configs = res.page_items.unwrap_or_default(); 67 | for config in &configs { 68 | log::info!( 69 | "config item,tenant:{:?},data:{},group:{}", 70 | config.tenant, 71 | config.data_id, 72 | config.group, 73 | ) 74 | } 75 | if configs.is_empty() { 76 | break; 77 | } 78 | } 79 | log::info!("[namespace {}],config count:{}", namespace_id, total_count); 80 | Ok(()) 81 | } 82 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/utils.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use super::{api_model::BaseResponse, nacos_proto}; 4 | 5 | pub struct PayloadUtils; 6 | 7 | impl PayloadUtils { 8 | pub fn new_metadata( 9 | r#type: &str, 10 | client_ip: &str, 11 | headers: HashMap, 12 | ) -> nacos_proto::Metadata { 13 | nacos_proto::Metadata { 14 | r#type: r#type.to_owned(), 15 | client_ip: client_ip.to_owned(), 16 | headers, 17 | } 18 | } 19 | 20 | pub fn build_error_payload(error_code: u16, error_msg: String) -> nacos_proto::Payload { 21 | let error_val = BaseResponse::build_error_response(error_code, error_msg).to_json_string(); 22 | Self::build_payload("ErrorResponse", error_val) 23 | } 24 | 25 | pub fn build_payload(url: &str, val: String) -> nacos_proto::Payload { 26 | Self::build_full_payload(url, val, "", Default::default()) 27 | } 28 | 29 | pub fn build_full_payload( 30 | url: &str, 31 | val: String, 32 | client_ip: &str, 33 | headers: HashMap, 34 | ) -> nacos_proto::Payload { 35 | let body = nacos_proto::Any { 36 | type_url: "".into(), 37 | value: val.into_bytes(), 38 | }; 39 | let meta = Self::new_metadata(url, client_ip, headers); 40 | nacos_proto::Payload { 41 | body: Some(body), 42 | metadata: Some(meta), 43 | } 44 | } 45 | 46 | pub fn get_payload_header(payload: &nacos_proto::Payload) -> String { 47 | let mut str = String::default(); 48 | if let Some(meta) = &payload.metadata { 49 | str.push_str(&format!("type:{},", meta.r#type)); 50 | str.push_str(&format!("client_ip:{},", meta.client_ip)); 51 | str.push_str(&format!("header:{:?},", meta.headers)); 52 | } 53 | str 54 | } 55 | 56 | pub fn get_payload_string(payload: &nacos_proto::Payload) -> String { 57 | let mut str = String::default(); 58 | if let Some(meta) = &payload.metadata { 59 | str.push_str(&format!("type:{},\n\t", meta.r#type)); 60 | str.push_str(&format!("client_ip:{},\n\t", meta.client_ip)); 61 | str.push_str(&format!("header:{:?},\n\t", meta.headers)); 62 | } 63 | if let Some(body) = &payload.body { 64 | let new_value = body.clone(); 65 | let value_str = String::from_utf8(new_value.value).unwrap(); 66 | str.push_str(&format!("body:{}", value_str)); 67 | } 68 | str 69 | } 70 | 71 | pub fn get_payload_type(payload: &nacos_proto::Payload) -> Option<&String> { 72 | if let Some(meta) = &payload.metadata { 73 | return Some(&meta.r#type); 74 | } 75 | None 76 | } 77 | 78 | pub fn get_metadata_type(metadata: &Option) -> Option<&String> { 79 | if let Some(meta) = metadata { 80 | return Some(&meta.r#type); 81 | } 82 | None 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /examples/src/naming_register.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports, unreachable_code)] 2 | use nacos_rust_client::client::naming_client::{InstanceDefaultListener, ServiceInstanceKey}; 3 | use std::sync::Arc; 4 | 5 | use std::time::Duration; 6 | 7 | use nacos_rust_client::client::naming_client::{Instance, NamingClient, QueryInstanceListParams}; 8 | use nacos_rust_client::client::{AuthInfo, ClientBuilder, HostInfo}; 9 | 10 | #[tokio::main] 11 | async fn main() { 12 | //std::env::set_var("RUST_LOG","INFO"); 13 | std::env::set_var("RUST_LOG", "INFO"); 14 | env_logger::init(); 15 | //let host = HostInfo::parse("127.0.0.1:8848"); 16 | //let client = NamingClient::new(host,"".to_owned()); 17 | let namespace_id = "public".to_owned(); //default teant 18 | let auth_info = Some(AuthInfo::new("nacos", "nacos")); 19 | //let auth_info = None; 20 | //let client = NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848", namespace_id, auth_info); 21 | let client = ClientBuilder::new() 22 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 23 | .set_auth_info(auth_info) 24 | .set_tenant(namespace_id) 25 | .set_use_grpc(true) 26 | .set_app_name("foo".to_owned()) 27 | .build_naming_client(); 28 | let servcie_key = ServiceInstanceKey::new("foo", "DEFAULT_GROUP"); 29 | //可以通过监听器获取指定服务的最新实现列表,并支持触发变更回调函数,可用于适配微服务地址选择器。 30 | let default_listener = InstanceDefaultListener::new( 31 | servcie_key, 32 | Some(Arc::new(|instances, add_list, remove_list| { 33 | println!( 34 | "service instances change,count:{},add count:{},remove count:{}", 35 | instances.len(), 36 | add_list.len(), 37 | remove_list.len() 38 | ); 39 | })), 40 | ); 41 | //tokio::time::sleep(Duration::from_millis(3000)).await; 42 | client 43 | .subscribe(Box::new(default_listener.clone())) 44 | .await 45 | .unwrap(); 46 | let ip = local_ipaddress::get().unwrap(); 47 | let service_name = "foo"; 48 | let group_name = "DEFAULT_GROUP"; 49 | for i in 0..10 { 50 | let port = 10000 + i; 51 | let instance = Instance::new_simple(&ip, port, service_name, group_name); 52 | //注册 53 | client.register(instance); 54 | tokio::time::sleep(Duration::from_millis(1000)).await; 55 | } 56 | 57 | //tokio::spawn(async{query_params2().await.unwrap();}); 58 | //let client2 = client.clone(); 59 | tokio::spawn(async move { 60 | query_params().await.unwrap(); 61 | }); 62 | 63 | //let mut buf = vec![0u8;1]; 64 | //stdin().read(&mut buf).unwrap(); 65 | tokio::signal::ctrl_c() 66 | .await 67 | .expect("failed to listen for event"); 68 | println!("n:{}", &client.namespace_id); 69 | } 70 | 71 | async fn query_params() -> anyhow::Result<()> { 72 | //get client from global 73 | let client = nacos_rust_client::get_last_naming_client().unwrap(); 74 | let service_name = "foo"; 75 | let group_name = "DEFAULT_GROUP"; 76 | let params = QueryInstanceListParams::new_simple(service_name, group_name); 77 | // 模拟每秒钟获取一次实例 78 | loop { 79 | //查询并按权重随机选择其中一个实例 80 | match client.select_instance(params.clone()).await { 81 | Ok(instances) => { 82 | println!("select instance {}:{}", &instances.ip, &instances.port); 83 | } 84 | Err(e) => { 85 | println!("select_instance error {:?}", &e) 86 | } 87 | } 88 | tokio::time::sleep(Duration::from_millis(1000)).await; 89 | } 90 | Ok(()) 91 | } 92 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/utils.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::collections::HashMap; 3 | use std::io::Read; 4 | use std::time::Duration; 5 | 6 | pub fn ms(millis: u64) -> Duration { 7 | Duration::from_millis(millis) 8 | } 9 | 10 | pub struct Utils; 11 | 12 | #[derive(Default, Clone, Debug)] 13 | pub struct ResponseWrap { 14 | pub status: u16, 15 | pub headers: Vec<(String, String)>, 16 | pub body: Vec, 17 | } 18 | 19 | impl ResponseWrap { 20 | pub fn status_is_200(&self) -> bool { 21 | self.status == 200 22 | } 23 | 24 | pub fn get_lossy_string_body(&self) -> Cow { 25 | String::from_utf8_lossy(&self.body) 26 | } 27 | 28 | pub fn get_string_body(&self) -> String { 29 | String::from_utf8(self.body.clone()).unwrap() 30 | } 31 | 32 | pub fn get_map_headers(&self) -> HashMap { 33 | Self::convert_to_map_headers(self.headers.clone()) 34 | } 35 | 36 | pub fn convert_to_map_headers(headers: Vec<(String, String)>) -> HashMap { 37 | let mut h = HashMap::new(); 38 | for (k, v) in headers { 39 | h.insert(k, v); 40 | } 41 | h 42 | } 43 | } 44 | 45 | impl Utils { 46 | async fn get_response_wrap(resp: reqwest::Response) -> anyhow::Result { 47 | let status = resp.status().as_u16(); 48 | let mut resp_headers = vec![]; 49 | for (k, v) in resp.headers() { 50 | let value = String::from_utf8(v.as_bytes().to_vec())?; 51 | resp_headers.push((k.as_str().to_owned(), value)); 52 | } 53 | let body = resp.bytes().await?.to_vec(); 54 | Ok(ResponseWrap { 55 | status, 56 | headers: resp_headers, 57 | body, 58 | }) 59 | } 60 | 61 | pub async fn request( 62 | client: &reqwest::Client, 63 | method_name: &str, 64 | url: &str, 65 | body: Vec, 66 | headers: Option<&HashMap>, 67 | timeout_millis: Option, 68 | ) -> anyhow::Result { 69 | let mut req_builer = match method_name { 70 | "GET" => client.get(url), 71 | "POST" => client.post(url), 72 | "PUT" => client.put(url), 73 | "DELETE" => client.delete(url), 74 | _ => client.post(url), 75 | }; 76 | if let Some(headers) = headers { 77 | for (k, v) in headers.iter() { 78 | req_builer = req_builer.header(k, v.to_string()); 79 | } 80 | } 81 | if let Some(timeout) = timeout_millis { 82 | req_builer = req_builer.timeout(Duration::from_millis(timeout)); 83 | } 84 | if !body.is_empty() { 85 | req_builer = req_builer.body(body); 86 | } 87 | let res = req_builer.send().await?; 88 | Self::get_response_wrap(res).await 89 | } 90 | 91 | pub fn gz_encode(data: &[u8], threshold: usize) -> Vec { 92 | use flate2::read::GzEncoder; 93 | if data.len() <= threshold { 94 | data.to_vec() 95 | } else { 96 | let mut result = Vec::new(); 97 | let mut z = GzEncoder::new(data, flate2::Compression::fast()); 98 | z.read_to_end(&mut result).unwrap(); 99 | result 100 | } 101 | } 102 | 103 | pub fn is_gzdata(data: &[u8]) -> bool { 104 | if data.len() > 2 { 105 | return data[0] == 0x1f && data[1] == 0x8b; 106 | } 107 | false 108 | } 109 | 110 | pub fn gz_decode(data: &[u8]) -> Option> { 111 | if !Self::is_gzdata(data) { 112 | return None; 113 | } 114 | use flate2::read::GzDecoder; 115 | let mut result = Vec::new(); 116 | let mut z = GzDecoder::new(data); 117 | match z.read_to_end(&mut result) { 118 | Ok(_) => Some(result), 119 | Err(_) => None, 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /examples/src/config.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] 2 | use std::sync::Arc; 3 | use std::time::Duration; 4 | 5 | use nacos_rust_client::client::config_client::{ConfigClient, ConfigDefaultListener, ConfigKey}; 6 | use nacos_rust_client::client::{AuthInfo, ClientBuilder, HostInfo}; 7 | use serde::{Deserialize, Serialize}; 8 | use serde_json; 9 | 10 | #[derive(Debug, Serialize, Deserialize, Default, Clone)] 11 | pub struct Foo { 12 | pub name: String, 13 | pub number: u64, 14 | } 15 | 16 | #[tokio::main] 17 | async fn main() { 18 | std::env::set_var("RUST_LOG", "INFO"); 19 | env_logger::init(); 20 | //let host = HostInfo::parse("127.0.0.1:8848"); 21 | //let config_client = ConfigClient::new(host,String::new()); 22 | let tenant = "public".to_owned(); //default teant 23 | let auth_info = Some(AuthInfo::new("nacos", "nacos")); 24 | //let auth_info = None; 25 | //let config_client = ConfigClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848",tenant,auth_info); 26 | let config_client = ClientBuilder::new() 27 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 28 | .set_auth_info(auth_info) 29 | .set_tenant(tenant) 30 | .set_use_grpc(true) 31 | .build_config_client(); 32 | tokio::time::sleep(Duration::from_millis(1000)).await; 33 | 34 | let key = ConfigKey::new("001", "foo", ""); 35 | //设置 36 | config_client.set_config(&key, "1234").await.unwrap(); 37 | // 配置推送到服务端后, 监听更新可能需要一点时间 38 | tokio::time::sleep(Duration::from_millis(1000)).await; 39 | //获取 40 | let v = config_client.get_config(&key).await.unwrap(); 41 | println!("{:?},{}", &key, v); 42 | check_listener_value().await; 43 | nacos_rust_client::close_current_system(); 44 | } 45 | 46 | async fn check_listener_value() { 47 | //获取全局最后一次创建的config_client 48 | let config_client = nacos_rust_client::get_last_config_client().unwrap(); 49 | let mut foo_obj = Foo { 50 | name: "foo name".to_owned(), 51 | number: 0u64, 52 | }; 53 | let key = ConfigKey::new("foo_config", "foo", ""); 54 | let foo_config_obj_listener = Box::new(ConfigDefaultListener::new( 55 | key.clone(), 56 | Arc::new(|s| { 57 | //字符串反序列化为对象,如:serde_json::from_str::(s) 58 | Some(serde_json::from_str::(s).unwrap()) 59 | }), 60 | )); 61 | let foo_config_string_listener = Box::new(ConfigDefaultListener::new( 62 | key.clone(), 63 | Arc::new(|s| { 64 | println!("change value: {}", &s); 65 | //字符串反序列化为对象,如:serde_json::from_str::(s) 66 | Some(s.to_owned()) 67 | }), 68 | )); 69 | config_client 70 | .set_config(&key, &serde_json::to_string(&foo_obj).unwrap()) 71 | .await 72 | .unwrap(); 73 | //监听 74 | config_client 75 | .subscribe(foo_config_obj_listener.clone()) 76 | .await 77 | .unwrap(); 78 | config_client 79 | .subscribe(foo_config_string_listener.clone()) 80 | .await 81 | .unwrap(); 82 | //从监听对象中获取 83 | println!( 84 | "key:{:?} ,value:{:?}", 85 | &key.data_id, 86 | foo_config_string_listener.get_value() 87 | ); 88 | for i in 1..10 { 89 | foo_obj.number = i; 90 | let foo_json_string = serde_json::to_string(&foo_obj).unwrap(); 91 | config_client 92 | .set_config(&key, &foo_json_string) 93 | .await 94 | .unwrap(); 95 | // 配置推送到服务端后, 监听更新需要一点时间 96 | tokio::time::sleep(Duration::from_millis(1000)).await; 97 | let foo_obj_from_listener = foo_config_obj_listener.get_value().unwrap(); 98 | let foo_obj_string_from_listener = foo_config_string_listener.get_value().unwrap(); 99 | // 监听项的内容有变更后会被服务端推送,监听项会自动更新为最新的配置 100 | println!("foo_obj_from_listener :{}", &foo_obj_string_from_listener); 101 | assert_eq!(foo_obj_string_from_listener.to_string(), foo_json_string); 102 | assert_eq!(foo_obj_from_listener.number, foo_obj.number); 103 | assert_eq!(foo_obj_from_listener.number, i); 104 | } 105 | 106 | tokio::signal::ctrl_c() 107 | .await 108 | .expect("failed to listen for event"); 109 | } 110 | -------------------------------------------------------------------------------- /examples/src/naming_only_register.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports, unreachable_code)] 2 | use actix::{Actor, Addr}; 3 | use ctrlc; 4 | use nacos_rust_client::client::auth::AuthActor; 5 | use nacos_rust_client::client::naming_client::{InstanceDefaultListener, ServiceInstanceKey}; 6 | use nacos_rust_client::conn_manage; 7 | use nacos_rust_client::conn_manage::conn_msg::NamingRequest; 8 | use nacos_rust_client::conn_manage::manage::ConnManage; 9 | use std::sync::mpsc::channel; 10 | use std::sync::Arc; 11 | 12 | use std::time::Duration; 13 | 14 | use nacos_rust_client::client::naming_client::{Instance, NamingClient, QueryInstanceListParams}; 15 | use nacos_rust_client::client::{AuthInfo, HostInfo, ServerEndpointInfo}; 16 | 17 | fn get_service_ip_list(hundreds_count: u64) -> Vec { 18 | let mut rlist = vec![]; 19 | for i in 100..(100 + hundreds_count) { 20 | for j in 100..200 { 21 | let ip = format!("192.168.{}.{}", &i, &j); 22 | rlist.push(ip); 23 | } 24 | } 25 | rlist 26 | } 27 | 28 | /* 29 | async fn register(service_name:&str,group_name:&str,ips:&Vec,port:u32,client:&NamingClient) { 30 | log::info!("register,{},{}",service_name,group_name); 31 | for ip in ips { 32 | let instance = Instance::new_simple(&ip,port,service_name,group_name); 33 | //注册 34 | client.register(instance); 35 | } 36 | } 37 | */ 38 | 39 | fn register( 40 | service_name: &str, 41 | group_name: &str, 42 | ips: &Vec, 43 | port: u32, 44 | conn_manage: &Addr, 45 | ) { 46 | log::info!("register,{},{}", service_name, group_name); 47 | for ip in ips { 48 | let instance = Instance::new_simple(&ip, port, service_name, group_name); 49 | //注册 50 | let msg = NamingRequest::Register(instance); 51 | conn_manage.do_send(msg); 52 | } 53 | } 54 | 55 | fn start_actor_at_new_thread(actor: T) -> Addr 56 | where 57 | T: Actor> + Send, 58 | { 59 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 60 | std::thread::spawn(move || { 61 | let rt = actix::System::new(); 62 | let addrs = rt.block_on(async { actor.start() }); 63 | tx.send(addrs).unwrap(); 64 | rt.run().unwrap(); 65 | }); 66 | let addrs = rx.recv().unwrap(); 67 | addrs 68 | } 69 | 70 | /* 71 | fn build_one_manage_addr(conn_manage:ConnManage) -> Addr { 72 | let (tx,rx) = std::sync::mpsc::sync_channel(1); 73 | std::thread::spawn(move || { 74 | let rt = actix::System::new(); 75 | let addrs = rt.block_on(async { 76 | conn_manage.start() 77 | }); 78 | tx.send(addrs).unwrap(); 79 | rt.run().unwrap(); 80 | }); 81 | let addrs = rx.recv().unwrap(); 82 | addrs 83 | } 84 | */ 85 | 86 | fn build_conn_manages(thread_num: u16) -> Vec> { 87 | let mut rlist = vec![]; 88 | let endpoint = Arc::new(ServerEndpointInfo::new("127.0.0.1:8848,127.0.0.1:8848")); 89 | 90 | let auth_actor = AuthActor::new(endpoint.clone(), None); 91 | let auth_addr = start_actor_at_new_thread(auth_actor); 92 | 93 | for _ in 0..thread_num { 94 | let conn_manage = ConnManage::new( 95 | endpoint.hosts.clone(), 96 | true, 97 | None, 98 | Default::default(), 99 | Default::default(), 100 | auth_addr.clone(), 101 | ); 102 | let conn_manage_addr = start_actor_at_new_thread(conn_manage); 103 | rlist.push(conn_manage_addr); 104 | } 105 | rlist 106 | } 107 | 108 | fn main() { 109 | let (tx, rx) = channel(); 110 | ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel.")) 111 | .expect("Error setting Ctrl-C handler"); 112 | std::env::set_var("RUST_LOG", "INFO"); 113 | env_logger::init(); 114 | let thread_num = 10usize; 115 | let addrs = build_conn_manages(thread_num as u16); 116 | std::thread::sleep(Duration::from_millis(1000)); 117 | 118 | let ips = get_service_ip_list(1); 119 | let group_name = "DEFAULT_GROUP"; 120 | for i in 0..100 { 121 | let index = i % thread_num; 122 | let conn_manage_addr = &addrs.get(index).unwrap(); 123 | let service_name = format!("foo_{}", i); 124 | register(&service_name, group_name, &ips, 10000, &conn_manage_addr); 125 | } 126 | 127 | println!("Waiting for Ctrl-C..."); 128 | rx.recv().expect("Could not receive from channel."); 129 | println!("Got it! Exiting..."); 130 | } 131 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/auth.rs: -------------------------------------------------------------------------------- 1 | use crate::client::ServerEndpointInfo; 2 | use std::sync::Arc; 3 | use std::time::Duration; 4 | 5 | use super::AuthInfo; 6 | use crate::client::nacos_client::{ActixSystemCmd, ActixSystemResult}; 7 | use crate::init_global_system_actor; 8 | use actix::{prelude::*, Context}; 9 | 10 | pub struct AuthActor { 11 | endpoints: Arc, 12 | auth: Option, 13 | client: reqwest::Client, 14 | use_auth: bool, 15 | token: Arc, 16 | token_time_out: u64, 17 | } 18 | 19 | impl AuthActor { 20 | pub fn new(endpoints: Arc, auth_info: Option) -> Self { 21 | let use_auth = if let Some(auth) = &auth_info { 22 | auth.is_valid() 23 | } else { 24 | false 25 | }; 26 | Self { 27 | endpoints, 28 | auth: auth_info, 29 | client: reqwest::Client::new(), 30 | use_auth, 31 | token: Default::default(), 32 | token_time_out: Default::default(), 33 | } 34 | } 35 | 36 | fn update_token(&mut self, ctx: &mut Context) { 37 | if !self.use_auth { 38 | return; 39 | } 40 | let client = self.client.clone(); 41 | let endpoints = self.endpoints.clone(); 42 | let auth = self.auth.clone(); 43 | async move { 44 | let auth = auth.unwrap(); 45 | super::Client::login(&client, endpoints, &auth).await 46 | } 47 | .into_actor(self) 48 | .map(|result, this, _| { 49 | if let Ok(token_info) = result { 50 | this.token = Arc::new(token_info.access_token); 51 | this.token_time_out = super::now_millis() + (token_info.token_ttl - 5) * 1000; 52 | } 53 | }) 54 | .wait(ctx); 55 | } 56 | 57 | fn get_token(&mut self, ctx: &mut Context) -> Arc { 58 | if !self.use_auth { 59 | return Default::default(); 60 | } 61 | let now = super::now_millis(); 62 | if now < self.token_time_out { 63 | return self.token.clone(); 64 | } 65 | self.update_token(ctx); 66 | if self.token.is_empty() { 67 | log::warn!("get token is empty"); 68 | } 69 | self.token.clone() 70 | } 71 | 72 | pub fn hb(&mut self, ctx: &mut Context) { 73 | if !self.use_auth { 74 | return; 75 | } 76 | let now = super::now_millis(); 77 | if now + 60 * 1000 > self.token_time_out { 78 | self.update_token(ctx); 79 | } 80 | ctx.run_later(Duration::from_secs(30), |act, ctx| { 81 | act.hb(ctx); 82 | }); 83 | } 84 | 85 | pub fn init_auth_actor( 86 | endpoints: Arc, 87 | auth_info: Option, 88 | ) -> Addr { 89 | let system_addr = init_global_system_actor(); 90 | let actor = AuthActor::new(endpoints, auth_info); 91 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 92 | let msg = ActixSystemCmd::AuthActor(actor, tx); 93 | system_addr.do_send(msg); 94 | match rx.recv().unwrap() { 95 | ActixSystemResult::AuthActorAddr(auth_addr) => auth_addr, 96 | _ => panic!("init actor error"), 97 | } 98 | } 99 | } 100 | 101 | impl Actor for AuthActor { 102 | type Context = Context; 103 | 104 | fn started(&mut self, ctx: &mut Self::Context) { 105 | log::info!("AuthActor started"); 106 | self.hb(ctx); 107 | //ctx.run_later(Duration::from_nanos(1), |act,ctx|{ 108 | // act.hb(ctx); 109 | //}); 110 | } 111 | } 112 | 113 | //type AuthHandleResultSender = tokio::sync::oneshot::Sender; 114 | 115 | #[derive(Message)] 116 | #[rtype(result = "Result")] 117 | pub enum AuthCmd { 118 | //QueryToken(AuthHandleResultSender), 119 | QueryToken, 120 | } 121 | 122 | pub enum AuthHandleResult { 123 | None, 124 | Token(Arc), 125 | } 126 | 127 | impl Handler for AuthActor { 128 | type Result = Result; 129 | fn handle(&mut self, msg: AuthCmd, ctx: &mut Context) -> Self::Result { 130 | match msg { 131 | AuthCmd::QueryToken => { 132 | let token = self.get_token(ctx); 133 | Ok(AuthHandleResult::Token(token)) 134 | } 135 | } 136 | } 137 | } 138 | 139 | pub async fn get_token_result(auth_addr: &Addr) -> anyhow::Result> { 140 | match auth_addr.send(AuthCmd::QueryToken).await?? { 141 | AuthHandleResult::None => {} 142 | AuthHandleResult::Token(v) => { 143 | if v.len() > 0 { 144 | return Ok(v); 145 | } 146 | } 147 | }; 148 | Ok(Default::default()) 149 | } 150 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/builder.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, sync::Arc}; 2 | 3 | use super::{ 4 | config_client::inner_client::ConfigInnerRequestClient, nacos_client::ActixSystemActorSetCmd, 5 | naming_client::InnerNamingRequestClient, AuthInfo, ClientInfo, ConfigClient, HostInfo, 6 | NamingClient, ServerEndpointInfo, 7 | }; 8 | use crate::client::auth::AuthActor; 9 | use crate::{conn_manage::manage::ConnManage, init_global_system_actor}; 10 | 11 | #[derive(Clone, Debug)] 12 | pub struct ClientBuilder { 13 | endpoint: ServerEndpointInfo, 14 | tenant: String, 15 | auth_info: Option, 16 | use_grpc: bool, 17 | client_info: ClientInfo, 18 | } 19 | 20 | impl Default for ClientBuilder { 21 | fn default() -> Self { 22 | Self::new() 23 | } 24 | } 25 | 26 | impl ClientBuilder { 27 | pub fn new() -> Self { 28 | let endpoint = ServerEndpointInfo::new(""); 29 | Self { 30 | endpoint, 31 | tenant: "public".to_owned(), 32 | auth_info: None, 33 | use_grpc: true, 34 | client_info: Default::default(), 35 | } 36 | } 37 | 38 | pub fn set_tenant(mut self, tenant: String) -> Self { 39 | self.tenant = tenant; 40 | self 41 | } 42 | 43 | pub fn set_endpoint_addrs(mut self, addrs: &str) -> Self { 44 | self.endpoint = ServerEndpointInfo::new(addrs); 45 | self 46 | } 47 | 48 | pub fn set_endpoint(mut self, endpoint: ServerEndpointInfo) -> Self { 49 | self.endpoint = endpoint; 50 | self 51 | } 52 | 53 | pub fn set_hosts(mut self, hosts: Vec) -> Self { 54 | self.endpoint = ServerEndpointInfo { hosts }; 55 | self 56 | } 57 | 58 | pub fn set_auth_info(mut self, auth_info: Option) -> Self { 59 | self.auth_info = auth_info; 60 | self 61 | } 62 | 63 | pub fn set_use_grpc(mut self, use_grpc: bool) -> Self { 64 | self.use_grpc = use_grpc; 65 | self 66 | } 67 | 68 | pub fn set_client_info(mut self, client_info: ClientInfo) -> Self { 69 | self.client_info = client_info; 70 | self 71 | } 72 | 73 | pub fn set_client_ip(mut self, client_ip: String) -> Self { 74 | self.client_info.client_ip = client_ip; 75 | self 76 | } 77 | 78 | pub fn set_app_name(mut self, app_name: String) -> Self { 79 | self.client_info.app_name = app_name; 80 | self 81 | } 82 | 83 | pub fn set_headers(mut self, headers: HashMap) -> Self { 84 | self.client_info.headers = headers; 85 | self 86 | } 87 | 88 | pub fn build_config_client(self) -> Arc { 89 | let (config_client, _) = self.build(); 90 | config_client 91 | } 92 | 93 | pub fn build_naming_client(self) -> Arc { 94 | let (_, naming_client) = self.build(); 95 | naming_client 96 | } 97 | 98 | pub fn build(self) -> (Arc, Arc) { 99 | let use_grpc = self.use_grpc; 100 | let auth_info = self.auth_info; 101 | let endpoint = Arc::new(self.endpoint); 102 | let namespace_id = self.tenant.clone(); 103 | let tenant = self.tenant; 104 | let current_ip = self.client_info.client_ip.clone(); 105 | let auth_actor = AuthActor::init_auth_actor(endpoint.clone(), auth_info.clone()); 106 | 107 | let conn_manage = ConnManage::new( 108 | endpoint.hosts.clone(), 109 | use_grpc, 110 | auth_info.clone(), 111 | Default::default(), 112 | Arc::new(self.client_info), 113 | auth_actor.clone(), 114 | ); 115 | let conn_manage_addr = conn_manage.start_at_global_system(); 116 | let request_client = 117 | InnerNamingRequestClient::new_with_endpoint(endpoint.clone(), Some(auth_actor.clone())); 118 | let addrs = NamingClient::init_register( 119 | namespace_id.clone(), 120 | current_ip.clone(), 121 | request_client, 122 | Some(conn_manage_addr.clone().downgrade()), 123 | use_grpc, 124 | ); 125 | let naming_client = Arc::new(NamingClient { 126 | namespace_id, 127 | register: addrs.0, 128 | listener_addr: addrs.1, 129 | current_ip, 130 | _conn_manage_addr: conn_manage_addr.clone(), 131 | }); 132 | let system_addr = init_global_system_actor(); 133 | system_addr.do_send(ActixSystemActorSetCmd::LastNamingClient( 134 | naming_client.clone(), 135 | )); 136 | 137 | let request_client = 138 | ConfigInnerRequestClient::new_with_endpoint(endpoint, Some(auth_actor.clone())); 139 | let config_inner_addr = ConfigClient::init_register( 140 | request_client.clone(), 141 | Some(conn_manage_addr.clone().downgrade()), 142 | use_grpc, 143 | ); 144 | let config_client = Arc::new(ConfigClient { 145 | tenant, 146 | request_client, 147 | config_inner_addr, 148 | conn_manage_addr, 149 | }); 150 | //let system_addr = init_global_system_actor(); 151 | system_addr.do_send(ActixSystemActorSetCmd::LastConfigClient( 152 | config_client.clone(), 153 | )); 154 | (config_client, naming_client) 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/listener.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use super::config_key::ConfigKey; 4 | 5 | pub struct ListenerItem { 6 | pub key: ConfigKey, 7 | pub md5: String, 8 | } 9 | 10 | impl ListenerItem { 11 | pub fn new(key: ConfigKey, md5: String) -> Self { 12 | Self { key, md5 } 13 | } 14 | 15 | pub fn decode_listener_items(configs: &str) -> Vec { 16 | let mut list = vec![]; 17 | let mut start = 0; 18 | let bytes = configs.as_bytes(); 19 | let mut tmp_list = vec![]; 20 | for i in 0..bytes.len() { 21 | let char = bytes[i]; 22 | if char == 2 { 23 | if tmp_list.len() > 2 { 24 | continue; 25 | } 26 | //tmpList.push(configs[start..i].to_owned()); 27 | tmp_list.push(String::from_utf8(configs[start..i].into()).unwrap()); 28 | start = i + 1; 29 | } else if char == 1 { 30 | let mut end_value = String::new(); 31 | if start < i { 32 | //endValue = configs[start..i].to_owned(); 33 | end_value = String::from_utf8(configs[start..i].into()).unwrap(); 34 | } 35 | start = i + 1; 36 | if tmp_list.len() == 2 { 37 | let key = ConfigKey::new(&tmp_list[0], &tmp_list[1], ""); 38 | list.push(ListenerItem::new(key, end_value)); 39 | } else { 40 | let key = ConfigKey::new(&tmp_list[0], &tmp_list[1], &end_value); 41 | list.push(ListenerItem::new(key, tmp_list[2].to_owned())); 42 | } 43 | tmp_list.clear(); 44 | } 45 | } 46 | list 47 | } 48 | 49 | pub fn decode_listener_change_keys(configs: &str) -> Vec { 50 | let mut list = vec![]; 51 | let mut start = 0; 52 | let bytes = configs.as_bytes(); 53 | let mut tmp_list = vec![]; 54 | for i in 0..bytes.len() { 55 | let char = bytes[i]; 56 | if char == 2 { 57 | if tmp_list.len() > 2 { 58 | continue; 59 | } 60 | //tmpList.push(configs[start..i].to_owned()); 61 | tmp_list.push(String::from_utf8(configs[start..i].into()).unwrap()); 62 | start = i + 1; 63 | } else if char == 1 { 64 | let mut end_value = String::new(); 65 | if start < i { 66 | //endValue = configs[start..i].to_owned(); 67 | end_value = String::from_utf8(configs[start..i].into()).unwrap(); 68 | } 69 | start = i + 1; 70 | if tmp_list.len() == 1 { 71 | let key = ConfigKey::new(&tmp_list[0], &end_value, ""); 72 | list.push(key); 73 | } else { 74 | let key = ConfigKey::new(&tmp_list[0], &tmp_list[1], &end_value); 75 | list.push(key); 76 | } 77 | tmp_list.clear(); 78 | } 79 | } 80 | list 81 | } 82 | } 83 | 84 | pub trait ConfigListener { 85 | fn get_key(&self) -> ConfigKey; 86 | fn change(&self, key: &ConfigKey, value: &str); 87 | } 88 | 89 | pub type ListenerConvert = Arc Option + Send + Sync>; 90 | 91 | #[derive(Clone)] 92 | pub struct ConfigDefaultListener { 93 | key: ConfigKey, 94 | pub content: Arc>>>, 95 | pub convert: ListenerConvert, 96 | } 97 | 98 | impl ConfigDefaultListener { 99 | pub fn new(key: ConfigKey, convert: ListenerConvert) -> Self { 100 | Self { 101 | key, 102 | content: Default::default(), 103 | convert, 104 | } 105 | } 106 | 107 | pub fn get_value(&self) -> Option> { 108 | self.content.read().unwrap().as_ref().map(|c| c.clone()) 109 | } 110 | 111 | fn set_value(content: Arc>>>, value: T) { 112 | let mut r = content.write().unwrap(); 113 | *r = Some(Arc::new(value)); 114 | } 115 | } 116 | 117 | impl ConfigListener for ConfigDefaultListener { 118 | fn get_key(&self) -> ConfigKey { 119 | self.key.clone() 120 | } 121 | 122 | fn change(&self, key: &ConfigKey, value: &str) { 123 | log::debug!("ConfigDefaultListener change:{:?},{}", key, value); 124 | let content = self.content.clone(); 125 | let convert = self.convert.as_ref(); 126 | if let Some(value) = convert(value) { 127 | Self::set_value(content, value); 128 | } 129 | } 130 | } 131 | 132 | pub(crate) struct ListenerValue { 133 | pub(crate) md5: String, 134 | listeners: Vec<(u64, Box)>, 135 | } 136 | 137 | impl ListenerValue { 138 | pub(crate) fn new(listeners: Vec<(u64, Box)>, md5: String) -> Self { 139 | Self { md5, listeners } 140 | } 141 | 142 | pub(crate) fn push(&mut self, id: u64, func: Box) { 143 | self.listeners.push((id, func)); 144 | } 145 | 146 | pub(crate) fn notify(&self, key: &ConfigKey, content: &str) { 147 | for (_, func) in self.listeners.iter() { 148 | func.change(key, content); 149 | } 150 | } 151 | 152 | pub(crate) fn remove(&mut self, id: u64) -> usize { 153 | let mut indexs = Vec::new(); 154 | for i in 0..self.listeners.len() { 155 | if let Some((item_id, _)) = self.listeners.get(i) { 156 | if id == *item_id { 157 | indexs.push(i); 158 | } 159 | } 160 | } 161 | for index in indexs.iter().rev() { 162 | let index = *index; 163 | self.listeners.remove(index); 164 | } 165 | self.listeners.len() 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /nacos-tonic-discover/README.md: -------------------------------------------------------------------------------- 1 | 2 | # nacos-tonic-discover 3 | 4 | ## 介绍 5 | nacos_rust_client 对 tonic 服务地址选择器的适配 6 | 7 | ## 使用方式 8 | 9 | ```toml 10 | [dependencies] 11 | nacos-tonic-discover = "0.1" 12 | nacos_rust_client = "0.3" 13 | tonic = "0.7" 14 | ``` 15 | 16 | ### 地址选择器工厂 17 | 18 | 地址选择器工厂,背后会缓存channel,监听服务地址变更然后更新到channel。 19 | 20 | 1. 创建地址选择器工厂 21 | 22 | ```rust 23 | let discover_factory = TonicDiscoverFactory::new(naming_client.clone()); 24 | ``` 25 | 26 | 创建地址选择器工厂,后会把工厂的一个引用加入到全局对象,可以通过 `get_last_factory`获取. 27 | 28 | ```rust 29 | let discover_factory = nacos_tonic_discover::get_last_factory().unwrap();``` 30 | 31 | 2. 构建指定服务对应的 `tonic::transport::Channel` 32 | 33 | ```rust 34 | let service_key = ServiceInstanceKey::new("helloworld","AppName"); 35 | let channel = discover_factory.build_service_channel(service_key.clone()).await?; 36 | ``` 37 | 38 | 地址选择器工厂,背后会维护 `Channel`的最新有效地址;对同一个service_key实际只创建一个`Channel`,第一次构建,后续直接返回缓存拷贝。 39 | 40 | 3. 使用Channel创建service client,并使用 41 | 42 | ```rust 43 | let mut client = GreeterClient::new(channel); 44 | let request = tonic::Request::new(HelloRequest { 45 | name: format!("Tonic"), 46 | }); 47 | let response = client.say_hello(request).await?; 48 | ``` 49 | 50 | ## 例子 51 | 52 | 运行下面的例子,需要先启动nacos服务,把例子中的host改成实际的地址。 53 | 54 | 例子完整依赖与代码可以参考 examples/下的代码。 55 | 56 | 57 | 58 | 59 | ### tonic service示例 60 | 61 | ```sh 62 | # 运行方式 63 | cargo run --example tonic_discover_service 64 | ``` 65 | 66 | 67 | ```rust 68 | // file: examples/src/tonic-discover/service.rs 69 | 70 | use nacos_rust_client::client::naming_client::Instance; 71 | use nacos_rust_client::client::naming_client::NamingClient; 72 | use tokio::sync::mpsc; 73 | use tonic::{transport::Server, Request, Response, Status}; 74 | 75 | use hello_world::greeter_server::{Greeter, GreeterServer}; 76 | use hello_world::{HelloReply, HelloRequest}; 77 | 78 | pub mod hello_world { 79 | tonic::include_proto!("helloworld"); 80 | } 81 | 82 | #[derive(Default)] 83 | pub struct MyGreeter {} 84 | 85 | #[tonic::async_trait] 86 | impl Greeter for MyGreeter { 87 | async fn say_hello( 88 | &self, 89 | request: Request, 90 | ) -> Result, Status> { 91 | println!("Got a request from {:?}", request.remote_addr()); 92 | 93 | let reply = hello_world::HelloReply { 94 | message: format!("Hello {}!", request.into_inner().name), 95 | }; 96 | Ok(Response::new(reply)) 97 | } 98 | } 99 | 100 | #[tokio::main] 101 | async fn main() -> Result<(), Box> { 102 | //let ip="[::]" ; //only use at localhost 103 | let ip = local_ipaddress::get().unwrap(); 104 | let addrs = [(ip.clone(),10051),(ip.clone(),10052)]; 105 | let namespace_id = "public".to_owned(); //default teant 106 | let auth_info = None; // Some(AuthInfo::new("nacos","nacos")) 107 | let client = NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848", namespace_id, auth_info); 108 | 109 | let (tx, mut rx) = mpsc::unbounded_channel(); 110 | 111 | for (ip,port) in &addrs { 112 | let addr = format!("{}:{}","0.0.0.0",port).parse()?; 113 | let tx = tx.clone(); 114 | let greeter = MyGreeter::default(); 115 | let serve = Server::builder() 116 | .add_service(GreeterServer::new(greeter)) 117 | .serve(addr); 118 | 119 | tokio::spawn(async move { 120 | if let Err(e) = serve.await { 121 | eprintln!("Error = {:?}", e); 122 | } 123 | 124 | tx.send(()).unwrap(); 125 | }); 126 | } 127 | 128 | for (ip,port) in &addrs { 129 | let instance = Instance::new_simple(&ip,port.to_owned(),"helloworld","AppName"); 130 | client.register(instance); 131 | } 132 | 133 | rx.recv().await; 134 | 135 | Ok(()) 136 | } 137 | ``` 138 | 139 | ### tonic client示例 140 | 141 | ```sh 142 | # 运行方式 143 | cargo run --example tonic_discover_client 144 | ``` 145 | 146 | ```rust 147 | // file: examples/src/tonic-discover/client.rs 148 | 149 | use std::time::Duration; 150 | use nacos_rust_client::client::naming_client::{ServiceInstanceKey, QueryInstanceListParams}; 151 | use nacos_tonic_discover::TonicDiscoverFactory; 152 | use nacos_rust_client::client::naming_client::NamingClient; 153 | use hello_world::greeter_client::GreeterClient; 154 | use hello_world::HelloRequest; 155 | 156 | pub mod hello_world { 157 | tonic::include_proto!("helloworld"); 158 | } 159 | 160 | #[tokio::main] 161 | async fn main() -> Result<(), Box> { 162 | let namespace_id = "public".to_owned(); //default teant 163 | let auth_info = None; // Some(AuthInfo::new("nacos","nacos")) 164 | let naming_client = NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848", namespace_id, auth_info); 165 | 166 | 167 | let service_key = ServiceInstanceKey::new("helloworld","AppName"); 168 | //build client by discover factory 169 | let discover_factory = TonicDiscoverFactory::new(naming_client.clone()); 170 | let channel = discover_factory.build_service_channel(service_key.clone()).await?; 171 | let mut client = GreeterClient::new(channel); 172 | 173 | for i in 0..5 { 174 | let request = tonic::Request::new(HelloRequest { 175 | name: format!("Tonic {} [client by discover factory]",i), 176 | }); 177 | let response = client.say_hello(request).await?; 178 | println!("RESPONSE={:?}", response); 179 | tokio::time::sleep(Duration::from_millis(1000)).await; 180 | } 181 | 182 | //build client by naming client select 183 | let param = QueryInstanceListParams::new_by_serivce_key(&service_key); 184 | 185 | for i in 5..10 { 186 | let instance=naming_client.select_instance(param.clone()).await?; 187 | let mut client = GreeterClient::connect(format!("http://{}:{}",&instance.ip,&instance.port)).await?; 188 | let request = tonic::Request::new(HelloRequest { 189 | name: format!("Tonic {} [client by naming client select]",i), 190 | }); 191 | let response = client.say_hello(request).await?; 192 | println!("RESPONSE={:?}", response); 193 | tokio::time::sleep(Duration::from_millis(1000)).await; 194 | } 195 | Ok(()) 196 | } 197 | 198 | ``` -------------------------------------------------------------------------------- /nacos_rust_client/src/client/naming_client/request_client.rs: -------------------------------------------------------------------------------- 1 | use crate::client; 2 | use crate::client::auth::{AuthActor, AuthCmd, AuthHandleResult}; 3 | use crate::client::naming_client::Instance; 4 | use crate::client::naming_client::QueryInstanceListParams; 5 | use crate::client::naming_client::QueryListResult; 6 | use crate::client::utils::Utils; 7 | use crate::client::ServerEndpointInfo; 8 | use actix::Addr; 9 | use std::{collections::HashMap, sync::Arc}; 10 | 11 | #[derive(Clone)] 12 | pub struct InnerNamingRequestClient { 13 | pub(crate) client: reqwest::Client, 14 | pub(crate) headers: HashMap, 15 | pub(crate) endpoints: Arc, 16 | pub(crate) auth_addr: Option>, 17 | } 18 | 19 | impl InnerNamingRequestClient { 20 | /* 21 | pub(crate) fn new(host:HostInfo) -> Self{ 22 | let client = reqwest::Client::builder() 23 | .build().unwrap(); 24 | let mut headers = HashMap::new(); 25 | headers.insert("Content-Type".to_owned(), "application/x-www-form-urlencoded".to_owned()); 26 | let endpoints = Arc::new(ServerEndpointInfo{ 27 | hosts: vec![host], 28 | }); 29 | Self{ 30 | client, 31 | headers, 32 | endpoints, 33 | auth_addr:None, 34 | } 35 | } 36 | */ 37 | 38 | pub(crate) fn new_with_endpoint( 39 | endpoints: Arc, 40 | auth_addr: Option>, 41 | ) -> Self { 42 | let client = reqwest::Client::builder().build().unwrap(); 43 | Self { 44 | endpoints, 45 | client, 46 | headers: client::Client::build_http_headers(), 47 | auth_addr, 48 | } 49 | } 50 | 51 | pub(crate) fn set_auth_addr(&mut self, addr: Addr) { 52 | self.auth_addr = Some(addr); 53 | } 54 | 55 | pub(crate) async fn get_token_result(&self) -> anyhow::Result { 56 | if let Some(auth_addr) = &self.auth_addr { 57 | match auth_addr.send(AuthCmd::QueryToken).await?? { 58 | AuthHandleResult::None => {} 59 | AuthHandleResult::Token(v) => { 60 | if v.len() > 0 { 61 | return Ok(format!("accessToken={}", &v)); 62 | } 63 | } 64 | }; 65 | } 66 | Ok(String::new()) 67 | } 68 | 69 | pub(crate) async fn get_token(&self) -> String { 70 | self.get_token_result().await.unwrap_or_default() 71 | } 72 | 73 | pub(crate) async fn register(&self, instance: &Instance) -> anyhow::Result { 74 | let params = instance.to_web_params(); 75 | let body = serde_urlencoded::to_string(¶ms)?; 76 | let host = self.endpoints.select_host(); 77 | let token_param = self.get_token().await; 78 | let url = format!( 79 | "http://{}:{}/nacos/v1/ns/instance?{}", 80 | &host.ip, &host.port, token_param 81 | ); 82 | let resp = Utils::request( 83 | &self.client, 84 | "POST", 85 | &url, 86 | body.as_bytes().to_vec(), 87 | Some(&self.headers), 88 | Some(3000), 89 | ) 90 | .await?; 91 | //log::info!("register:{}",resp.get_lossy_string_body()); 92 | Ok("ok" == resp.get_string_body()) 93 | } 94 | 95 | pub(crate) async fn remove(&self, instance: &Instance) -> anyhow::Result { 96 | let params = instance.to_web_params(); 97 | let body = serde_urlencoded::to_string(¶ms)?; 98 | let host = self.endpoints.select_host(); 99 | let token_param = self.get_token().await; 100 | let url = format!( 101 | "http://{}:{}/nacos/v1/ns/instance?{}", 102 | &host.ip, &host.port, token_param 103 | ); 104 | let resp = Utils::request( 105 | &self.client, 106 | "DELETE", 107 | &url, 108 | body.as_bytes().to_vec(), 109 | Some(&self.headers), 110 | Some(3000), 111 | ) 112 | .await?; 113 | //log::info!("remove:{}",resp.get_lossy_string_body()); 114 | Ok("ok" == resp.get_string_body()) 115 | } 116 | 117 | pub(crate) async fn heartbeat(&self, beat_string: Arc) -> anyhow::Result { 118 | let host = self.endpoints.select_host(); 119 | let token_param = self.get_token().await; 120 | let url = format!( 121 | "http://{}:{}/nacos/v1/ns/instance/beat?{}", 122 | &host.ip, &host.port, token_param 123 | ); 124 | let resp = Utils::request( 125 | &self.client, 126 | "PUT", 127 | &url, 128 | beat_string.as_bytes().to_vec(), 129 | Some(&self.headers), 130 | Some(3000), 131 | ) 132 | .await?; 133 | //log::debug!("heartbeat:{}",resp.get_lossy_string_body()); 134 | Ok("ok" == resp.get_string_body()) 135 | } 136 | 137 | pub(crate) async fn get_instance_list( 138 | &self, 139 | query_param: &QueryInstanceListParams, 140 | ) -> anyhow::Result { 141 | let params = query_param.to_web_params(); 142 | let token_param = self.get_token().await; 143 | let host = self.endpoints.select_host(); 144 | let url = format!( 145 | "http://{}:{}/nacos/v1/ns/instance/list?{}&{}", 146 | &host.ip, 147 | &host.port, 148 | token_param, 149 | &serde_urlencoded::to_string(¶ms)? 150 | ); 151 | let resp = Utils::request( 152 | &self.client, 153 | "GET", 154 | &url, 155 | vec![], 156 | Some(&self.headers), 157 | Some(3000), 158 | ) 159 | .await?; 160 | 161 | let result: Result = serde_json::from_slice(&resp.body); 162 | match result { 163 | Ok(r) => { 164 | //log::debug!("get_instance_list instance:{}",&r.hosts.is_some()); 165 | Ok(r) 166 | } 167 | Err(e) => { 168 | log::error!( 169 | "get_instance_list error:\n\turl:{}\n\t{}", 170 | &url, 171 | resp.get_string_body() 172 | ); 173 | Err(anyhow::format_err!(e)) 174 | } 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/naming_client/udp_actor.rs: -------------------------------------------------------------------------------- 1 | use actix::prelude::*; 2 | use std::net::SocketAddr; 3 | use std::sync::Arc; 4 | use std::time::Duration; 5 | use tokio::net::UdpSocket; 6 | 7 | use super::InnerNamingListener; 8 | 9 | const MAX_DATAGRAM_SIZE: usize = 65_507; 10 | pub struct UdpWorker { 11 | local_addr_str: Option, 12 | socket: Option>, 13 | addr: Option>, 14 | udp_port: u16, 15 | buf: Option>, 16 | } 17 | 18 | impl UdpWorker { 19 | pub fn new(addr: Option>) -> Self { 20 | Self { 21 | local_addr_str: None, 22 | socket: None, 23 | addr, 24 | udp_port: 0, 25 | buf: Some(vec![]), 26 | } 27 | } 28 | 29 | pub fn new_with_socket(socket: UdpSocket, addr: Option>) -> Self { 30 | let local_addr = socket.local_addr().unwrap(); 31 | let udp_port = local_addr.port(); 32 | Self { 33 | local_addr_str: None, 34 | socket: Some(Arc::new(socket)), 35 | addr, 36 | udp_port, 37 | buf: Some(vec![]), 38 | } 39 | } 40 | 41 | fn init(&mut self, ctx: &mut actix::Context) { 42 | self.init_socket(ctx); 43 | //self.init_loop_recv(ctx); 44 | } 45 | 46 | fn init_socket(&mut self, ctx: &mut actix::Context) { 47 | if self.socket.is_some() { 48 | self.init_loop_recv(ctx); 49 | return; 50 | } 51 | let local_addr_str = if let Some(addr) = self.local_addr_str.as_ref() { 52 | addr.to_owned() 53 | } else { 54 | "0.0.0.0:0".to_owned() 55 | }; 56 | async move { UdpSocket::bind(&local_addr_str).await.unwrap() } 57 | .into_actor(self) 58 | .map(|r, act, ctx| { 59 | act.udp_port = r.local_addr().unwrap().port(); 60 | if let Some(_addr) = &act.addr { 61 | _addr.do_send(InitLocalAddr { port: act.udp_port }); 62 | } 63 | act.socket = Some(Arc::new(r)); 64 | act.init_loop_recv(ctx); 65 | }) 66 | .wait(ctx); 67 | } 68 | 69 | fn init_loop_recv(&mut self, ctx: &mut actix::Context) { 70 | let socket = self.socket.as_ref().unwrap().clone(); 71 | let notify_addr = self.addr.clone(); 72 | let buf = self.buf.replace(Vec::new()); 73 | async move { 74 | let mut buf = buf.unwrap_or_default(); 75 | if buf.len() < MAX_DATAGRAM_SIZE { 76 | buf = vec![0u8; MAX_DATAGRAM_SIZE]; 77 | } 78 | //let mut buf = buf.unwrap_or_else(|| vec![0u8; MAX_DATAGRAM_SIZE]); 79 | //buf=vec![0u8;MAX_DATAGRAM_SIZE]; 80 | if let Ok((len, addr)) = socket.recv_from(&mut buf).await { 81 | //let mut data:Vec = Vec::with_capacity(len); 82 | let mut data: Vec = vec![0u8; len]; 83 | data.clone_from_slice(&buf[..len]); 84 | let msg = UdpDataCmd { 85 | data, 86 | target_addr: addr, 87 | }; 88 | //let s=String::from_utf8_lossy(&buf[..len]); 89 | //println!("rece from:{} | len:{} | str:{}",&addr,len,s); 90 | if let Some(_notify_addr) = notify_addr { 91 | _notify_addr.do_send(msg); 92 | } 93 | } 94 | buf 95 | } 96 | .into_actor(self) 97 | .map(|buf, act, ctx| { 98 | act.buf.replace(buf); 99 | ctx.run_later(Duration::new(1, 0), |act, ctx| { 100 | act.init_loop_recv(ctx); 101 | }); 102 | }) 103 | .spawn(ctx); 104 | } 105 | } 106 | 107 | impl Actor for UdpWorker { 108 | type Context = Context; 109 | 110 | fn started(&mut self, ctx: &mut Self::Context) { 111 | log::info!(" UdpWorker started"); 112 | self.init(ctx); 113 | } 114 | } 115 | 116 | #[derive(Debug, Message)] 117 | #[rtype(result = "Result<(),std::io::Error>")] 118 | pub struct UdpDataCmd { 119 | pub data: Vec, 120 | pub target_addr: SocketAddr, 121 | } 122 | 123 | #[derive(Debug, Message)] 124 | #[rtype(result = "Result<(),std::io::Error>")] 125 | pub struct InitLocalAddr { 126 | pub port: u16, 127 | } 128 | 129 | impl UdpDataCmd { 130 | pub fn new(data: Vec, addr: SocketAddr) -> Self { 131 | Self { 132 | data, 133 | target_addr: addr, 134 | } 135 | } 136 | } 137 | 138 | impl Handler for UdpWorker { 139 | type Result = Result<(), std::io::Error>; 140 | fn handle(&mut self, msg: UdpDataCmd, ctx: &mut Context) -> Self::Result { 141 | let socket = self.socket.as_ref().unwrap().clone(); 142 | async move { 143 | socket 144 | .send_to(&msg.data, msg.target_addr) 145 | .await 146 | .unwrap_or_default(); 147 | } 148 | .into_actor(self) 149 | .map(|_, _, _| {}) 150 | .spawn(ctx); 151 | Ok(()) 152 | } 153 | } 154 | 155 | #[derive(Message)] 156 | #[rtype(result = "Result")] 157 | pub enum UdpWorkerCmd { 158 | QueryUdpPort, 159 | SetListenerAddr(Addr), 160 | Close, 161 | } 162 | 163 | pub enum UdpWorkerResult { 164 | None, 165 | UdpPort(u16), 166 | } 167 | 168 | impl Handler for UdpWorker { 169 | type Result = Result; 170 | 171 | fn handle(&mut self, msg: UdpWorkerCmd, ctx: &mut Self::Context) -> Self::Result { 172 | match msg { 173 | UdpWorkerCmd::QueryUdpPort => { 174 | if let Some(_addr) = &self.addr { 175 | _addr.do_send(InitLocalAddr { 176 | port: self.udp_port, 177 | }); 178 | } 179 | return Ok(UdpWorkerResult::UdpPort(self.udp_port)); 180 | } 181 | UdpWorkerCmd::Close => { 182 | log::info!("UdpWorker close"); 183 | self.addr = None; 184 | self.socket = None; 185 | ctx.stop(); 186 | } 187 | UdpWorkerCmd::SetListenerAddr(addr) => { 188 | self.addr = Some(addr); 189 | } 190 | }; 191 | Ok(UdpWorkerResult::None) 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/naming_client/register.rs: -------------------------------------------------------------------------------- 1 | use crate::client::naming_client::REGISTER_PERIOD; 2 | use crate::client::now_millis; 3 | use crate::conn_manage::conn_msg::NamingRequest; 4 | use crate::conn_manage::manage::ConnManage; 5 | use crate::conn_manage::manage::ConnManageCmd; 6 | use actix::prelude::*; 7 | use actix::WeakAddr; 8 | use std::collections::HashMap; 9 | use std::time::Duration; 10 | //use crate::client::naming_client::InnerNamingRequestClient; 11 | use crate::client::naming_client::Instance; 12 | use crate::client::naming_client::TimeoutSet; 13 | 14 | //#[derive()] 15 | pub struct InnerNamingRegister { 16 | instances: HashMap, 17 | timeout_set: TimeoutSet, 18 | conn_manage: Option>, 19 | period: u64, 20 | stop_remove_all: bool, 21 | use_grpc: bool, 22 | } 23 | 24 | impl InnerNamingRegister { 25 | pub fn new(use_grpc: bool, conn_manage: Option>) -> Self { 26 | Self { 27 | instances: Default::default(), 28 | timeout_set: Default::default(), 29 | period: REGISTER_PERIOD, 30 | stop_remove_all: false, 31 | conn_manage, 32 | use_grpc, 33 | } 34 | } 35 | 36 | pub fn hb(&self, ctx: &mut actix::Context) { 37 | if self.use_grpc { 38 | return; 39 | } 40 | ctx.run_later(Duration::new(1, 0), |act, ctx| { 41 | let current_time = now_millis(); 42 | let addr = ctx.address(); 43 | for key in act.timeout_set.timeout(current_time) { 44 | addr.do_send(NamingRegisterCmd::Heartbeat(key, current_time)); 45 | } 46 | act.hb(ctx); 47 | }); 48 | } 49 | 50 | fn remove_instance(&self, instance: Instance, _ctx: &mut actix::Context) { 51 | if let Some(conn_manage) = &self.conn_manage { 52 | if let Some(addr) = conn_manage.upgrade() { 53 | addr.do_send(NamingRequest::Unregister(instance.clone())); 54 | } 55 | } 56 | } 57 | 58 | fn remove_all_instance(&mut self, ctx: &mut actix::Context) { 59 | let instances = self.instances.clone(); 60 | for (_, instance) in instances { 61 | self.remove_instance(instance, ctx); 62 | } 63 | self.instances = HashMap::new(); 64 | } 65 | 66 | fn register_instance(&self, instance: Instance) { 67 | if let Some(conn_manage) = &self.conn_manage { 68 | if let Some(addr) = conn_manage.upgrade() { 69 | addr.do_send(NamingRequest::Register(instance)); 70 | } 71 | } 72 | } 73 | 74 | fn heartbeat_instance(&self, instance: &Instance) { 75 | if let Some(conn_manage) = &self.conn_manage { 76 | if let Some(addr) = conn_manage.upgrade() { 77 | addr.do_send(NamingRequest::V1Heartbeat( 78 | instance.beat_string.clone().unwrap_or_default(), 79 | )); 80 | } 81 | } 82 | } 83 | 84 | fn register_all_instances(&self) { 85 | if !self.use_grpc { 86 | return; 87 | } 88 | if let Some(conn_manage) = &self.conn_manage { 89 | if let Some(addr) = conn_manage.upgrade() { 90 | for instance in self.instances.values() { 91 | addr.do_send(NamingRequest::Register(instance.to_owned())); 92 | } 93 | } 94 | } 95 | } 96 | } 97 | 98 | impl Actor for InnerNamingRegister { 99 | type Context = Context; 100 | 101 | fn started(&mut self, ctx: &mut Self::Context) { 102 | log::info!(" InnerNamingRegister started"); 103 | if let Some(addr) = &self.conn_manage { 104 | if let Some(addr) = addr.upgrade() { 105 | addr.do_send(ConnManageCmd::NamingRegisterActorAddr( 106 | ctx.address().downgrade(), 107 | )); 108 | } 109 | } 110 | self.hb(ctx); 111 | } 112 | 113 | fn stopping(&mut self, ctx: &mut Self::Context) -> Running { 114 | log::info!(" InnerNamingRegister stopping "); 115 | if self.stop_remove_all { 116 | return Running::Stop; 117 | } 118 | self.remove_all_instance(ctx); 119 | Running::Continue 120 | } 121 | } 122 | 123 | #[derive(Debug, Message)] 124 | #[rtype(result = "Result<(),std::io::Error>")] 125 | pub enum NamingRegisterCmd { 126 | Register(Instance), 127 | Remove(Instance), 128 | Heartbeat(String, u64), 129 | Close, 130 | Reregister, 131 | } 132 | 133 | impl Handler for InnerNamingRegister { 134 | type Result = Result<(), std::io::Error>; 135 | 136 | fn handle(&mut self, msg: NamingRegisterCmd, ctx: &mut Context) -> Self::Result { 137 | match msg { 138 | NamingRegisterCmd::Register(mut instance) => { 139 | instance.init_beat_string(); 140 | let key = instance.generate_key(); 141 | if self.instances.contains_key(&key) { 142 | return Ok(()); 143 | } 144 | // request register 145 | self.register_instance(instance.clone()); 146 | self.instances.insert(key.clone(), instance); 147 | if !self.use_grpc { 148 | let time = now_millis(); 149 | self.timeout_set.add(time + self.period, key); 150 | } 151 | } 152 | NamingRegisterCmd::Remove(instance) => { 153 | let key = instance.generate_key(); 154 | if let Some(instance) = self.instances.remove(&key) { 155 | // request unregister 156 | self.remove_instance(instance, ctx); 157 | } 158 | } 159 | NamingRegisterCmd::Heartbeat(key, time) => { 160 | if self.use_grpc { 161 | //不需要单独维持心跳 162 | return Ok(()); 163 | } 164 | if let Some(instance) = self.instances.get(&key) { 165 | self.heartbeat_instance(instance); 166 | self.timeout_set.add(time + self.period, key); 167 | } 168 | } 169 | NamingRegisterCmd::Close => { 170 | ctx.stop(); 171 | } 172 | NamingRegisterCmd::Reregister => { 173 | self.register_all_instances(); 174 | } 175 | } 176 | Ok(()) 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/mod.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::sync::Arc; 3 | 4 | pub mod builder; 5 | pub mod config_client; 6 | pub mod nacos_client; 7 | pub mod naming_client; 8 | 9 | pub mod utils; 10 | 11 | pub mod api_model; 12 | pub mod auth; 13 | 14 | use md5::{Digest, Md5}; 15 | use serde::{Deserialize, Serialize}; 16 | 17 | pub use self::builder::ClientBuilder; 18 | pub use self::config_client::ConfigClient; 19 | pub use self::nacos_client::NacosClient; 20 | pub use self::naming_client::NamingClient; 21 | 22 | #[derive(Debug, Clone, Default)] 23 | pub struct HostInfo { 24 | pub ip: String, 25 | pub port: u32, 26 | pub grpc_port: u32, 27 | } 28 | 29 | pub fn now_millis() -> u64 { 30 | use std::time::SystemTime; 31 | SystemTime::now() 32 | .duration_since(SystemTime::UNIX_EPOCH) 33 | .unwrap() 34 | .as_millis() as u64 35 | } 36 | 37 | pub fn get_md5(content: &str) -> String { 38 | let mut m = Md5::new(); 39 | m.update(content.as_bytes()); 40 | 41 | hex::encode(&m.finalize()[..]) 42 | } 43 | 44 | impl HostInfo { 45 | pub fn new(ip: &str, port: u32) -> Self { 46 | Self { 47 | ip: ip.to_owned(), 48 | port, 49 | grpc_port: port + 1000, 50 | } 51 | } 52 | 53 | pub fn new_with_grpc(ip: &str, port: u32, grpc_port: u32) -> Self { 54 | Self { 55 | ip: ip.to_owned(), 56 | port, 57 | grpc_port, 58 | } 59 | } 60 | 61 | pub fn parse(addr: &str) -> Self { 62 | let strs = addr.split(':').collect::>(); 63 | let mut port = 8848u32; 64 | let mut grpc_port = port + 1000; 65 | let ip = strs.first().unwrap_or(&"127.0.0.1"); 66 | if let Some(p) = strs.get(1) { 67 | let ports = p.split('#').collect::>(); 68 | if let Some(p) = ports.first() { 69 | let pstr = (*p).to_owned(); 70 | port = pstr.parse::().unwrap_or(8848u32); 71 | grpc_port = port + 1000; 72 | } 73 | if let Some(p) = ports.get(1) { 74 | let pstr = (*p).to_owned(); 75 | grpc_port = pstr.parse::().unwrap_or(port + 1000); 76 | } 77 | } 78 | Self { 79 | ip: (*ip).to_owned(), 80 | port, 81 | grpc_port, 82 | } 83 | } 84 | } 85 | 86 | #[derive(Debug, Clone)] 87 | pub struct AuthInfo { 88 | pub username: String, 89 | pub password: String, 90 | } 91 | 92 | impl AuthInfo { 93 | pub fn new(username: &str, password: &str) -> Self { 94 | Self { 95 | username: username.to_owned(), 96 | password: password.to_owned(), 97 | } 98 | } 99 | pub fn is_valid(&self) -> bool { 100 | !self.username.is_empty() && !self.password.is_empty() 101 | } 102 | } 103 | 104 | /// 客户端信息 105 | #[derive(Debug, Clone)] 106 | pub struct ClientInfo { 107 | /// 客户端IP 108 | pub client_ip: String, 109 | /// 应用名 110 | pub app_name: String, 111 | /// 链接扩展信息 112 | pub headers: HashMap, 113 | } 114 | 115 | impl Default for ClientInfo { 116 | fn default() -> Self { 117 | Self::new() 118 | } 119 | } 120 | 121 | impl ClientInfo { 122 | pub fn new() -> Self { 123 | let client_ip = match std::env::var("NACOS_CLIENT_IP") { 124 | Ok(v) => v, 125 | Err(_) => local_ipaddress::get().unwrap_or("127.0.0.1".to_owned()), 126 | }; 127 | let app_name = match std::env::var("NACOS_CLIENT_APP_NAME") { 128 | Ok(v) => v, 129 | Err(_) => "UNKNOWN".to_owned(), 130 | }; 131 | Self { 132 | client_ip, 133 | app_name, 134 | headers: HashMap::new(), 135 | } 136 | } 137 | } 138 | 139 | #[derive(Debug, Serialize, Deserialize, Default)] 140 | #[serde(rename_all = "camelCase")] 141 | pub struct TokenInfo { 142 | pub access_token: String, 143 | pub token_ttl: u64, 144 | } 145 | 146 | #[derive(Debug, Clone, Default)] 147 | pub struct ServerEndpointInfo { 148 | pub hosts: Vec, 149 | } 150 | 151 | impl ServerEndpointInfo { 152 | pub fn new(addrs: &str) -> Self { 153 | let addrs = addrs.split(',').collect::>(); 154 | let mut hosts = Vec::new(); 155 | for addr in addrs { 156 | hosts.push(HostInfo::parse(addr)); 157 | } 158 | if hosts.is_empty() { 159 | hosts.push(HostInfo::parse("127.0.0.1:8848")); 160 | } 161 | Self { hosts } 162 | } 163 | 164 | pub fn select_host(&self) -> &HostInfo { 165 | let index = naming_client::NamingUtils::select_by_weight_fn(&self.hosts, |_| 1); 166 | self.hosts.get(index).unwrap() 167 | } 168 | } 169 | 170 | pub struct Client { 171 | //server_addr: String, 172 | //tenant: Option, 173 | } 174 | 175 | impl Client { 176 | pub fn new(_: &str) -> Client { 177 | Client{ 178 | //server_addr: addr.to_string(), 179 | //tenant: None, 180 | } 181 | } 182 | 183 | pub async fn login( 184 | client: &reqwest::Client, 185 | endpoints: Arc, 186 | auth_info: &AuthInfo, 187 | ) -> anyhow::Result { 188 | let mut param: HashMap<&str, &str> = HashMap::new(); 189 | param.insert("username", &auth_info.username); 190 | param.insert("password", &auth_info.password); 191 | let mut headers = HashMap::new(); 192 | headers.insert( 193 | "Content-Type".to_owned(), 194 | "application/x-www-form-urlencoded".to_owned(), 195 | ); 196 | 197 | let host = endpoints.select_host(); 198 | let url = format!("http://{}:{}/nacos/v1/auth/login", host.ip, host.port); 199 | let resp = utils::Utils::request( 200 | client, 201 | "POST", 202 | &url, 203 | serde_urlencoded::to_string(¶m) 204 | .unwrap() 205 | .as_bytes() 206 | .to_vec(), 207 | Some(&headers), 208 | Some(3000), 209 | ) 210 | .await?; 211 | if !resp.status_is_200() { 212 | return Err(anyhow::anyhow!("get config error")); 213 | } 214 | let text = resp.get_string_body(); 215 | let token = serde_json::from_str(&text)?; 216 | Ok(token) 217 | } 218 | 219 | pub(crate) fn build_http_headers() -> HashMap { 220 | let mut headers = HashMap::new(); 221 | headers.insert( 222 | "Content-Type".to_owned(), 223 | "application/x-www-form-urlencoded".to_owned(), 224 | ); 225 | headers.insert("User-Agent".to_owned(), "nacos-rust-client 0.3".to_owned()); 226 | headers 227 | } 228 | } 229 | 230 | pub enum ProtocolMode { 231 | Http, 232 | Grpc, 233 | } 234 | 235 | #[cfg(test)] 236 | mod tests { 237 | use super::*; 238 | 239 | #[test] 240 | fn test_md5() { 241 | assert_eq!( 242 | get_md5("hello"), 243 | String::from("5d41402abc4b2a76b9719d911017c592") 244 | ); 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /nacos_rust_client/src/conn_manage/breaker.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_variables, dead_code)] 2 | use std::sync::Arc; 3 | 4 | use crate::client::now_millis; 5 | 6 | #[derive(Debug, Clone)] 7 | pub enum BreakerStatus { 8 | Close, 9 | Open(u64), //半开启时间戳 10 | HalfOpen(u32, u32), //(连续成功次数,已申请尝试次数) 11 | } 12 | 13 | impl Default for BreakerStatus { 14 | fn default() -> Self { 15 | Self::Close 16 | } 17 | } 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct BreakerConfig { 21 | ///失败多少次开启 22 | pub open_more_than_times: u32, 23 | ///开启多久后半开启 24 | pub half_open_after_open_second: u64, 25 | ///半开启后可访问的比率(分母) 26 | pub half_open_rate_times: u32, 27 | ///半开启后成功多少次关闭 28 | pub close_more_than_times: u32, 29 | } 30 | 31 | impl Default for BreakerConfig { 32 | fn default() -> Self { 33 | Self { 34 | open_more_than_times: 2, 35 | half_open_after_open_second: 300, 36 | half_open_rate_times: 3, 37 | close_more_than_times: 2, 38 | } 39 | } 40 | } 41 | 42 | #[derive(Default, Debug, Clone)] 43 | pub struct Breaker { 44 | pub status: BreakerStatus, 45 | pub config: Arc, 46 | pub error_times: u32, 47 | } 48 | 49 | impl Breaker { 50 | pub fn new(status: BreakerStatus, config: Arc) -> Self { 51 | Self { 52 | status, 53 | config, 54 | error_times: 0, 55 | } 56 | } 57 | 58 | pub fn clear(&mut self) { 59 | self.status = BreakerStatus::Close; 60 | self.error_times = 0; 61 | } 62 | 63 | pub fn error(&mut self) -> &BreakerStatus { 64 | self.error_times += 1; 65 | match &self.status { 66 | BreakerStatus::Close => { 67 | if self.error_times >= self.config.open_more_than_times { 68 | self.status = BreakerStatus::Open( 69 | now_millis() + self.config.half_open_after_open_second * 1000, 70 | ); 71 | } 72 | } 73 | BreakerStatus::Open(_) => {} 74 | BreakerStatus::HalfOpen(_, _) => { 75 | self.status = BreakerStatus::Open( 76 | now_millis() + self.config.half_open_after_open_second * 1000, 77 | ); 78 | } 79 | } 80 | &self.status 81 | } 82 | 83 | pub fn success(&mut self) -> &BreakerStatus { 84 | match &mut self.status { 85 | BreakerStatus::Close => { 86 | if self.error_times != 0 { 87 | self.error_times = 0; 88 | } 89 | } 90 | BreakerStatus::Open(_) => { 91 | self.status = BreakerStatus::HalfOpen(0, 0); 92 | } 93 | BreakerStatus::HalfOpen(num, _) => { 94 | *num += 1; 95 | if *num >= self.config.close_more_than_times { 96 | self.status = BreakerStatus::Close; 97 | } 98 | } 99 | } 100 | &self.status 101 | } 102 | 103 | pub fn is_close(&self) -> bool { 104 | matches!(self.status, BreakerStatus::Close) 105 | } 106 | 107 | pub fn is_open(&self) -> bool { 108 | matches!(self.status, BreakerStatus::Open(_)) 109 | } 110 | 111 | pub fn is_half_open(&self) -> bool { 112 | matches!(self.status, BreakerStatus::HalfOpen(_, _)) 113 | } 114 | 115 | pub fn can_try(&mut self) -> bool { 116 | match &mut self.status { 117 | BreakerStatus::Close => true, 118 | BreakerStatus::Open(last_time) => { 119 | if now_millis() >= *last_time { 120 | self.status = BreakerStatus::HalfOpen(0, 1); 121 | } 122 | false 123 | } 124 | BreakerStatus::HalfOpen(_, try_num) => { 125 | *try_num += 1; 126 | if *try_num >= self.config.half_open_rate_times { 127 | *try_num = 0; 128 | true 129 | } else { 130 | false 131 | } 132 | } 133 | } 134 | } 135 | } 136 | 137 | #[cfg(test)] 138 | mod tests { 139 | use std::{sync::Arc, time::Duration}; 140 | 141 | use crate::conn_manage::breaker::BreakerConfig; 142 | 143 | use super::Breaker; 144 | 145 | #[test] 146 | fn test_breaker_close_to_open() { 147 | //let mut breaker = Breaker::default(); 148 | let mut breaker = Breaker::new(Default::default(), Arc::new(BreakerConfig::default())); 149 | assert!(breaker.is_close()); 150 | breaker.error(); 151 | assert!(breaker.is_close()); 152 | breaker.error(); 153 | assert!(breaker.is_open()); 154 | assert!(!breaker.can_try()); 155 | assert!(breaker.is_open()); 156 | } 157 | 158 | #[test] 159 | fn test_breaker_open_to_half_open() { 160 | let config = BreakerConfig { 161 | half_open_after_open_second: 1, 162 | ..Default::default() 163 | }; 164 | let mut breaker = Breaker::new(Default::default(), Arc::new(config)); 165 | assert!(breaker.is_close()); 166 | breaker.error(); 167 | assert!(breaker.is_close()); 168 | breaker.error(); 169 | assert!(breaker.is_open()); 170 | assert!(!breaker.is_half_open()); 171 | 172 | std::thread::sleep(Duration::from_millis(1000)); 173 | breaker.can_try(); 174 | assert!(breaker.is_half_open()); 175 | } 176 | 177 | #[test] 178 | fn test_breaker_half_open_to_close() { 179 | let config = BreakerConfig { 180 | half_open_after_open_second: 1, 181 | ..Default::default() 182 | }; 183 | let mut breaker = Breaker::new(Default::default(), Arc::new(config)); 184 | assert!(breaker.is_close()); 185 | breaker.error(); 186 | assert!(breaker.is_close()); 187 | breaker.error(); 188 | assert!(breaker.is_open()); 189 | assert!(!breaker.is_half_open()); 190 | 191 | std::thread::sleep(Duration::from_millis(1000)); 192 | breaker.can_try(); 193 | assert!(breaker.is_half_open()); 194 | 195 | for _ in 0..10 { 196 | if breaker.can_try() { 197 | breaker.success(); 198 | } 199 | } 200 | assert!(breaker.is_close()); 201 | } 202 | 203 | #[test] 204 | fn test_breaker_half_open_to_open() { 205 | let config = BreakerConfig { 206 | half_open_after_open_second: 1, 207 | ..Default::default() 208 | }; 209 | let mut breaker = Breaker::new(Default::default(), Arc::new(config)); 210 | assert!(breaker.is_close()); 211 | breaker.error(); 212 | assert!(breaker.is_close()); 213 | breaker.error(); 214 | assert!(breaker.is_open()); 215 | assert!(!breaker.is_half_open()); 216 | 217 | std::thread::sleep(Duration::from_millis(1000)); 218 | breaker.can_try(); 219 | assert!(breaker.is_half_open()); 220 | 221 | for _ in 0..10 { 222 | if breaker.can_try() { 223 | breaker.success(); 224 | break; 225 | } 226 | } 227 | breaker.error(); 228 | assert!(breaker.is_open()); 229 | } 230 | } 231 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/naming_client/api_model.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use std::collections::HashMap; 3 | 4 | use super::Instance; 5 | 6 | #[derive(Debug, Serialize, Deserialize, Default)] 7 | #[serde(rename_all = "camelCase")] 8 | pub struct BeatInfo { 9 | pub cluster: String, 10 | pub ip: String, 11 | pub port: u32, 12 | pub metadata: HashMap, 13 | pub period: i64, 14 | pub scheduled: bool, 15 | pub service_name: String, 16 | pub stopped: bool, 17 | pub weight: f32, 18 | } 19 | 20 | #[derive(Debug, Serialize, Deserialize, Default)] 21 | #[serde(rename_all = "camelCase")] 22 | pub struct BeatRequest { 23 | pub namespace_id: String, 24 | pub service_name: String, 25 | pub cluster_name: String, 26 | pub group_name: String, 27 | pub ephemeral: Option, 28 | pub beat: String, 29 | } 30 | 31 | #[derive(Debug, Serialize, Deserialize, Default)] 32 | #[serde(rename_all = "camelCase")] 33 | pub struct InstanceWebParams { 34 | pub ip: String, 35 | pub port: u32, 36 | pub namespace_id: String, 37 | pub weight: f32, 38 | pub enabled: bool, 39 | pub healthy: bool, 40 | pub ephemeral: bool, 41 | pub metadata: String, 42 | pub cluster_name: String, 43 | pub service_name: String, 44 | pub group_name: String, 45 | } 46 | 47 | #[derive(Debug, Default, Serialize, Deserialize)] 48 | #[serde(rename_all = "camelCase")] 49 | pub struct InstanceWebQueryListParams { 50 | pub namespace_id: String, 51 | pub service_name: String, 52 | pub group_name: String, 53 | pub clusters: String, 54 | pub healthy_only: bool, 55 | #[serde(rename = "clientIP")] 56 | pub client_ip: Option, 57 | pub udp_port: Option, 58 | } 59 | 60 | #[derive(Debug, Serialize, Deserialize, Default, Clone)] 61 | #[serde(rename_all = "camelCase")] 62 | pub struct InstanceVO { 63 | service: Option, 64 | ip: Option, 65 | port: Option, 66 | cluster_name: Option, 67 | weight: Option, 68 | healthy: Option, 69 | instance_id: Option, 70 | metadata: Option>, 71 | marked: Option, 72 | enabled: Option, 73 | service_name: Option, 74 | ephemeral: Option, 75 | } 76 | 77 | impl InstanceVO { 78 | pub fn get_group_name(&self) -> String { 79 | if let Some(service) = &self.service { 80 | if let Some((group_name, _)) = NamingUtils::split_group_and_serivce_name(service) { 81 | return group_name; 82 | } 83 | } 84 | "DEFAULT_GROUP".to_owned() 85 | } 86 | 87 | pub fn to_instance(self) -> Instance { 88 | let mut instance = Instance::default(); 89 | if let Some(service_name) = &self.service_name { 90 | if let Some((group_name, service_name)) = 91 | NamingUtils::split_group_and_serivce_name(service_name) 92 | { 93 | instance.group_name = group_name; 94 | instance.service_name = service_name; 95 | } 96 | } 97 | //if let Some(service_name) = self.serviceName { instance.service_name = service_name; } 98 | if let Some(ip) = self.ip { 99 | instance.ip = ip; 100 | } 101 | if let Some(port) = self.port { 102 | instance.port = port; 103 | } 104 | if let Some(cluster_name) = self.cluster_name { 105 | instance.cluster_name = cluster_name; 106 | } 107 | if let Some(weight) = self.weight { 108 | instance.weight = weight; 109 | } 110 | if let Some(healthy) = self.healthy { 111 | instance.healthy = healthy; 112 | } 113 | instance.metadata = self.metadata; 114 | if let Some(enabled) = self.enabled { 115 | instance.enabled = enabled; 116 | } 117 | if let Some(ephemeral) = self.ephemeral { 118 | instance.ephemeral = ephemeral; 119 | } 120 | instance 121 | } 122 | } 123 | 124 | #[derive(Debug, Serialize, Deserialize, Default)] 125 | #[serde(rename_all = "camelCase")] 126 | pub struct QueryListResult { 127 | pub name: Option, 128 | pub clusters: Option, 129 | pub cache_millis: Option, 130 | pub hosts: Option>, 131 | pub last_ref_time: Option, 132 | pub checksum: Option, 133 | #[serde(rename = "useSpecifiedURL")] 134 | pub use_specified_url: Option, 135 | pub env: Option, 136 | pub protect_threshold: Option, 137 | pub reach_local_site_call_threshold: Option, 138 | pub dom: Option, 139 | pub metadata: Option>, 140 | } 141 | 142 | pub struct NamingUtils; 143 | 144 | impl NamingUtils { 145 | pub fn get_group_and_service_name(service_name: &str, group_name: &str) -> String { 146 | if group_name.is_empty() { 147 | return format!("DEFAULT_GROUP@@{}", service_name); 148 | } 149 | format!("{}@@{}", group_name, service_name) 150 | } 151 | 152 | pub fn split_group_and_serivce_name(grouped_name: &str) -> Option<(String, String)> { 153 | let split = grouped_name.split("@@").collect::>(); 154 | if split.is_empty() { 155 | return None; 156 | } 157 | let a = split.first(); 158 | let b = split.get(1); 159 | match b { 160 | Some(b) => { 161 | let a = a.unwrap(); 162 | if a.is_empty() { 163 | return None; 164 | } 165 | Some(((*a).to_owned(), (*b).to_owned())) 166 | } 167 | None => match a { 168 | Some(a) => { 169 | if a.is_empty() { 170 | return None; 171 | } 172 | Some(("DEFAULT_GROUP".to_owned(), (*a).to_owned())) 173 | } 174 | None => None, 175 | }, 176 | } 177 | } 178 | 179 | fn do_select_index(list: &[u64], rand_value: u64) -> usize { 180 | let len = list.len(); 181 | if len <= 1 { 182 | return 0; 183 | } 184 | match list.binary_search(&rand_value) { 185 | Ok(i) => i, 186 | Err(i) => { 187 | if i >= len { 188 | len - 1 189 | } else { 190 | i 191 | } 192 | } 193 | } 194 | } 195 | 196 | pub fn select_by_weight(weight_list: &Vec) -> usize { 197 | use rand::distributions::Uniform; 198 | use rand::prelude::*; 199 | 200 | let mut superposition_list = vec![]; 201 | let mut sum = 0; 202 | for v in weight_list { 203 | sum += *v; 204 | superposition_list.push(sum); 205 | } 206 | if sum == 0 { 207 | return 0; 208 | } 209 | //let rng = rand::thread_rng(); 210 | let mut rng: StdRng = StdRng::from_entropy(); 211 | let range_uniform = Uniform::new(1, sum + 1); 212 | let rand_value = range_uniform.sample(&mut rng); 213 | //let rand_value= rand::thread_rng().gen_range(0..sum); 214 | Self::do_select_index(&superposition_list, rand_value) 215 | } 216 | 217 | pub fn select_by_weight_fn(list: &[T], f: F) -> usize 218 | where 219 | F: Fn(&T) -> u64, 220 | { 221 | let weight_list: Vec = list.iter().map(f).collect(); 222 | Self::select_by_weight(&weight_list) 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/client.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_variables, dead_code)] 2 | use std::sync::Arc; 3 | 4 | use actix::{Addr, WeakAddr}; 5 | 6 | use super::{ 7 | config_key::ConfigKey, 8 | inner::{ConfigInnerActor, ConfigInnerCmd}, 9 | inner_client::ConfigInnerRequestClient, 10 | listener::ConfigListener, 11 | }; 12 | use crate::client::api_model::{ConsoleResult, NamespaceInfo}; 13 | use crate::client::config_client::api_model::{ConfigInfoDto, ConfigQueryParams, ConfigSearchPage}; 14 | use crate::{ 15 | client::{ 16 | auth::AuthActor, 17 | get_md5, 18 | nacos_client::{ActixSystemActorSetCmd, ActixSystemCmd, ActixSystemResult}, 19 | AuthInfo, HostInfo, ServerEndpointInfo, 20 | }, 21 | conn_manage::{ 22 | conn_msg::{ConfigRequest, ConfigResponse}, 23 | manage::ConnManage, 24 | }, 25 | init_global_system_actor, 26 | }; 27 | 28 | pub struct ConfigClient { 29 | pub(crate) tenant: String, 30 | pub(crate) request_client: ConfigInnerRequestClient, 31 | pub(crate) config_inner_addr: Addr, 32 | pub(crate) conn_manage_addr: Addr, 33 | } 34 | 35 | impl Drop for ConfigClient { 36 | fn drop(&mut self) { 37 | self.config_inner_addr.do_send(ConfigInnerCmd::Close); 38 | //std::thread::sleep(utils::ms(500)); 39 | } 40 | } 41 | 42 | impl ConfigClient { 43 | pub fn new(host: HostInfo, tenant: String) -> Arc { 44 | let use_grpc = false; 45 | let endpoint = Arc::new(ServerEndpointInfo { 46 | hosts: vec![host.clone()], 47 | }); 48 | let auth_actor = AuthActor::init_auth_actor(endpoint.clone(), None); 49 | let conn_manage = ConnManage::new( 50 | vec![host.clone()], 51 | use_grpc, 52 | None, 53 | Default::default(), 54 | Default::default(), 55 | auth_actor.clone(), 56 | ); 57 | let conn_manage_addr = conn_manage.start_at_global_system(); 58 | let request_client = 59 | ConfigInnerRequestClient::new_with_endpoint(endpoint, Some(auth_actor.clone())); 60 | let config_inner_addr = Self::init_register( 61 | request_client.clone(), 62 | Some(conn_manage_addr.clone().downgrade()), 63 | use_grpc, 64 | ); 65 | //request_client.set_auth_addr(auth_addr); 66 | let r = Arc::new(Self { 67 | tenant, 68 | request_client, 69 | config_inner_addr, 70 | conn_manage_addr, 71 | }); 72 | let system_addr = init_global_system_actor(); 73 | system_addr.do_send(ActixSystemActorSetCmd::LastConfigClient(r.clone())); 74 | r 75 | } 76 | 77 | pub fn new_with_addrs(addrs: &str, tenant: String, auth_info: Option) -> Arc { 78 | let use_grpc = false; 79 | let endpoint = Arc::new(ServerEndpointInfo::new(addrs)); 80 | let auth_actor = AuthActor::init_auth_actor(endpoint.clone(), auth_info.clone()); 81 | let conn_manage = ConnManage::new( 82 | endpoint.hosts.clone(), 83 | use_grpc.to_owned(), 84 | auth_info.clone(), 85 | Default::default(), 86 | Default::default(), 87 | auth_actor.clone(), 88 | ); 89 | let conn_manage_addr = conn_manage.start_at_global_system(); 90 | let request_client = 91 | ConfigInnerRequestClient::new_with_endpoint(endpoint, Some(auth_actor)); 92 | let config_inner_addr = Self::init_register( 93 | request_client.clone(), 94 | Some(conn_manage_addr.clone().downgrade()), 95 | use_grpc, 96 | ); 97 | let r = Arc::new(Self { 98 | tenant, 99 | request_client, 100 | config_inner_addr, 101 | conn_manage_addr, 102 | }); 103 | let system_addr = init_global_system_actor(); 104 | system_addr.do_send(ActixSystemActorSetCmd::LastConfigClient(r.clone())); 105 | r 106 | } 107 | 108 | pub(crate) fn init_register( 109 | request_client: ConfigInnerRequestClient, 110 | conn_manage_addr: Option>, 111 | use_grpc: bool, 112 | ) -> Addr { 113 | let system_addr = init_global_system_actor(); 114 | let actor = ConfigInnerActor::new(request_client, use_grpc, conn_manage_addr); 115 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 116 | let msg = ActixSystemCmd::ConfigInnerActor(actor, tx); 117 | system_addr.do_send(msg); 118 | match rx.recv().unwrap() { 119 | ActixSystemResult::ConfigInnerActor(addr) => addr, 120 | _ => panic!("init actor error"), 121 | } 122 | } 123 | 124 | pub fn gene_config_key(&self, data_id: &str, group: &str) -> ConfigKey { 125 | ConfigKey { 126 | data_id: data_id.to_owned(), 127 | group: group.to_owned(), 128 | tenant: self.tenant.to_owned(), 129 | } 130 | } 131 | 132 | pub async fn get_namespace_list(&self) -> anyhow::Result>> { 133 | self.request_client.get_namespace_list().await 134 | } 135 | 136 | pub async fn query_blur_config_page( 137 | &self, 138 | mut params: ConfigQueryParams, 139 | ) -> anyhow::Result> { 140 | if params.tenant.is_none() { 141 | params.tenant = Some(self.tenant.to_owned()); 142 | } 143 | self.request_client.query_blur_config_page(params).await 144 | } 145 | 146 | pub async fn query_accurate_config_page( 147 | &self, 148 | mut params: ConfigQueryParams, 149 | ) -> anyhow::Result> { 150 | if params.tenant.is_none() { 151 | params.tenant = Some(self.tenant.to_owned()); 152 | } 153 | self.request_client.query_accurate_config_page(params).await 154 | } 155 | 156 | pub async fn get_config(&self, key: &ConfigKey) -> anyhow::Result { 157 | let cmd = ConfigRequest::GetConfig(key.clone()); 158 | let res: ConfigResponse = self.conn_manage_addr.send(cmd).await??; 159 | match res { 160 | ConfigResponse::ConfigValue(content, _md5) => Ok(content), 161 | _ => Err(anyhow::anyhow!("get config error")), 162 | } 163 | } 164 | 165 | pub async fn set_config(&self, key: &ConfigKey, value: &str) -> anyhow::Result<()> { 166 | let cmd = ConfigRequest::SetConfig(key.clone(), value.to_owned()); 167 | let _res: ConfigResponse = self.conn_manage_addr.send(cmd).await??; 168 | Ok(()) 169 | } 170 | 171 | pub async fn del_config(&self, key: &ConfigKey) -> anyhow::Result<()> { 172 | let cmd = ConfigRequest::DeleteConfig(key.clone()); 173 | let _res: ConfigResponse = self.conn_manage_addr.send(cmd).await??; 174 | Ok(()) 175 | } 176 | 177 | /* 178 | pub(crate) async fn listene(&self,content:&str,timeout:Option) -> anyhow::Result> { 179 | self.request_client.listene(content, timeout).await 180 | } 181 | */ 182 | 183 | pub async fn subscribe( 184 | &self, 185 | listener: Box, 186 | ) -> anyhow::Result<()> { 187 | let key = listener.get_key(); 188 | self.subscribe_with_key(key, listener).await 189 | } 190 | 191 | pub async fn subscribe_with_key( 192 | &self, 193 | key: ConfigKey, 194 | listener: Box, 195 | ) -> anyhow::Result<()> { 196 | let id = 0u64; 197 | let md5 = match self.get_config(&key).await { 198 | Ok(text) => { 199 | listener.change(&key, &text); 200 | get_md5(&text) 201 | } 202 | Err(_) => "".to_owned(), 203 | }; 204 | let msg = ConfigInnerCmd::SUBSCRIBE(key, id, md5, listener); 205 | self.config_inner_addr.do_send(msg); 206 | //let msg=ConfigInnerMsg::SUBSCRIBE(key,id,md5,listener); 207 | //self.subscribe_sender.send(msg).await; 208 | Ok(()) 209 | } 210 | 211 | pub async fn unsubscribe(&self, key: ConfigKey) -> anyhow::Result<()> { 212 | let id = 0u64; 213 | let msg = ConfigInnerCmd::REMOVE(key, id); 214 | self.config_inner_addr.do_send(msg); 215 | Ok(()) 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /nacos-tonic-discover/src/lib.rs: -------------------------------------------------------------------------------- 1 | use nacos_rust_client::client::naming_client::{Instance, NamingClient}; 2 | use nacos_rust_client::client::naming_client::{InstanceDefaultListener, ServiceInstanceKey}; 3 | use nacos_rust_client::{init_global_system_actor, ActixSystemCreateCmd, ActorCreate}; 4 | use std::collections::HashMap; 5 | use std::str::FromStr; 6 | use std::sync::Arc; 7 | use std::sync::Mutex; 8 | use tonic::transport::Channel; 9 | use tonic::transport::Endpoint; 10 | use tower::discover::Change; 11 | 12 | use actix::{prelude::*, Context}; 13 | 14 | type DiscoverChangeSender = tokio::sync::mpsc::Sender>; 15 | pub struct DiscoverEntity { 16 | channel: Channel, 17 | sender: DiscoverChangeSender, 18 | key: ServiceInstanceKey, 19 | //listener:InstanceDefaultListener, 20 | } 21 | 22 | impl DiscoverEntity { 23 | pub fn new(key: ServiceInstanceKey, channel: Channel, sender: DiscoverChangeSender) -> Self { 24 | Self { 25 | channel, 26 | sender, 27 | key, 28 | } 29 | } 30 | } 31 | 32 | #[derive(Clone)] 33 | pub struct TonicDiscoverFactory { 34 | tonic_discover_addr: Addr, 35 | naming_client: Arc, 36 | } 37 | 38 | impl TonicDiscoverFactory { 39 | pub fn new(naming_client: Arc) -> Arc { 40 | let system_addr = init_global_system_actor(); 41 | let creator = InnerTonicDiscoverCreate::new(naming_client.clone()); 42 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 43 | let msg = ActixSystemCreateCmd::ActorInit(Box::new(creator.clone()), tx); 44 | system_addr.do_send(msg); 45 | rx.recv().unwrap(); 46 | let tonic_discover_addr = creator.get_value().unwrap(); 47 | let r = Arc::new(Self { 48 | tonic_discover_addr, 49 | naming_client, 50 | }); 51 | set_last_factory(r.clone()); 52 | r 53 | } 54 | 55 | /** 56 | * 如果已存在Channel,则直接返回;否则创建后再返回Channel 57 | */ 58 | pub async fn build_service_channel(&self, key: ServiceInstanceKey) -> anyhow::Result { 59 | let key_str = key.get_key(); 60 | if let Ok(v) = self.get_channel(&key_str).await { 61 | return Ok(v); 62 | } 63 | self.insert_channel(key).await?; 64 | self.get_channel(&key_str).await 65 | } 66 | 67 | async fn get_channel(&self, key_str: &String) -> anyhow::Result { 68 | let msg = DiscoverCmd::Get(key_str.to_owned()); 69 | match self.tonic_discover_addr.send(msg).await?? { 70 | DiscoverResult::None => Err(anyhow::anyhow!("not found channel")), 71 | DiscoverResult::Channel(v) => Ok(v), 72 | } 73 | } 74 | 75 | async fn insert_channel(&self, key: ServiceInstanceKey) -> anyhow::Result<()> { 76 | let (channel, rx) = Channel::balance_channel(10); 77 | let addr = self.tonic_discover_addr.clone(); 78 | let new_key = key.clone(); 79 | 80 | let listener = InstanceDefaultListener::new( 81 | key.clone(), 82 | Some(Arc::new(move |_, add_list, remove_list| { 83 | if !add_list.is_empty() || !remove_list.is_empty() { 84 | let msg = DiscoverCmd::Change(new_key.clone(), add_list, remove_list); 85 | addr.do_send(msg); 86 | } 87 | })), 88 | ); 89 | let entity = DiscoverEntity::new(key.clone(), channel, rx); 90 | let msg = DiscoverCmd::Insert(entity); 91 | self.tonic_discover_addr.send(msg).await??; 92 | self.naming_client.subscribe(Box::new(listener)).await?; 93 | Ok(()) 94 | } 95 | 96 | pub fn get_naming_client(&self) -> &Arc { 97 | &self.naming_client 98 | } 99 | } 100 | 101 | pub struct InnerTonicDiscover { 102 | service_map: HashMap, 103 | } 104 | 105 | impl InnerTonicDiscover { 106 | pub fn new(_: Arc) -> Self { 107 | Self { 108 | service_map: Default::default(), 109 | } 110 | } 111 | 112 | fn change( 113 | &mut self, 114 | ctx: &mut Context, 115 | key: &ServiceInstanceKey, 116 | add_list: Vec>, 117 | remove_list: Vec>, 118 | ) { 119 | let key_str = key.get_key(); 120 | if let Some(entity) = self.service_map.get(&key_str) { 121 | let sender = entity.sender.clone(); 122 | async move { 123 | for item in &add_list { 124 | let host = format!("{}:{}", &item.ip, item.port); 125 | match Endpoint::from_str(&format!("http://{}", host)) { 126 | Ok(endpoint) => { 127 | let change = Change::Insert(host, endpoint); 128 | sender.send(change).await.unwrap_or_default(); 129 | } 130 | Err(_) => todo!(), 131 | }; 132 | } 133 | for item in &remove_list { 134 | let host = format!("{}:{}", &item.ip, item.port); 135 | let change = Change::Remove(host); 136 | sender.send(change).await.unwrap_or_default(); 137 | } 138 | } 139 | .into_actor(self) 140 | .map(|_, _, _| {}) 141 | .wait(ctx); 142 | } 143 | } 144 | } 145 | 146 | impl Actor for InnerTonicDiscover { 147 | type Context = Context; 148 | 149 | fn started(&mut self, _: &mut Self::Context) { 150 | log::info!("AuthActor started"); 151 | //ctx.run_later(Duration::from_nanos(1), |act,ctx|{ 152 | // act.hb(ctx); 153 | //}); 154 | } 155 | } 156 | 157 | #[derive(Message)] 158 | #[rtype(result = "Result")] 159 | pub enum DiscoverCmd { 160 | Change(ServiceInstanceKey, Vec>, Vec>), 161 | Insert(DiscoverEntity), 162 | Get(String), 163 | } 164 | 165 | pub enum DiscoverResult { 166 | None, 167 | Channel(Channel), 168 | } 169 | 170 | impl Handler for InnerTonicDiscover { 171 | type Result = Result; 172 | fn handle(&mut self, msg: DiscoverCmd, ctx: &mut Context) -> Self::Result { 173 | match msg { 174 | DiscoverCmd::Change(key, add_list, remove_list) => { 175 | self.change(ctx, &key, add_list, remove_list); 176 | } 177 | DiscoverCmd::Insert(entity) => { 178 | let key = entity.key.get_key(); 179 | self.service_map.insert(key, entity); 180 | } 181 | DiscoverCmd::Get(key) => { 182 | if let Some(e) = self.service_map.get(&key) { 183 | return Ok(DiscoverResult::Channel(e.channel.clone())); 184 | } 185 | } 186 | }; 187 | Ok(DiscoverResult::None) 188 | } 189 | } 190 | 191 | #[derive(Clone)] 192 | pub struct InnerTonicDiscoverCreate { 193 | pub(crate) content: Arc>>>, 194 | pub(crate) params: Arc, 195 | } 196 | 197 | impl InnerTonicDiscoverCreate { 198 | pub(crate) fn new(params: Arc) -> Self { 199 | Self { 200 | content: Default::default(), 201 | params, 202 | } 203 | } 204 | 205 | pub fn get_value(&self) -> Option> { 206 | self.content.read().unwrap().as_ref().map(|c| c.clone()) 207 | } 208 | 209 | fn set_value( 210 | content: Arc>>>, 211 | value: Addr, 212 | ) { 213 | let mut r = content.write().unwrap(); 214 | *r = Some(value); 215 | } 216 | } 217 | 218 | impl ActorCreate for InnerTonicDiscoverCreate { 219 | fn create(&self) { 220 | let actor = InnerTonicDiscover::new(self.params.clone()); 221 | let addr = actor.start(); 222 | Self::set_value(self.content.clone(), addr); 223 | } 224 | } 225 | 226 | lazy_static::lazy_static! { 227 | static ref LAST_FACTORY: Mutex>> = Mutex::new(None); 228 | } 229 | 230 | pub fn get_last_factory() -> Option> { 231 | let r = LAST_FACTORY.lock().unwrap(); 232 | r.clone() 233 | } 234 | 235 | pub(crate) fn set_last_factory(addr: Arc) { 236 | let mut r = LAST_FACTORY.lock().unwrap(); 237 | *r = Some(addr); 238 | } 239 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/config_request_utils.rs: -------------------------------------------------------------------------------- 1 | use actix::Addr; 2 | use std::sync::Arc; 3 | use tonic::transport::Channel; 4 | 5 | use super::{ 6 | api_model::{ 7 | BaseResponse, ConfigBatchListenRequest, ConfigChangeBatchListenResponse, 8 | ConfigListenContext, ConfigPublishRequest, ConfigQueryRequest, ConfigQueryResponse, 9 | ConfigRemoveRequest, 10 | }, 11 | build_request_payload, do_timeout_request, 12 | }; 13 | use crate::client::auth::AuthActor; 14 | use crate::client::ClientInfo; 15 | use crate::{ 16 | client::{config_client::ConfigKey, get_md5, now_millis}, 17 | conn_manage::conn_msg::ConfigResponse, 18 | grpc::constant::LABEL_MODULE_CONFIG, 19 | }; 20 | 21 | pub(crate) struct GrpcConfigRequestUtils; 22 | 23 | impl GrpcConfigRequestUtils { 24 | pub async fn check_register( 25 | channel: Channel, 26 | auth_addr: Addr, 27 | client_info: Arc, 28 | ) -> anyhow::Result { 29 | let check_id = format!("__check_register_{}", now_millis()); 30 | let config_key = ConfigKey::new(&check_id, "__check", ""); 31 | let request = ConfigQueryRequest { 32 | data_id: config_key.data_id, 33 | group: config_key.group, 34 | tenant: config_key.tenant, 35 | module: Some(LABEL_MODULE_CONFIG.to_owned()), 36 | request_id: Some(check_id), 37 | ..Default::default() 38 | }; 39 | let payload = 40 | build_request_payload("ConfigQueryRequest", &request, &auth_addr, &client_info).await?; 41 | let payload = do_timeout_request(channel, payload).await?; 42 | //debug 43 | //log::info!("check_register,{}",&PayloadUtils::get_payload_string(&payload)); 44 | let body_vec = payload.body.unwrap_or_default().value; 45 | let response: BaseResponse = serde_json::from_slice(&body_vec)?; 46 | if response.error_code == 301u16 { 47 | Ok(false) 48 | } else { 49 | Ok(true) 50 | } 51 | } 52 | 53 | pub async fn config_query( 54 | channel: Channel, 55 | request_id: Option, 56 | config_key: ConfigKey, 57 | auth_addr: Addr, 58 | client_info: Arc, 59 | ) -> anyhow::Result { 60 | let request = ConfigQueryRequest { 61 | data_id: config_key.data_id, 62 | group: config_key.group, 63 | tenant: config_key.tenant, 64 | module: Some(LABEL_MODULE_CONFIG.to_owned()), 65 | request_id, 66 | ..Default::default() 67 | }; 68 | let payload = 69 | build_request_payload("ConfigQueryRequest", &request, &auth_addr, &client_info).await?; 70 | let payload = do_timeout_request(channel, payload).await?; 71 | //debug 72 | //log::info!("config_query,{}",&PayloadUtils::get_payload_string(&payload)); 73 | let body_vec = payload.body.unwrap_or_default().value; 74 | let response: ConfigQueryResponse = serde_json::from_slice(&body_vec)?; 75 | if response.result_code != 200u16 { 76 | log::warn!( 77 | "config_query response error,{}", 78 | String::from_utf8(body_vec)? 79 | ); 80 | return Err(anyhow::anyhow!("response error code")); 81 | } 82 | let md5 = response.md5.unwrap_or_else(|| get_md5(&response.content)); 83 | Ok(ConfigResponse::ConfigValue(response.content, md5)) 84 | } 85 | 86 | pub async fn config_publish( 87 | channel: Channel, 88 | request_id: Option, 89 | config_key: ConfigKey, 90 | content: String, 91 | auth_addr: Addr, 92 | client_info: Arc, 93 | ) -> anyhow::Result { 94 | let request = ConfigPublishRequest { 95 | data_id: config_key.data_id, 96 | group: config_key.group, 97 | tenant: config_key.tenant, 98 | content, 99 | request_id, 100 | module: Some(LABEL_MODULE_CONFIG.to_owned()), 101 | ..Default::default() 102 | }; 103 | let payload = 104 | build_request_payload("ConfigPublishRequest", &request, &auth_addr, &client_info) 105 | .await?; 106 | let payload = do_timeout_request(channel, payload).await?; 107 | //debug 108 | //log::info!("config_publish,{}",&PayloadUtils::get_payload_string(&payload)); 109 | let body_vec = payload.body.unwrap_or_default().value; 110 | let response: BaseResponse = serde_json::from_slice(&body_vec)?; 111 | if response.result_code != 200u16 { 112 | log::warn!( 113 | "config_publish response error,{}", 114 | String::from_utf8(body_vec)? 115 | ); 116 | return Err(anyhow::anyhow!("response error code")); 117 | } 118 | Ok(ConfigResponse::None) 119 | } 120 | 121 | pub async fn config_remove( 122 | channel: Channel, 123 | request_id: Option, 124 | config_key: ConfigKey, 125 | auth_addr: Addr, 126 | client_info: Arc, 127 | ) -> anyhow::Result { 128 | let request = ConfigRemoveRequest { 129 | data_id: config_key.data_id, 130 | group: config_key.group, 131 | tenant: config_key.tenant, 132 | module: Some(LABEL_MODULE_CONFIG.to_owned()), 133 | request_id, 134 | ..Default::default() 135 | }; 136 | let payload = 137 | build_request_payload("ConfigRemoveRequest", &request, &auth_addr, &client_info) 138 | .await?; 139 | let payload = do_timeout_request(channel, payload).await?; 140 | //debug 141 | //log::info!("config_remove,{}",&PayloadUtils::get_payload_string(&payload)); 142 | let body_vec = payload.body.unwrap_or_default().value; 143 | let response: BaseResponse = serde_json::from_slice(&body_vec)?; 144 | if response.result_code != 200u16 { 145 | log::warn!( 146 | "config_remove response error,{}", 147 | String::from_utf8(body_vec)? 148 | ); 149 | return Err(anyhow::anyhow!("response error code")); 150 | } 151 | Ok(ConfigResponse::None) 152 | } 153 | 154 | pub async fn config_change_batch_listen( 155 | channel: Channel, 156 | request_id: Option, 157 | listen_items: Vec<(ConfigKey, String)>, 158 | listen: bool, 159 | auth_addr: Addr, 160 | client_info: Arc, 161 | ) -> anyhow::Result { 162 | let config_listen_contexts: Vec = listen_items 163 | .into_iter() 164 | .map(|(config_key, md5)| ConfigListenContext { 165 | data_id: config_key.data_id, 166 | group: config_key.group, 167 | tenant: config_key.tenant, 168 | md5, 169 | ..Default::default() 170 | }) 171 | .collect::<_>(); 172 | let request = ConfigBatchListenRequest { 173 | config_listen_contexts, 174 | listen, 175 | module: Some(LABEL_MODULE_CONFIG.to_owned()), 176 | request_id, 177 | ..Default::default() 178 | }; 179 | let payload = build_request_payload( 180 | "ConfigBatchListenRequest", 181 | &request, 182 | &auth_addr, 183 | &client_info, 184 | ) 185 | .await?; 186 | let payload = do_timeout_request(channel, payload).await?; 187 | //debug 188 | //log::info!("config_change_batch_listen,{}",&PayloadUtils::get_payload_string(&payload)); 189 | let body_vec = payload.body.unwrap_or_default().value; 190 | let response: ConfigChangeBatchListenResponse = serde_json::from_slice(&body_vec)?; 191 | if response.result_code != 200u16 { 192 | log::warn!( 193 | "config_change_batch_listen response error,{}", 194 | String::from_utf8(body_vec)? 195 | ); 196 | return Err(anyhow::anyhow!("response error code")); 197 | } 198 | let keys: Vec = response 199 | .changed_configs 200 | .into_iter() 201 | .map(|e| ConfigKey { 202 | tenant: e.tenant, 203 | data_id: e.data_id, 204 | group: e.group, 205 | }) 206 | .collect::<_>(); 207 | Ok(ConfigResponse::ChangeKeys(keys)) 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/inner.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, time::Duration}; 2 | 3 | use actix::{prelude::*, WeakAddr}; 4 | 5 | use crate::{ 6 | client::get_md5, 7 | conn_manage::{ 8 | conn_msg::{ConfigRequest, ConfigResponse}, 9 | manage::{ConnManage, ConnManageCmd}, 10 | }, 11 | }; 12 | 13 | use super::{ 14 | config_key::ConfigKey, 15 | inner_client::ConfigInnerRequestClient, 16 | listener::{ConfigListener, ListenerValue}, 17 | model::NotifyConfigItem, 18 | }; 19 | 20 | pub struct ConfigInnerActor { 21 | pub request_client: ConfigInnerRequestClient, 22 | subscribe_map: HashMap, 23 | conn_manage: Option>, 24 | use_grpc: bool, 25 | } 26 | 27 | //type ConfigInnerHandleResultSender = tokio::sync::oneshot::Sender; 28 | 29 | #[derive(Message)] 30 | #[rtype(result = "Result")] 31 | pub enum ConfigInnerCmd { 32 | SUBSCRIBE( 33 | ConfigKey, 34 | u64, 35 | String, 36 | Box, 37 | ), 38 | REMOVE(ConfigKey, u64), 39 | Notify(Vec), 40 | Close, 41 | GrpcResubscribe, 42 | } 43 | 44 | pub enum ConfigInnerHandleResult { 45 | None, 46 | Value(String), 47 | } 48 | 49 | impl ConfigInnerActor { 50 | pub(crate) fn new( 51 | request_client: ConfigInnerRequestClient, 52 | use_grpc: bool, 53 | conn_manage: Option>, 54 | ) -> Self { 55 | Self { 56 | request_client, 57 | subscribe_map: Default::default(), 58 | conn_manage, 59 | use_grpc, 60 | } 61 | } 62 | 63 | fn do_change_config(&mut self, key: &ConfigKey, content: String) { 64 | let md5 = get_md5(&content); 65 | if let Some(v) = self.subscribe_map.get_mut(key) { 66 | v.md5 = md5; 67 | v.notify(key, &content); 68 | } 69 | } 70 | 71 | async fn send( 72 | conn_manage: &Addr, 73 | request: ConfigRequest, 74 | ) -> anyhow::Result { 75 | match conn_manage.send(request).await { 76 | Ok(res) => res, 77 | _ => Err(anyhow::anyhow!("send msg to ConnManage failed")), 78 | } 79 | } 80 | 81 | fn grpc_resubscribe(&mut self, _ctx: &mut actix::Context) { 82 | if !self.use_grpc { 83 | return; 84 | } 85 | if let Some(addr) = &self.conn_manage { 86 | if let Some(addr) = addr.upgrade() { 87 | let items = self 88 | .subscribe_map 89 | .keys() 90 | .map(|key| (key.clone(), "".to_owned())) 91 | .collect::>(); 92 | addr.do_send(ConfigRequest::Listen(items, true)); 93 | } 94 | } 95 | } 96 | 97 | fn listener(&mut self, ctx: &mut actix::Context) { 98 | if self.use_grpc { 99 | return; 100 | } 101 | if let Some(content) = self.get_listener_body() { 102 | let conn_manage = self.conn_manage.clone(); 103 | async move { 104 | let mut list = vec![]; 105 | if let Some(addr) = conn_manage { 106 | if let Some(addr) = addr.upgrade() { 107 | if let Ok(ConfigResponse::ChangeKeys(config_keys)) = 108 | Self::send(&addr, ConfigRequest::V1Listen(content.clone())).await 109 | { 110 | for key in config_keys { 111 | if let Ok(ConfigResponse::ConfigValue(value, _)) = 112 | Self::send(&addr, ConfigRequest::GetConfig(key.clone())).await 113 | { 114 | list.push((key, value)); 115 | } 116 | } 117 | } 118 | } 119 | } 120 | list 121 | } 122 | .into_actor(self) 123 | .map(|r, this, ctx| { 124 | for (key, context) in r { 125 | this.do_change_config(&key, context) 126 | } 127 | if !this.subscribe_map.is_empty() { 128 | ctx.run_later(Duration::from_millis(5), |act, ctx| { 129 | act.listener(ctx); 130 | }); 131 | } 132 | }) 133 | .spawn(ctx); 134 | } 135 | } 136 | 137 | fn get_listener_body(&self) -> Option { 138 | let items = self.subscribe_map.iter().collect::>(); 139 | if items.is_empty() { 140 | return None; 141 | } 142 | let mut body = String::new(); 143 | for (k, v) in items { 144 | body += &format!( 145 | "{}\x02{}\x02{}\x02{}\x01", 146 | k.data_id, k.group, v.md5, k.tenant 147 | ); 148 | } 149 | Some(body) 150 | } 151 | } 152 | 153 | impl Actor for ConfigInnerActor { 154 | type Context = Context; 155 | 156 | fn started(&mut self, ctx: &mut Self::Context) { 157 | log::info!("ConfigInnerActor started"); 158 | if let Some(addr) = &self.conn_manage { 159 | if let Some(addr) = addr.upgrade() { 160 | addr.do_send(ConnManageCmd::ConfigInnerActorAddr( 161 | ctx.address().downgrade(), 162 | )); 163 | } 164 | } 165 | //ctx.run_later(Duration::from_millis(5), |act, ctx| { 166 | // act.listener(ctx); 167 | //}); 168 | } 169 | } 170 | 171 | impl Handler for ConfigInnerActor { 172 | type Result = Result; 173 | fn handle(&mut self, msg: ConfigInnerCmd, ctx: &mut Context) -> Self::Result { 174 | match msg { 175 | ConfigInnerCmd::SUBSCRIBE(key, id, md5, func) => { 176 | let first = self.subscribe_map.is_empty(); 177 | let list = self.subscribe_map.get_mut(&key); 178 | match list { 179 | Some(v) => { 180 | v.push(id, func); 181 | if !md5.is_empty() { 182 | v.md5 = md5; 183 | } 184 | } 185 | None => { 186 | let v = ListenerValue::new(vec![(id, func)], md5.clone()); 187 | if self.use_grpc { 188 | if let Some(addr) = &self.conn_manage { 189 | if let Some(addr) = addr.upgrade() { 190 | addr.do_send(ConfigRequest::Listen( 191 | vec![(key.clone(), md5.clone())], 192 | true, 193 | )); 194 | } 195 | } 196 | } 197 | self.subscribe_map.insert(key, v); 198 | } 199 | }; 200 | if first { 201 | ctx.run_later(Duration::from_millis(5), |act, ctx| { 202 | act.listener(ctx); 203 | }); 204 | } 205 | Ok(ConfigInnerHandleResult::None) 206 | } 207 | ConfigInnerCmd::REMOVE(key, id) => { 208 | if let Some(v) = self.subscribe_map.get_mut(&key) { 209 | let size = v.remove(id); 210 | if size == 0 && self.subscribe_map.remove(&key).is_some() && self.use_grpc { 211 | if let Some(Some(addr)) = self.conn_manage.as_ref().map(WeakAddr::upgrade) { 212 | addr.do_send(ConfigRequest::Listen( 213 | vec![(key.clone(), "".to_owned())], 214 | false, 215 | )); 216 | } 217 | } 218 | }; 219 | Ok(ConfigInnerHandleResult::None) 220 | } 221 | ConfigInnerCmd::Close => { 222 | self.conn_manage = None; 223 | ctx.stop(); 224 | Ok(ConfigInnerHandleResult::None) 225 | } 226 | ConfigInnerCmd::Notify(items) => { 227 | for item in items { 228 | self.do_change_config(&item.key, item.content); 229 | } 230 | Ok(ConfigInnerHandleResult::None) 231 | } 232 | ConfigInnerCmd::GrpcResubscribe => { 233 | self.grpc_resubscribe(ctx); 234 | Ok(ConfigInnerHandleResult::None) 235 | } 236 | } 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/naming_client/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::should_implement_trait)] 2 | use std::sync::Arc; 3 | use std::time::Duration; 4 | //use actix::prelude::*; 5 | use inner_mem_cache::TimeoutSet; 6 | use std::collections::HashMap; 7 | 8 | mod api_model; 9 | mod client; 10 | mod listerner; 11 | mod register; 12 | mod request_client; 13 | mod udp_actor; 14 | 15 | pub use request_client::InnerNamingRequestClient; 16 | 17 | pub use api_model::{ 18 | BeatInfo, BeatRequest, InstanceVO, InstanceWebParams, InstanceWebQueryListParams, NamingUtils, 19 | QueryListResult, 20 | }; 21 | pub use client::NamingClient; 22 | pub use listerner::{ 23 | InnerNamingListener, InstanceDefaultListener, InstanceListener, NamingListenerCmd, 24 | NamingQueryCmd, NamingQueryResult, 25 | }; 26 | pub use register::{InnerNamingRegister, NamingRegisterCmd}; 27 | pub use udp_actor::{UdpDataCmd, UdpWorker}; 28 | 29 | pub(crate) static REGISTER_PERIOD: u64 = 5000u64; 30 | 31 | #[derive(Debug, Clone, Default)] 32 | pub struct Instance { 33 | //pub id:String, 34 | pub ip: String, 35 | pub port: u32, 36 | pub weight: f32, 37 | pub enabled: bool, 38 | pub healthy: bool, 39 | pub ephemeral: bool, 40 | pub cluster_name: String, 41 | pub service_name: String, 42 | pub group_name: String, 43 | pub metadata: Option>, 44 | pub namespace_id: String, 45 | //pub app_name:String, 46 | pub beat_string: Option>, 47 | } 48 | 49 | impl Instance { 50 | pub fn new_simple(ip: &str, port: u32, service_name: &str, group_name: &str) -> Self { 51 | Self::new(ip, port, service_name, group_name, "", "", None) 52 | } 53 | 54 | pub fn new( 55 | ip: &str, 56 | port: u32, 57 | service_name: &str, 58 | group_name: &str, 59 | cluster_name: &str, 60 | namespace_id: &str, 61 | metadata: Option>, 62 | ) -> Self { 63 | let cluster_name = if cluster_name.is_empty() { 64 | "DEFAULT".to_owned() 65 | } else { 66 | cluster_name.to_owned() 67 | }; 68 | let group_name = if group_name.is_empty() { 69 | "DEFAULT_GROUP".to_owned() 70 | } else { 71 | group_name.to_owned() 72 | }; 73 | let namespace_id = if namespace_id.is_empty() { 74 | "public".to_owned() 75 | } else { 76 | namespace_id.to_owned() 77 | }; 78 | Self { 79 | ip: ip.to_owned(), 80 | port, 81 | weight: 1.0f32, 82 | enabled: true, 83 | healthy: true, 84 | ephemeral: true, 85 | cluster_name, 86 | service_name: service_name.to_owned(), 87 | group_name, 88 | metadata, 89 | namespace_id, 90 | beat_string: None, 91 | } 92 | } 93 | 94 | pub fn generate_key(&self) -> String { 95 | format!( 96 | "{}#{}#{}#{}#{}#{}", 97 | &self.ip, 98 | &self.port, 99 | &self.cluster_name, 100 | &self.service_name, 101 | &self.group_name, 102 | &self.namespace_id 103 | ) 104 | } 105 | 106 | pub fn get_service_named(&self) -> String { 107 | format!("{}@@{}", self.group_name, self.service_name) 108 | } 109 | 110 | fn generate_beat_info(&self) -> BeatInfo { 111 | BeatInfo { 112 | cluster: self.cluster_name.to_owned(), 113 | ip: self.ip.to_owned(), 114 | port: self.port, 115 | metadata: self.metadata.clone().unwrap_or_default(), 116 | period: REGISTER_PERIOD as i64, 117 | scheduled: false, 118 | service_name: self.get_service_named(), 119 | stopped: false, 120 | weight: self.weight, 121 | } 122 | } 123 | 124 | fn generate_beat_request(&self) -> BeatRequest { 125 | let mut req = BeatRequest::default(); 126 | let beat = self.generate_beat_info(); 127 | req.beat = serde_json::to_string(&beat).unwrap(); 128 | req.namespace_id = self.namespace_id.to_owned(); 129 | req.service_name = beat.service_name; 130 | req.cluster_name = beat.cluster; 131 | req.group_name = self.group_name.to_owned(); 132 | req 133 | } 134 | 135 | fn generate_beat_request_urlencode(&self) -> String { 136 | let req = self.generate_beat_request(); 137 | serde_urlencoded::to_string(&req).unwrap() 138 | } 139 | 140 | pub fn init_beat_string(&mut self) { 141 | self.beat_string = Some(Arc::new(self.generate_beat_request_urlencode())); 142 | } 143 | 144 | pub fn to_web_params(&self) -> InstanceWebParams { 145 | InstanceWebParams { 146 | ip: self.ip.to_owned(), 147 | port: self.port, 148 | namespace_id: self.namespace_id.to_owned(), 149 | weight: self.weight, 150 | enabled: true, 151 | healthy: true, 152 | ephemeral: true, 153 | metadata: self 154 | .metadata 155 | .as_ref() 156 | .map(|v| serde_json::to_string(v).unwrap()) 157 | .unwrap_or_default(), 158 | cluster_name: self.cluster_name.to_owned(), 159 | service_name: self.get_service_named(), 160 | group_name: self.group_name.to_owned(), 161 | } 162 | } 163 | } 164 | 165 | #[derive(Debug, Clone, Default)] 166 | pub struct ServiceInstanceKey { 167 | pub namespace_id: Option, 168 | pub group_name: String, 169 | pub service_name: String, 170 | } 171 | 172 | impl ServiceInstanceKey { 173 | pub fn new(service_name: &str, group_name: &str) -> Self { 174 | Self { 175 | group_name: group_name.to_owned(), 176 | service_name: service_name.to_owned(), 177 | ..Default::default() 178 | } 179 | } 180 | 181 | pub fn new_with_namespace(&mut self, namespace_id: &str) { 182 | self.namespace_id = Some(namespace_id.to_owned()); 183 | } 184 | 185 | pub fn get_key(&self) -> String { 186 | NamingUtils::get_group_and_service_name(&self.service_name, &self.group_name) 187 | } 188 | 189 | #[deprecated(since = "0.3.2", note = "Use `&str.into` instead.")] 190 | pub fn from_str(key_str: &str) -> Self { 191 | key_str.into() 192 | } 193 | } 194 | 195 | impl From<&str> for ServiceInstanceKey { 196 | fn from(key_str: &str) -> Self { 197 | if let Some((group_name, service_name)) = NamingUtils::split_group_and_serivce_name(key_str) 198 | { 199 | Self { 200 | namespace_id: None, 201 | group_name, 202 | service_name, 203 | } 204 | } else { 205 | Self::new("", "") 206 | } 207 | } 208 | } 209 | 210 | #[derive(Debug, Clone, Default)] 211 | pub struct QueryInstanceListParams { 212 | pub namespace_id: String, 213 | pub group_name: String, 214 | pub service_name: String, 215 | pub clusters: Option>, 216 | pub healthy_only: bool, 217 | client_ip: Option, 218 | udp_port: Option, 219 | } 220 | 221 | impl QueryInstanceListParams { 222 | pub fn new( 223 | namespace_id: &str, 224 | group_name: &str, 225 | service_name: &str, 226 | clusters: Option>, 227 | healthy_only: bool, 228 | ) -> Self { 229 | Self { 230 | namespace_id: namespace_id.to_owned(), 231 | group_name: group_name.to_owned(), 232 | service_name: service_name.to_owned(), 233 | clusters, 234 | healthy_only, 235 | client_ip: None, 236 | udp_port: None, 237 | } 238 | } 239 | 240 | pub fn new_simple(service_name: &str, group_name: &str) -> Self { 241 | Self::new("", group_name, service_name, None, true) 242 | } 243 | 244 | pub fn new_by_serivce_key(key: &ServiceInstanceKey) -> Self { 245 | Self::new_simple(&key.service_name, &key.group_name) 246 | } 247 | 248 | pub fn get_key(&self) -> String { 249 | NamingUtils::get_group_and_service_name(&self.service_name, &self.group_name) 250 | } 251 | 252 | pub fn build_key(&self) -> ServiceInstanceKey { 253 | ServiceInstanceKey { 254 | namespace_id: Some(self.namespace_id.clone()), 255 | group_name: self.group_name.clone(), 256 | service_name: self.service_name.clone(), 257 | } 258 | } 259 | 260 | fn to_web_params(&self) -> InstanceWebQueryListParams { 261 | InstanceWebQueryListParams { 262 | namespace_id: self.namespace_id.to_owned(), 263 | service_name: NamingUtils::get_group_and_service_name( 264 | &self.service_name, 265 | &self.group_name, 266 | ), 267 | group_name: self.group_name.to_owned(), 268 | clusters: self 269 | .clusters 270 | .as_ref() 271 | .map(|v| v.join(",")) 272 | .unwrap_or_default(), 273 | healthy_only: self.healthy_only, 274 | client_ip: self.client_ip.clone(), 275 | udp_port: self.udp_port, 276 | } 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/naming_client/client.rs: -------------------------------------------------------------------------------- 1 | use crate::client::auth::AuthActor; 2 | use crate::client::nacos_client::ActixSystemActorSetCmd; 3 | use crate::client::nacos_client::ActixSystemCmd; 4 | use crate::client::nacos_client::ActixSystemResult; 5 | use crate::client::AuthInfo; 6 | use crate::client::ServerEndpointInfo; 7 | use crate::conn_manage::manage::ConnManage; 8 | use crate::init_global_system_actor; 9 | use std::env; 10 | use std::sync::Arc; 11 | 12 | use super::Instance; 13 | use super::InstanceListener; 14 | use super::NamingQueryCmd; 15 | use super::NamingQueryResult; 16 | use super::QueryInstanceListParams; 17 | use super::ServiceInstanceKey; 18 | use super::{ 19 | InnerNamingListener, InnerNamingRegister, InnerNamingRequestClient, NamingListenerCmd, 20 | NamingRegisterCmd, UdpWorker, 21 | }; 22 | use crate::client::HostInfo; 23 | use actix::prelude::*; 24 | use actix::WeakAddr; 25 | 26 | pub struct NamingClient { 27 | pub namespace_id: String, 28 | pub(crate) register: Addr, 29 | pub(crate) listener_addr: Addr, 30 | pub(crate) _conn_manage_addr: Addr, 31 | pub current_ip: String, 32 | } 33 | 34 | impl Drop for NamingClient { 35 | fn drop(&mut self) { 36 | self.droping(); 37 | //std::thread::sleep(utils::ms(50)); 38 | } 39 | } 40 | 41 | impl NamingClient { 42 | pub fn new(host: HostInfo, namespace_id: String) -> Arc { 43 | let use_grpc = false; 44 | let current_ip = match env::var("NACOS_CLIENT_IP") { 45 | Ok(v) => v, 46 | Err(_) => local_ipaddress::get().unwrap_or("127.0.0.1".to_owned()), 47 | }; 48 | let endpoint = Arc::new(ServerEndpointInfo { hosts: vec![host] }); 49 | let auth_actor = AuthActor::init_auth_actor(endpoint.clone(), None); 50 | let conn_manage = ConnManage::new( 51 | endpoint.hosts.clone(), 52 | use_grpc, 53 | None, 54 | Default::default(), 55 | Default::default(), 56 | auth_actor.clone(), 57 | ); 58 | let conn_manage_addr = conn_manage.start_at_global_system(); 59 | let request_client = 60 | InnerNamingRequestClient::new_with_endpoint(endpoint, Some(auth_actor.clone())); 61 | let addrs = Self::init_register( 62 | namespace_id.clone(), 63 | current_ip.clone(), 64 | request_client, 65 | Some(conn_manage_addr.clone().downgrade()), 66 | use_grpc, 67 | ); 68 | let r = Arc::new(Self { 69 | namespace_id, 70 | register: addrs.0, 71 | listener_addr: addrs.1, 72 | current_ip, 73 | _conn_manage_addr: conn_manage_addr, 74 | }); 75 | let system_addr = init_global_system_actor(); 76 | system_addr.do_send(ActixSystemActorSetCmd::LastNamingClient(r.clone())); 77 | r 78 | } 79 | 80 | pub fn new_with_addrs( 81 | addrs: &str, 82 | namespace_id: String, 83 | auth_info: Option, 84 | ) -> Arc { 85 | let use_grpc = false; 86 | let endpoint = Arc::new(ServerEndpointInfo::new(addrs)); 87 | let auth_actor = AuthActor::init_auth_actor(endpoint.clone(), auth_info.clone()); 88 | let conn_manage = ConnManage::new( 89 | endpoint.hosts.clone(), 90 | use_grpc, 91 | auth_info.clone(), 92 | Default::default(), 93 | Default::default(), 94 | auth_actor.clone(), 95 | ); 96 | let conn_manage_addr = conn_manage.start_at_global_system(); 97 | let request_client = 98 | InnerNamingRequestClient::new_with_endpoint(endpoint, Some(auth_actor.clone())); 99 | let current_ip = match env::var("NACOS_CLIENT_IP") { 100 | Ok(v) => v, 101 | Err(_) => local_ipaddress::get().unwrap_or("127.0.0.1".to_owned()), 102 | }; 103 | let addrs = Self::init_register( 104 | namespace_id.clone(), 105 | current_ip.clone(), 106 | request_client, 107 | Some(conn_manage_addr.clone().downgrade()), 108 | use_grpc, 109 | ); 110 | let r = Arc::new(Self { 111 | namespace_id, 112 | register: addrs.0, 113 | listener_addr: addrs.1, 114 | current_ip, 115 | _conn_manage_addr: conn_manage_addr, 116 | }); 117 | let system_addr = init_global_system_actor(); 118 | system_addr.do_send(ActixSystemActorSetCmd::LastNamingClient(r.clone())); 119 | r 120 | } 121 | 122 | pub(crate) fn init_register( 123 | namespace_id: String, 124 | client_ip: String, 125 | request_client: InnerNamingRequestClient, 126 | conn_manage_addr: Option>, 127 | use_grpc: bool, 128 | ) -> (Addr, Addr) { 129 | let system_addr = init_global_system_actor(); 130 | 131 | let actor = InnerNamingRegister::new(use_grpc, conn_manage_addr.clone()); 132 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 133 | let msg = ActixSystemCmd::InnerNamingRegister(actor, tx); 134 | system_addr.do_send(msg); 135 | let register_addr = match rx.recv().unwrap() { 136 | ActixSystemResult::InnerNamingRegister(addr) => addr, 137 | _ => panic!("init actor error"), 138 | }; 139 | 140 | let actor = UdpWorker::new(None); 141 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 142 | let msg = ActixSystemCmd::UdpWorker(actor, tx); 143 | system_addr.do_send(msg); 144 | let udp_work_addr = match rx.recv().unwrap() { 145 | ActixSystemResult::UdpWorker(addr) => addr, 146 | _ => panic!("init actor error"), 147 | }; 148 | 149 | let actor = InnerNamingListener::new( 150 | &namespace_id, 151 | &client_ip, 152 | 0, 153 | request_client, 154 | udp_work_addr, 155 | conn_manage_addr, 156 | use_grpc, 157 | ); 158 | let (tx, rx) = std::sync::mpsc::sync_channel(1); 159 | let msg = ActixSystemCmd::InnerNamingListener(actor, tx); 160 | system_addr.do_send(msg); 161 | let listener_addr = match rx.recv().unwrap() { 162 | ActixSystemResult::InnerNamingListener(addr) => addr, 163 | _ => panic!("init actor error"), 164 | }; 165 | (register_addr, listener_addr) 166 | } 167 | 168 | pub(crate) fn droping(&self) { 169 | log::info!("NamingClient droping"); 170 | self.register.do_send(NamingRegisterCmd::Close); 171 | self.listener_addr.do_send(NamingListenerCmd::Close); 172 | } 173 | 174 | pub fn register(&self, mut instance: Instance) { 175 | instance.namespace_id = self.namespace_id.clone(); 176 | self.register.do_send(NamingRegisterCmd::Register(instance)); 177 | } 178 | 179 | pub fn unregister(&self, mut instance: Instance) { 180 | instance.namespace_id = self.namespace_id.clone(); 181 | self.register.do_send(NamingRegisterCmd::Remove(instance)); 182 | } 183 | 184 | pub async fn query_instances( 185 | &self, 186 | mut params: QueryInstanceListParams, 187 | ) -> anyhow::Result>> { 188 | params.namespace_id = self.namespace_id.clone(); 189 | let (tx, rx) = tokio::sync::oneshot::channel(); 190 | self.listener_addr 191 | .do_send(NamingQueryCmd::QueryList(params, tx)); 192 | match rx.await? { 193 | NamingQueryResult::List(list) => Ok(list), 194 | _ => Err(anyhow::anyhow!("not found instance")), 195 | } 196 | } 197 | 198 | pub async fn select_instance( 199 | &self, 200 | mut params: QueryInstanceListParams, 201 | ) -> anyhow::Result> { 202 | params.namespace_id = self.namespace_id.clone(); 203 | let (tx, rx) = tokio::sync::oneshot::channel(); 204 | self.listener_addr 205 | .do_send(NamingQueryCmd::Select(params, tx)); 206 | match rx.await? { 207 | NamingQueryResult::One(one) => Ok(one), 208 | _ => Err(anyhow::anyhow!("not found instance")), 209 | } 210 | } 211 | 212 | pub async fn subscribe( 213 | &self, 214 | listener: Box, 215 | ) -> anyhow::Result<()> { 216 | let key = listener.get_key(); 217 | self.subscribe_with_key(key, listener).await 218 | } 219 | 220 | pub async fn subscribe_with_key( 221 | &self, 222 | key: ServiceInstanceKey, 223 | listener: Box, 224 | ) -> anyhow::Result<()> { 225 | let id = 0u64; 226 | //如果之前没有数据,会触发加载数据 227 | let params = QueryInstanceListParams::new( 228 | &self.namespace_id, 229 | &key.group_name, 230 | &key.service_name, 231 | None, 232 | true, 233 | ); 234 | self.query_instances(params).await.ok(); 235 | let msg = NamingListenerCmd::Add(key, id, listener); 236 | self.listener_addr.do_send(msg); 237 | Ok(()) 238 | } 239 | 240 | pub async fn unsubscribe(&self, key: ServiceInstanceKey) -> anyhow::Result<()> { 241 | let id = 0u64; 242 | let msg = NamingListenerCmd::Remove(key, id); 243 | self.listener_addr.do_send(msg); 244 | Ok(()) 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /nacos_rust_client/src/client/config_client/inner_client.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, sync::Arc}; 2 | 3 | use super::{listener::ListenerItem, ConfigKey}; 4 | use crate::client; 5 | use crate::client::api_model::{ConsoleResult, NamespaceInfo}; 6 | use crate::client::config_client::api_model::{ConfigInfoDto, ConfigQueryParams, ConfigSearchPage}; 7 | use crate::client::{ 8 | auth::{AuthActor, AuthCmd, AuthHandleResult}, 9 | utils::Utils, 10 | HostInfo, ServerEndpointInfo, 11 | }; 12 | use actix::Addr; 13 | 14 | #[derive(Clone)] 15 | pub struct ConfigInnerRequestClient { 16 | pub(crate) endpoints: Arc, 17 | pub(crate) client: reqwest::Client, 18 | pub(crate) headers: HashMap, 19 | pub(crate) auth_addr: Option>, 20 | } 21 | 22 | impl ConfigInnerRequestClient { 23 | pub fn new(host: HostInfo) -> Self { 24 | let client = reqwest::Client::builder().build().unwrap(); 25 | let endpoints = ServerEndpointInfo { hosts: vec![host] }; 26 | Self { 27 | endpoints: Arc::new(endpoints), 28 | client, 29 | headers: client::Client::build_http_headers(), 30 | auth_addr: None, 31 | } 32 | } 33 | 34 | pub fn new_with_endpoint( 35 | endpoints: Arc, 36 | auth_addr: Option>, 37 | ) -> Self { 38 | let client = reqwest::Client::builder().build().unwrap(); 39 | Self { 40 | endpoints, 41 | client, 42 | headers: client::Client::build_http_headers(), 43 | auth_addr, 44 | } 45 | } 46 | 47 | pub fn set_auth_addr(&mut self, addr: Addr) { 48 | self.auth_addr = Some(addr); 49 | } 50 | 51 | pub async fn get_token_result(&self) -> anyhow::Result { 52 | if let Some(auth_addr) = &self.auth_addr { 53 | match auth_addr.send(AuthCmd::QueryToken).await?? { 54 | AuthHandleResult::None => {} 55 | AuthHandleResult::Token(v) => { 56 | if v.len() > 0 { 57 | return Ok(format!("accessToken={}", &v)); 58 | } 59 | } 60 | }; 61 | } 62 | Ok(String::new()) 63 | } 64 | 65 | pub async fn get_token(&self) -> String { 66 | self.get_token_result().await.unwrap_or_default() 67 | } 68 | 69 | pub(crate) async fn get_namespace_list( 70 | &self, 71 | ) -> anyhow::Result>> { 72 | let token_param = self.get_token().await; 73 | let host = self.endpoints.select_host(); 74 | let url = format!( 75 | "http://{}:{}/nacos/v1/console/namespaces?{}", 76 | &host.ip, &host.port, token_param, 77 | ); 78 | let resp = Utils::request( 79 | &self.client, 80 | "GET", 81 | &url, 82 | vec![], 83 | Some(&self.headers), 84 | Some(10000), 85 | ) 86 | .await?; 87 | Ok(serde_json::from_slice(&resp.body)?) 88 | } 89 | 90 | pub(crate) async fn query_blur_config_page( 91 | &self, 92 | mut params: ConfigQueryParams, 93 | ) -> anyhow::Result> { 94 | params.search = Some("blur".to_string()); 95 | let token_param = self.get_token().await; 96 | let host = self.endpoints.select_host(); 97 | let url = format!( 98 | "http://{}:{}/nacos/v1/cs/configs?{}&{}", 99 | &host.ip, 100 | &host.port, 101 | token_param, 102 | &serde_urlencoded::to_string(¶ms)? 103 | ); 104 | let resp = Utils::request( 105 | &self.client, 106 | "GET", 107 | &url, 108 | vec![], 109 | Some(&self.headers), 110 | Some(10000), 111 | ) 112 | .await?; 113 | Ok(serde_json::from_slice(&resp.body)?) 114 | } 115 | 116 | pub(crate) async fn query_accurate_config_page( 117 | &self, 118 | mut params: ConfigQueryParams, 119 | ) -> anyhow::Result> { 120 | params.search = Some("accurate".to_string()); 121 | let token_param = self.get_token().await; 122 | let host = self.endpoints.select_host(); 123 | let url = format!( 124 | "http://{}:{}/nacos/v1/cs/configs?{}&{}", 125 | &host.ip, 126 | &host.port, 127 | token_param, 128 | &serde_urlencoded::to_string(¶ms)? 129 | ); 130 | let resp = Utils::request( 131 | &self.client, 132 | "GET", 133 | &url, 134 | vec![], 135 | Some(&self.headers), 136 | Some(10000), 137 | ) 138 | .await?; 139 | //println!("query_accurate_config_page result:{}",resp.get_lossy_string_body()); 140 | Ok(serde_json::from_slice(&resp.body)?) 141 | } 142 | 143 | pub async fn get_config(&self, key: &ConfigKey) -> anyhow::Result { 144 | let mut param: HashMap<&str, &str> = HashMap::new(); 145 | param.insert("group", &key.group); 146 | param.insert("dataId", &key.data_id); 147 | if !key.tenant.is_empty() { 148 | param.insert("tenant", &key.tenant); 149 | } 150 | let host = self.endpoints.select_host(); 151 | let token_param = self.get_token().await; 152 | let url = format!( 153 | "http://{}:{}/nacos/v1/cs/configs?{}&{}", 154 | host.ip, 155 | host.port, 156 | token_param, 157 | serde_urlencoded::to_string(¶m).unwrap() 158 | ); 159 | let resp = Utils::request( 160 | &self.client, 161 | "GET", 162 | &url, 163 | vec![], 164 | Some(&self.headers), 165 | Some(3000), 166 | ) 167 | .await?; 168 | if !resp.status_is_200() { 169 | return Err(anyhow::anyhow!("get config error")); 170 | } 171 | let text = resp.get_string_body(); 172 | log::debug!("get_config:{}", &text); 173 | Ok(text) 174 | } 175 | 176 | pub async fn set_config(&self, key: &ConfigKey, value: &str) -> anyhow::Result<()> { 177 | let mut param: HashMap<&str, &str> = HashMap::new(); 178 | param.insert("group", &key.group); 179 | param.insert("dataId", &key.data_id); 180 | if !key.tenant.is_empty() { 181 | param.insert("tenant", &key.tenant); 182 | } 183 | param.insert("content", value); 184 | let token_param = self.get_token().await; 185 | let host = self.endpoints.select_host(); 186 | let url = format!( 187 | "http://{}:{}/nacos/v1/cs/configs?{}", 188 | host.ip, host.port, token_param 189 | ); 190 | 191 | let body = serde_urlencoded::to_string(¶m).unwrap(); 192 | let resp = Utils::request( 193 | &self.client, 194 | "POST", 195 | &url, 196 | body.as_bytes().to_vec(), 197 | Some(&self.headers), 198 | Some(3000), 199 | ) 200 | .await?; 201 | if !resp.status_is_200() { 202 | log::error!("{}", resp.get_lossy_string_body()); 203 | return Err(anyhow::anyhow!("set config error")); 204 | } 205 | Ok(()) 206 | } 207 | 208 | pub async fn del_config(&self, key: &ConfigKey) -> anyhow::Result<()> { 209 | let mut param: HashMap<&str, &str> = HashMap::new(); 210 | param.insert("group", &key.group); 211 | param.insert("dataId", &key.data_id); 212 | if !key.tenant.is_empty() { 213 | param.insert("tenant", &key.tenant); 214 | } 215 | let token_param = self.get_token().await; 216 | let host = self.endpoints.select_host(); 217 | let url = format!( 218 | "http://{}:{}/nacos/v1/cs/configs?{}", 219 | host.ip, host.port, token_param 220 | ); 221 | let body = serde_urlencoded::to_string(¶m).unwrap(); 222 | let resp = Utils::request( 223 | &self.client, 224 | "DELETE", 225 | &url, 226 | body.as_bytes().to_vec(), 227 | Some(&self.headers), 228 | Some(3000), 229 | ) 230 | .await?; 231 | if !resp.status_is_200() { 232 | log::error!("{}", resp.get_lossy_string_body()); 233 | return Err(anyhow::anyhow!("del config error")); 234 | } 235 | Ok(()) 236 | } 237 | 238 | pub async fn listene( 239 | &self, 240 | content: &str, 241 | timeout: Option, 242 | ) -> anyhow::Result> { 243 | let mut param: HashMap<&str, &str> = HashMap::new(); 244 | let timeout = timeout.unwrap_or(30000u64); 245 | let timeout_str = timeout.to_string(); 246 | param.insert("Listening-Configs", content); 247 | let token_param = self.get_token().await; 248 | let host = self.endpoints.select_host(); 249 | let url = format!( 250 | "http://{}:{}/nacos/v1/cs/configs/listener?{}", 251 | host.ip, host.port, token_param 252 | ); 253 | let body = serde_urlencoded::to_string(¶m).unwrap(); 254 | let mut headers = self.headers.clone(); 255 | headers.insert("Long-Pulling-Timeout".to_owned(), timeout_str); 256 | let resp = Utils::request( 257 | &self.client, 258 | "POST", 259 | &url, 260 | body.as_bytes().to_vec(), 261 | Some(&headers), 262 | Some(timeout + 1000), 263 | ) 264 | .await?; 265 | if !resp.status_is_200() { 266 | log::error!( 267 | "{},{},{},{}", 268 | &url, 269 | &body, 270 | resp.status, 271 | resp.get_lossy_string_body() 272 | ); 273 | return Err(anyhow::anyhow!("listener config error")); 274 | } 275 | let text = resp.get_string_body(); 276 | let t = format!("v={}", &text); 277 | let map: HashMap<&str, String> = serde_urlencoded::from_str(&t)?; 278 | let text = map.get("v").unwrap_or(&text); 279 | let items = ListenerItem::decode_listener_change_keys(text); 280 | Ok(items) 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/naming_request_utils.rs: -------------------------------------------------------------------------------- 1 | use actix::Addr; 2 | use std::sync::Arc; 3 | use tonic::transport::Channel; 4 | 5 | use super::{ 6 | api_model::{ 7 | BaseResponse, BatchInstanceRequest, Instance as ApiInstance, ServiceQueryRequest, 8 | ServiceQueryResponse, SubscribeServiceRequest, SubscribeServiceResponse, 9 | }, 10 | build_request_payload, do_timeout_request, 11 | }; 12 | use crate::client::auth::AuthActor; 13 | use crate::client::ClientInfo; 14 | use crate::{ 15 | client::naming_client::{Instance, ServiceInstanceKey}, 16 | conn_manage::conn_msg::{NamingResponse, ServiceResult}, 17 | grpc::{api_model::InstanceRequest, constant::LABEL_MODULE_NAMING}, 18 | }; 19 | 20 | const REGISTER_INSTANCE: &str = "registerInstance"; 21 | 22 | const DE_REGISTER_INSTANCE: &str = "deregisterInstance"; 23 | 24 | const BATCH_REGISTER_INSTANCE: &str = "batchRegisterInstance"; 25 | 26 | pub(crate) struct GrpcNamingRequestUtils; 27 | 28 | impl GrpcNamingRequestUtils { 29 | pub(crate) fn convert_to_api_instance(input: Instance) -> ApiInstance { 30 | ApiInstance { 31 | ip: Some(input.ip), 32 | port: input.port, 33 | weight: input.weight, 34 | enabled: input.enabled, 35 | healthy: input.healthy, 36 | ephemeral: input.ephemeral, 37 | cluster_name: Some(input.cluster_name), 38 | service_name: Some(input.service_name), 39 | metadata: input.metadata.unwrap_or_default(), 40 | ..Default::default() 41 | } 42 | } 43 | 44 | pub(crate) fn convert_to_instance( 45 | input: ApiInstance, 46 | service_key: &ServiceInstanceKey, 47 | ) -> Instance { 48 | Instance { 49 | ip: input.ip.unwrap_or_default(), 50 | port: input.port, 51 | weight: input.weight, 52 | enabled: input.enabled, 53 | healthy: input.healthy, 54 | ephemeral: input.ephemeral, 55 | cluster_name: input.cluster_name.unwrap_or_default(), 56 | service_name: input.service_name.unwrap_or_default(), 57 | metadata: Some(input.metadata), 58 | group_name: service_key.group_name.clone(), 59 | namespace_id: service_key.namespace_id.clone().unwrap_or_default(), 60 | ..Default::default() 61 | } 62 | } 63 | 64 | pub async fn instance_register( 65 | channel: Channel, 66 | instance: Instance, 67 | is_reqister: bool, 68 | auth_addr: Addr, 69 | client_info: Arc, 70 | ) -> anyhow::Result { 71 | let request = InstanceRequest { 72 | namespace: Some(instance.namespace_id.to_owned()), 73 | service_name: Some(instance.service_name.to_owned()), 74 | group_name: Some(instance.group_name.to_owned()), 75 | r#type: Some(if is_reqister { 76 | REGISTER_INSTANCE.to_owned() 77 | } else { 78 | DE_REGISTER_INSTANCE.to_owned() 79 | }), 80 | instance: Some(Self::convert_to_api_instance(instance)), 81 | module: Some(LABEL_MODULE_NAMING.to_owned()), 82 | ..Default::default() 83 | }; 84 | let payload = 85 | build_request_payload("InstanceRequest", &request, &auth_addr, &client_info).await?; 86 | //debug 87 | //log::info!("instance_register request,{}",&PayloadUtils::get_payload_string(&payload)); 88 | let payload = do_timeout_request(channel, payload).await?; 89 | //debug 90 | //log::info!("instance_register,{}",&PayloadUtils::get_payload_string(&payload)); 91 | let body_vec = payload.body.unwrap_or_default().value; 92 | let res: BaseResponse = serde_json::from_slice(&body_vec)?; 93 | if res.result_code != 200u16 { 94 | log::warn!( 95 | "instance_register response error,{}", 96 | String::from_utf8(body_vec)? 97 | ); 98 | return Err(anyhow::anyhow!("response error code")); 99 | } 100 | Ok(NamingResponse::None) 101 | } 102 | 103 | pub async fn batch_register( 104 | channel: Channel, 105 | instances: Vec, 106 | auth_addr: Addr, 107 | client_info: Arc, 108 | ) -> anyhow::Result { 109 | if instances.is_empty() { 110 | return Err(anyhow::anyhow!("register instances is empty")); 111 | } 112 | let first_instance = instances.first().unwrap(); 113 | let mut request = BatchInstanceRequest { 114 | namespace: Some(first_instance.namespace_id.to_owned()), 115 | service_name: Some(first_instance.service_name.to_owned()), 116 | group_name: Some(first_instance.group_name.to_owned()), 117 | r#type: Some(BATCH_REGISTER_INSTANCE.to_owned()), 118 | module: Some(LABEL_MODULE_NAMING.to_owned()), 119 | ..Default::default() 120 | }; 121 | let api_instances: Vec = instances 122 | .into_iter() 123 | .map(Self::convert_to_api_instance) 124 | .collect::>(); 125 | request.instances = Some(api_instances); 126 | 127 | let payload = 128 | build_request_payload("BatchInstanceRequest", &request, &auth_addr, &client_info) 129 | .await?; 130 | let payload = do_timeout_request(channel, payload).await?; 131 | //debug 132 | //log::info!("batch_register,{}",&PayloadUtils::get_payload_string(&payload)); 133 | let body_vec = payload.body.unwrap_or_default().value; 134 | let res: BaseResponse = serde_json::from_slice(&body_vec)?; 135 | if res.result_code != 200u16 { 136 | log::warn!( 137 | "batch_register response error,{}", 138 | String::from_utf8(body_vec)? 139 | ); 140 | return Err(anyhow::anyhow!("response error code")); 141 | } 142 | Ok(NamingResponse::None) 143 | } 144 | 145 | pub async fn subscribe( 146 | channel: Channel, 147 | service_key: ServiceInstanceKey, 148 | is_subscribe: bool, 149 | clusters: Option, 150 | auth_addr: Addr, 151 | client_info: Arc, 152 | ) -> anyhow::Result { 153 | let clone_key = service_key.clone(); 154 | let request = SubscribeServiceRequest { 155 | namespace: service_key.namespace_id, 156 | group_name: Some(service_key.group_name), 157 | service_name: Some(service_key.service_name), 158 | subscribe: is_subscribe, 159 | clusters, 160 | module: Some(LABEL_MODULE_NAMING.to_owned()), 161 | ..Default::default() 162 | }; 163 | let payload = build_request_payload( 164 | "SubscribeServiceRequest", 165 | &request, 166 | &auth_addr, 167 | &client_info, 168 | ) 169 | .await?; 170 | let payload = do_timeout_request(channel, payload).await?; 171 | //debug 172 | //log::info!("subscribe,{}",&PayloadUtils::get_payload_string(&payload)); 173 | let body_vec = payload.body.unwrap_or_default().value; 174 | let res: SubscribeServiceResponse = serde_json::from_slice(&body_vec)?; 175 | if res.result_code != 200u16 { 176 | log::warn!("subscribe response error,{}", String::from_utf8(body_vec)?); 177 | return Err(anyhow::anyhow!("response error code")); 178 | } 179 | if let Some(service_info) = res.service_info { 180 | let hosts = service_info.hosts.unwrap_or_default(); 181 | let hosts = hosts 182 | .into_iter() 183 | .map(|e| Arc::new(Self::convert_to_instance(e, &clone_key))) 184 | .collect::>>(); 185 | let service_result = ServiceResult { 186 | cache_millis: Some(service_info.cache_millis as u64), 187 | hosts, 188 | }; 189 | Ok(NamingResponse::ServiceResult(service_result)) 190 | } else { 191 | if is_subscribe { 192 | log::warn!("subscribe service result is empty"); 193 | } 194 | Ok(NamingResponse::None) 195 | } 196 | } 197 | 198 | pub async fn query_service( 199 | channel: Channel, 200 | service_key: ServiceInstanceKey, 201 | cluster: Option, 202 | healthy_only: Option, 203 | auth_addr: Addr, 204 | client_info: Arc, 205 | ) -> anyhow::Result { 206 | let clone_key = service_key.clone(); 207 | let request = ServiceQueryRequest { 208 | namespace: service_key.namespace_id, 209 | group_name: Some(service_key.group_name), 210 | service_name: Some(service_key.service_name), 211 | cluster, 212 | healthy_only, 213 | module: Some(LABEL_MODULE_NAMING.to_owned()), 214 | ..Default::default() 215 | }; 216 | let payload = 217 | build_request_payload("ServiceQueryRequest", &request, &auth_addr, &client_info) 218 | .await?; 219 | let payload = do_timeout_request(channel, payload).await?; 220 | //log::info!("query_service,{}",&PayloadUtils::get_payload_string(&payload)); 221 | let body_vec = payload.body.unwrap_or_default().value; 222 | let res: ServiceQueryResponse = serde_json::from_slice(&body_vec)?; 223 | if res.result_code != 200u16 { 224 | log::warn!( 225 | "query_service response error,{}", 226 | String::from_utf8(body_vec)? 227 | ); 228 | return Err(anyhow::anyhow!("response error code")); 229 | } 230 | if let Some(service_info) = res.service_info { 231 | let hosts = service_info.hosts.unwrap_or_default(); 232 | let hosts = hosts 233 | .into_iter() 234 | .map(|e| Arc::new(Self::convert_to_instance(e, &clone_key))) 235 | .collect::>>(); 236 | let service_result = ServiceResult { 237 | cache_millis: Some(service_info.cache_millis as u64), 238 | hosts, 239 | }; 240 | Ok(NamingResponse::ServiceResult(service_result)) 241 | } else { 242 | log::warn!("subscribe service result is empty"); 243 | Ok(NamingResponse::None) 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /nacos_rust_client/src/grpc/api_model.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | 5 | pub const SUCCESS_CODE: u16 = 200u16; 6 | pub const ERROR_CODE: u16 = 500u16; 7 | 8 | #[derive(Debug, Serialize, Deserialize, Default)] 9 | #[serde(rename_all = "camelCase")] 10 | pub struct BaseResponse { 11 | pub result_code: u16, 12 | pub error_code: u16, 13 | pub message: Option, 14 | pub request_id: Option, 15 | } 16 | 17 | pub type ErrorResponse = BaseResponse; 18 | 19 | impl BaseResponse { 20 | pub fn build_with_request_id(request_id: Option) -> Self { 21 | Self { 22 | result_code: SUCCESS_CODE, 23 | error_code: 0, 24 | message: None, 25 | request_id, 26 | } 27 | } 28 | 29 | pub fn build_success_response() -> Self { 30 | Self { 31 | result_code: SUCCESS_CODE, 32 | error_code: 0, 33 | message: None, 34 | request_id: None, 35 | } 36 | } 37 | 38 | pub fn build_error_response(error_code: u16, error_msg: String) -> Self { 39 | Self { 40 | result_code: ERROR_CODE, 41 | error_code, 42 | message: Some(error_msg), 43 | request_id: None, 44 | } 45 | } 46 | 47 | pub fn to_json_string(&self) -> String { 48 | serde_json::to_string(&self).unwrap() 49 | } 50 | } 51 | 52 | #[derive(Debug, Serialize, Deserialize, Default)] 53 | #[serde(rename_all = "camelCase")] 54 | pub struct ConnectionSetupRequest { 55 | pub module: Option, 56 | pub request_id: Option, 57 | pub headers: HashMap, 58 | 59 | pub client_version: Option, 60 | pub tenant: Option, 61 | pub labels: HashMap, 62 | //pub abilities: Option, 63 | } 64 | 65 | #[derive(Debug, Serialize, Deserialize, Default)] 66 | #[serde(rename_all = "camelCase")] 67 | pub struct ServerCheckResponse { 68 | pub result_code: u16, 69 | pub error_code: u16, 70 | pub message: Option, 71 | pub request_id: Option, 72 | pub connection_id: Option, 73 | } 74 | 75 | #[derive(Debug, Serialize, Deserialize, Default)] 76 | #[serde(rename_all = "camelCase")] 77 | pub struct ClientDetectionRequest { 78 | pub module: Option, 79 | pub request_id: Option, 80 | pub headers: HashMap, 81 | } 82 | 83 | // --- config --- 84 | 85 | #[derive(Debug, Serialize, Deserialize, Default)] 86 | #[serde(rename_all = "camelCase")] 87 | pub struct ConfigPublishRequest { 88 | pub module: Option, 89 | pub request_id: Option, 90 | pub headers: HashMap, 91 | pub data_id: String, 92 | pub group: String, 93 | pub tenant: String, 94 | pub content: String, 95 | pub cas_md5: Option, 96 | pub addition_map: HashMap, 97 | } 98 | 99 | #[derive(Debug, Serialize, Deserialize, Default)] 100 | #[serde(rename_all = "camelCase")] 101 | pub struct ConfigQueryRequest { 102 | pub module: Option, 103 | pub request_id: Option, 104 | pub headers: HashMap, 105 | pub data_id: String, 106 | pub group: String, 107 | pub tenant: String, 108 | pub tag: Option, 109 | } 110 | 111 | #[derive(Debug, Serialize, Deserialize, Default)] 112 | #[serde(rename_all = "camelCase")] 113 | pub struct ConfigQueryResponse { 114 | pub result_code: u16, 115 | pub error_code: u16, 116 | pub message: Option, 117 | pub request_id: Option, 118 | 119 | pub content: String, 120 | pub encrypted_data_key: Option, 121 | pub content_type: Option, 122 | pub md5: Option, 123 | pub last_modified: u64, 124 | pub beta: bool, 125 | pub tag: Option, 126 | } 127 | 128 | #[derive(Debug, Serialize, Deserialize, Default)] 129 | #[serde(rename_all = "camelCase")] 130 | pub struct ConfigRemoveRequest { 131 | pub module: Option, 132 | pub request_id: Option, 133 | pub headers: HashMap, 134 | 135 | pub data_id: String, 136 | pub group: String, 137 | pub tenant: String, 138 | pub tag: Option, 139 | } 140 | 141 | #[derive(Debug, Serialize, Deserialize, Default)] 142 | #[serde(rename_all = "camelCase")] 143 | pub struct ConfigListenContext { 144 | pub data_id: String, 145 | pub group: String, 146 | pub tenant: String, 147 | pub md5: String, 148 | pub tag: Option, 149 | } 150 | 151 | #[derive(Debug, Serialize, Deserialize, Default)] 152 | #[serde(rename_all = "camelCase")] 153 | pub struct ConfigBatchListenRequest { 154 | pub module: Option, 155 | pub request_id: Option, 156 | pub headers: HashMap, 157 | 158 | pub listen: bool, 159 | pub config_listen_contexts: Vec, 160 | } 161 | 162 | #[derive(Debug, Serialize, Deserialize, Default)] 163 | #[serde(rename_all = "camelCase")] 164 | pub struct ConfigContext { 165 | pub data_id: String, 166 | pub group: String, 167 | pub tenant: String, 168 | } 169 | 170 | #[derive(Debug, Serialize, Deserialize, Default)] 171 | #[serde(rename_all = "camelCase")] 172 | pub struct ConfigChangeBatchListenResponse { 173 | pub result_code: u16, 174 | pub error_code: u16, 175 | pub message: Option, 176 | pub request_id: Option, 177 | 178 | pub changed_configs: Vec, 179 | } 180 | 181 | #[derive(Debug, Serialize, Deserialize, Default)] 182 | #[serde(rename_all = "camelCase")] 183 | pub struct ConfigChangeNotifyRequest { 184 | pub module: Option, 185 | pub request_id: Option, 186 | pub headers: HashMap, 187 | 188 | pub data_id: String, 189 | pub group: String, 190 | pub tenant: Option, 191 | } 192 | 193 | // ----- naming model ----- 194 | 195 | #[derive(Debug, Serialize, Deserialize, Default)] 196 | #[serde(rename_all = "camelCase")] 197 | pub struct Instance { 198 | pub instance_id: Option, 199 | pub ip: Option, 200 | pub port: u32, 201 | pub weight: f32, 202 | pub healthy: bool, 203 | pub enabled: bool, 204 | pub ephemeral: bool, 205 | pub cluster_name: Option, 206 | pub service_name: Option, 207 | pub metadata: HashMap, 208 | pub instance_heart_beat_interval: Option, 209 | pub instance_heart_beat_time_out: Option, 210 | pub ip_delete_timeout: Option, 211 | pub instance_id_generator: Option, 212 | } 213 | 214 | #[derive(Debug, Serialize, Deserialize, Default)] 215 | #[serde(rename_all = "camelCase")] 216 | pub struct InstanceRequest { 217 | pub module: Option, 218 | pub request_id: Option, 219 | pub headers: HashMap, 220 | 221 | pub namespace: Option, 222 | pub service_name: Option, 223 | pub group_name: Option, 224 | 225 | pub r#type: Option, 226 | pub instance: Option, 227 | } 228 | 229 | #[derive(Debug, Serialize, Deserialize, Default)] 230 | #[serde(rename_all = "camelCase")] 231 | pub struct InstanceResponse { 232 | pub result_code: u16, 233 | pub error_code: u16, 234 | pub message: Option, 235 | pub request_id: Option, 236 | 237 | pub r#type: Option, 238 | } 239 | 240 | #[derive(Debug, Serialize, Deserialize, Default)] 241 | #[serde(rename_all = "camelCase")] 242 | pub struct SubscribeServiceRequest { 243 | pub module: Option, 244 | pub request_id: Option, 245 | pub headers: HashMap, 246 | 247 | pub namespace: Option, 248 | pub service_name: Option, 249 | pub group_name: Option, 250 | 251 | pub subscribe: bool, 252 | pub clusters: Option, 253 | } 254 | 255 | #[derive(Debug, Serialize, Deserialize, Default)] 256 | #[serde(rename_all = "camelCase")] 257 | pub struct ServiceInfo { 258 | pub name: Option, 259 | pub group_name: Option, 260 | pub clusters: Option, 261 | pub cache_millis: i64, 262 | pub hosts: Option>, 263 | pub last_ref_time: i64, 264 | //pub checksum: Option, 265 | #[serde(rename = "allIPs")] 266 | pub all_ips: bool, 267 | pub reach_protection_threshold: bool, 268 | } 269 | 270 | #[derive(Debug, Serialize, Deserialize, Default)] 271 | #[serde(rename_all = "camelCase")] 272 | pub struct SubscribeServiceResponse { 273 | pub result_code: u16, 274 | pub error_code: u16, 275 | pub message: Option, 276 | pub request_id: Option, 277 | 278 | pub service_info: Option, 279 | } 280 | 281 | #[derive(Debug, Serialize, Deserialize, Default)] 282 | #[serde(rename_all = "camelCase")] 283 | pub struct BatchInstanceRequest { 284 | pub module: Option, 285 | pub request_id: Option, 286 | pub headers: HashMap, 287 | 288 | pub namespace: Option, 289 | pub service_name: Option, 290 | pub group_name: Option, 291 | 292 | pub r#type: Option, 293 | pub instances: Option>, 294 | } 295 | 296 | #[derive(Debug, Serialize, Deserialize, Default)] 297 | #[serde(rename_all = "camelCase")] 298 | pub struct BatchInstanceResponse { 299 | pub result_code: u16, 300 | pub error_code: u16, 301 | pub message: Option, 302 | pub request_id: Option, 303 | 304 | pub r#type: Option, 305 | } 306 | 307 | #[derive(Debug, Serialize, Deserialize, Default)] 308 | #[serde(rename_all = "camelCase")] 309 | pub struct ServiceQueryRequest { 310 | pub module: Option, 311 | pub request_id: Option, 312 | pub headers: HashMap, 313 | 314 | pub namespace: Option, 315 | pub service_name: Option, 316 | pub group_name: Option, 317 | 318 | pub cluster: Option, 319 | pub healthy_only: Option, 320 | } 321 | 322 | #[derive(Debug, Serialize, Deserialize, Default)] 323 | #[serde(rename_all = "camelCase")] 324 | pub struct ServiceQueryResponse { 325 | pub result_code: u16, 326 | pub error_code: u16, 327 | pub message: Option, 328 | pub request_id: Option, 329 | 330 | pub service_info: Option, 331 | } 332 | 333 | #[derive(Debug, Serialize, Deserialize, Default)] 334 | #[serde(rename_all = "camelCase")] 335 | pub struct NotifySubscriberRequest { 336 | pub module: Option, 337 | pub request_id: Option, 338 | pub headers: HashMap, 339 | 340 | pub namespace: Option, 341 | pub service_name: Option, 342 | pub group_name: Option, 343 | 344 | pub service_info: Option, 345 | } 346 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # nacos_rust_client 3 | 4 | ## 介绍 5 | rust实现的nacos客户端。 6 | 7 | nacos_rust_client是我在写[r-nacos](https://github.com/heqingpan/rnacos) (用rust重写的nacos服务)过程中实现的客户端,服务端与客户端相互验证,目前已比较稳定推荐使用。 8 | 9 | 0.3.x版本开始同时支持nacos `1.x`版http协议和`2.x`版本协议,支持在创建client时指定使用协议类型。 10 | 11 | 0.2.x版本只支持nacos `1.x`版http协议. 12 | 13 | 0.3.x版本兼容0.2版本api,建议使用nacos_rust_client都升级到0.3.x版本。 14 | 15 | 特点: 16 | 17 | 1. 使用 actix + tokio 实现。 18 | 2. 支持配置中心的推送、获取、监听。 19 | 3. 支持注册中心的服务实例注册(自动维护心跳)、服务实例获取(自动监听缓存实例列表)。 20 | 4. 创建的客户端后台处理,都放在同一个actix环境线程; 高性能,不会有线程膨胀,稳定可控。 21 | 22 | 23 | ## 使用方式 24 | 25 | 首先加入引用 26 | 27 | ```toml 28 | [dependencies] 29 | nacos_rust_client = "0.3" 30 | ``` 31 | 32 | ### 使用配置中心 33 | 34 | 1. 创建客户端 35 | 36 | 使用`ClientBuilder`创建配置客户端,支持设置集群地址列表,支持验权校验. 37 | 38 | ```rust 39 | use nacos_rust_client::client::config_client::ConfigClient; 40 | use nacos_rust_client::client::ClientBuilder; 41 | //... 42 | //兼容旧版本的创建方式,旧版本创建方式使用http协议 43 | //let config_client = ConfigClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848",tenant,auth_info); 44 | let config_client = ClientBuilder::new() 45 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 46 | .set_auth_info(auth_info) 47 | .set_tenant(tenant) 48 | .set_use_grpc(true) //select communication protocol 49 | .build_config_client(); 50 | ``` 51 | 52 | 创建客户端,后会把客户端的一个引用加入到全局对象,可以通过 `get_last_config_client`获取. 53 | 54 | ```rust 55 | let config_client = nacos_rust_client::get_last_config_client().unwrap(); 56 | ``` 57 | 58 | 2. 设置获取配置信息 59 | 60 | ```rust 61 | let key = ConfigKey::new("data_id","group_name","" /*tenant_id*/); 62 | config_client.set_config(&key, "config_value").await.unwrap(); 63 | let v=config_client.get_config(&key).await.unwrap(); 64 | ``` 65 | 66 | 3. 配置监听器 67 | 68 | 实时的接收服务端的变更推送,更新监听器的内容,用于应用配置动态下发。 69 | 70 | ```rust 71 | #[derive(Debug,Serialize,Deserialize,Default,Clone)] 72 | pub struct Foo { 73 | pub name: String, 74 | pub number: u64, 75 | } 76 | //... 77 | let foo_config_obj_listener = Box::new(ConfigDefaultListener::new(key.clone(),Arc::new(|s|{ 78 | //字符串反序列化为对象,如:serde_json::from_str::(s) 79 | Some(serde_json::from_str::(s).unwrap()) 80 | }))); 81 | config_client.subscribe(foo_config_obj_listener.clone()).await; 82 | let foo_obj_from_listener = foo_config_obj_listener.get_value().unwrap(); 83 | ``` 84 | 85 | ### 使用注册中心 86 | 87 | 1. 创建客户端 88 | 89 | 使用`NamingClient::new_with_addrs`创建配置客户端,支持设置集群地址列表,支持验权校验. 90 | 91 | ```rust 92 | use nacos_rust_client::client::naming_client::NamingClient; 93 | use nacos_rust_client::client::ClientBuilder; 94 | //... 95 | //兼容旧版本的创建方式,旧版本创建方式使用http协议 96 | //let naming_client = NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848",namespace_id,auth_info); 97 | let naming_client = ClientBuilder::new() 98 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 99 | .set_auth_info(auth_info) 100 | .set_tenant(tenant) 101 | .set_use_grpc(true) //select communication protocol 102 | .build_naming_client(); 103 | ``` 104 | 105 | 创建客户端,后会把客户端的一个引用加入到全局对象,可以通过 `get_last_naming_client`获取. 106 | 107 | ```rust 108 | let naming_client = nacos_rust_client::get_last_naming_client().unwrap(); 109 | ``` 110 | 111 | 2. 注册服务实例 112 | 113 | 只要调拨一次注册实例,客户端会自动在后面维持心跳保活。 114 | 115 | ```rust 116 | let instance = Instance::new_simple(&ip,port,service_name,group_name); 117 | naming_client.register(instance); 118 | ``` 119 | 120 | 3. 服务地址路由 121 | 122 | 查询指定服务的地址列表 123 | 124 | ```rust 125 | let params = QueryInstanceListParams::new_simple(service_name,group_name); 126 | let instance_list_result=client.query_instances(params).await; 127 | ``` 128 | 129 | 查询指定服务的地址列表并按重选中一个地址做服务调用。 130 | 131 | ```rust 132 | let params = QueryInstanceListParams::new_simple(service_name,group_name); 133 | let instance_result=client.select_instance(params).await; 134 | ``` 135 | 136 | 如果要在tonic中使用服务地址选择,可以使用对tonic的适配 (nacos-tonic-discover)[https://crates.io/crates/nacos-tonic-discover] 137 | 138 | ### 其它 139 | 140 | 应用结束时,nacos_rust_client可能还有后台的调用,可以调用`nacos_rust_client::close_current_system()` 优雅退出nacos_rust_client后台线程。 141 | 142 | 143 | ## 例子 144 | 145 | 运行下面的例子,需要先启动nacos服务,把例子中的host改成实际的地址。 146 | 147 | 例子完整依赖与代码可以参考 examples/下的代码。 148 | 149 | 150 | ### 配置中心例子 151 | 152 | ```rust 153 | use std::time::Duration; 154 | use std::sync::Arc; 155 | 156 | use nacos_rust_client::client::{ HostInfo, ClientBuilder, AuthInfo }; 157 | use nacos_rust_client::client::config_client::{ 158 | ConfigClient,ConfigKey,ConfigDefaultListener 159 | }; 160 | use serde::{Serialize,Deserialize}; 161 | use serde_json; 162 | 163 | #[derive(Debug,Serialize,Deserialize,Default,Clone)] 164 | pub struct Foo { 165 | pub name: String, 166 | pub number: u64, 167 | } 168 | 169 | #[tokio::main] 170 | async fn main() { 171 | std::env::set_var("RUST_LOG","INFO"); 172 | env_logger::init(); 173 | //let host = HostInfo::parse("127.0.0.1:8848"); 174 | //let config_client = ConfigClient::new(host,String::new()); 175 | let tenant = "public".to_owned(); //default teant 176 | //let auth_info = Some(AuthInfo::new("nacos","nacos")); 177 | let auth_info = None; 178 | //let config_client = ConfigClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848",tenant,auth_info); 179 | let config_client = ClientBuilder::new() 180 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 181 | .set_auth_info(auth_info) 182 | .set_tenant(tenant) 183 | .set_use_grpc(true) 184 | .build_config_client(); 185 | tokio::time::sleep(Duration::from_millis(1000)).await; 186 | 187 | let key = ConfigKey::new("001","foo",""); 188 | //设置 189 | config_client.set_config(&key, "1234").await.unwrap(); 190 | //获取 191 | let v=config_client.get_config(&key).await.unwrap(); 192 | println!("{:?},{}",&key,v); 193 | check_listener_value().await; 194 | nacos_rust_client::close_current_system(); 195 | } 196 | 197 | async fn check_listener_value(){ 198 | //获取全局最后一次创建的config_client 199 | let config_client = nacos_rust_client::get_last_config_client().unwrap(); 200 | let mut foo_obj= Foo { 201 | name:"foo name".to_owned(), 202 | number:0u64, 203 | }; 204 | let key = ConfigKey::new("foo_config","foo",""); 205 | let foo_config_obj_listener = Box::new(ConfigDefaultListener::new(key.clone(),Arc::new(|s|{ 206 | //字符串反序列化为对象,如:serde_json::from_str::(s) 207 | Some(serde_json::from_str::(s).unwrap()) 208 | }))); 209 | let foo_config_string_listener = Box::new(ConfigDefaultListener::new(key.clone(),Arc::new(|s|{ 210 | //字符串反序列化为对象,如:serde_json::from_str::(s) 211 | Some(s.to_owned()) 212 | }))); 213 | config_client.set_config(&key,&serde_json::to_string(&foo_obj).unwrap()).await.unwrap(); 214 | //监听 215 | config_client.subscribe(foo_config_obj_listener.clone()).await; 216 | config_client.subscribe(foo_config_string_listener.clone()).await; 217 | //从监听对象中获取 218 | println!("key:{:?} ,value:{:?}",&key.data_id,foo_config_string_listener.get_value()); 219 | for i in 1..10 { 220 | foo_obj.number=i; 221 | let foo_json_string = serde_json::to_string(&foo_obj).unwrap(); 222 | config_client.set_config(&key,&foo_json_string).await.unwrap(); 223 | // 配置推送到服务端后, 监听更新需要一点时间 224 | tokio::time::sleep(Duration::from_millis(1000)).await; 225 | let foo_obj_from_listener = foo_config_obj_listener.get_value().unwrap(); 226 | let foo_obj_string_from_listener = foo_config_string_listener.get_value().unwrap(); 227 | // 监听项的内容有变更后会被服务端推送,监听项会自动更新为最新的配置 228 | println!("foo_obj_from_listener :{}",&foo_obj_string_from_listener); 229 | assert_eq!(foo_obj_string_from_listener.to_string(),foo_json_string); 230 | assert_eq!(foo_obj_from_listener.number,foo_obj.number); 231 | assert_eq!(foo_obj_from_listener.number,i); 232 | } 233 | } 234 | ``` 235 | 236 | 237 | ### 服务中心例子 238 | 239 | ```rust 240 | use nacos_rust_client::client::naming_client::{ServiceInstanceKey, InstanceDefaultListener}; 241 | use std::sync::Arc; 242 | 243 | use std::time::Duration; 244 | 245 | use nacos_rust_client::client::{HostInfo, ClientBuilder, AuthInfo, naming_client::{NamingClient, Instance,QueryInstanceListParams}}; 246 | 247 | 248 | 249 | #[tokio::main] 250 | async fn main(){ 251 | //std::env::set_var("RUST_LOG","INFO"); 252 | std::env::set_var("RUST_LOG","INFO"); 253 | env_logger::init(); 254 | //let host = HostInfo::parse("127.0.0.1:8848"); 255 | //let client = NamingClient::new(host,"".to_owned()); 256 | let namespace_id = "public".to_owned(); //default teant 257 | //let auth_info = Some(AuthInfo::new("nacos","nacos")); 258 | let auth_info = None; 259 | //let client = NamingClient::new_with_addrs("127.0.0.1:8848,127.0.0.1:8848", namespace_id, auth_info); 260 | let client = ClientBuilder::new() 261 | .set_endpoint_addrs("127.0.0.1:8848,127.0.0.1:8848") 262 | .set_auth_info(auth_info) 263 | .set_tenant(namespace_id) 264 | .set_use_grpc(true) 265 | .set_app_name("foo".to_owned()) 266 | .build_naming_client(); 267 | let servcie_key = ServiceInstanceKey::new("foo","DEFAULT_GROUP"); 268 | //可以通过监听器获取指定服务的最新实现列表,并支持触发变更回调函数,可用于适配微服务地址选择器。 269 | let default_listener = InstanceDefaultListener::new(servcie_key,Some(Arc::new( 270 | |instances,add_list,remove_list| { 271 | println!("service instances change,count:{},add count:{},remove count:{}",instances.len(),add_list.len(),remove_list.len()); 272 | }))); 273 | client.subscribe(Box::new(default_listener.clone())).await.unwrap(); 274 | let ip = local_ipaddress::get().unwrap(); 275 | let service_name = "foo"; 276 | let group_name="DEFAULT_GROUP"; 277 | for i in 0..10{ 278 | let port=10000+i; 279 | let instance = Instance::new_simple(&ip,port,service_name,group_name); 280 | //注册 281 | client.register(instance); 282 | tokio::time::sleep(Duration::from_millis(1000)).await; 283 | } 284 | 285 | //tokio::spawn(async{query_params2().await.unwrap();}); 286 | //let client2 = client.clone(); 287 | tokio::spawn( 288 | async move { 289 | query_params().await; 290 | } 291 | ); 292 | 293 | //let mut buf = vec![0u8;1]; 294 | //stdin().read(&mut buf).unwrap(); 295 | tokio::signal::ctrl_c().await.expect("failed to listen for event"); 296 | println!("n:{}",&client.namespace_id); 297 | } 298 | 299 | async fn query_params() -> anyhow::Result<()>{ 300 | //get client from global 301 | let client = nacos_rust_client::get_last_naming_client().unwrap(); 302 | let service_name = "foo"; 303 | let group_name="DEFAULT_GROUP"; 304 | let params = QueryInstanceListParams::new_simple(service_name,group_name); 305 | // 模拟每秒钟获取一次实例 306 | loop{ 307 | //查询并按权重随机选择其中一个实例 308 | match client.select_instance(params.clone()).await{ 309 | Ok(instances) =>{ 310 | println!("select instance {}:{}",&instances.ip,&instances.port); 311 | }, 312 | Err(e) => { 313 | println!("select_instance error {:?}",&e) 314 | }, 315 | } 316 | tokio::time::sleep(Duration::from_millis(1000)).await; 317 | } 318 | Ok(()) 319 | } 320 | 321 | 322 | ``` 323 | 324 | 325 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------