use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ConsensusState {
pub holonomy: f64,
pub peer_agreement: f64,
pub crdt_version: BTreeMap<u64, u64>,
}
impl ConsensusState {
pub fn new(holonomy: f64, peer_agreement: f64, crdt_version: BTreeMap<u64, u64>) -> Self {
Self { holonomy, peer_agreement, crdt_version }
}
pub fn default() -> Self {
Self {
holonomy: 0.0,
peer_agreement: 1.0,
crdt_version: BTreeMap::new(),
}
}
pub fn check_alignment(&self) -> Vec<String> {
let mut violations = Vec::new();
if !(0.0..=1.0).contains(&self.peer_agreement) {
violations.push("consensus.peer_agreement must be 0-1".into());
}
violations
}
pub fn merge(&self, other: &Self) -> Self {
let holonomy = self.holonomy.min(other.holonomy);
let peer_agreement = self.peer_agreement.max(other.peer_agreement);
let mut crdt_version = self.crdt_version.clone();
for (k, v) in &other.crdt_version {
crdt_version
.entry(*k)
.and_modify(|existing| *existing = (*existing).max(*v))
.or_insert(*v);
}
Self { holonomy, peer_agreement, crdt_version }
}
}