use std::{
fmt,
hash::{BuildHasher as _, RandomState},
sync::Arc,
time::Duration,
};
use fraiseql_error::{FraiseQLError, Result};
use serde::{Deserialize, Serialize};
pub const MAX_BACKOFF_MS: u64 = 5_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetryEvent<'a> {
Retrying {
function: &'a str,
sql_state: &'a str,
attempt: u32,
backoff: Duration,
},
Exhausted {
function: &'a str,
sql_state: &'a str,
attempts: u32,
},
}
pub type RetryObserver = Arc<dyn Fn(RetryEvent<'_>) + Send + Sync>;
#[derive(Clone)]
pub struct TransactionRetry {
max_attempts: u32,
base_ms: u64,
max_ms: u64,
observer: Option<RetryObserver>,
}
impl TransactionRetry {
#[must_use]
pub const fn off() -> Self {
Self {
max_attempts: 1,
base_ms: 0,
max_ms: 0,
observer: None,
}
}
pub fn new(max_attempts: u32, base_ms: u64, max_ms: u64) -> Result<Self> {
if max_attempts == 0 {
return Err(refused(
"max_attempts must be at least 1 (the first attempt): 1 turns retry off",
));
}
if max_ms > MAX_BACKOFF_MS {
return Err(refused(&format!(
"max_ms ({max_ms}) must be at most {MAX_BACKOFF_MS}: the connection is held \
while a retry waits"
)));
}
if base_ms > max_ms {
return Err(refused(&format!("base_ms ({base_ms}) must be at most max_ms ({max_ms})")));
}
Ok(Self {
max_attempts,
base_ms,
max_ms,
observer: None,
})
}
#[must_use]
pub fn with_observer(mut self, observer: RetryObserver) -> Self {
self.observer = Some(observer);
self
}
#[must_use]
pub const fn max_attempts(&self) -> u32 {
self.max_attempts
}
pub(crate) const fn allows_after(&self, attempt: u32) -> bool {
attempt < self.max_attempts
}
pub(crate) fn backoff(&self, retry: u32, entropy: u64) -> Duration {
let doublings = retry.saturating_sub(1).min(63);
let cap = self.base_ms.saturating_mul(1_u64 << doublings).min(self.max_ms);
Duration::from_millis(entropy % (cap + 1))
}
pub(crate) fn draw_backoff(&self, retry: u32) -> Duration {
self.backoff(retry, RandomState::new().hash_one(retry))
}
pub(crate) fn observe(&self, event: RetryEvent<'_>) {
if let Some(observer) = &self.observer {
observer(event);
}
}
}
impl Default for TransactionRetry {
fn default() -> Self {
Self::off()
}
}
impl fmt::Debug for TransactionRetry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TransactionRetry")
.field("max_attempts", &self.max_attempts)
.field("base_ms", &self.base_ms)
.field("max_ms", &self.max_ms)
.field("observer", &self.observer.is_some())
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct TransactionRetryConfig {
pub max_attempts: u32,
pub base_ms: u64,
pub max_ms: u64,
}
impl Default for TransactionRetryConfig {
fn default() -> Self {
Self {
max_attempts: 3,
base_ms: 10,
max_ms: 200,
}
}
}
impl TransactionRetryConfig {
pub fn policy(&self) -> std::result::Result<TransactionRetry, String> {
TransactionRetry::new(self.max_attempts, self.base_ms, self.max_ms).map_err(|e| match e {
FraiseQLError::Configuration { message } => message,
other => other.to_string(),
})
}
}
fn refused(message: &str) -> FraiseQLError {
FraiseQLError::Configuration {
message: message.to_string(),
}
}
#[cfg(test)]
#[path = "transaction_retry_tests.rs"]
mod tests;