Skip to content

Commit add53eb

Browse files
committed
internal loop for client re-creation, keeping the lock
1 parent ef3ddfd commit add53eb

File tree

1 file changed

+22
-19
lines changed

1 file changed

+22
-19
lines changed

src/client.rs

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,8 @@ pub struct Client {
3737
macro_rules! impl_inner_call {
3838
( $self:expr, $name:ident $(, $args:expr)* ) => {
3939
{
40-
let mut count = 0;
41-
let mut errors = Vec::with_capacity(count as usize);
40+
let mut errors = vec![];
4241
loop {
43-
if count == $self.config.retry() {
44-
return Err(Error::AllAttemptsErrored(errors));
45-
}
46-
count += 1;
4742
let read_client = $self.client_type.read().unwrap();
4843
let res = match &*read_client {
4944
ClientType::TCP(inner) => inner.$name( $($args, )* ),
@@ -53,32 +48,40 @@ macro_rules! impl_inner_call {
5348
drop(read_client);
5449
match res {
5550
Ok(val) => return Ok(val),
56-
Err(Error::Protocol(e)) => {
57-
warn!("Error::Protocol {:?}", e);
58-
continue
51+
Err(Error::Protocol(_)) => {
52+
return res;
5953
},
6054
Err(e) => {
61-
match $self.client_type.try_write() {
62-
Ok(mut write_client) => {
63-
warn!("retry:{}/{} {:?}", count, $self.config.retry(), e);
64-
errors.push(e);
55+
warn!("call retry:{}/{} {:?}", errors.len() + 1 , $self.config.retry(), e);
56+
errors.push(e);
57+
if errors.len() as u8 == $self.config.retry() {
58+
return Err(Error::AllAttemptsErrored(errors));
59+
}
60+
61+
// Only one thread will try to recreate the client getting the write lock,
62+
// other eventual threads will get Err and will block at the beginning of
63+
// previous loop when trying to read()
64+
if let Ok(mut write_client) = $self.client_type.try_write() {
65+
loop {
66+
std::thread::sleep(std::time::Duration::from_secs(errors.len() as u64));
6567
match ClientType::from_config(&$self.url, &$self.config) {
6668
Ok(new_client) => {
6769
info!("Succesfully created new client");
6870
*write_client = new_client;
71+
break;
6972
},
7073
Err(e) => {
71-
warn!("Cannot create new client {:?}", e);
74+
warn!("client retry:{}/{} {:?}", errors.len() + 1, $self.config.retry(), e);
75+
errors.push(e);
76+
if errors.len() as u8 == $self.config.retry() {
77+
return Err(Error::AllAttemptsErrored(errors));
78+
}
7279
}
7380
}
74-
75-
},
76-
Err(_) => (), // another thread is trying to retrying the client
81+
}
7782
}
7883
},
7984
}
80-
81-
std::thread::sleep(std::time::Duration::from_secs(count as u64));
8285
}}
8386
}
8487
}

0 commit comments

Comments
 (0)