capsule_core/metadata/crdt/counter.rs
1//! The per-device monotonic `add_id` counter (SSoT: [Metadata — Add-id Binding §
2//! Counter durability across restarts]).
3//!
4//! A `monotonic_counter` must never repeat for a given `(device, asset, OR-set)`: a reused
5//! `add_id` would alias two distinct adds. On restart/reinstall the counter is reseeded to
6//! **one past the maximum counter this device has ever issued** (recovered from the signed
7//! sidecars it wrote). It resets to zero only when the device can prove it has issued
8//! nothing. This makes the counter monotonic over a `device_id`'s lifetime, not just a
9//! process.
10//!
11//! [Metadata — Add-id Binding § Counter durability across restarts]: https://docs/design/metadata/#add-id-binding
12
13use uuid::Uuid;
14
15use super::or_set::AddId;
16
17/// A monotonic counter issuing `add_id`s for one device.
18#[derive(Debug, Clone)]
19pub struct Counter {
20 device: Uuid,
21 next: u64,
22}
23
24impl Counter {
25 /// A counter for `device` that has issued nothing yet (next = 0).
26 pub fn new(device: Uuid) -> Self {
27 Self { device, next: 0 }
28 }
29
30 /// Reseed from the maximum `add_id.counter` this device has ever issued (recovered from
31 /// its own signed sidecars). `None` means it has issued nothing → reset to zero.
32 pub fn reseed_from_max(&mut self, max_issued: Option<u64>) {
33 self.next = match max_issued {
34 Some(m) => m + 1,
35 None => 0,
36 };
37 }
38
39 /// Issue the next `add_id` and advance the counter.
40 pub fn issue(&mut self) -> AddId {
41 let id = AddId {
42 device: self.device,
43 counter: self.next,
44 };
45 self.next += 1;
46 id
47 }
48
49 /// The next counter value that would be issued.
50 pub fn peek(&self) -> u64 {
51 self.next
52 }
53}
54
55#[cfg(test)]
56mod tests;