mod error;
pub use error::*;
mod mutex_backend;
mod rwlock_backend;
mod mutex;
pub use mutex::*;
mod rwlock;
pub use rwlock::*;
use std::time::Duration;
use redis::aio::ConnectionManager;
use crate::DistkitRedisKey;
#[cfg(test)]
mod tests;
const DEFAULT_LOCK_NAMESPACE: &str = "distkit-locks";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockMode {
Shared,
Exclusive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockGuardState {
Released,
Lost,
Acquired,
}
#[derive(Debug, Clone)]
pub struct LockOptions {
pub key: DistkitRedisKey,
pub connection_manager: ConnectionManager,
pub namespace: DistkitRedisKey,
pub ttl: Duration,
pub owner_id: Option<String>,
pub max_wait: Option<Duration>,
pub retry_interval: Duration,
}
impl LockOptions {
pub fn new(key: DistkitRedisKey, connection_manager: ConnectionManager) -> Self {
Self {
key,
connection_manager,
namespace: DistkitRedisKey::new_or_panic(DEFAULT_LOCK_NAMESPACE.to_string()),
ttl: Duration::from_secs(30),
owner_id: Some(uuid::Uuid::new_v4().to_string()),
max_wait: None,
retry_interval: Duration::from_millis(50),
}
}
pub fn builder(
key: DistkitRedisKey,
connection_manager: ConnectionManager,
) -> LockOptionsBuilder {
LockOptionsBuilder::new(key, connection_manager)
}
}
#[derive(Debug, Clone)]
pub struct LockOptionsBuilder {
options: LockOptions,
}
impl LockOptionsBuilder {
pub fn new(key: DistkitRedisKey, connection_manager: ConnectionManager) -> Self {
Self {
options: LockOptions::new(key, connection_manager),
}
}
pub fn namespace(mut self, namespace: DistkitRedisKey) -> Self {
self.options.namespace = namespace;
self
}
pub fn ttl(mut self, ttl: Duration) -> Self {
self.options.ttl = ttl;
self
}
pub fn owner_id(mut self, owner_id: impl Into<String>) -> Self {
self.options.owner_id = Some(owner_id.into());
self
}
pub fn max_wait(mut self, max_wait: Duration) -> Self {
self.options.max_wait = Some(max_wait);
self
}
pub fn retry_interval(mut self, retry_interval: Duration) -> Self {
self.options.retry_interval = retry_interval;
self
}
pub fn build(self) -> LockOptions {
self.options
}
}