coven_database/store_state.rs
1//! Membership and audience state after one committed sequence prefix.
2use crate::DbError;
3use coven_crypto::MemberPublicKeys;
4use coven_format::admin::{MemberRole, SnapshotId};
5use coven_foundation::id_source::{CircleId, DeviceId, MemberId, StoreId};
6use coven_merge::{Audience, Slot};
7use std::collections::{BTreeMap, BTreeSet};
8
9/// Store state, including removed identities needed to check older writes (§10.4).
10///
11/// Schema versions belong to each audience: the store's raise is under
12/// [`Audience::Store`], and each circle has its own. A raise is absent until a
13/// kept raise selects it, as in §18.3; before one, the audience is at its base
14/// ([`StoreState::reached`]). These are independent of the local app
15/// migration version returned by [`crate::StoreDatabase::schema_version`].
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct StoreState {
18 /// Absent before the first entry creates the store.
19 pub store: Option<StoreIdentity>,
20 /// Every member added by a kept entry, including removed members.
21 pub members: BTreeMap<MemberId, StoreMember>,
22 /// Every public pair a kept creation, addition or member-key replacement
23 /// bound, including pairs of removed members and pairs a later replacement
24 /// retired. An addition of an id not active in its view, and every
25 /// replacement, must share no key with these (§10).
26 pub bound_keys: BTreeSet<MemberPublicKeys>,
27 /// Every device added by a kept entry, including removed devices.
28 pub devices: BTreeMap<DeviceId, StoreDevice>,
29 /// Every circle made by a kept entry, including deleted circles.
30 pub circles: BTreeMap<CircleId, StoreCircle>,
31 /// Deleted circles and their deciding slots; absence means no deletion.
32 pub circle_deletions: BTreeMap<CircleId, Slot>,
33 /// The selected schema raise per audience; creation itself carries no raise.
34 /// [`Self::reached`] gives an audience's version, a circle's base included.
35 pub schema: BTreeMap<Audience, StoreVersion>,
36 /// The last kept reset of each audience (§19.4).
37 pub resets: BTreeMap<Audience, SnapshotId>,
38}
39
40impl StoreState {
41 /// The member, unless a kept removal removed it.
42 pub fn active_member(&self, id: &MemberId) -> Option<&StoreMember> {
43 self.members.get(id).filter(|member| !member.removed)
44 }
45
46 /// Whether `device` is installed and active, and belongs to `member`.
47 pub fn device_acts_for(&self, device: &DeviceId, member: &MemberId) -> bool {
48 self.devices.get(device).is_some_and(|device| device.active() && device.member == *member)
49 }
50
51 /// Whether `id` is a member who has not been removed and holds the admin role.
52 pub fn active_admin(&self, id: &MemberId) -> bool {
53 self.active_member(id).is_some_and(|member| member.role == MemberRole::Admin)
54 }
55
56 /// Whether `member` remains in the store and in `circle`, which exists and
57 /// is not deleted (§15.5).
58 pub fn reads_circle(&self, circle: CircleId, member: &MemberId) -> bool {
59 self.active_member(member).is_some()
60 && !self.circle_deletions.contains_key(&circle)
61 && self.circles.get(&circle).is_some_and(|c| c.members.contains(member))
62 }
63
64 /// Every circle `member` reads under [`Self::reads_circle`]: the circles
65 /// whose parts its devices open, snapshot and reload (§15.6, §16).
66 pub fn readable_circles(&self, member: &MemberId) -> BTreeSet<CircleId> {
67 self.circles.keys().copied().filter(|circle| self.reads_circle(*circle, member)).collect()
68 }
69
70 /// The schema version `audience` has reached: the one its latest kept
71 /// raise selected, or before any raise its base, zero for the store and
72 /// for a circle the breaking version its creation recorded. A raise goes
73 /// past the base, so this is the greater of the two (§16.3, §18.3).
74 pub fn reached(&self, audience: &Audience) -> u32 {
75 self.schema.get(audience).map(|raised| raised.number).unwrap_or_else(|| match audience {
76 Audience::Store => 0,
77 Audience::Circle(circle) => self.circles.get(circle).map_or(0, |circle| circle.base),
78 })
79 }
80
81 /// Whether a part at `version` in `audience` waits for a raise: the
82 /// audience is below that version and can still be raised. Nobody can
83 /// raise a deleted circle, and its parts are taken out wherever they land
84 /// (§15.9, §18.5).
85 pub fn awaits_raise(&self, audience: &Audience, version: u32) -> bool {
86 !self.deleted(audience) && self.reached(audience) < version
87 }
88
89 /// Whether `audience`, which a slot makes this state ask a device whose
90 /// newest breaking migration is `breaking` to reload, is one the device
91 /// must rebuild rather than load: below that version and not deleted. A
92 /// circle becomes readable below it, and the store itself can be raised
93 /// or reset below it by a device on an older app (§18.3).
94 pub fn rebuilt_by(&self, audience: &Audience, breaking: u32) -> bool {
95 breaking > 0 && self.awaits_raise(audience, breaking)
96 }
97
98 /// Whether `circle` is one this state doesn't hold, or deleted: a change
99 /// aimed at it meets a gone target (§10.4, §15.9).
100 pub fn gone_circle(&self, circle: &CircleId) -> bool {
101 !self.circles.contains_key(circle) || self.circle_deletions.contains_key(circle)
102 }
103
104 /// Whether `audience` is a deleted circle (§15.9).
105 pub fn deleted(&self, audience: &Audience) -> bool {
106 match audience {
107 Audience::Store => false,
108 Audience::Circle(circle) => self.circle_deletions.contains_key(circle),
109 }
110 }
111
112 /// Every audience `member` reads: the store's, then each of
113 /// [`Self::readable_circles`] in id order.
114 pub fn readable_audiences(&self, member: &MemberId) -> Vec<Audience> {
115 std::iter::once(Audience::Store)
116 .chain(self.readable_circles(member).into_iter().map(Audience::Circle))
117 .collect()
118 }
119}
120
121/// A store's identity and current name (§10).
122#[derive(Clone, Debug, PartialEq, Eq)]
123pub struct StoreIdentity {
124 /// The store's id.
125 pub id: StoreId,
126 /// Its name.
127 pub name: String,
128 /// The slot that set `name`: creation's slot 1, or the latest applied
129 /// rename that changed it. A saved restore code's name is replaced only
130 /// by one from a later slot (§13.1).
131 pub named_at: Slot,
132}
133
134impl StoreIdentity {
135 /// Opening requires directory settings to match checked creation (§10).
136 pub fn check_settings(
137 &self,
138 settings: &coven_foundation::files::StoreSettings,
139 ) -> Result<(), DbError> {
140 check_creation(self.id, settings.id)
141 }
142}
143
144/// The sequence's store id must match the directory settings (§10).
145pub(crate) fn check_creation(store: StoreId, settings_store: StoreId) -> Result<(), DbError> {
146 if store != settings_store {
147 return Err(DbError::StoreSettingsMismatch { store });
148 }
149 Ok(())
150}
151
152/// A member in the applied prefix, keyed by stable id in [`StoreState::members`].
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub struct StoreMember {
155 /// The current public pair: the signing key that verifies this member's
156 /// objects in this view and the sealing key copies go to (§10, §12.1).
157 pub keys: MemberPublicKeys,
158 /// Current access after the applied slot, `None` for the store's creator
159 /// until Set up storage records it (§10.3). Revocation also reads
160 /// superseded access from the retained administrative objects (§14.2).
161 pub access: Option<coven_format::MemberAccess>,
162 /// The member's role, retained when removed.
163 pub role: MemberRole,
164 /// Whether a kept removal removed this member.
165 pub removed: bool,
166 /// The facts of the member's latest admission, which their devices'
167 /// joining write reads as each registers (§13.2). Slot 1 records the
168 /// store's creator's as an admission records a joiner's (§10.3).
169 pub joined: Joined,
170}
171
172/// What a member's latest admission recorded of them (§13.2): the person's
173/// name, which a new person's request carried, and the circle it made. For
174/// the store's creator, slot 1 records her name and her private circle.
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Joined {
177 /// The name the member's request carried; none for a recovery, whose
178 /// member already has a profile.
179 pub person: Option<String>,
180 /// The circle the admission made for the member.
181 pub circle: CircleId,
182}
183
184/// One install, retained after removal or replacement so its older objects
185/// remain attributable (§10.4).
186#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct StoreDevice {
188 /// The member who added the device.
189 pub member: MemberId,
190 /// The device's name from its addition.
191 pub name: String,
192 /// Whether kept entries removed or replaced it.
193 pub state: DeviceState,
194}
195
196impl StoreDevice {
197 /// Neither removed nor replaced: it may still author objects (§14.1).
198 pub fn active(&self) -> bool {
199 self.state == DeviceState::Active
200 }
201
202 /// Removed, by its own removal or its member's: it stops for good.
203 pub fn removed(&self) -> bool {
204 self.state == DeviceState::Removed
205 }
206}
207
208/// What counted administrative slots did to a device id (E9). Later slots
209/// from a removed or replaced device are refused (§14.1, D6).
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub enum DeviceState {
212 /// Registered and neither removed nor replaced.
213 Active,
214 /// A kept removal of the device or of its member.
215 Removed,
216 /// A kept add-device entry names this id as the one it replaces.
217 Replaced,
218}
219
220// `_coven_devices.state` and `coven_devices.state` hold a state by its name
221// (api.md E4).
222coven_foundation::column_names!(DeviceState, "device state", {
223 Active => "active",
224 Removed => "removed",
225 Replaced => "replaced",
226});
227
228/// A circle and its current membership; deleted circles retain their name.
229/// Its keys come from received introductions, not this membership projection (§12.1).
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub struct StoreCircle {
232 /// The last kept name.
233 pub name: String,
234 /// Current members; empty after deletion.
235 pub members: BTreeSet<MemberId>,
236 /// The breaking version its creation entry recorded: its schema version
237 /// until a raise of its own goes past it (§15.5, §16.3).
238 pub base: u32,
239}
240
241/// A selected version raise and the snapshot it chose (§18.3).
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct StoreVersion {
244 /// The raised schema version.
245 pub number: u32,
246 /// The snapshot in this version.
247 pub snapshot: SnapshotId,
248 /// The kept raise that selected it.
249 pub entry: Slot,
250}
251
252#[cfg(test)]
253#[path = "store_state_tests.rs"]
254mod tests;