Skip to content

Commit

Permalink
refactor(issue #79): AuthPlugin support multi server-addr (#80)
Browse files Browse the repository at this point in the history
* refactor(issue #79): AuthPlugin support multi server-addr

* chore: multi server-addr random/shuffle

* chore: into_grpc_server_addr shuffle
CherishCai authored Dec 8, 2022
1 parent b9cf7a4 commit 06d5f37
Showing 6 changed files with 45 additions and 16 deletions.
8 changes: 6 additions & 2 deletions src/api/plugin/auth/auth_by_http.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use rand::Rng;
use std::ops::{Add, Deref};
use std::sync::RwLock;
use std::time::{Duration, Instant};
@@ -49,8 +50,11 @@ impl AuthPlugin for HttpLoginAuthPlugin {

let server_addr = {
let mutex = self.server_list.read().unwrap();
// todo random one
mutex.first().unwrap().to_string()
// random one
mutex
.get(rand::thread_rng().gen_range(0..mutex.len()))
.unwrap()
.to_string()
};

// todo support https
18 changes: 18 additions & 0 deletions src/api/props.rs
Original file line number Diff line number Diff line change
@@ -16,6 +16,24 @@ pub struct ClientProps {
pub(crate) auth_context: HashMap<String, String>,
}

impl ClientProps {
pub(crate) fn get_server_list(&self) -> crate::api::error::Result<Vec<String>> {
let hosts: Vec<&str> = self.server_addr.split(',').collect::<Vec<&str>>();
if hosts.is_empty() {
return Err(crate::api::error::Error::WrongServerAddress(
self.server_addr.clone(),
));
}

let mut result = vec![];
for host in hosts {
result.push(host.to_string());
}

Ok(result)
}
}

#[allow(clippy::new_without_default)]
impl ClientProps {
/// Creates a new `ClientConfig`.
2 changes: 1 addition & 1 deletion src/common/remote/grpc/grpc_client.rs
Original file line number Diff line number Diff line change
@@ -27,7 +27,7 @@ pub(crate) struct GrpcClient {

impl GrpcClient {
pub(crate) async fn new(address: &str) -> Result<Self> {
let address = crate::common::remote::into_grpc_server_addr(address)?;
let address = crate::common::remote::into_grpc_server_addr(address, true)?;
let address = address.as_str();
info!("init grpc client: {}", address);
let env = Arc::new(Environment::new(2));
28 changes: 17 additions & 11 deletions src/common/remote/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
pub mod grpc;

use crate::api::error::Error::WrongServerAddress;
use crate::api::error::Result;
use rand::prelude::SliceRandom;
use std::sync::atomic::{AtomicI64, Ordering};

use crate::api::error::{Error, Result};

// odd by client request id.
const SEQUENCE_INITIAL_VALUE: i64 = 1;
const SEQUENCE_DELTA: i64 = 2;
@@ -19,12 +19,18 @@ pub(crate) fn generate_request_id() -> String {
}

/// make address's port plus 1000
pub(crate) fn into_grpc_server_addr(address: &str) -> Result<String> {
let hosts = address.split(',').collect::<Vec<&str>>();
if hosts.len() == 0 {
#[allow(clippy::get_first)]
pub(crate) fn into_grpc_server_addr(address: &str, shuffle: bool) -> Result<String> {
let mut hosts = address.split(',').collect::<Vec<&str>>();
if hosts.is_empty() {
return Err(WrongServerAddress(address.into()));
}

if shuffle {
// shuffle for grpcio LbPolicy::PickFirst, It is a sequential attempt to link, so reorder to balance the load as much as possible.
hosts.shuffle(&mut rand::thread_rng());
}

let mut result = vec![];
for host in hosts {
let host_port_pair = host.split(':').collect::<Vec<&str>>();
@@ -49,7 +55,7 @@ pub(crate) fn into_grpc_server_addr(address: &str) -> Result<String> {

match result.len() {
0 => Err(WrongServerAddress(address.into())),
1 => Ok(format!("{}", result.get(0).unwrap())),
1 => Ok(result.get(0).unwrap().to_string()),
_ => Ok(format!("ipv4:{}", result.join(","))),
}
}
@@ -60,23 +66,23 @@ mod tests {

#[test]
fn test_empty_address() {
match into_grpc_server_addr("") {
match into_grpc_server_addr("", false) {
Ok(_) => assert!(false),
Err(_) => assert!(true),
}
}

#[test]
fn test_host_address_without_port() {
match into_grpc_server_addr("127.0.0.1") {
match into_grpc_server_addr("127.0.0.1", false) {
Ok(_) => assert!(false),
Err(_) => assert!(true),
}
}

#[test]
fn test_host_addresses_without_one_port() {
match into_grpc_server_addr("127.0.0.1:8848,127.0.0.1") {
match into_grpc_server_addr("127.0.0.1:8848,127.0.0.1", false) {
Ok(_) => assert!(false),
Err(_) => assert!(true),
}
@@ -86,15 +92,15 @@ mod tests {
fn test_single_host_address() {
let addr = "127.0.0.1:8848";
let expected = "127.0.0.1:9848";
let result = into_grpc_server_addr(addr).unwrap();
let result = into_grpc_server_addr(addr, false).unwrap();
assert_eq!(expected, result);
}

#[test]
fn test_multiple_ipv4_address() {
let addr = "127.0.0.1:8848,127.0.0.1:8849,127.0.0.1:8850";
let expected = "ipv4:127.0.0.1:9848,127.0.0.1:9849,127.0.0.1:9850";
let result = into_grpc_server_addr(addr).unwrap();
let result = into_grpc_server_addr(addr, false).unwrap();
assert_eq!(expected, result);
}
}
2 changes: 1 addition & 1 deletion src/config/worker.rs
Original file line number Diff line number Diff line change
@@ -83,7 +83,7 @@ impl ConfigWorker {
notify_change_tx_clone,
));

let server_list = Arc::new(vec![client_props.server_addr.clone()]);
let server_list = Arc::new(client_props.get_server_list()?);
let plugin = Arc::clone(&auth_plugin);
let auth_context =
Arc::new(AuthContext::default().add_params(client_props.auth_context.clone()));
3 changes: 2 additions & 1 deletion src/naming/mod.rs
Original file line number Diff line number Diff line change
@@ -73,6 +73,8 @@ pub(crate) struct NacosNamingService {

impl NacosNamingService {
pub(crate) fn new(client_props: ClientProps, auth_plugin: Arc<dyn AuthPlugin>) -> Result<Self> {
let server_list = Arc::new(client_props.get_server_list()?);

let mut namespace = client_props.namespace;
if namespace.is_empty() {
namespace = self::constants::DEFAULT_NAMESPACE.to_owned();
@@ -103,7 +105,6 @@ impl NacosNamingService {
))
.build()?;

let server_list = Arc::new(vec![client_props.server_addr.clone()]);
let plugin = Arc::clone(&auth_plugin);
let auth_context =
Arc::new(AuthContext::default().add_params(client_props.auth_context.clone()));

0 comments on commit 06d5f37

Please sign in to comment.