use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::Duration;
use crate::Result;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) enum Kind {
Lock,
Semaphore,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct Place {
kind: Kind,
name: Arc<str>,
key: String,
}
impl Place {
pub(crate) fn new(kind: Kind, name: Arc<str>, key: String) -> Place {
Place { kind, name, key }
}
pub(crate) fn name(&self) -> &Arc<str> {
&self.name
}
}
impl fmt::Display for Place {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self.kind {
Kind::Lock => "lock",
Kind::Semaphore => "semaphore",
};
write!(f, "{kind} {}: key {:?}", self.name, self.key)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Fence(u128);
impl Fence {
pub(crate) fn of(epoch: u64, count: u64) -> Fence {
Fence((u128::from(epoch) << 64) | u128::from(count))
}
pub fn get(self) -> u128 {
self.0
}
}
impl fmt::Display for Fence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Debug for Fence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Fence({}ยท{})", self.0 >> 64, self.0 & u128::from(u64::MAX))
}
}
pub(crate) type LeaseId = [u8; 16];
pub(crate) type RequestId = [u8; 16];
pub(crate) struct Ask {
pub(crate) place: Place,
pub(crate) limit: u32,
pub(crate) ttl: Option<Duration>,
pub(crate) max_hold: Option<Duration>,
pub(crate) wait: Duration,
pub(crate) request: Option<RequestId>,
}
pub(crate) enum Answer {
Granted(Granted),
Busy,
}
pub(crate) type Reply = Box<dyn FnOnce(Result<Answer>) + Send>;
#[derive(Clone)]
pub(crate) struct Granted {
pub(crate) lease: LeaseId,
pub(crate) fence: Fence,
pub(crate) expires: Option<i64>,
pub(crate) revokes: Option<i64>,
pub(crate) watch: Arc<Watch>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Ending {
Live,
Lost,
Closed,
}
#[derive(Default)]
pub(crate) struct Watch {
ending: AtomicU8,
}
impl Watch {
pub(crate) fn ending(&self) -> Ending {
match self.ending.load(Ordering::Acquire) {
0 => Ending::Live,
1 => Ending::Lost,
_ => Ending::Closed,
}
}
pub(crate) fn end(&self, ending: Ending) {
let code = if ending == Ending::Closed { 2 } else { 1 };
let _ = self.ending.compare_exchange(0, code, Ordering::AcqRel, Ordering::Acquire);
}
}