-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.rs
More file actions
54 lines (48 loc) · 1.56 KB
/
Copy pathretry.rs
File metadata and controls
54 lines (48 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use tokio::time::{Duration, sleep};
use tonic::transport::{Channel, Endpoint};
const MAX_BACKOFF: u64 = 2000 * 60;
const MAX_RETRIES: i8 = 10;
// Will create a channel and retry if its not possible
pub async fn create_channel_with_retry(
channel_name: &str,
url: String,
connect_timeout: Duration,
request_timeout: Duration,
) -> Channel {
let mut backoff = 100;
let mut retries = 0;
loop {
let channel = match Endpoint::from_shared(url.clone()) {
Ok(c) => {
log::debug!("Creating a new endpoint for the: {} Service", channel_name);
c.connect_timeout(connect_timeout).timeout(request_timeout)
}
Err(err) => {
panic!(
"Cannot create Endpoint for Service: `{}`. Reason: {:?}",
channel_name, err
);
}
};
match channel.connect().await {
Ok(ch) => {
return ch;
}
Err(err) => {
log::warn!(
"Retry connect to `{}` using url: `{}` failed: {:?}, retrying in {}ms",
channel_name,
url,
err,
backoff
);
sleep(Duration::from_millis(backoff)).await;
backoff = (backoff * 2).min(MAX_BACKOFF);
retries += 1;
if retries >= MAX_RETRIES {
panic!("Reached max retries to url {}", url)
}
}
}
}
}