use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use crate::{CommitInfo, Durability, Error, ErrorCode, Pigeonhole, Result, Transaction};
#[derive(Debug, Clone)]
pub struct RetryPolicy {
max_attempts: Option<u32>,
deadline: Option<Duration>,
base: Duration,
cap: Duration,
retry_busy: bool,
durability: Option<Durability>,
}
impl Default for RetryPolicy {
fn default() -> Self {
Self {
max_attempts: None,
deadline: Some(Duration::from_secs(30)),
base: Duration::from_micros(5),
cap: Duration::from_millis(100),
retry_busy: false,
durability: None,
}
}
}
impl RetryPolicy {
pub fn max_attempts(mut self, n: u32) -> Self {
self.max_attempts = Some(n.max(1));
self
}
pub fn unlimited_attempts(mut self) -> Self {
self.max_attempts = None;
self
}
pub fn deadline(mut self, d: Duration) -> Self {
self.deadline = Some(d);
self
}
pub fn no_deadline(mut self) -> Self {
self.deadline = None;
self
}
pub fn backoff(mut self, base: Duration, cap: Duration) -> Self {
self.base = base;
self.cap = cap.max(base);
self
}
pub fn retry_busy(mut self, yes: bool) -> Self {
self.retry_busy = yes;
self
}
pub fn durability(mut self, durability: Durability) -> Self {
self.durability = Some(durability);
self
}
pub fn retries(&self, error: &Error) -> bool {
self.retries_code(error.code())
}
pub fn retries_code(&self, code: ErrorCode) -> bool {
match code {
ErrorCode::Conflict | ErrorCode::SnapshotExpired => true,
ErrorCode::Busy => self.retry_busy,
_ => false,
}
}
pub fn next_pause(&self, code: ErrorCode, attempt: u32, elapsed: Duration) -> Option<Duration> {
let more = self.max_attempts.is_none_or(|n| attempt < n)
&& self.deadline.is_none_or(|d| elapsed < d);
if !more || !self.retries_code(code) {
return None;
}
let pause = self.delay(attempt + 1);
Some(match self.deadline {
Some(d) => pause.min(d.saturating_sub(elapsed)),
None => pause,
})
}
pub fn delay(&self, attempt: u32) -> Duration {
if attempt <= 1 {
return Duration::ZERO;
}
let shift = (attempt - 2).min(32);
let bound = self
.base
.checked_mul(1u32 << shift.min(31))
.unwrap_or(self.cap)
.min(self.cap);
let nanos = bound.as_nanos() as u64;
if nanos == 0 {
return Duration::ZERO;
}
Duration::from_nanos(jitter() % nanos)
}
}
fn jitter() -> u64 {
use std::cell::Cell;
thread_local! {
static STATE: Cell<u64> = Cell::new({
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as u64);
let here = &t as *const u64 as u64;
(t ^ here.rotate_left(32)) | 1
});
}
STATE.with(|s| {
let mut x = s.get();
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
s.set(x);
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
})
}
impl Pigeonhole {
pub fn transact<T, E>(
&self,
policy: &RetryPolicy,
mut body: impl FnMut(&mut Transaction) -> std::result::Result<T, E>,
) -> std::result::Result<(T, CommitInfo), E>
where
E: From<Error>,
{
let started = Instant::now();
let mut attempt = 1u32;
loop {
let mut given_up = None;
let retryable = match self.transaction() {
Err(e) => Some(e),
Ok(mut txn) => match body(&mut txn) {
Err(app) => match txn.failed_read() {
Some(e) if policy.retries(&e) => Some(e),
_ => {
given_up = Some(app);
None
}
},
Ok(value) => {
let commit = match policy.durability {
Some(d) => txn.commit_with(d),
None => txn.commit(),
};
match commit {
Ok(info) => return Ok((value, info)),
Err(e) => Some(e),
}
}
},
};
if let Some(app) = given_up {
return Err(app);
}
let error = retryable.expect("an error when nothing was given up");
let Some(pause) = policy.next_pause(error.code(), attempt, started.elapsed()) else {
return Err(E::from(error));
};
attempt += 1;
self.db.txn_counts.retries.fetch_add(1, Ordering::Relaxed);
wait(pause);
}
}
}
const SPIN_BELOW: Duration = Duration::from_micros(100);
fn wait(pause: Duration) {
if pause.is_zero() {
return;
}
if pause >= SPIN_BELOW {
std::thread::sleep(pause);
return;
}
let until = Instant::now() + pause;
while Instant::now() < until {
std::thread::yield_now();
}
}
#[derive(Debug, Default)]
pub(crate) struct TxnCounts {
pub(crate) commits: AtomicU64,
pub(crate) conflicts: AtomicU64,
pub(crate) retries: AtomicU64,
}
impl TxnCounts {
pub(crate) fn count(&self, result: &Result<CommitInfo>) {
match result {
Ok(_) => self.commits.fetch_add(1, Ordering::Relaxed),
Err(e) if e.code() == ErrorCode::Conflict => {
self.conflicts.fetch_add(1, Ordering::Relaxed)
}
Err(_) => return,
};
}
pub(crate) fn fill(&self, m: &mut crate::EngineMetrics) {
m.transactions = self.commits.load(Ordering::Relaxed);
m.transaction_conflicts = self.conflicts.load(Ordering::Relaxed);
m.transaction_retries = self.retries.load(Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wait_lasts_at_least_the_pause_spun_or_slept() {
for pause in [
Duration::from_micros(20),
SPIN_BELOW,
Duration::from_micros(300),
] {
let started = Instant::now();
wait(pause);
assert!(started.elapsed() >= pause, "{pause:?}");
}
let started = Instant::now();
wait(Duration::ZERO);
assert!(started.elapsed() < Duration::from_millis(50));
}
}