use std::fmt;
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Revision {
scope: String,
value: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Reached {
Yes,
Behind,
OtherScope,
}
impl Reached {
pub fn is_reached(self) -> bool {
self == Reached::Yes
}
}
impl Revision {
pub fn new(scope: impl Into<String>, value: u64) -> Self {
let scope = scope.into();
Self {
scope: if scope.is_empty() {
DEFAULT_SCOPE.to_owned()
} else {
scope
},
value,
}
}
pub fn scope(&self) -> &str {
&self.scope
}
pub fn value(&self) -> u64 {
self.value
}
pub fn reached_by(required: &Revision, have: Option<&Revision>) -> Reached {
match have {
Some(have) => have.reaches(required),
None => Reached::OtherScope,
}
}
pub fn reaches(&self, required: &Revision) -> Reached {
if self.scope != required.scope {
Reached::OtherScope
} else if self.value >= required.value {
Reached::Yes
} else {
Reached::Behind
}
}
#[must_use]
pub fn advanced(&self, by: u64) -> Self {
Self {
scope: self.scope.clone(),
value: self.value.saturating_add(by),
}
}
}
pub const DEFAULT_SCOPE: &str = "default";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RevisionParseError;
impl std::error::Error for RevisionParseError {}
impl fmt::Display for RevisionParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("not a revision token")
}
}
impl fmt::Display for Revision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}@{}", self.scope, self.value)
}
}
impl FromStr for Revision {
type Err = RevisionParseError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let (scope, value) = text.rsplit_once('@').ok_or(RevisionParseError)?;
if scope.is_empty() {
return Err(RevisionParseError);
}
let value = value.parse::<u64>().map_err(|_| RevisionParseError)?;
Ok(Revision::new(scope, value))
}
}
impl Serialize for Revision {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Revision {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
pub trait RevisionSource: Send + Sync {
fn next(&self) -> Revision;
fn current(&self) -> Revision;
}
#[derive(Debug)]
pub struct MemoryRevisions {
scope: String,
counter: AtomicU64,
}
impl MemoryRevisions {
pub fn new(scope: impl Into<String>) -> Self {
Self::starting_at(scope, 0)
}
pub fn starting_at(scope: impl Into<String>, value: u64) -> Self {
Self {
scope: Revision::new(scope, 0).scope,
counter: AtomicU64::new(value),
}
}
}
impl RevisionSource for MemoryRevisions {
fn next(&self) -> Revision {
let value = self.counter.fetch_add(1, Ordering::SeqCst).saturating_add(1);
Revision::new(self.scope.clone(), value)
}
fn current(&self) -> Revision {
Revision::new(self.scope.clone(), self.counter.load(Ordering::SeqCst))
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Revised<T> {
pub value: T,
pub revision: Option<Revision>,
}
impl<T> Revised<T> {
pub fn new(value: T, revision: Option<Revision>) -> Self {
Self { value, revision }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_round_trip_keeps_an_at_sign_in_the_scope() {
let revision = Revision::new("tenant@eu", 7);
assert_eq!(revision.to_string(), "tenant@eu@7");
assert_eq!("tenant@eu@7".parse::<Revision>().unwrap(), revision);
let json = serde_json::to_string(&revision).unwrap();
assert_eq!(json, "\"tenant@eu@7\"");
assert_eq!(serde_json::from_str::<Revision>(&json).unwrap(), revision);
}
#[test]
fn garbage_does_not_parse() {
for text in ["", "7", "@7", "a@", "a@-1", "a@x"] {
assert!(text.parse::<Revision>().is_err(), "{text}");
}
assert!(serde_json::from_str::<Revision>("3").is_err());
}
#[test]
fn comparison_is_per_scope() {
let have = Revision::new("a", 5);
assert_eq!(have.reaches(&Revision::new("a", 5)), Reached::Yes);
assert_eq!(have.reaches(&Revision::new("a", 4)), Reached::Yes);
assert_eq!(have.reaches(&Revision::new("a", 6)), Reached::Behind);
assert_eq!(have.reaches(&Revision::new("b", 1)), Reached::OtherScope);
assert_eq!(Revision::reached_by(&Revision::new("a", 1), None), Reached::OtherScope);
}
#[test]
fn memory_source_is_monotonic() {
let source = MemoryRevisions::new("t");
assert_eq!(source.current().value(), 0);
let (a, b) = (source.next(), source.next());
assert!(b.value() > a.value());
assert_eq!(source.current(), b);
}
}