nibkeep_sync/
reconcile.rs1use std::collections::BTreeMap;
5
6use negentropy::{Id, Negentropy, NegentropyStorageVector};
7use nibkeep_base::cbor::{self, ToCbor, Value};
8use nibkeep_base::{Hash, StatementId};
9use nibkeep_log::{ChangeId, WrappedBlobKey, WrappedKey};
10
11use crate::SyncError;
12
13const FRAME_LIMIT: u64 = 4 * 1024 * 1024;
16
17#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum Holding {
21 Change {
23 id: ChangeId,
25 millis: u64,
27 depth: u64,
30 complete: bool,
32 },
33 RecordKey {
35 statement: StatementId,
37 key: WrappedKey,
39 },
40 BlobKey {
42 sealed: Hash,
44 key: WrappedBlobKey,
46 },
47 Account {
50 id: Hash,
52 issued: u64,
54 },
55}
56
57impl Holding {
58 const fn timestamp(&self) -> u64 {
61 match self {
62 Self::Change { millis, .. } => *millis,
63 Self::Account { issued, .. } => *issued,
64 _ => 0,
65 }
66 }
67
68 fn order(&self) -> (u8, u64) {
71 match self {
72 Self::Change { depth, .. } => (0, *depth),
73 Self::RecordKey { .. } => (1, 0),
74 Self::BlobKey { .. } => (2, 0),
75 Self::Account { .. } => (4, 0),
76 }
77 }
78}
79
80#[must_use]
82pub fn item_id(holding: &Holding) -> [u8; 32] {
83 let described = match holding {
84 Holding::Change { id, complete, .. } => {
85 Value::Array(vec![0_u8.to_cbor(), id.to_cbor(), Value::Bool(*complete)])
86 }
87 Holding::RecordKey { statement, key } => {
88 Value::Array(vec![1_u8.to_cbor(), statement.to_cbor(), key.to_cbor()])
89 }
90 Holding::BlobKey { sealed, key } => {
91 Value::Array(vec![2_u8.to_cbor(), sealed.to_cbor(), key.to_cbor()])
92 }
93 Holding::Account { id, .. } => Value::Array(vec![4_u8.to_cbor(), id.to_cbor()]),
94 };
95 let digest = Hash::of(&cbor::encode(&described));
96 digest
97 .digest()
98 .try_into()
99 .unwrap_or_else(|_| unreachable!("BLAKE3 digests are 32 bytes"))
100}
101
102pub(crate) struct Reconciling {
104 negentropy: Negentropy<'static, NegentropyStorageVector>,
105 held: BTreeMap<[u8; 32], Holding>,
106}
107
108impl Reconciling {
109 pub(crate) fn new(holdings: Vec<Holding>) -> Result<Self, SyncError> {
111 let mut held = BTreeMap::new();
112 for holding in holdings {
113 held.entry(item_id(&holding)).or_insert(holding);
114 }
115 let mut storage = NegentropyStorageVector::with_capacity(held.len());
116 for (id, holding) in &held {
117 storage
118 .insert(holding.timestamp(), Id::from_byte_array(*id))
119 .map_err(negentropy_error)?;
120 }
121 storage.seal().map_err(negentropy_error)?;
122 let negentropy = Negentropy::owned(storage, FRAME_LIMIT).map_err(negentropy_error)?;
123 Ok(Self { negentropy, held })
124 }
125
126 pub(crate) fn initiate(&mut self) -> Result<Vec<u8>, SyncError> {
128 self.negentropy.initiate().map_err(negentropy_error)
129 }
130
131 pub(crate) fn answer(
135 &mut self,
136 message: &[u8],
137 have: &mut Vec<[u8; 32]>,
138 need: &mut Vec<[u8; 32]>,
139 ) -> Result<Option<Vec<u8>>, SyncError> {
140 let (mut haves, mut needs) = (Vec::new(), Vec::new());
141 let answer = self
142 .negentropy
143 .reconcile_with_ids(message, &mut haves, &mut needs)
144 .map_err(negentropy_error)?;
145 have.extend(haves.iter().map(|id| **id));
146 need.extend(needs.iter().map(|id| **id));
147 Ok(answer)
148 }
149
150 pub(crate) fn respond(&mut self, message: &[u8]) -> Result<Vec<u8>, SyncError> {
152 self.negentropy.reconcile(message).map_err(negentropy_error)
153 }
154
155 pub(crate) fn in_order(&self, ids: &[[u8; 32]]) -> Vec<Holding> {
158 let mut holdings: Vec<(&[u8; 32], &Holding)> = ids
159 .iter()
160 .filter_map(|id| self.held.get_key_value(id))
161 .collect();
162 holdings.sort_by(|(a_id, a), (b_id, b)| a.order().cmp(&b.order()).then(a_id.cmp(b_id)));
163 holdings.dedup_by(|(a, _), (b, _)| a == b);
164 holdings
165 .into_iter()
166 .map(|(_, holding)| holding.clone())
167 .collect()
168 }
169}
170
171#[expect(clippy::needless_pass_by_value, reason = "for map_err")]
172fn negentropy_error(error: negentropy::Error) -> SyncError {
173 SyncError::protocol(format!("negentropy: {error}"))
174}