use crate::lww_register_capnp;
use crate::traits::{Crdt, CrdtError, CrdtReader};
use crate::vector_clock::VectorClock;
use capnp::message::{Builder, HeapAllocator, ReaderOptions};
use capnp::serialize;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(serialize = "T: Serialize", deserialize = "T: DeserializeOwned"))]
pub struct LWWRegister<T> {
pub value: T,
pub timestamp: u64,
pub node_id: String,
pub vclock: VectorClock,
}
impl<T: Clone + Default + Serialize + DeserializeOwned + Send + Sync + 'static> Default
for LWWRegister<T>
{
fn default() -> Self {
Self {
value: T::default(),
timestamp: 0,
node_id: String::new(),
vclock: VectorClock::new(),
}
}
}
impl<T: Clone + Serialize + DeserializeOwned + Ord + Send + Sync + 'static> LWWRegister<T> {
pub fn new(value: T, timestamp: u64, node_id: impl Into<String>) -> Self {
let node_id = node_id.into();
let mut vclock = VectorClock::new();
vclock.increment(&node_id);
Self {
value,
timestamp,
node_id,
vclock,
}
}
pub fn set(&mut self, value: T, timestamp: u64, node_id: impl Into<String>) {
let node_id = node_id.into();
let update = timestamp > self.timestamp
|| (timestamp == self.timestamp && node_id > self.node_id)
|| (timestamp == self.timestamp
&& node_id == self.node_id
&& value > self.value);
if update {
self.value = value;
self.timestamp = timestamp;
self.node_id = node_id.clone();
self.vclock.increment(&node_id);
}
}
pub fn merge(&mut self, other: &Self) {
let update = other.timestamp > self.timestamp
|| (other.timestamp == self.timestamp && other.node_id > self.node_id)
|| (other.timestamp == self.timestamp
&& other.node_id == self.node_id
&& other.value > self.value);
if update {
self.value = other.value.clone();
self.timestamp = other.timestamp;
self.node_id = other.node_id.clone();
}
self.vclock.merge(&other.vclock);
}
}
pub struct LWWRegisterReader<'a, T> {
bytes: &'a [u8],
_phantom: std::marker::PhantomData<T>,
}
impl<'a, T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> LWWRegisterReader<'a, T> {
pub fn new(bytes: &'a [u8]) -> Self {
Self {
bytes,
_phantom: std::marker::PhantomData,
}
}
fn to_register(&self) -> Result<LWWRegister<T>, CrdtError> {
let reader = serialize::read_message(self.bytes, ReaderOptions::new())
.map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
let reg = reader
.get_root::<lww_register_capnp::lww_register::Reader>()
.map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
let value_bytes = reg
.get_value()
.map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
let value: T = bincode::deserialize(value_bytes)
.map_err(|e: bincode::Error| CrdtError::Deserialization(e.to_string()))?;
let node_id = reg
.get_node_id()
.map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?
.to_string()
.map_err(|e: std::str::Utf8Error| CrdtError::Deserialization(e.to_string()))?;
let vclock = if reg.has_vclock() {
let vc_bytes = reg
.get_vclock()
.map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
VectorClock::merge_from_readers(&[crate::vector_clock::VectorClockReader::new(
vc_bytes,
)])?
} else {
VectorClock::new()
};
Ok(LWWRegister {
value,
timestamp: reg.get_timestamp(),
node_id,
vclock,
})
}
}
impl<'a, T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> CrdtReader<'a>
for LWWRegisterReader<'a, T>
{
fn is_empty(&self) -> Result<bool, CrdtError> {
Ok(self.to_register()?.timestamp == 0)
}
}
impl<T: Clone + Default + Serialize + DeserializeOwned + Ord + Send + Sync + 'static> Crdt
for LWWRegister<T>
{
type Reader<'a> = LWWRegisterReader<'a, T>;
fn merge_from_readers(readers: &[Self::Reader<'_>]) -> Result<Self, CrdtError> {
if readers.is_empty() {
return Ok(LWWRegister::default());
}
let mut result = readers[0].to_register()?;
for reader in &readers[1..] {
result.merge(&reader.to_register()?);
}
Ok(result)
}
fn to_capnp_bytes(&self) -> Vec<u8> {
let mut message = Builder::new(HeapAllocator::new());
{
let mut reg = message.init_root::<lww_register_capnp::lww_register::Builder>();
let bytes =
bincode::serialize(&self.value).expect("LWWRegister value serialization fail");
reg.set_value(&bytes);
reg.set_timestamp(self.timestamp);
reg.set_node_id(self.node_id.as_str().into());
let vclock_bytes = self.vclock.to_capnp_bytes();
reg.set_vclock(&vclock_bytes);
}
let mut buf = Vec::new();
serialize::write_message(&mut buf, &message).expect("LWWRegister serialization fail");
buf
}
fn is_empty(&self) -> bool {
self.timestamp == 0
}
fn validate(&self) -> Result<(), CrdtError> {
Ok(())
}
}