capsule_core/metadata/crdt/or_set.rs
1//! Observed-remove set (OR-set) with explicit `add_id` binding (SSoT: [Metadata —
2//! Add-id Binding] and [Collaborative Metadata]).
3//!
4//! Tags are modelled as an OR-set so a tag added on one device and removed on another
5//! converge predictably. Every add carries an `add_id = (device_id, monotonic_counter)`;
6//! every remove targets a specific `add_id`. A remove naming an `add_id` the receiver has
7//! never observed an add for is **rejected**, not silently no-op — defeating the "remove an
8//! element you never added" attack. Merge is the union of adds and removes, so it is
9//! commutative, associative, and idempotent.
10//!
11//! [Metadata — Add-id Binding]: https://docs/design/metadata/#add-id-binding
12//! [Collaborative Metadata]: https://docs/design/metadata/#collaborative-metadata
13
14use std::collections::{BTreeMap, BTreeSet};
15
16use serde::{Deserialize, Serialize};
17use uuid::Uuid;
18
19/// A per-device, per-(asset, OR-set) monotonic add identifier.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
21pub struct AddId {
22 /// The issuing device (UUIDv4).
23 pub device: Uuid,
24 /// Monotonic counter, unique per `(device, asset, OR-set)`.
25 pub counter: u64,
26}
27
28/// A remove targeted an `add_id` that was never observed locally as an add.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct UnobservedRemove;
31
32/// An observed-remove set of `T`.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct OrSet<T: Ord + Clone> {
35 /// Observed adds: `add_id -> element`.
36 adds: BTreeMap<AddId, T>,
37 /// Tombstoned `add_id`s.
38 removes: BTreeSet<AddId>,
39}
40
41// Manual `Default` so it does not require `T: Default` (the maps are empty regardless).
42impl<T: Ord + Clone> Default for OrSet<T> {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48impl<T: Ord + Clone> OrSet<T> {
49 /// An empty set.
50 pub fn new() -> Self {
51 Self {
52 adds: BTreeMap::new(),
53 removes: BTreeSet::new(),
54 }
55 }
56
57 /// Record an add of `element` under `add_id`.
58 pub fn add(&mut self, element: T, add_id: AddId) {
59 self.adds.insert(add_id, element);
60 }
61
62 /// Tombstone `add_id`. Returns [`UnobservedRemove`] if no add for it was ever observed
63 /// locally (a fabricated remove), rather than silently no-oping.
64 pub fn remove(&mut self, add_id: AddId) -> Result<(), UnobservedRemove> {
65 if !self.adds.contains_key(&add_id) {
66 return Err(UnobservedRemove);
67 }
68 self.removes.insert(add_id);
69 Ok(())
70 }
71
72 /// Merge another replica's state: the union of adds and of removes. Commutative,
73 /// associative, idempotent — order of arrival does not matter.
74 pub fn merge(&mut self, other: &Self) {
75 for (id, el) in &other.adds {
76 self.adds.insert(*id, el.clone());
77 }
78 self.removes.extend(other.removes.iter().copied());
79 }
80
81 /// The current logical value: every element whose `add_id` is not tombstoned.
82 pub fn value(&self) -> BTreeSet<T> {
83 self.adds
84 .iter()
85 .filter(|(id, _)| !self.removes.contains(id))
86 .map(|(_, el)| el.clone())
87 .collect()
88 }
89
90 /// Whether `add_id` has been observed as an add.
91 pub fn observed(&self, add_id: &AddId) -> bool {
92 self.adds.contains_key(add_id)
93 }
94
95 /// The highest `add_id.counter` this set has ever observed from `device`, or `None` if it
96 /// has observed none.
97 ///
98 /// Deliberately spans **tombstoned adds as well as live ones**: a removed add still *burned*
99 /// its counter, so the high-water mark a restarting device reseeds from
100 /// ([`Counter::reseed_from_max`](super::counter::Counter::reseed_from_max)) must count it.
101 /// Using [`entries`](Self::entries) here instead would let a device re-issue the `add_id` of
102 /// a tag it had removed, aliasing two distinct adds — exactly the failure the add-id binding
103 /// rule exists to prevent (SSoT: [Metadata — Add-id Binding]).
104 ///
105 /// [Metadata — Add-id Binding]: https://docs/design/metadata/#add-id-binding
106 pub fn max_add_counter_for(&self, device: &Uuid) -> Option<u64> {
107 self.adds
108 .keys()
109 .chain(self.removes.iter())
110 .filter(|id| &id.device == device)
111 .map(|id| id.counter)
112 .max()
113 }
114
115 /// The live `(add_id, element)` pairs — those not tombstoned. Unlike [`value`](Self::value)
116 /// this preserves each element's `add_id`, so a caller can surface elements (e.g. AI tags) and
117 /// later target a specific one by `add_id` (dismiss, promote).
118 pub fn entries(&self) -> Vec<(AddId, T)> {
119 self.adds
120 .iter()
121 .filter(|(id, _)| !self.removes.contains(id))
122 .map(|(id, el)| (*id, el.clone()))
123 .collect()
124 }
125}
126
127#[cfg(test)]
128mod tests;