Skip to main content

nibkeep_node/library/
links.rs

1//! Links read from their other end, and relationships recorded twice. A link is a reference
2//! statement on one entity, stored in one direction; the state file finds the statements
3//! that refer to an entity, so links are read in both (`docs/spec/model.md`, section 10).
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use nibkeep_base::{EntityId, SpaceId};
8use nibkeep_model::schema::{FIELD_DEFINITION, TYPE_DEFINITION};
9use nibkeep_model::storage::Statements;
10use nibkeep_model::{FieldDef, FieldName, Languages, Resolution, State, TypeName, Types, Value};
11use nibkeep_time::Day;
12
13use super::Library;
14use super::entities::{Listed, More, Searched, defines_types, display_name, resolve};
15use crate::NodeError;
16
17/// The entities that link to an entity through one field.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Links {
20	/// The field that links them.
21	pub field: FieldName,
22	/// The name that the field goes by from its other end, if its types give one, such as
23	/// `std.author-of` for `std.author`.
24	pub reverse: Option<FieldName>,
25	/// Whether the field is a role, so that the entities that link are relationships.
26	pub role: bool,
27	/// How many entities link through the field.
28	pub count: usize,
29	/// The first of them by name, without regard to case, unnamed ones last, as many as
30	/// were asked for.
31	pub entities: Vec<Linking>,
32}
33
34/// An entity that links to another.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct Linking {
37	/// The entity, or of entities merged together, the one they were merged into.
38	pub id: EntityId,
39	/// The name to show for it, if it has one.
40	pub name: Option<String>,
41	/// Its types.
42	pub types: Vec<TypeName>,
43	/// Of a relationship, which links through a role: the participants of its other roles
44	/// on the day, by role, ordered by the role's name.
45	pub participants: Vec<(FieldName, Vec<EntityId>)>,
46}
47
48impl Library {
49	/// The entities of a space that link to an entity on `day`, grouped by the field that
50	/// links them and ordered by its name: those whose field shows a reference to it, or to
51	/// an entity merged into it, on that day. Deleted entities, and those that define types,
52	/// are left out. Of each field, `limit` entities are given, and how many there are.
53	///
54	/// # Errors
55	///
56	/// Returns an error if the library has no such space, or the space cannot be read.
57	pub fn links_to(
58		&self,
59		space: SpaceId,
60		entity: EntityId,
61		day: Day,
62		limit: usize,
63	) -> Result<Vec<Links>, NodeError> {
64		let open = self.space(space)?;
65		open.stored.reading(|_| {
66			links_to(
67				open.stored.log().state(),
68				&open.types,
69				&self.languages,
70				(entity, Some(day)),
71				(day, limit),
72			)
73		})
74	}
75
76	/// The entities of a space that link to an entity on any day, as [`Library::links_to`]
77	/// gives those that link on one: those whose field shows a reference to it on some day,
78	/// as a publisher that had someone as its head for some years, and has another now. A
79	/// relationship's participants are those on `day`.
80	///
81	/// # Errors
82	///
83	/// Returns an error if the library has no such space, or the space cannot be read.
84	pub fn links_to_on_any_day(
85		&self,
86		space: SpaceId,
87		entity: EntityId,
88		day: Day,
89		limit: usize,
90	) -> Result<Vec<Links>, NodeError> {
91		let open = self.space(space)?;
92		open.stored.reading(|_| {
93			links_to(
94				open.stored.log().state(),
95				&open.types,
96				&self.languages,
97				(entity, None),
98				(day, limit),
99			)
100		})
101	}
102
103	/// The entities of a space, not deleted, that are relationships of all these types
104	/// with the participants that these values give in roles: those that hold, of each such
105	/// role, every entity given, on whichever days. None if the values give no participant
106	/// in a role. A relationship is an entity, so two devices that record one make two,
107	/// which this finds, as recorded rather than as shown on some day.
108	///
109	/// # Errors
110	///
111	/// Returns an error if the library has no such space, or the space cannot be read.
112	pub fn same_relationship(
113		&self,
114		space: SpaceId,
115		kinds: &[TypeName],
116		values: &[(FieldName, Value)],
117	) -> Result<Vec<EntityId>, NodeError> {
118		let open = self.space(space)?;
119		let state = open.stored.log().state();
120		let types = &open.types;
121		let mut roles: BTreeMap<&FieldName, BTreeSet<EntityId>> = BTreeMap::new();
122		for (field, value) in values {
123			if let Some(participant) = value.as_reference()
124				&& types.field(field).is_some_and(|field| field.is_role())
125			{
126				roles
127					.entry(field)
128					.or_default()
129					.insert(state.canonical(participant)?);
130			}
131		}
132		let Some((first_role, first_participants)) = roles.first_key_value() else {
133			return Ok(Vec::new());
134		};
135		let Some(&first) = first_participants.first() else {
136			return Ok(Vec::new());
137		};
138		let mut same = BTreeSet::new();
139		for statement in state.referrers(first)? {
140			if statement.field != **first_role {
141				continue;
142			}
143			let candidate = state.canonical(statement.entity)?;
144			if same.contains(&candidate) || !may_link(state, candidate, first)? {
145				continue;
146			}
147			let held = state.types(candidate)?;
148			if !kinds.iter().all(|kind| held.contains(kind)) {
149				continue;
150			}
151			let mut holds_all = true;
152			for (field, participants) in &roles {
153				let mut current = BTreeSet::new();
154				for statement in state.current(candidate, field)? {
155					if let Some(reference) = statement.value.as_reference() {
156						current.insert(state.canonical(reference)?);
157					}
158				}
159				if !participants.is_subset(&current) {
160					holds_all = false;
161					break;
162				}
163			}
164			if holds_all {
165				same.insert(candidate);
166			}
167		}
168		Ok(same.into_iter().collect())
169	}
170}
171
172/// Whether an entity counts as linking to another: it is not deleted, defines no types, and
173/// is not the other entity, which an entity merged into the one it referred to would be.
174pub(crate) fn may_link<S: Statements>(
175	state: &State<S>,
176	holder: EntityId,
177	entity: EntityId,
178) -> Result<bool, NodeError>
179where
180	NodeError: From<S::Error>,
181{
182	Ok(holder != entity && !state.is_deleted(holder)? && !defines_types(state, holder)?)
183}
184
185/// Whether one of the statements shown refers to the entity, or to one merged into it.
186fn refers_to<S: Statements>(
187	state: &State<S>,
188	shown: &[std::borrow::Cow<'_, nibkeep_model::Statement>],
189	entity: EntityId,
190) -> Result<bool, NodeError>
191where
192	NodeError: From<S::Error>,
193{
194	for statement in shown {
195		if let Some(reference) = statement.value.as_reference()
196			&& state.canonical(reference)? == entity
197		{
198			return Ok(true);
199		}
200	}
201	Ok(false)
202}
203
204/// The participants of a relationship on `day` in its roles other than `through`, by role,
205/// ordered by the role's name.
206fn participants<S: Statements>(
207	state: &State<S>,
208	types: &Types,
209	languages: &Languages,
210	relationship: EntityId,
211	through: &FieldName,
212	day: Day,
213) -> Result<Vec<(FieldName, Vec<EntityId>)>, NodeError>
214where
215	NodeError: From<S::Error>,
216{
217	let mut participants = Vec::new();
218	for field in state.fields(relationship)? {
219		if field == *through || !types.field(&field).is_some_and(|field| field.is_role()) {
220			continue;
221		}
222		let (shown, _) = resolve(state, types, languages, relationship, &field, day)?;
223		let mut entities = Vec::new();
224		for statement in &shown {
225			if let Some(reference) = statement.value.as_reference() {
226				let reference = state.canonical(reference)?;
227				if !entities.contains(&reference) {
228					entities.push(reference);
229				}
230			}
231		}
232		if !entities.is_empty() {
233			participants.push((field, entities));
234		}
235	}
236	Ok(participants)
237}
238
239/// What a search lists of what it finds, given the entities found by their words, in order:
240/// each of them, or the file it is an origin of, then the entities found through links, each
241/// with the entity it was found through, as [`Library::search`] says; of those, the first
242/// `first` that `keep` keeps, given each one's ID and types, and how many more it keeps.
243///
244/// Links come after every entity found by its words, so they are followed only when no more
245/// than `first` of those are kept, and the count is then exact. Otherwise it is of those
246/// found by their words alone, at least as many as there are. Links are those of current
247/// statements, which hold on some day, as the words that a search finds are.
248///
249/// The entities listed are named, and so are, to order them, the others of a group found
250/// through one entity that the page ends in, and those that stand for an entity found, while
251/// the page is not full.
252pub(crate) fn searched_through<S: Statements>(
253	state: &State<S>,
254	(types, languages): (&Types, &Languages),
255	(hits, first): (&[EntityId], usize),
256	keep: &mut Keep<'_>,
257) -> Result<Searched, NodeError>
258where
259	NodeError: From<S::Error>,
260{
261	let listed = |id: EntityId,
262	              kinds: BTreeSet<TypeName>,
263	              via: Option<EntityId>|
264	 -> Result<Listed, NodeError> {
265		Ok(Listed {
266			id,
267			name: display_name(state, types, languages, id)?,
268			types: kinds.into_iter().collect(),
269			via,
270		})
271	};
272	// Every hit is seen, so that an origin or a checkout is never found, through links
273	// either.
274	let mut seen: BTreeSet<EntityId> = hits.iter().copied().collect();
275	let by_words = found_by_words(state, hits, &mut seen)?;
276	// The first entities kept, and how many are kept in all.
277	let mut found = Vec::new();
278	let mut kept = 0_usize;
279	for (entity, kinds) in &by_words {
280		if keep(*entity, kinds)? {
281			kept += 1;
282			if found.len() < first {
283				found.push(listed(*entity, kinds.clone(), None)?);
284			}
285		}
286	}
287	if kept > first {
288		return Ok(Searched {
289			listed: found,
290			more: More::AtLeast(kept - first),
291		});
292	}
293	// Adds the entities not found yet, through `via`: those kept, ordered by name, while
294	// fewer than `first` are listed, or else only counted. Returns every new one, kept or
295	// not, as the links of each are followed either way.
296	let searched = types.searched_fields();
297	let mut add = |entities: Vec<EntityId>,
298	               via: EntityId,
299	               (found, kept): (&mut Vec<Listed>, &mut usize)|
300	 -> Result<Vec<EntityId>, NodeError> {
301		let mut new = Vec::new();
302		let mut listing = Vec::new();
303		for entity in entities {
304			if !seen.insert(entity) {
305				continue;
306			}
307			new.push(entity);
308			let kinds = state.types(entity)?;
309			if keep(entity, &kinds)? {
310				*kept += 1;
311				if found.len() < first {
312					listing.push(listed(entity, kinds, Some(via))?);
313				}
314			}
315		}
316		listing.sort_by_cached_key(|entity| by_name(entity.name.as_deref(), entity.id));
317		found.extend(listing);
318		Ok(new)
319	};
320	for (hit, _) in by_words {
321		let (stand_ins, linked) = linking_for_search(state, (types, &searched), hit)?;
322		let both: Vec<EntityId> = stand_ins.iter().chain(&linked).copied().collect();
323		let listed_before = found.len();
324		let added = add(both, hit, (&mut found, &mut kept))?;
325		// Through each new entity that stands for the hit, in the order they are listed in,
326		// kept or not, named as they were listed. Once the page is full, the order changes
327		// nothing.
328		let mut through: Vec<EntityId> = added
329			.into_iter()
330			.filter(|entity| stand_ins.contains(entity))
331			.collect();
332		if found.len() < first && through.len() > 1 {
333			let mut ordered = Vec::with_capacity(through.len());
334			for entity in through {
335				let name = match found[listed_before..]
336					.iter()
337					.find(|listed| listed.id == entity)
338				{
339					Some(listed) => listed.name.clone(),
340					None => display_name(state, types, languages, entity)?,
341				};
342				ordered.push((by_name(name.as_deref(), entity), entity));
343			}
344			ordered.sort();
345			through = ordered.into_iter().map(|(_, entity)| entity).collect();
346		}
347		for stand_in in through {
348			let (_, linked) = linking_for_search(state, (types, &searched), stand_in)?;
349			add(
350				linked.into_iter().collect(),
351				stand_in,
352				(&mut found, &mut kept),
353			)?;
354		}
355	}
356	found.truncate(first);
357	Ok(Searched {
358		more: More::Exactly(kept - found.len()),
359		listed: found,
360	})
361}
362
363/// The order of entities that link to another, found by a search or listed: by name without
364/// regard to case, unnamed ones last, then by ID.
365fn by_name(name: Option<&str>, id: EntityId) -> (bool, Option<String>, EntityId) {
366	let name = name.map(str::to_lowercase);
367	(name.is_none(), name, id)
368}
369
370/// Which entities a search lists and counts, given each one's ID and types.
371pub(crate) type Keep<'a> = dyn FnMut(EntityId, &BTreeSet<TypeName>) -> Result<bool, NodeError> + 'a;
372
373/// The entities that a search finds by their words, given what holds them, in order, each
374/// with its types: each of them, or the file it is an origin or a checkout of, if that is
375/// not seen yet nor deleted, which it then sees; never an entity that defines types, nor a
376/// thumbnail, whose media type and way of making are no words of a picture.
377fn found_by_words<S: Statements>(
378	state: &State<S>,
379	hits: &[EntityId],
380	seen: &mut BTreeSet<EntityId>,
381) -> Result<Vec<(EntityId, BTreeSet<TypeName>)>, NodeError>
382where
383	NodeError: From<S::Error>,
384{
385	let mut found = Vec::with_capacity(hits.len());
386	for &hit in hits {
387		// Each hit's types are read once, to tell an origin or a checkout from what it stands
388		// for.
389		let kinds = state.types(hit)?;
390		// The entities that define types are never found, even by words that a version
391		// which did not reserve their fields indexed, such as labels; nor the records of the
392		// names of spaces, which name spaces, not entities.
393		if kinds.contains(&TYPE_DEFINITION)
394			|| kinds.contains(&FIELD_DEFINITION)
395			|| kinds.contains(&nibkeep_std::THUMBNAIL)
396			|| kinds.contains(&nibkeep_governance::SPACE_NAMES)
397		{
398			continue;
399		}
400		let of = if kinds.contains(&nibkeep_std::ORIGIN) {
401			nibkeep_std::ORIGIN_OF
402		} else if kinds.contains(&nibkeep_std::CHECKOUT) {
403			nibkeep_std::CHECKOUT_OF
404		} else {
405			found.push((hit, kinds));
406			continue;
407		};
408		for file in super::files::found_at(state, (hit, &of))? {
409			if !seen.insert(file) || state.is_deleted(file)? {
410				continue;
411			}
412			let kinds = state.types(file)?;
413			if kinds.contains(&nibkeep_std::FILE) {
414				found.push((file, kinds));
415			}
416		}
417	}
418	Ok(found)
419}
420
421/// The entities, not deleted and not defining types, that link to an entity through a
422/// current statement of a field that searches go through: those that stand for it, and
423/// those that link to it otherwise. Only those fields are read, through the index of
424/// references by field.
425fn linking_for_search<S: Statements>(
426	state: &State<S>,
427	(types, searched): (&Types, &BTreeSet<FieldName>),
428	entity: EntityId,
429) -> Result<(BTreeSet<EntityId>, BTreeSet<EntityId>), NodeError>
430where
431	NodeError: From<S::Error>,
432{
433	let mut stand_ins = BTreeSet::new();
434	let mut linked = BTreeSet::new();
435	for field in searched {
436		let stands_for = types
437			.field(field)
438			.is_some_and(|definition| definition.is_stands_for());
439		for statement in state.referrers_in(entity, field)? {
440			let holder = state.canonical(statement.entity)?;
441			if !may_link(state, holder, entity)? {
442				continue;
443			}
444			if stands_for {
445				stand_ins.insert(holder);
446			} else {
447				linked.insert(holder);
448			}
449		}
450	}
451	linked.retain(|holder| !stand_ins.contains(holder));
452	Ok((stand_ins, linked))
453}
454
455/// The entities that link to an entity on a day, `shown`, as [`Library::links_to`] says, or
456/// without one, on any day, as [`Library::links_to_on_any_day`] says; `limit` of each field,
457/// with the participants of relationships on `day`.
458pub(crate) fn links_to<S: Statements>(
459	state: &State<S>,
460	types: &Types,
461	languages: &Languages,
462	(entity, shown): (EntityId, Option<Day>),
463	(day, limit): (Day, usize),
464) -> Result<Vec<Links>, NodeError>
465where
466	NodeError: From<S::Error>,
467{
468	let entity = state.canonical(entity)?;
469	let mut linking: BTreeMap<FieldName, BTreeSet<EntityId>> = BTreeMap::new();
470	let mut checked: BTreeSet<(EntityId, FieldName)> = BTreeSet::new();
471	for statement in state.referrers(entity)? {
472		let holder = state.canonical(statement.entity)?;
473		if !checked.insert((holder, statement.field.clone())) || !may_link(state, holder, entity)? {
474			continue;
475		}
476		// A link counts on the days its field shows it, as any value does: on any day, as
477		// one of the values the field shows on the days they hold, which leaves out those
478		// written before the last of a field whose last writer wins.
479		let counts = if let Some(day) = shown {
480			let (shown, _) = resolve(state, types, languages, holder, &statement.field, day)?;
481			refers_to(state, &shown, entity)?
482		} else {
483			let definition = types.field(&statement.field);
484			let (Resolution::Values(shown) | Resolution::Competing(shown)) =
485				state.resolve(holder, &statement.field, definition.as_ref())?;
486			refers_to(state, &shown, entity)?
487		};
488		if counts {
489			linking
490				.entry(statement.field.clone())
491				.or_default()
492				.insert(holder);
493		}
494	}
495	let mut links = Vec::new();
496	for (field, holders) in linking {
497		let definition = types.field(&field);
498		let role = definition.as_ref().is_some_and(FieldDef::is_role);
499		let mut entities = Vec::new();
500		// Every name is needed to order them; the rest, only for those given.
501		for id in &holders {
502			entities.push(Linking {
503				id: *id,
504				name: display_name(state, types, languages, *id)?,
505				types: Vec::new(),
506				participants: Vec::new(),
507			});
508		}
509		entities.sort_by_cached_key(|linking| by_name(linking.name.as_deref(), linking.id));
510		entities.truncate(limit);
511		for linking in &mut entities {
512			linking.types = state.types(linking.id)?.into_iter().collect();
513			if role {
514				linking.participants =
515					participants(state, types, languages, linking.id, &field, day)?;
516			}
517		}
518		links.push(Links {
519			reverse: definition.and_then(|field| field.reverse().cloned()),
520			field,
521			role,
522			count: holders.len(),
523			entities,
524		});
525	}
526	Ok(links)
527}