Skip to main content

nibkeep_node/library/
merge.rs

1//! Merging entities that turn out to be the same, and undoing a merge (`docs/spec/model.md`,
2//! section 7).
3
4use nibkeep_base::{EntityId, SpaceId, StatementId};
5use nibkeep_crypto::rand_core::CryptoRng;
6use nibkeep_model::storage::Statements;
7use nibkeep_model::{FieldName, Operation, State, Statement, TypeName, Value, fields};
8
9use super::Library;
10use super::entities::{Listed, SHORTEST_PREFIX, defines_types};
11use super::export::OWN_RECORDS;
12use crate::NodeError;
13
14impl Library {
15	/// Merges an entity of a space into another that it turns out to be the same as: from
16	/// then on, the entity it is merged into shows what both say, and references to either
17	/// lead to it. The entities merged into `from` go with it. A merge of `from` into another
18	/// entity is replaced. A merge is undone by [`Library::undo_merge`].
19	///
20	/// # Errors
21	///
22	/// Returns an error if the library has no such space, the space no such entities; if
23	/// they are one entity already, merged or not; if either is deleted, defines a type or
24	/// a field, or is one of NibKeep's own records of a user, device, replica or space; or if
25	/// the change cannot be saved.
26	pub fn merge_entities(
27		&mut self,
28		space: SpaceId,
29		from: EntityId,
30		into: EntityId,
31		wall_millis: u64,
32		rng: &mut impl CryptoRng,
33	) -> Result<(), NodeError> {
34		let operations = {
35			let state = self.space(space)?.stored.log().state();
36			for entity in [from, into] {
37				if !exists(state, entity)? {
38					return Err(NodeError::NoEntity(entity.to_string()));
39				}
40				if defines_types(state, entity)? {
41					return Err(NodeError::DefinesTypes(entity.to_string()));
42				}
43				let types = state.types(entity)?;
44				if OWN_RECORDS.iter().any(|own| types.contains(own)) {
45					return Err(NodeError::OwnRecord(entity.to_string()));
46				}
47				if state.is_deleted(entity)? {
48					return Err(NodeError::Deleted(entity.to_string()));
49				}
50			}
51			if state.canonical(from)? == state.canonical(into)? {
52				return Err(NodeError::SameEntity(from.to_string()));
53			}
54			let replaced = own_merges(state, from)?;
55			let statement = Statement::new(
56				StatementId::random(rng),
57				from,
58				fields::MERGED_INTO,
59				Value::Reference(into),
60			);
61			vec![Operation::replace(statement, replaced)]
62		};
63		self.commit(space, operations, wall_millis, rng)
64	}
65
66	/// Undoes the merge of an entity of a space into another: it shows what it says again,
67	/// apart from the entity it was merged into, with the entities merged into it.
68	///
69	/// # Errors
70	///
71	/// Returns an error if the library has no such space, if the entity was not merged into
72	/// another, or if the change cannot be saved.
73	pub fn undo_merge(
74		&mut self,
75		space: SpaceId,
76		entity: EntityId,
77		wall_millis: u64,
78		rng: &mut impl CryptoRng,
79	) -> Result<(), NodeError> {
80		let merges = own_merges(self.space(space)?.stored.log().state(), entity)?;
81		if merges.is_empty() {
82			return Err(NodeError::NotMerged(entity.to_string()));
83		}
84		self.commit(
85			space,
86			vec![Operation::retract(entity, merges)],
87			wall_millis,
88			rng,
89		)
90	}
91
92	/// The other entities merged with an entity of a space, by their own names, ordered by
93	/// name without regard to case, unnamed ones last: those that a merge undone would set
94	/// apart.
95	///
96	/// # Errors
97	///
98	/// Returns an error if the library has no such space, or the space cannot be read.
99	pub fn merged(&self, space: SpaceId, entity: EntityId) -> Result<Vec<Listed>, NodeError> {
100		merged(self.space(space)?.stored.log().state(), entity)
101	}
102
103	/// The other entities merged with an entity of a space, as the library had recorded them
104	/// at the end of the millisecond `millis`, as [`Library::merged`] gives them.
105	///
106	/// # Errors
107	///
108	/// Returns an error if the library has no such space, or the space cannot be read.
109	pub fn merged_as_of(
110		&self,
111		space: SpaceId,
112		entity: EntityId,
113		millis: u64,
114	) -> Result<Vec<Listed>, NodeError> {
115		let open = self.space(space)?;
116		open.stored
117			.reading(|stored| merged(&stored.log().state_as_of(millis), entity))
118	}
119
120	/// The types that an entity's own statements give it, apart from those of the entities
121	/// merged with it: what it is, set apart from a merge.
122	///
123	/// # Errors
124	///
125	/// Returns an error if the library has no such space, or the space cannot be read.
126	pub fn own_types(&self, space: SpaceId, entity: EntityId) -> Result<Vec<TypeName>, NodeError> {
127		let state = self.space(space)?.stored.log().state();
128		let mut types: Vec<TypeName> = state
129			.storage()
130			.current_of_field(entity, &fields::TYPE)?
131			.iter()
132			.filter_map(|recorded| recorded.statement.value.as_text()?.parse().ok())
133			.collect();
134		types.sort();
135		types.dedup();
136		Ok(types)
137	}
138
139	/// One of the other entities merged with an entity of a space, found by its ID, a
140	/// prefix of its ID of at least six characters, or one of its own names, in any form,
141	/// without regard to case: what a merge undone would set apart, or merged again move.
142	///
143	/// # Errors
144	///
145	/// Returns an error if the library has no such space, the space cannot be read, or no
146	/// entity merged with it, or several, match.
147	pub fn find_merged(
148		&self,
149		space: SpaceId,
150		entity: EntityId,
151		reference: &str,
152	) -> Result<EntityId, NodeError> {
153		let state = self.space(space)?.stored.log().state();
154		let canonical = state.canonical(entity)?;
155		let lowered = reference.to_lowercase();
156		let looks_like_id = lowered.len() >= SHORTEST_PREFIX
157			&& lowered
158				.chars()
159				.all(|character| character.is_ascii_hexdigit() || character == '-');
160		let mut matching = Vec::new();
161		for member in state.merged(canonical)? {
162			if member == canonical {
163				continue;
164			}
165			let by_id = looks_like_id && member.to_string().starts_with(&lowered);
166			if by_id || own_names(state, member)?.contains(&lowered) {
167				matching.push(member);
168			}
169		}
170		match matching.as_slice() {
171			[] => Err(NodeError::NotMerged(reference.to_owned())),
172			&[member] => Ok(member),
173			_ => Err(NodeError::Ambiguous {
174				reference: reference.to_owned(),
175				candidates: matching,
176			}),
177		}
178	}
179}
180
181/// The other entities merged with an entity of a state, as [`Library::merged`] gives them.
182fn merged<S: Statements>(state: &State<S>, entity: EntityId) -> Result<Vec<Listed>, NodeError>
183where
184	NodeError: From<S::Error>,
185{
186	let canonical = state.canonical(entity)?;
187	let mut merged = Vec::new();
188	for member in state.merged(canonical)? {
189		if member == canonical {
190			continue;
191		}
192		merged.push(Listed {
193			id: member,
194			name: own_name(state, member)?,
195			types: Vec::new(),
196			via: None,
197		});
198	}
199	merged.sort_by_cached_key(|listed| {
200		let name = listed.name.as_deref().map(str::to_lowercase);
201		(name.is_none(), name, listed.id)
202	});
203	Ok(merged)
204}
205
206/// Whether the space says anything of an entity, or of one merged with it.
207fn exists<S: Statements>(state: &State<S>, entity: EntityId) -> Result<bool, NodeError>
208where
209	NodeError: From<S::Error>,
210{
211	Ok(!state.fields(state.canonical(entity)?)?.is_empty())
212}
213
214/// The current statements that merge an entity itself into another.
215fn own_merges<S: Statements>(
216	state: &State<S>,
217	entity: EntityId,
218) -> Result<Vec<StatementId>, NodeError>
219where
220	NodeError: From<S::Error>,
221{
222	Ok(state
223		.storage()
224		.current_of_field(entity, &fields::MERGED_INTO)?
225		.iter()
226		.map(|recorded| recorded.statement.id)
227		.collect())
228}
229
230/// The name that an entity's own statements give it, apart from those merged with it: the
231/// first of [`own_names_in`].
232fn own_name<S: Statements>(state: &State<S>, entity: EntityId) -> Result<Option<String>, NodeError>
233where
234	NodeError: From<S::Error>,
235{
236	Ok(own_names_in(state, entity)?.into_iter().next())
237}
238
239/// The names that an entity's own statements give it, in every form, lowercased.
240fn own_names<S: Statements>(state: &State<S>, entity: EntityId) -> Result<Vec<String>, NodeError>
241where
242	NodeError: From<S::Error>,
243{
244	Ok(own_names_in(state, entity)?
245		.iter()
246		.map(|name| name.to_lowercase())
247		.collect())
248}
249
250/// The names that an entity's own statements give it, apart from those merged with it, in
251/// every form: those of the first field that names it, `org.nibkeep.name`, or else the first
252/// by name that ends in `.name`, or else in `.title`, each written in full, or text.
253pub(crate) fn own_names_in<S: Statements>(
254	state: &State<S>,
255	entity: EntityId,
256) -> Result<Vec<String>, NodeError>
257where
258	NodeError: From<S::Error>,
259{
260	let storage = state.storage();
261	let held: Vec<FieldName> = storage
262		.of_entity(entity)?
263		.into_iter()
264		.map(|(field, _)| field)
265		.collect();
266	let mut naming: Vec<&FieldName> = held
267		.iter()
268		.filter(|field| **field == fields::NAME)
269		.collect();
270	for suffix in fields::NAMING_SUFFIXES {
271		naming.extend(
272			held.iter()
273				.filter(|field| fields::has_suffix(field, suffix)),
274		);
275	}
276	for field in naming {
277		let names: Vec<String> = storage
278			.current_of_field(entity, field)?
279			.iter()
280			.filter_map(|recorded| recorded.statement.value.as_name_text().map(str::to_owned))
281			.collect();
282		if !names.is_empty() {
283			return Ok(names);
284		}
285	}
286	Ok(Vec::new())
287}