use std::collections::BTreeMap;
use negentropy::{Id, Negentropy, NegentropyStorageVector};
use nibkeep_base::cbor::{self, ToCbor, Value};
use nibkeep_base::{Hash, StatementId};
use nibkeep_log::{ChangeId, WrappedBlobKey, WrappedKey};
use crate::SyncError;
const FRAME_LIMIT: u64 = 4 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Holding {
Change {
id: ChangeId,
millis: u64,
depth: u64,
complete: bool,
},
RecordKey {
statement: StatementId,
key: WrappedKey,
},
BlobKey {
sealed: Hash,
key: WrappedBlobKey,
},
Account {
id: Hash,
issued: u64,
},
}
impl Holding {
const fn timestamp(&self) -> u64 {
match self {
Self::Change { millis, .. } => *millis,
Self::Account { issued, .. } => *issued,
_ => 0,
}
}
fn order(&self) -> (u8, u64) {
match self {
Self::Change { depth, .. } => (0, *depth),
Self::RecordKey { .. } => (1, 0),
Self::BlobKey { .. } => (2, 0),
Self::Account { .. } => (4, 0),
}
}
}
#[must_use]
pub fn item_id(holding: &Holding) -> [u8; 32] {
let described = match holding {
Holding::Change { id, complete, .. } => {
Value::Array(vec![0_u8.to_cbor(), id.to_cbor(), Value::Bool(*complete)])
}
Holding::RecordKey { statement, key } => {
Value::Array(vec![1_u8.to_cbor(), statement.to_cbor(), key.to_cbor()])
}
Holding::BlobKey { sealed, key } => {
Value::Array(vec![2_u8.to_cbor(), sealed.to_cbor(), key.to_cbor()])
}
Holding::Account { id, .. } => Value::Array(vec![4_u8.to_cbor(), id.to_cbor()]),
};
let digest = Hash::of(&cbor::encode(&described));
digest
.digest()
.try_into()
.unwrap_or_else(|_| unreachable!("BLAKE3 digests are 32 bytes"))
}
pub(crate) struct Reconciling {
negentropy: Negentropy<'static, NegentropyStorageVector>,
held: BTreeMap<[u8; 32], Holding>,
}
impl Reconciling {
pub(crate) fn new(holdings: Vec<Holding>) -> Result<Self, SyncError> {
let mut held = BTreeMap::new();
for holding in holdings {
held.entry(item_id(&holding)).or_insert(holding);
}
let mut storage = NegentropyStorageVector::with_capacity(held.len());
for (id, holding) in &held {
storage
.insert(holding.timestamp(), Id::from_byte_array(*id))
.map_err(negentropy_error)?;
}
storage.seal().map_err(negentropy_error)?;
let negentropy = Negentropy::owned(storage, FRAME_LIMIT).map_err(negentropy_error)?;
Ok(Self { negentropy, held })
}
pub(crate) fn initiate(&mut self) -> Result<Vec<u8>, SyncError> {
self.negentropy.initiate().map_err(negentropy_error)
}
pub(crate) fn answer(
&mut self,
message: &[u8],
have: &mut Vec<[u8; 32]>,
need: &mut Vec<[u8; 32]>,
) -> Result<Option<Vec<u8>>, SyncError> {
let (mut haves, mut needs) = (Vec::new(), Vec::new());
let answer = self
.negentropy
.reconcile_with_ids(message, &mut haves, &mut needs)
.map_err(negentropy_error)?;
have.extend(haves.iter().map(|id| **id));
need.extend(needs.iter().map(|id| **id));
Ok(answer)
}
pub(crate) fn respond(&mut self, message: &[u8]) -> Result<Vec<u8>, SyncError> {
self.negentropy.reconcile(message).map_err(negentropy_error)
}
pub(crate) fn in_order(&self, ids: &[[u8; 32]]) -> Vec<Holding> {
let mut holdings: Vec<(&[u8; 32], &Holding)> = ids
.iter()
.filter_map(|id| self.held.get_key_value(id))
.collect();
holdings.sort_by(|(a_id, a), (b_id, b)| a.order().cmp(&b.order()).then(a_id.cmp(b_id)));
holdings.dedup_by(|(a, _), (b, _)| a == b);
holdings
.into_iter()
.map(|(_, holding)| holding.clone())
.collect()
}
}
#[expect(clippy::needless_pass_by_value, reason = "for map_err")]
fn negentropy_error(error: negentropy::Error) -> SyncError {
SyncError::protocol(format!("negentropy: {error}"))
}