mod merkle;
mod store;
mod sync;
mod types;
pub use merkle::MerkleTree;
pub use store::{CrdtStore, LwwRegister};
pub use sync::CrdtSyncService;
pub use types::{GCounter, MvRegister, OrSet, PnCounter};
use async_trait::async_trait;
use bytes::Bytes;
use pollen_types::{NodeId, Result};
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use tokio::sync::broadcast;
pub trait CrdtValue: Serialize + DeserializeOwned + Clone + Send + Sync + 'static {
fn merge(&mut self, other: &Self);
}
#[async_trait]
pub trait CrdtKv: Send + Sync + 'static {
fn get<T: CrdtValue>(&self, key: &str) -> Option<T>;
async fn set<T: CrdtValue>(&self, key: &str, value: T) -> Result<()>;
async fn delete(&self, key: &str) -> Result<()>;
fn subscribe(&self, prefix: &str) -> broadcast::Receiver<CrdtEvent>;
async fn sync_with(&self, peer: NodeId) -> Result<()>;
fn keys(&self) -> Vec<String>;
fn keys_with_prefix(&self, prefix: &str) -> Vec<String>;
}
#[derive(Clone, Debug)]
pub enum CrdtEvent {
Updated { key: String },
Deleted { key: String },
}
pub type SharedCrdtKv = Arc<dyn CrdtKv>;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CrdtEntry {
pub key: String,
pub crdt_type: String,
pub data: Bytes,
pub timestamp: u64,
pub deleted: bool,
}
impl CrdtEntry {
pub fn new(key: String, crdt_type: String, data: Bytes, timestamp: u64) -> Self {
Self {
key,
crdt_type,
data,
timestamp,
deleted: false,
}
}
pub fn tombstone(key: String, timestamp: u64) -> Self {
Self {
key,
crdt_type: "tombstone".to_string(),
data: Bytes::new(),
timestamp,
deleted: true,
}
}
}