use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use crate::error::StateError;
pub mod memory;
#[cfg(feature = "state-disk")]
pub mod redb;
pub use memory::MemoryKv;
#[cfg(feature = "state-disk")]
pub use redb::RedbKv;
#[cfg(feature = "state-disk")]
pub fn open_disk(path: &std::path::Path) -> Result<std::sync::Arc<dyn AwKv>, StateError> {
Ok(std::sync::Arc::new(RedbKv::open(path)?))
}
pub type KvFut<'a, T> = Pin<Box<dyn Future<Output = Result<T, StateError>> + Send + 'a>>;
pub trait AwKv: Send + Sync {
fn get<'a>(&'a self, key: &'a str) -> KvFut<'a, Option<Vec<u8>>>;
fn set_ex<'a>(&'a self, key: &'a str, val: Vec<u8>, ttl: Duration) -> KvFut<'a, ()>;
fn del<'a>(&'a self, key: &'a str) -> KvFut<'a, ()>;
fn set_nx<'a>(&'a self, key: &'a str, val: Vec<u8>, ttl: Duration) -> KvFut<'a, bool>;
fn compare_refresh<'a>(
&'a self,
key: &'a str,
expected: &'a [u8],
ttl: Duration,
) -> KvFut<'a, bool>;
fn compare_del<'a>(&'a self, key: &'a str, expected: &'a [u8]) -> KvFut<'a, bool>;
fn incr_by<'a>(&'a self, key: &'a str, delta: u64, ttl: Duration) -> KvFut<'a, u64>;
fn get_u64<'a>(&'a self, key: &'a str) -> KvFut<'a, u64> {
Box::pin(async move {
match self.get(key).await? {
Some(bytes) => decode_u64(&bytes),
None => Ok(0),
}
})
}
}
pub(crate) fn encode_u64(value: u64) -> Vec<u8> {
value.to_be_bytes().to_vec()
}
pub(crate) fn decode_u64(bytes: &[u8]) -> Result<u64, StateError> {
let arr: [u8; 8] = bytes
.try_into()
.map_err(|_| StateError::Decode(format!("counter not 8 bytes: len={}", bytes.len())))?;
Ok(u64::from_be_bytes(arr))
}