summaryrefslogtreecommitdiff
path: root/common/src/reconnect.rs
diff options
context:
space:
mode:
Diffstat (limited to 'common/src/reconnect.rs')
-rw-r--r--common/src/reconnect.rs11
1 files changed, 8 insertions, 3 deletions
diff --git a/common/src/reconnect.rs b/common/src/reconnect.rs
index f569fc9..f2892f5 100644
--- a/common/src/reconnect.rs
+++ b/common/src/reconnect.rs
@@ -15,10 +15,13 @@
*/
use std::time::Duration;
+use exponential_backoff::Backoff;
use log::error;
use postgres::{Client, NoTls};
-const RECONNECT_DELAY: Duration = Duration::from_secs(5);
+const MIN_RECONNECT_DELAY: Duration = Duration::from_millis(300);
+const MAX_RECONNECT_DELAY: Duration = Duration::from_secs(10);
+const VALID_DELAY: Duration = Duration::from_secs(3);
pub struct AutoReconnect<S, C> {
config: S,
@@ -39,10 +42,12 @@ impl<S, C> AutoReconnect<S, C> {
/// Create a new client, loop on error
fn connect(config: &S, connect: fn(&S) -> Option<C>) -> C {
+ let backoff = Backoff::new(8, MIN_RECONNECT_DELAY, MAX_RECONNECT_DELAY);
+ let mut iter = backoff.iter();
loop {
match connect(config) {
Some(new) => return new,
- None => std::thread::sleep(RECONNECT_DELAY),
+ None => std::thread::sleep(iter.next().unwrap_or(MAX_RECONNECT_DELAY)),
}
}
}
@@ -67,6 +72,6 @@ pub fn auto_reconnect_db(config: postgres::Config) -> AutoReconnectDb {
.map_err(|err| error!("connect DB: {}", err))
.ok()
},
- |client| client.is_valid(RECONNECT_DELAY).is_err(),
+ |client| client.is_valid(VALID_DELAY).is_err(),
)
}