use std::cmp::Ordering;
use std::fmt;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{Error, Result};
pub const MAX_COUNTER: u32 = 65_535;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Hlc {
pub wall_ms: u64,
pub counter: u32,
pub node: String,
}
impl Hlc {
pub fn parse(s: &str) -> Result<Hlc> {
let bad = || Error::new("invalid_hlc", format!("not an HLC stamp: {s:?}"));
let mut parts = s.splitn(3, ':');
let (w, c, n) = match (parts.next(), parts.next(), parts.next()) {
(Some(w), Some(c), Some(n)) => (w, c, n),
_ => return Err(bad()),
};
if w.len() != 13 || !w.bytes().all(|b| b.is_ascii_digit()) {
return Err(bad());
}
if c.len() != 5 || !c.bytes().all(|b| b.is_ascii_digit()) {
return Err(bad());
}
if !valid_node(n) {
return Err(bad());
}
let counter: u32 = c.parse().map_err(|_| bad())?;
if counter > MAX_COUNTER {
return Err(bad());
}
Ok(Hlc { wall_ms: w.parse().map_err(|_| bad())?, counter, node: n.to_string() })
}
}
impl fmt::Display for Hlc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:013}:{:05}:{}", self.wall_ms, self.counter, self.node)
}
}
impl PartialOrd for Hlc {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Hlc {
fn cmp(&self, other: &Self) -> Ordering {
self.wall_ms
.cmp(&other.wall_ms)
.then(self.counter.cmp(&other.counter))
.then_with(|| self.node.as_bytes().cmp(other.node.as_bytes()))
}
}
pub fn compare(a: &str, b: &str) -> Ordering {
match (Hlc::parse(a), Hlc::parse(b)) {
(Ok(x), Ok(y)) => x.cmp(&y),
_ => a.cmp(b),
}
}
pub fn newer(hlc: &str, than: Option<&str>) -> bool {
match than {
None => true,
Some(t) => compare(hlc, t) == Ordering::Greater,
}
}
pub fn valid_node(n: &str) -> bool {
!n.is_empty() && n.len() <= 64 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
pub struct Clock {
node: String,
max_drift_ms: u64,
last: Mutex<(u64, u32)>,
now: Box<dyn Fn() -> u64 + Send + Sync>,
}
impl fmt::Debug for Clock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Clock").field("node", &self.node).finish()
}
}
pub fn now_ms() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}
impl Clock {
pub fn new(node: impl Into<String>) -> Clock {
Clock::with_time(node, now_ms)
}
pub fn with_time(node: impl Into<String>, now: impl Fn() -> u64 + Send + Sync + 'static) -> Clock {
let node = node.into();
assert!(valid_node(&node), "invalid HLC node id {node:?}");
Clock { node, max_drift_ms: 5 * 60 * 1000, last: Mutex::new((0, 0)), now: Box::new(now) }
}
pub fn with_max_drift(mut self, ms: u64) -> Clock {
self.max_drift_ms = ms;
self
}
pub fn node(&self) -> &str {
&self.node
}
pub fn tick(&self) -> String {
let pt = (self.now)();
let mut last = self.last.lock().unwrap();
let (w, c) = *last;
let next = if pt > w {
(pt, 0)
} else if c >= MAX_COUNTER {
(w + 1, 0) } else {
(w, c + 1)
};
*last = next;
Hlc { wall_ms: next.0, counter: next.1, node: self.node.clone() }.to_string()
}
pub fn observe(&self, stamp: &str) -> Result<()> {
let r = Hlc::parse(stamp)?;
let pt = (self.now)();
if self.max_drift_ms > 0 && r.wall_ms > pt + self.max_drift_ms {
return Err(Error::new(
"clock_drift",
format!("{stamp} is more than {} ms ahead of this clock", self.max_drift_ms),
));
}
let mut last = self.last.lock().unwrap();
let (lw, lc) = *last;
let wall = lw.max(r.wall_ms).max(pt);
let counter = if wall == lw && wall == r.wall_ms {
lc.max(r.counter) + 1
} else if wall == lw {
lc + 1
} else if wall == r.wall_ms {
r.counter + 1
} else {
0
};
*last = if counter > MAX_COUNTER { (wall + 1, 0) } else { (wall, counter) };
Ok(())
}
pub fn last(&self) -> String {
let (w, c) = *self.last.lock().unwrap();
Hlc { wall_ms: w, counter: c, node: self.node.clone() }.to_string()
}
pub fn restore(&self, stamp: &str) {
if let Ok(h) = Hlc::parse(stamp) {
let mut last = self.last.lock().unwrap();
if (h.wall_ms, h.counter) > *last {
*last = (h.wall_ms, h.counter);
}
}
}
}
pub fn random_node() -> String {
let mut b = [0u8; 6];
let _ = getrandom::fill(&mut b);
format!("rs-{}", hex::encode(b))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering as AO};
use std::sync::Arc;
#[test]
fn format_and_parse() {
let h = Hlc::parse("1764314700123:00002:mobile-19c2").unwrap();
assert_eq!(h.wall_ms, 1764314700123);
assert_eq!(h.counter, 2);
assert_eq!(h.to_string(), "1764314700123:00002:mobile-19c2");
assert!(Hlc::parse("1764314700123:65536:n").is_err());
assert!(Hlc::parse("1764314700123:2:n").is_err());
assert!(Hlc::parse("1764314700123:00002:").is_err());
assert!(Hlc::parse("1764314700123:00002:a b").is_err());
}
#[test]
fn counter_borrows_a_millisecond() {
let t = Arc::new(AtomicU64::new(1_000_000_000_000));
let t2 = t.clone();
let c = Clock::with_time("n", move || t2.load(AO::SeqCst));
c.restore("1000000000000:65534:n");
assert_eq!(c.tick(), "1000000000000:65535:n");
assert_eq!(c.tick(), "1000000000001:00000:n");
let _ = t;
}
#[test]
fn observe_orders_after_remote() {
let c = Clock::with_time("n", || 1_000_000_000_000);
c.observe("1000000000500:00007:other").unwrap();
let s = c.tick();
assert!(newer(&s, Some("1000000000500:00007:other")), "{s}");
}
}