Skip to main content

nibkeep_node/library/
holding.rs

1//! What reads who holds a space
2//! ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
3//!
4//! A device of the user's holds a space where its newest choice of it, in the personal space,
5//! holds it, as every device states as it takes a space. So a revocation and a recovery name
6//! the spaces that they cannot reach, and the devices that do; a backup's update names the
7//! spaces that it did not write; a move takes along only the origins and checkouts of the
8//! devices that hold the new space; and a pin names a file only for a device that holds its
9//! space.
10
11use std::collections::{BTreeMap, BTreeSet};
12
13use nibkeep_base::{EntityId, SpaceId};
14use nibkeep_governance::{Choice, Roster};
15
16use super::Library;
17use super::taking::{SpaceHolder, by_name};
18use crate::NodeError;
19
20/// A space of the user's that this device does not hold, with the devices of theirs that do.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct HeldElsewhere {
23	/// The space.
24	pub space: SpaceId,
25	/// Its name, as the devices that hold it keep it in the personal space.
26	pub name: Option<String>,
27	/// The other devices of the user's that hold it, as their choices say, but those revoked
28	/// and those that the question leaves out: none where no other device holds it.
29	pub holders: Vec<SpaceHolder>,
30}
31
32/// The newest choice of each replica of the user's for each space, by space and key, as
33/// [`Library::newest_choices`] reads them.
34type Newest = BTreeMap<(SpaceId, [u8; 32]), (EntityId, Choice)>;
35
36impl Library {
37	/// The spaces of the user's that a revocation of `replicas`, by their records in the
38	/// personal space, cannot reach from this device: those that one of them holds, as its
39	/// choices say, and this device does not. Each comes with the other devices of the user's
40	/// that hold it, but `replicas`, which revoke them there after a sync that brings them the
41	/// revocation; where none does, a replica revoked there stays in the user's place, as no
42	/// device of theirs can revoke it there. By name, then by ID; the same after the
43	/// revocation as before.
44	///
45	/// # Errors
46	///
47	/// Returns an error if the personal space cannot be read.
48	pub fn out_of_reach(&self, replicas: &[EntityId]) -> Result<Vec<HeldElsewhere>, NodeError> {
49		let (_, newest) = self.newest()?;
50		let mut spaces = BTreeSet::new();
51		for (record, choice) in newest.values() {
52			if choice.holds
53				&& replicas.contains(record)
54				&& choice.space != self.info.personal
55				&& !self.holds_here(choice.space)?
56			{
57				spaces.insert(choice.space);
58			}
59		}
60		self.held_elsewhere_with(&spaces, replicas, &newest)
61	}
62
63	/// Of `spaces`, those that this device does not have, each with the devices of the user's
64	/// that hold it, as [`HeldElsewhere`] says. By name, then by ID.
65	///
66	/// # Errors
67	///
68	/// Returns an error if the personal space cannot be read.
69	pub(crate) fn spaces_held_elsewhere(
70		&self,
71		spaces: &[SpaceId],
72	) -> Result<Vec<HeldElsewhere>, NodeError> {
73		let elsewhere: BTreeSet<SpaceId> = spaces
74			.iter()
75			.copied()
76			.filter(|space| *space != self.info.personal && !self.spaces.contains_key(space))
77			.collect();
78		if elsewhere.is_empty() {
79			return Ok(Vec::new());
80		}
81		let (_, newest) = self.newest()?;
82		self.held_elsewhere_with(&elsewhere, &[], &newest)
83	}
84
85	/// The replicas of the user's, and the newest choices that they state in the personal
86	/// space, as [`Library::newest_choices`] reads them.
87	fn newest(&self) -> Result<(Roster, Newest), NodeError> {
88		let read = self.read_personal()?;
89		let roster = self.roster(self.info.personal)?;
90		let newest = Self::newest_choices(&read, &roster);
91		Ok((roster, newest))
92	}
93
94	/// Each of `spaces` with its name and the devices that hold it by `newest`, but those of
95	/// `left_out`. By name, then by ID.
96	fn held_elsewhere_with(
97		&self,
98		spaces: &BTreeSet<SpaceId>,
99		left_out: &[EntityId],
100		newest: &Newest,
101	) -> Result<Vec<HeldElsewhere>, NodeError> {
102		let names = self.kept_space_names()?;
103		let mut found = Vec::new();
104		for &space in spaces {
105			let mut holders = self.space_holders((space, false), newest)?;
106			holders.retain(|holder| !left_out.contains(&holder.replica));
107			let name = if self.spaces.contains_key(&space) {
108				self.space_name(space)?
109			} else {
110				names.get(&space).cloned().flatten()
111			};
112			found.push(HeldElsewhere {
113				space,
114				name,
115				holders,
116			});
117		}
118		found.sort_by_key(|each| by_name(each.name.as_deref(), each.space));
119		Ok(found)
120	}
121
122	/// Whether this replica holds `space`: it has it, and its choices do not drop it.
123	pub(crate) fn holds_here(&self, space: SpaceId) -> Result<bool, NodeError> {
124		let Some(open) = self.spaces.get(&space) else {
125			return Ok(false);
126		};
127		let own = self.replica.signing.verifying_key();
128		Ok(open.stored.log().holds_space(&own, &open.keys)?)
129	}
130
131	/// The devices of the user's that hold `space`, by their records in the personal space,
132	/// as they show there: this one where it holds it, and each on which a replica that is not
133	/// revoked holds it, as its choices say.
134	///
135	/// # Errors
136	///
137	/// Returns an error if the personal space cannot be read.
138	pub(crate) fn holding_devices(&self, space: SpaceId) -> Result<BTreeSet<EntityId>, NodeError> {
139		let personal = self.info.personal;
140		let (roster, newest) = self.newest()?;
141		let held = space == personal || self.holds_here(space)?;
142		let records: BTreeSet<EntityId> = self
143			.space_holders((space, held), &newest)?
144			.into_iter()
145			.map(|holder| holder.replica)
146			.collect();
147		let open = self.space(personal)?;
148		let log = open.stored.log();
149		let state = log.state();
150		let mut devices = BTreeSet::new();
151		for record in roster.replicas() {
152			if !(space == personal || records.contains(&record)) {
153				continue;
154			}
155			// One whose keys are all revoked holds nothing, as a record without keys.
156			let mut revoked = true;
157			for key in roster.keys_of(record) {
158				revoked &= log.is_revoked(key, &open.keys)?;
159			}
160			if revoked {
161				continue;
162			}
163			if let Some(device) =
164				nibkeep_governance::replica(state, record)?.and_then(|on| on.device)
165			{
166				devices.insert(state.canonical(device)?);
167			}
168		}
169		Ok(devices)
170	}
171}