summaryrefslogtreecommitdiff
path: root/common
diff options
context:
space:
mode:
Diffstat (limited to 'common')
-rw-r--r--common/Cargo.toml2
-rw-r--r--common/src/reconnect.rs11
2 files changed, 10 insertions, 3 deletions
diff --git a/common/Cargo.toml b/common/Cargo.toml
index 5b9f4ef..0c165de 100644
--- a/common/Cargo.toml
+++ b/common/Cargo.toml
@@ -33,3 +33,5 @@ rand = { version = "0.8.5", features = ["getrandom"] }
zeroize = "1.6.0"
# Optimized uri binary format
uri-pack = { path = "../uri-pack" }
+# Exponential backoff generator
+exponential-backoff = "1.2.0"
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(),
)
}