Skip to main content

nibkeep_sync/
reconcile.rs

1//! What a space holds, as items of negentropy's set, each with a timestamp and an ID of 32
2//! bytes ([Sync](../../../docs/spec/sync.md#3-syncing)).
3
4use 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
13/// How long a message of negentropy may be: messages that would be longer are split, at the
14/// cost of more round trips.
15const FRAME_LIMIT: u64 = 4 * 1024 * 1024;
16
17/// A thing that a space holds, as a replica tells it to reconciliation. Sealed blobs are not
18/// among them: each side asks for those it keeps ([`crate::Holder::wanted_blobs`]).
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum Holding {
21	/// An accepted change.
22	Change {
23		/// The change.
24		id: ChangeId,
25		/// The milliseconds of its timestamp.
26		millis: u64,
27		/// Its depth: deeper than its parents, so changes sent in the order of their depths
28		/// come after their parents.
29		depth: u64,
30		/// Whether the replica holds its sealed payload and a wrapped key.
31		complete: bool,
32	},
33	/// A wrapped record key of a secret statement.
34	RecordKey {
35		/// The statement.
36		statement: StatementId,
37		/// The wrapped key.
38		key: WrappedKey,
39	},
40	/// A wrapped blob key.
41	BlobKey {
42		/// The sealed hash of its blob.
43		sealed: Hash,
44		/// The wrapped key.
45		key: WrappedBlobKey,
46	},
47	/// A page of a replica's account of what it holds in the space, the latest that the
48	/// replica keeps of that page.
49	Account {
50		/// The hash of its encoding.
51		id: Hash,
52		/// When it was issued, in milliseconds since 1970.
53		issued: u64,
54	},
55}
56
57impl Holding {
58	/// The item's timestamp: a change's milliseconds, a page's time of issue, and 0 for the
59	/// rest.
60	const fn timestamp(&self) -> u64 {
61		match self {
62			Self::Change { millis, .. } => *millis,
63			Self::Account { issued, .. } => *issued,
64			_ => 0,
65		}
66	}
67
68	/// In which order items are sent: changes by depth, then wrapped record keys, wrapped
69	/// blob keys, and pages of accounts.
70	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/// The ID of an item: the BLAKE3 hash of the canonical encoding of what it is.
81#[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
102/// What a space holds, by item ID, and negentropy over it.
103pub(crate) struct Reconciling {
104	negentropy: Negentropy<'static, NegentropyStorageVector>,
105	held: BTreeMap<[u8; 32], Holding>,
106}
107
108impl Reconciling {
109	/// Puts everything a space holds into negentropy's set.
110	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	/// The initiator's first message.
127	pub(crate) fn initiate(&mut self) -> Result<Vec<u8>, SyncError> {
128		self.negentropy.initiate().map_err(negentropy_error)
129	}
130
131	/// The initiator's answer to a message, adding the IDs that only this side holds to
132	/// `have` and those only the other side holds to `need`; `None` once nothing differs
133	/// any more.
134	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	/// The responder's answer to a message.
151	pub(crate) fn respond(&mut self, message: &[u8]) -> Result<Vec<u8>, SyncError> {
152		self.negentropy.reconcile(message).map_err(negentropy_error)
153	}
154
155	/// What this side holds of these IDs, in the order they are to be sent; IDs it does not
156	/// hold are left out.
157	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}