Skip to main content

coven_foundation/
id_source.rs

1//! New ids, including each install's 64-bit device id (§10).
2
3use std::sync::Arc;
4
5use serde::{Deserialize, Serialize};
6use uuid::Uuid;
7
8/// A store's identity, independent of its name and location on disk.
9#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
10#[serde(transparent)]
11pub struct StoreId(
12    /// The store's UUID.
13    pub Uuid,
14);
15
16impl std::fmt::Display for StoreId {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        self.0.fmt(f)
19    }
20}
21
22/// A circle's identity, independent of its name or current key (§15.5).
23#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
24#[serde(transparent)]
25pub struct CircleId(
26    /// The circle's UUID, supplied by the id source.
27    pub Uuid,
28);
29
30impl std::fmt::Display for CircleId {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        self.0.fmt(f)
33    }
34}
35
36/// A store or circle key's identity, named by the entry introducing it (§12.1).
37#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
38#[serde(transparent)]
39pub struct KeyId(
40    /// The key's UUID, supplied by the id source.
41    pub Uuid,
42);
43
44impl std::fmt::Display for KeyId {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        self.0.fmt(f)
47    }
48}
49
50/// A member's identity, independent of their keys, which never changes (§10).
51/// coven takes it from the id source when the first device creates the store
52/// or an admin makes the invite that admits the member.
53/// Device ownership, circle membership and slot authors name it; a key
54/// replacement keeps it.
55#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
56#[serde(transparent)]
57pub struct MemberId(
58    /// The member's UUID, supplied by the id source.
59    pub Uuid,
60);
61
62impl std::fmt::Display for MemberId {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        self.0.fmt(f)
65    }
66}
67
68impl std::str::FromStr for MemberId {
69    type Err = InvalidMemberId;
70    /// Only the canonical lowercase hyphenated spelling (D10); a member
71    /// spelling never encodes a public key.
72    fn from_str(value: &str) -> Result<Self, Self::Err> {
73        canonical_uuid(value).map(Self).map_err(|_not_canonical| InvalidMemberId)
74    }
75}
76
77/// Text that is not a member id's canonical lowercase hyphenated UUID (D10).
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct InvalidMemberId;
80
81impl std::fmt::Display for InvalidMemberId {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.write_str("not a canonical member id")
84    }
85}
86
87impl std::error::Error for InvalidMemberId {}
88
89/// The UUID `text` spells in its one canonical form, lowercase and
90/// hyphenated (D10). Any other spelling of the same UUID names nothing.
91pub fn canonical_uuid(text: &str) -> Result<Uuid, NotCanonicalUuid> {
92    match Uuid::try_parse(text) {
93        Ok(id) if id.hyphenated().to_string() == text => Ok(id),
94        _ => Err(NotCanonicalUuid),
95    }
96}
97
98/// Text that is not a UUID's canonical lowercase hyphenated spelling (D10).
99#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
100#[error("not a canonical lowercase hyphenated UUID")]
101pub struct NotCanonicalUuid;
102
103/// An invitation's identity, independent of its one-time secret (§13.2).
104#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
105#[serde(transparent)]
106pub struct InviteId(
107    /// The invite's UUID, supplied by the id source.
108    pub Uuid,
109);
110
111impl std::fmt::Display for InviteId {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        self.0.fmt(f)
114    }
115}
116
117/// A file record's identity, independent of its content and of where its
118/// bytes are stored (§17.2). coven takes it from the id source when the app
119/// stages the file, or when a write moves a row that names a file to another
120/// audience and gives it a new file there.
121#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
122#[serde(transparent)]
123pub struct FileId(
124    /// The file's UUID, supplied by the id source.
125    pub Uuid,
126);
127
128impl std::fmt::Display for FileId {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        self.0.fmt(f)
131    }
132}
133
134/// A stored object's id, the last part of its path
135/// `<store>/files/<uploader>/<object>` (§17.5). coven takes it from the id
136/// source when a write queues the upload of bytes this device holds.
137#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
138#[serde(transparent)]
139pub struct ObjectId(
140    /// The object's UUID, supplied by the id source.
141    pub Uuid,
142);
143
144impl std::fmt::Display for ObjectId {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        self.0.fmt(f)
147    }
148}
149
150/// One install of the app, by its 64-bit device id (§10).
151#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
152#[serde(transparent)]
153pub struct DeviceId(
154    /// The install's 64-bit id.
155    pub u64,
156);
157
158/// The source of new ids, supplied when creating or opening a store.
159pub trait IdSource: Send + Sync {
160    /// A fresh UUID. Distinct calls must yield distinct ids.
161    fn new_id(&self) -> Uuid;
162
163    /// A fresh device id derived from this source, without another randomness
164    /// source. Every install and restored copy receives a new device id (§10.4).
165    ///
166    /// Uses 62 payload bits from the UUID's last eight bytes and two from its
167    /// eighth byte: all 64 are random in UUIDv4 and UUIDv7. The version,
168    /// variant and UUIDv7 timestamp contribute no bits.
169    fn new_device_id(&self) -> DeviceId {
170        let (high, low) = self.new_id().as_u64_pair();
171        DeviceId((low & 0x3fff_ffff_ffff_ffff) | ((high & 3) << 62))
172    }
173}
174
175/// A shared source of new ids.
176pub type IdSourceRef = Arc<dyn IdSource>;
177
178/// Random UUIDv4 ids, independent of the clock (E1).
179pub struct UuidIds;
180
181impl IdSource for UuidIds {
182    fn new_id(&self) -> Uuid {
183        Uuid::new_v4()
184    }
185}
186
187/// A deterministic sequence of UUIDs and device ids, starting at one.
188///
189/// One source shares its sequence across both methods. It panics on exhaustion
190/// instead of wrapping and reusing an id. Separate sources repeat the sequence.
191#[cfg(feature = "test-utils")]
192pub struct SequentialIds(std::sync::atomic::AtomicU64);
193
194#[cfg(feature = "test-utils")]
195impl SequentialIds {
196    /// A sequence whose first UUID's payload and first device id are one.
197    pub fn new() -> Self {
198        Self(std::sync::atomic::AtomicU64::new(1))
199    }
200}
201
202#[cfg(feature = "test-utils")]
203impl IdSource for SequentialIds {
204    fn new_id(&self) -> Uuid {
205        use std::sync::atomic::Ordering;
206        let n = self
207            .0
208            .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
209            .expect("sequential id source exhausted");
210        // Preserve all 64 sequence bits in the payload positions used above.
211        Uuid::from_u64_pair(0x7000 | (n >> 62), 0x8000_0000_0000_0000 | (n & 0x3fff_ffff_ffff_ffff))
212    }
213}
214
215#[cfg(test)]
216#[path = "id_source_tests.rs"]
217mod tests;