use anyhow::{Context, Result};
use etcd_client::ConnectOptions;
use parking_lot::RwLock;
use std::{sync::Arc, time::Duration};
use tokio::{sync::Mutex, time::sleep};
const MAX_DECODING_MESSAGE_SIZE: usize = i32::MAX as usize;
pub struct Connector {
client: RwLock<etcd_client::Client>,
etcd_urls: Vec<String>,
connect_options: Option<ConnectOptions>,
backoff_state: Mutex<BackoffState>,
}
impl Connector {
pub async fn new(
etcd_urls: Vec<String>,
connect_options: Option<ConnectOptions>,
) -> Result<Arc<Self>> {
let client = Self::connect(&etcd_urls, &connect_options).await?;
Ok(Arc::new(Self {
client: RwLock::new(client),
etcd_urls,
connect_options,
backoff_state: Mutex::new(BackoffState::default()),
}))
}
async fn connect(
etcd_urls: &[String],
connect_options: &Option<ConnectOptions>,
) -> Result<etcd_client::Client> {
etcd_client::Client::connect(etcd_urls.to_vec(), connect_options.clone())
.await
.with_context(|| {
format!(
"Unable to connect to etcd server at {}. Check etcd server status",
etcd_urls.join(", ")
)
})
}
pub fn get_client(&self) -> etcd_client::Client {
self.client.read().clone()
}
pub fn kv_client(&self) -> etcd_client::KvClient {
self.get_client()
.kv_client()
.max_decoding_message_size(MAX_DECODING_MESSAGE_SIZE)
}
pub fn watch_client(&self) -> etcd_client::WatchClient {
self.get_client()
.watch_client()
.max_decoding_message_size(MAX_DECODING_MESSAGE_SIZE)
}
pub async fn reconnect(&self, deadline: std::time::Instant) -> Result<()> {
let mut backoff_state = self.backoff_state.lock().await;
tracing::warn!("Reconnecting to ETCD cluster at: {:?}", self.etcd_urls);
backoff_state.attempt_reset();
loop {
backoff_state.apply_backoff(deadline).await;
if std::time::Instant::now() >= deadline {
anyhow::bail!("Unable to reconnect to ETCD cluster: deadline exceeded");
}
match Self::connect(&self.etcd_urls, &self.connect_options).await {
Ok(new_client) => {
tracing::info!("Successfully reconnected to ETCD cluster");
let mut client_guard = self.client.write();
*client_guard = new_client;
return Ok(());
}
Err(e) => {
tracing::warn!(
"Reconnection failed (remaining time: {:?}): {}",
deadline.saturating_duration_since(std::time::Instant::now()),
e
);
}
}
}
}
pub fn etcd_urls(&self) -> &[String] {
&self.etcd_urls
}
pub fn connect_options(&self) -> &Option<ConnectOptions> {
&self.connect_options
}
}
#[derive(Debug)]
struct BackoffState {
pub initial_backoff: Duration,
pub min_backoff: Duration,
pub max_backoff: Duration,
current_backoff: Duration,
last_connect_attempt: std::time::Instant,
}
impl Default for BackoffState {
fn default() -> Self {
Self {
initial_backoff: Duration::from_millis(500),
min_backoff: Duration::from_millis(50),
max_backoff: Duration::from_secs(5),
current_backoff: Duration::ZERO,
last_connect_attempt: std::time::Instant::now(),
}
}
}
impl BackoffState {
pub fn attempt_reset(&mut self) {
if std::time::Instant::now() > self.last_connect_attempt + self.current_backoff {
tracing::debug!("Resetting backoff to 0 (first reconnect or enough time has passed)");
self.current_backoff = Duration::ZERO;
}
}
pub async fn apply_backoff(&mut self, deadline: std::time::Instant) {
if self.current_backoff > Duration::ZERO {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let backoff = std::cmp::min(self.current_backoff, remaining / 2);
let backoff = std::cmp::min(backoff, self.max_backoff);
let backoff = std::cmp::max(backoff, self.min_backoff);
self.current_backoff = backoff * 2;
tracing::debug!(
"Applying backoff of {:?} (remaining time: {:?})",
backoff,
remaining
);
sleep(backoff).await;
} else {
self.current_backoff = self.initial_backoff;
}
self.last_connect_attempt = std::time::Instant::now();
}
}