use crate::{Error, Record, store};
use persistant_kv::{KvBackend, KvError, cas};
use std::fmt;
use std::time::Duration;
#[derive(Debug)]
pub enum RecordUpdateError {
Record(Error),
Kv(KvError),
Contended {
attempts: usize,
},
}
impl fmt::Display for RecordUpdateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RecordUpdateError::Record(e) => write!(f, "{e}"),
RecordUpdateError::Kv(e) => write!(f, "{e}"),
RecordUpdateError::Contended { attempts } => {
write!(
f,
"lost the race {attempts} times in a row; the key is too hot"
)
}
}
}
}
impl std::error::Error for RecordUpdateError {}
pub async fn update_record<K, R, F>(
kv: &K,
key: &str,
ttl: Option<Duration>,
mut f: F,
) -> Result<bool, RecordUpdateError>
where
K: KvBackend,
R: Record,
F: FnMut(Option<R>) -> Option<R>,
{
let mut failed: Option<Error> = None;
let out = cas::update(kv, key, ttl, |old| {
failed = None;
let current = match old {
None => None,
Some(bytes) => match store::decode_record::<R>(bytes) {
Ok(r) => Some(r),
Err(e) => {
failed = Some(e);
return None;
}
},
};
let next = f(current)?;
match store::encode_record(&next) {
Ok(b) => Some(b),
Err(e) => {
failed = Some(e);
None
}
}
})
.await;
if let Some(e) = failed {
return Err(RecordUpdateError::Record(e));
}
match out {
Ok(committed) => Ok(committed.is_some()),
Err(cas::UpdateError::Kv(e)) => Err(RecordUpdateError::Kv(e)),
Err(cas::UpdateError::Contended { attempts }) => {
Err(RecordUpdateError::Contended { attempts })
}
}
}