Skip to main content

nibkeep_node/library/
entities.rs

1//! The entities of a library's spaces: created, shown, listed and found.
2
3use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet};
5
6use nibkeep_base::{EntityId, SpaceId, StatementId};
7use nibkeep_crypto::rand_core::CryptoRng;
8use nibkeep_governance::{LINKED_PERSON, NAME, USER};
9use nibkeep_model::schema::{FIELD_DEFINITION, TYPE_DEFINITION};
10use nibkeep_model::storage::{Layers, Memory, Recorded, Statements};
11use nibkeep_model::{
12	FieldDef, FieldName, Languages, Multiplicity, Operation, Qualifiers, Resolution, State,
13	Statement, Tag, TypeName, Types, Value, content, fields, presence_on,
14};
15
16use nibkeep_store::{StateFile, StoredLog};
17use nibkeep_time::{Day, Edtf, Presence, Timestamp};
18
19use super::{Library, policies};
20use crate::NodeError;
21
22/// The shortest prefix of an ID that finds an entity: six characters leave few entities
23/// of a large library to choose from.
24pub(crate) const SHORTEST_PREFIX: usize = 6;
25
26/// An entity as a person sees it: its name, types, and the values of its fields.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct EntityView {
29	/// The entity, or of entities merged together, the one they were merged into.
30	pub id: EntityId,
31	/// The name to show for it, if it has one.
32	pub name: Option<String>,
33	/// Its types.
34	pub types: Vec<TypeName>,
35	/// Whether it is deleted.
36	pub deleted: bool,
37	/// The fields with values, ordered by name, without the fields of its types and of its
38	/// own record.
39	pub fields: Vec<FieldView>,
40}
41
42impl EntityView {
43	/// The values that a field shows, in the order to show them; none if it shows none.
44	#[must_use]
45	pub fn values(&self, field: &FieldName) -> &[ShownValue] {
46		self.fields
47			.iter()
48			.find(|shown| &shown.field == field)
49			.map_or(&[], |shown| shown.values.as_slice())
50	}
51}
52
53/// A field of an entity, and its values.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct FieldView {
56	/// The field.
57	pub field: FieldName,
58	/// The values to show, in the order to show them (`docs/spec/model.md`, section 6).
59	pub values: Vec<ShownValue>,
60	/// Whether the values compete: several values of a field with one value, until a person
61	/// chooses.
62	pub competing: bool,
63}
64
65/// A value as it is shown.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct ShownValue {
68	/// The statement that holds it.
69	pub statement: StatementId,
70	/// The value.
71	pub value: Value,
72	/// When it was true, if its valid time can be read: a date for something that happened,
73	/// an interval for a state.
74	pub valid_time: Option<Edtf>,
75	/// Whether it certainly holds on the day shown, only possibly holds there, or has no
76	/// date that can be read, and so shows on every day.
77	pub presence: Presence,
78	/// Whether it has a valid time that this version cannot read.
79	pub unreadable_date: bool,
80	/// Its language tag, as written, if it has one.
81	pub language: Option<String>,
82	/// How many other forms the value has, in other languages or scripts.
83	pub other_forms: usize,
84	/// The other forms, ordered by the IDs of their statements.
85	pub forms: Vec<OtherForm>,
86}
87
88/// Another form of a value shown, in another language or script.
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct OtherForm {
91	/// The form.
92	pub value: Value,
93	/// Its language tag, as written, if it has one.
94	pub language: Option<String>,
95}
96
97/// The time of an edit or a view: the day a person sees, and when they write.
98///
99/// A field shows its values as of [`Dating::day`]. Setting a field replaces what it shows
100/// on that day, and keeps what belongs to other days. Values written get
101/// [`Dating::valid_time`] if a person gave one, and otherwise, where a field with one value
102/// has dated values, a date of their own (`docs/spec/model.md`, section 6).
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct Dating {
105	/// The day a person sees: today, unless they chose another.
106	pub day: Day,
107	/// The date and time of writing, with the device's offset from UTC, when the day is
108	/// today.
109	pub now: Option<Edtf>,
110	/// When the values written are true, if the person said: a date for something that
111	/// happened, an interval for a state.
112	pub valid_time: Option<Edtf>,
113	/// The language that the text, names and files written are in, if the person said.
114	pub language: Option<Tag>,
115}
116
117impl Dating {
118	/// Today, at a moment in milliseconds since 1970 (UTC), at the device's offset from UTC
119	/// in minutes. Returns `None` if the offset is outside the range from −12 to +14 hours.
120	#[must_use]
121	pub fn today(wall_millis: u64, offset_minutes: i32) -> Option<Self> {
122		let day = Day::from_unix_millis(wall_millis, offset_minutes)?;
123		let second = Day::second_of_day(wall_millis, offset_minutes);
124		Some(Self {
125			day,
126			now: Some(Edtf::moment(day, second, offset_minutes)?),
127			valid_time: None,
128			language: None,
129		})
130	}
131
132	/// Another day than today.
133	#[must_use]
134	pub fn on(day: Day) -> Self {
135		Self {
136			day,
137			now: None,
138			valid_time: None,
139			language: None,
140		}
141	}
142
143	/// The same, with the valid time that a person gave for the values written.
144	#[must_use]
145	pub fn with_valid_time(mut self, valid_time: Edtf) -> Self {
146		self.valid_time = Some(valid_time);
147		self
148	}
149
150	/// The same, with the language that a person gave for the values written.
151	#[must_use]
152	pub fn with_language(mut self, language: Tag) -> Self {
153		self.language = Some(language);
154		self
155	}
156
157	/// The valid time of a value that supersedes nothing in a dated field with one value:
158	/// the moment of writing, if the day is today, and the day otherwise.
159	fn start(&self) -> Edtf {
160		self.now.clone().unwrap_or_else(|| Edtf::day(self.day))
161	}
162}
163
164/// A change to an entity.
165#[derive(Clone, Debug, PartialEq, Eq)]
166pub enum Edit {
167	/// Makes these the field's values, replacing those it has; without values, clears it.
168	Set(FieldName, Vec<Value>),
169	/// Adds a value to the field. A second value of a field with one value competes with
170	/// the first until a person chooses, as a claim against another.
171	Add(FieldName, Value),
172	/// Removes the values of the field that this one names, in any of their forms, with
173	/// every form they have.
174	Remove(FieldName, Value),
175	/// Removes the forms of the field's values that equal this one, and keeps the values'
176	/// other forms.
177	RemoveForm(FieldName, Value),
178	/// Removes the forms of the field's values that equal this one and are in this language,
179	/// or in none, and keeps the values' other forms, as those that say the same in another
180	/// language.
181	RemoveFormIn {
182		/// The field.
183		field: FieldName,
184		/// The form, as it says.
185		value: Value,
186		/// Its language, or `None` for a form in none.
187		language: Option<Tag>,
188	},
189	/// Adds another form of a value that the field shows, in another language or script,
190	/// with the value's valid time: of the value `of`, in any of its forms, or, without
191	/// it, of the only value the field shows.
192	AddForm {
193		/// The field.
194		field: FieldName,
195		/// The value, in any of its forms, if the field shows several.
196		of: Option<Value>,
197		/// The new form.
198		value: Value,
199	},
200	/// Deletes the entity: hides it and keeps it, until it is restored.
201	Delete,
202	/// Restores a deleted entity.
203	Restore,
204	/// Gives the entity another type, which it may have already: types combine, as a
205	/// photo is a file too.
206	AddType(TypeName),
207	/// Takes a type away from the entity, which keeps at least one; its values stay, as
208	/// values of fields that no type of it defines.
209	RemoveType(TypeName),
210}
211
212/// A value of a new entity: in a language, if given, and with other forms, each in its
213/// language, if given.
214#[derive(Clone, Debug, PartialEq, Eq)]
215pub struct NewValue {
216	/// The field.
217	pub field: FieldName,
218	/// The value, its first form.
219	pub value: Value,
220	/// The language of the value, if it can have one and it is known.
221	pub language: Option<Tag>,
222	/// Other forms of the value, in other languages or scripts.
223	pub forms: Vec<(Value, Option<Tag>)>,
224}
225
226impl NewValue {
227	/// A value without a language or other forms.
228	#[must_use]
229	pub fn new(field: FieldName, value: Value) -> Self {
230		Self {
231			field,
232			value,
233			language: None,
234			forms: Vec::new(),
235		}
236	}
237
238	/// The same, in a language.
239	#[must_use]
240	pub fn in_language(mut self, language: Tag) -> Self {
241		self.language = Some(language);
242		self
243	}
244
245	/// The same, with another form, in a language if given.
246	#[must_use]
247	pub fn with_form(mut self, form: Value, language: Option<Tag>) -> Self {
248		self.forms.push((form, language));
249		self
250	}
251}
252
253/// What a space holds, counted: [`Library::census`].
254#[derive(Clone, Debug, Default, PartialEq, Eq)]
255pub struct Census {
256	/// How many things have each type, of the things that [`Census::things`] counts: a
257	/// thing of several types counts for each.
258	pub types: BTreeMap<TypeName, usize>,
259	/// How many things the space holds, as [`Library::entities`] lists them: entities that
260	/// are not deleted and do not define types, those merged together as one.
261	pub things: usize,
262	/// How many deleted entities the space holds, as [`Library::deleted`] lists them: those
263	/// that can be restored.
264	pub deleted: usize,
265}
266
267/// A value with when it held: [`Library::dated_values`].
268#[derive(Clone, Debug, PartialEq, Eq)]
269pub struct DatedValue {
270	/// The statement that holds it.
271	pub statement: StatementId,
272	/// The value.
273	pub value: Value,
274	/// When it was true: a date for something that happened, an interval for a state.
275	pub valid_time: Edtf,
276}
277
278/// An entity in a list.
279#[derive(Clone, Debug, PartialEq, Eq)]
280pub struct Listed {
281	/// The entity.
282	pub id: EntityId,
283	/// The name to show for it, if it has one.
284	pub name: Option<String>,
285	/// Its types.
286	pub types: Vec<TypeName>,
287	/// Of an entity that a search found through a link, rather than by its own words, the
288	/// entity that it was found through.
289	pub via: Option<EntityId>,
290}
291
292/// The first entities that a search finds, and how many more there are, as
293/// [`Library::search_first`] lists them.
294#[derive(Clone, Debug, PartialEq, Eq)]
295pub struct Searched {
296	/// The first entities found, in the order of [`Library::search`].
297	pub listed: Vec<Listed>,
298	/// How many more it finds.
299	pub more: More,
300}
301
302/// How many more entities a search finds than it lists.
303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304pub enum More {
305	/// This many, exactly.
306	Exactly(usize),
307	/// At least this many: those found by their words, without those found through links,
308	/// which were not looked for.
309	AtLeast(usize),
310}
311
312impl More {
313	/// The number, exact or not.
314	#[must_use]
315	pub fn count(self) -> usize {
316		match self {
317			Self::Exactly(count) | Self::AtLeast(count) => count,
318		}
319	}
320}
321
322impl Library {
323	/// Adds an entity of these types, with these values, to a space. Returns the entity.
324	///
325	/// # Errors
326	///
327	/// Returns an error if the library has no such space; if a type is one of those that
328	/// define types, which [`Library::define_type`] defines; if a field is one of NibKeep's
329	/// own, which its own operations set; if a field with one value gets several; or if
330	/// the change cannot be saved, such as a secret value without the space's secrets key.
331	pub fn create_entity(
332		&mut self,
333		space: SpaceId,
334		types: &[TypeName],
335		values: Vec<(FieldName, Value)>,
336		wall_millis: u64,
337		rng: &mut impl CryptoRng,
338	) -> Result<EntityId, NodeError> {
339		let values = values
340			.into_iter()
341			.map(|(field, value)| NewValue::new(field, value))
342			.collect();
343		self.create_entity_with(space, types, values, wall_millis, rng)
344	}
345
346	/// Adds an entity as [`Library::create_entity`] does, with its text, names and files in
347	/// `language`.
348	///
349	/// # Errors
350	///
351	/// As [`Library::create_entity`].
352	pub fn create_entity_with_language(
353		&mut self,
354		space: SpaceId,
355		types: &[TypeName],
356		values: Vec<(FieldName, Value)>,
357		language: &Tag,
358		wall_millis: u64,
359		rng: &mut impl CryptoRng,
360	) -> Result<EntityId, NodeError> {
361		let values = values
362			.into_iter()
363			.map(|(field, value)| NewValue::new(field, value).in_language(language.clone()))
364			.collect();
365		self.create_entity_with(space, types, values, wall_millis, rng)
366	}
367
368	/// Adds an entity as [`Library::create_entity`] does, with values that can be in a
369	/// language and have other forms, as an import of data in several languages writes
370	/// them. Forms of one value count as one.
371	///
372	/// # Errors
373	///
374	/// As [`Library::create_entity`].
375	pub fn create_entity_with(
376		&mut self,
377		space: SpaceId,
378		types: &[TypeName],
379		values: Vec<NewValue>,
380		wall_millis: u64,
381		rng: &mut impl CryptoRng,
382	) -> Result<EntityId, NodeError> {
383		self.check_not_group(space)?;
384		let (entity, operations) = self.new_entity(space, types, values, rng)?;
385		self.commit(space, operations, wall_millis, rng)?;
386		Ok(entity)
387	}
388
389	/// A new entity and the operations that make it, as [`Library::create_entity_with`]
390	/// makes it, for a change that holds more.
391	pub(crate) fn new_entity(
392		&self,
393		space: SpaceId,
394		types: &[TypeName],
395		values: Vec<NewValue>,
396		rng: &mut impl CryptoRng,
397	) -> Result<(EntityId, Vec<Operation>), NodeError> {
398		let known = &self.space(space)?.types;
399		// The records of users, devices, replicas and spaces are made here too, by NibKeep's
400		// own operations, which apps reach through their own commands.
401		if let Some(own) = types.iter().find(|name| {
402			**name == TYPE_DEFINITION || **name == FIELD_DEFINITION || policies::is_own_type(name)
403		}) {
404			return Err(NodeError::OwnType(own.clone()));
405		}
406		let mut counts: BTreeMap<&FieldName, usize> = BTreeMap::new();
407		for value in &values {
408			if fields::is_reserved(&value.field) || policies::is_own_field(&value.field) {
409				return Err(NodeError::OwnField(value.field.clone()));
410			}
411			*counts.entry(&value.field).or_default() += 1;
412		}
413		if let Some((field, _)) = counts
414			.iter()
415			.find(|&(field, &count)| count > 1 && has_one_value(known, field))
416		{
417			return Err(NodeError::OneValue((*field).clone()));
418		}
419		let entity = EntityId::random(rng);
420		let mut operations: Vec<Operation> = types
421			.iter()
422			.map(|name| {
423				Operation::assert(Statement::new(
424					StatementId::random(rng),
425					entity,
426					fields::TYPE,
427					Value::Text(name.to_string()),
428				))
429			})
430			.collect();
431		for NewValue {
432			field,
433			value,
434			language,
435			forms,
436		} in values
437		{
438			let first = StatementId::random(rng);
439			let qualifiers = in_language(Qualifiers::new(), &value, language.as_ref());
440			let qualifiers = for_field(known, &field, qualifiers);
441			operations.push(Operation::assert(
442				Statement::new(first, entity, field.clone(), value).with_qualifiers(qualifiers),
443			));
444			for (form, language) in forms {
445				let qualifiers =
446					Qualifiers::new().with(fields::ALTERNATIVE, Value::Text(first.to_string()));
447				let qualifiers = in_language(qualifiers, &form, language.as_ref());
448				let qualifiers = for_field(known, &field, qualifiers);
449				operations.push(Operation::assert(
450					Statement::new(StatementId::random(rng), entity, field.clone(), form)
451						.with_qualifiers(qualifiers),
452				));
453			}
454		}
455		Ok((entity, operations))
456	}
457
458	/// Changes an entity of a space, with every edit in one change, as of `dating`, except
459	/// that edits of what governs the space, such as a replica's key, make a change of their
460	/// own, committed first. Each edit sees what the edits before it did. Edits that change
461	/// nothing, such as deleting a deleted entity or setting a field to the values it shows,
462	/// commit nothing.
463	///
464	/// # Errors
465	///
466	/// Returns an error if the library has no such space or the space no such entity; if the
467	/// entity defines a type or field, which only [`Library::define_type`] changes; if a field
468	/// is one of NibKeep's own; if a field with one value is set to several; if a value to
469	/// remove is not shown; if a type to give or take away is one of NibKeep's own, or one to
470	/// take away is not the entity's, or its only one; or if the change cannot be saved.
471	pub fn edit_entity(
472		&mut self,
473		space: SpaceId,
474		entity: EntityId,
475		edits: Vec<Edit>,
476		dating: &Dating,
477		wall_millis: u64,
478		rng: &mut impl CryptoRng,
479	) -> Result<(), NodeError> {
480		let types = &self.space(space)?.types;
481		let operations = {
482			let state = self.space(space)?.stored.log().state();
483			let entity = state.canonical(entity)?;
484			if state.fields(entity)?.is_empty() {
485				return Err(NodeError::NoEntity(entity.to_string()));
486			}
487			if let Some(own) = state.types(entity)?.into_iter().find(|name| {
488				*name == TYPE_DEFINITION || *name == FIELD_DEFINITION || policies::is_own_type(name)
489			}) {
490				return Err(NodeError::OwnType(own));
491			}
492			// In a space with members, a member's link to a person takes both sides, each
493			// replacing only its own statements: only `Library::link_member` writes it.
494			if self.has_members(space)?
495				&& edits.iter().any(|edit| {
496					matches!(edit, Edit::Set(field, _)
497						| Edit::Add(field, _)
498						| Edit::Remove(field, _)
499						| Edit::RemoveForm(field, _)
500						| Edit::RemoveFormIn { field, .. }
501						| Edit::AddForm { field, .. } if *field == LINKED_PERSON)
502				}) {
503				return Err(NodeError::OwnField(LINKED_PERSON));
504			}
505			// Each edit sees the ones before it, in a copy of the entity's part of the state.
506			let mut working = state.excerpt(entity)?;
507			let at = Timestamp::new(wall_millis, 0);
508			let mut operations = Vec::new();
509			for edit in edits {
510				let made =
511					edit_operations(&working, types, &self.languages, entity, edit, dating, rng)?;
512				// Each changes only the entity it names, so that what an edit replaced of an
513				// entity merged into this one is gone for the next edit too.
514				let made = super::scope(made, |id| {
515					Ok(working.statement(id)?.map(|statement| statement.entity))
516				})?;
517				for operation in &made {
518					working.apply(operation, at)?;
519				}
520				operations.extend(made);
521			}
522			operations
523		};
524		if operations.is_empty() {
525			return Ok(());
526		}
527		self.commit(space, operations, wall_millis, rng)
528	}
529
530	/// Finds the entities of a space that are not deleted and whose values shown hold every
531	/// word of `query`, in the order of the search index: those with more matching values
532	/// first. Secret values are never searched, nor the text of NibKeep's fields for
533	/// structure, keys and positions. A search that matches where a file was found, the path
534	/// of one of its origins, or where it is checked out, finds the file, unless it is
535	/// deleted, rather than the origin or the checkout. Entities that define types are never
536	/// found.
537	///
538	/// Through links, it finds more, each with the entity it was found through, after those
539	/// found by their words (`docs/spec/model.md`, section 10): for each of them, the
540	/// entities that stand for it, such as a pen name for a person who uses it, and those
541	/// that link to it through a field that searches go through, such as a book through its
542	/// author, ordered by name; and then, through each entity that stands for it, those that
543	/// link to that entity so. No entity is found twice.
544	///
545	/// Everything found is listed, which costs most for common words: where a page is
546	/// enough, [`Library::search_first`] costs less.
547	///
548	/// # Errors
549	///
550	/// Returns an error if the library has no such space, or the space cannot be read.
551	pub fn search(&self, space: SpaceId, query: &str) -> Result<Vec<Listed>, NodeError> {
552		Ok(self
553			.search_first(space, query, usize::MAX, |_, _| Ok(true))?
554			.listed)
555	}
556
557	/// Lists what [`Library::search`] finds, in its order, but only the entities that `keep`
558	/// keeps, given each one's ID and types, and only the first `first` of those; and counts
559	/// the others it keeps. Naming entities is most of what a search costs, and those past
560	/// the page are not named, but for those found through links in the group that the page
561	/// ends in, which are ordered by name. Entities found through links come after every
562	/// entity found by its words, so links are followed only when no more than `first` of
563	/// those are kept; otherwise the count leaves out what links would find, and is
564	/// [`More::AtLeast`].
565	///
566	/// # Errors
567	///
568	/// Returns an error if the library has no such space, the space cannot be read, or
569	/// `keep` fails.
570	pub fn search_first(
571		&self,
572		space: SpaceId,
573		query: &str,
574		first: usize,
575		mut keep: impl FnMut(EntityId, &BTreeSet<TypeName>) -> Result<bool, NodeError>,
576	) -> Result<Searched, NodeError> {
577		let open = self.space(space)?;
578		let state = open.stored.log().state();
579		open.stored.reading(|stored| {
580			let hits: Vec<EntityId> = stored
581				.search(query)?
582				.into_iter()
583				.map(|found| found.entity)
584				.collect();
585			super::links::searched_through(
586				state,
587				(&open.types, &self.languages),
588				(&hits, first),
589				&mut keep,
590			)
591		})
592	}
593
594	/// An entity of a space, as a person sees it on `day`, or `None` if the space says
595	/// nothing about it. Of entities merged together, the one they were merged into is shown.
596	///
597	/// # Errors
598	///
599	/// Returns an error if the library has no such space, or the space cannot be read.
600	pub fn entity(
601		&self,
602		space: SpaceId,
603		entity: EntityId,
604		day: Day,
605	) -> Result<Option<EntityView>, NodeError> {
606		let open = self.space(space)?;
607		open.stored.reading(|stored| {
608			entity_view(
609				stored.log().state(),
610				&open.types,
611				&self.languages,
612				entity,
613				day,
614			)
615		})
616	}
617
618	/// The name to show for an entity of a space, if it has one.
619	///
620	/// # Errors
621	///
622	/// Returns an error if the library has no such space, or the space cannot be read.
623	pub fn name(&self, space: SpaceId, entity: EntityId) -> Result<Option<String>, NodeError> {
624		let open = self.space(space)?;
625		open.stored.reading(|stored| {
626			let state = stored.log().state();
627			display_name(
628				state,
629				&open.types,
630				&self.languages,
631				state.canonical(entity)?,
632			)
633		})
634	}
635
636	/// The entities of a space that are not deleted, without those that define types, or
637	/// the entities of a type, ordered by name without regard to case, unnamed ones last.
638	///
639	/// # Errors
640	///
641	/// Returns an error if the library has no such space, or the space cannot be read.
642	pub fn entities(
643		&self,
644		space: SpaceId,
645		of_type: Option<&TypeName>,
646	) -> Result<Vec<Listed>, NodeError> {
647		let open = self.space(space)?;
648		let state = open.stored.log().state();
649		let Some(name) = of_type else {
650			// Every thing of the space, told apart and named part by part.
651			return listing(state, &open.types, &self.languages, PART);
652		};
653		let ids = with_type(&open.stored, name)?;
654		listed_from(state, &open.types, &self.languages, (ids, PART))
655	}
656
657	/// The deleted entities of a space, without those that define types, ordered by name
658	/// without regard to case, unnamed ones last: those that can be restored.
659	///
660	/// # Errors
661	///
662	/// Returns an error if the library has no such space, or the space cannot be read.
663	pub fn deleted(&self, space: SpaceId) -> Result<Vec<Listed>, NodeError> {
664		let open = self.space(space)?;
665		let state = open.stored.log().state();
666		let ids = entities_where(state, true, PART)?;
667		listed_from(state, &open.types, &self.languages, (ids, PART))
668	}
669
670	/// Counts what a space holds, as [`Library::entities`] and [`Library::deleted`] list
671	/// it, in one pass over the space that names nothing, which costs much less than
672	/// listing: for an overview of a large space.
673	///
674	/// # Errors
675	///
676	/// Returns an error if the library has no such space, or the space cannot be read.
677	pub fn census(&self, space: SpaceId) -> Result<Census, NodeError> {
678		let open = self.space(space)?;
679		// In one reading, so that the counts are of one state, whatever another program
680		// writes meanwhile.
681		open.stored
682			.reading(|stored| census(stored.log().state(), PART))
683	}
684
685	/// The current values of a field of an entity that have a valid time, with it, ordered
686	/// by statement ID: what the field held over time, such as each of a dog's weights, for
687	/// a chart of how it changed. Of entities merged together, those of all of them; a value
688	/// in several forms counts once, by its first, and statements that repeat one with a
689	/// smaller ID count as that one.
690	///
691	/// # Errors
692	///
693	/// Returns an error if the library has no such space, or the space cannot be read.
694	pub fn dated_values(
695		&self,
696		space: SpaceId,
697		entity: EntityId,
698		field: &FieldName,
699	) -> Result<Vec<DatedValue>, NodeError> {
700		let open = self.space(space)?;
701		open.stored.reading(|stored| {
702			let state = stored.log().state();
703			let entity = state.canonical(entity)?;
704			dated_in(state, entity, field)
705		})
706	}
707
708	/// Each field of an entity that `wanted` accepts and that has current values with a valid
709	/// time, with those values, as [`Library::dated_values`] gives them, ordered by field:
710	/// what an entity held over time in all its fields, read at once, for a time line of many
711	/// entities. Fields that `wanted` refuses, such as secret ones, are not read.
712	///
713	/// # Errors
714	///
715	/// Returns an error if the library has no such space, or the space cannot be read.
716	pub fn all_dated_values(
717		&self,
718		space: SpaceId,
719		entity: EntityId,
720		wanted: impl Fn(&FieldName) -> bool,
721	) -> Result<Vec<(FieldName, Vec<DatedValue>)>, NodeError> {
722		let open = self.space(space)?;
723		open.stored.reading(|stored| {
724			let state = stored.log().state();
725			let entity = state.canonical(entity)?;
726			let mut all = Vec::new();
727			for field in state.fields(entity)? {
728				if !wanted(&field) {
729					continue;
730				}
731				let dated = dated_in(state, entity, &field)?;
732				if !dated.is_empty() {
733					all.push((field, dated));
734				}
735			}
736			Ok(all)
737		})
738	}
739
740	/// Finds an entity of a space by its ID, or else by a prefix of its ID of at least six
741	/// characters or by its name, without regard to case. A name and a prefix that match
742	/// different entities are ambiguous. Names find only entities that are not deleted, so
743	/// that references never point to a deleted entity by accident.
744	///
745	/// # Errors
746	///
747	/// Returns an error if the library has no such space, the space cannot be read, or no
748	/// entity or several match.
749	pub fn find_entity(&self, space: SpaceId, reference: &str) -> Result<EntityId, NodeError> {
750		self.lookup(space, reference, false)
751	}
752
753	/// Finds an entity as [`Library::find_entity`] does, except that a name that finds no
754	/// entity that is not deleted finds deleted ones, for showing or restoring them.
755	///
756	/// # Errors
757	///
758	/// Returns an error if the library has no such space, the space cannot be read, or no
759	/// entity or several match.
760	pub fn find_entity_or_deleted(
761		&self,
762		space: SpaceId,
763		reference: &str,
764	) -> Result<EntityId, NodeError> {
765		self.lookup(space, reference, true)
766	}
767
768	fn lookup(
769		&self,
770		space: SpaceId,
771		reference: &str,
772		deleted: bool,
773	) -> Result<EntityId, NodeError> {
774		let open = self.space(space)?;
775		open.stored
776			.reading(|stored| lookup(stored, &open.types, &self.languages, reference, deleted))
777	}
778}
779
780/// Finds an entity as [`Library::find_entity`] does, or with `deleted`, as
781/// [`Library::find_entity_or_deleted`] does.
782fn lookup(
783	stored: &StoredLog,
784	types: &Types,
785	languages: &Languages,
786	reference: &str,
787	deleted: bool,
788) -> Result<EntityId, NodeError> {
789	let state = stored.log().state();
790	if let Ok(id) = reference.parse::<EntityId>() {
791		// The entity, or one merged with it, has a current statement: a merge, or another.
792		let canonical = state.canonical(id)?;
793		if canonical != id
794			|| !state.fields(canonical)?.is_empty()
795			|| state.merged(canonical)?.len() > 1
796		{
797			return Ok(canonical);
798		}
799	}
800	let lowered = reference.to_lowercase();
801	let looks_like_id = lowered.len() >= SHORTEST_PREFIX
802		&& lowered
803			.chars()
804			.all(|character| character.is_ascii_hexdigit() || character == '-');
805	// Every entity, only when a reference may be the beginning of an ID, or when the
806	// indexes cannot tell which entities have the name.
807	let named = stored.named(reference)?;
808	let entities = if looks_like_id || named.is_none() {
809		state.entities()?
810	} else {
811		BTreeSet::new()
812	};
813	let by_prefix = entities
814		.iter()
815		.copied()
816		.filter(|entity| looks_like_id && entity.to_string().starts_with(&lowered));
817	let mut with_name = Vec::new();
818	let mut live = Vec::new();
819	for entity in named.unwrap_or_else(|| entities.iter().copied().collect()) {
820		if names_now(state, types, entity)?.contains(&lowered) {
821			with_name.push(entity);
822			if !state.is_deleted(entity)? {
823				live.push(entity);
824			}
825		}
826	}
827	let mut named = if live.is_empty() && deleted {
828		with_name
829	} else {
830		live
831	};
832	// A user and the person linked to the user often share a name, which finds the person.
833	let mut linked = BTreeSet::new();
834	for &entity in &named {
835		if state.types(entity)?.contains(&USER)
836			&& let Some(person) = referred(state, types, languages, entity, &LINKED_PERSON)?
837			&& named.contains(&person)
838		{
839			linked.insert(entity);
840		}
841	}
842	named.retain(|entity| !linked.contains(entity));
843	let candidates: Vec<EntityId> = by_prefix
844		.chain(named)
845		.collect::<BTreeSet<EntityId>>()
846		.into_iter()
847		.collect();
848	match candidates.as_slice() {
849		[] => Err(NodeError::NoEntity(reference.to_owned())),
850		&[entity] => Ok(entity),
851		_ => Err(NodeError::Ambiguous {
852			reference: reference.to_owned(),
853			candidates,
854		}),
855	}
856}
857
858/// An entity of a state, as a person sees it on `day`, as [`Library::entity`] says.
859pub(crate) fn entity_view<S: Statements>(
860	state: &State<S>,
861	types: &Types,
862	languages: &Languages,
863	entity: EntityId,
864	day: Day,
865) -> Result<Option<EntityView>, NodeError>
866where
867	NodeError: From<S::Error>,
868{
869	let entity = state.canonical(entity)?;
870	let names = state.fields(entity)?;
871	if names.is_empty() {
872		return Ok(None);
873	}
874	let mut fields = Vec::new();
875	for field in names {
876		if [fields::TYPE, fields::DELETED, fields::MERGED_INTO].contains(&field) {
877			continue;
878		}
879		let definition = types.field(&field);
880		let (statements, competing) =
881			state.resolve_counted(entity, &field, definition.as_ref(), day, languages)?;
882		let mut values = Vec::new();
883		// The field's forms, read once for all its values, when one of them has several.
884		let groups = if statements.iter().any(|(_, forms)| *forms > 1) {
885			state.form_groups(entity, &field)?
886		} else {
887			Vec::new()
888		};
889		for (statement, forms) in statements {
890			let others = if forms > 1 {
891				other_forms(&groups, &statement)
892			} else {
893				Vec::new()
894			};
895			values.push(ShownValue {
896				statement: statement.id,
897				value: statement.value.clone(),
898				valid_time: statement.qualifiers.valid_time().cloned(),
899				presence: presence_on(&statement, day),
900				unreadable_date: statement.qualifiers.has_valid_time()
901					&& statement.qualifiers.valid_time().is_none(),
902				language: statement.qualifiers.language().map(str::to_owned),
903				other_forms: forms.saturating_sub(1),
904				forms: others,
905			});
906		}
907		if !values.is_empty() {
908			fields.push(FieldView {
909				field,
910				values,
911				competing,
912			});
913		}
914	}
915	Ok(Some(EntityView {
916		id: entity,
917		name: name_on(state, types, languages, entity, day)?,
918		types: state.types(entity)?.into_iter().collect(),
919		deleted: state.is_deleted(entity)?,
920		fields,
921	}))
922}
923
924/// The current values of an entity's field that have a valid time, with it, ordered by
925/// statement ID: a value in several forms by its first.
926fn dated_in<S: Statements>(
927	state: &State<S>,
928	entity: EntityId,
929	field: &FieldName,
930) -> Result<Vec<DatedValue>, NodeError>
931where
932	NodeError: From<S::Error>,
933{
934	let mut dated = Vec::new();
935	for forms in state.form_groups(entity, field)? {
936		let Some(first) = forms.first() else {
937			continue;
938		};
939		if let Some(valid_time) = first.qualifiers.valid_time() {
940			dated.push(DatedValue {
941				statement: first.id,
942				value: first.value.clone(),
943				valid_time: valid_time.clone(),
944			});
945		}
946	}
947	Ok(dated)
948}
949
950/// The other forms of the value that a statement shows, of a field's groups of forms: those
951/// that hold another value, or the same in another language. Tags compare without regard to
952/// case.
953fn other_forms(groups: &[Vec<Cow<'_, Statement>>], shown: &Statement) -> Vec<OtherForm> {
954	let same =
955		|value: &Value, language: Option<&str>, other: &Value, other_language: Option<&str>| {
956			value == other
957				&& language.map(str::to_lowercase) == other_language.map(str::to_lowercase)
958		};
959	let language = shown.qualifiers.language();
960	// The group that holds the statement, or else the one that holds what it repeats.
961	let Some(group) = groups
962		.iter()
963		.find(|group| group.iter().any(|form| form.id == shown.id))
964		.or_else(|| {
965			groups
966				.iter()
967				.find(|group| group.iter().any(|form| content(form) == content(shown)))
968		})
969	else {
970		return Vec::new();
971	};
972	let mut others: Vec<OtherForm> = Vec::new();
973	for form in group {
974		let form_language = form.qualifiers.language();
975		// A form written twice, or as the value shown, is one form.
976		let repeated = same(&form.value, form_language, &shown.value, language)
977			|| others.iter().any(|other| {
978				same(
979					&other.value,
980					other.language.as_deref(),
981					&form.value,
982					form_language,
983				)
984			});
985		if form.id != shown.id && !repeated {
986			others.push(OtherForm {
987				value: form.value.clone(),
988				language: form_language.map(str::to_owned),
989			});
990		}
991	}
992	others
993}
994
995/// The entities of a stored space that have a type, by the value index, deleted ones aside.
996pub(crate) fn with_type(
997	stored: &StoredLog,
998	name: &TypeName,
999) -> Result<BTreeSet<EntityId>, NodeError> {
1000	Ok(stored
1001		.find(&fields::TYPE, &Value::Text(name.to_string()))?
1002		.into_iter()
1003		.collect())
1004}
1005
1006/// The entities of a state that a person counts as things: not deleted, and not defining
1007/// types.
1008pub(crate) fn things<S: Statements>(state: &State<S>) -> Result<BTreeSet<EntityId>, NodeError>
1009where
1010	NodeError: From<S::Error>,
1011{
1012	entities_where(state, false, PART)
1013}
1014
1015/// How many entities a part holds when a whole space is read part by part: few enough for
1016/// what they say to sit in memory at once, and many enough for each read to take in much.
1017pub(crate) const PART: usize = 2_048;
1018
1019/// The fields that say what an entity is, whether it is deleted and what it is merged into.
1020const KINDS: [FieldName; 3] = [fields::TYPE, fields::DELETED, fields::MERGED_INTO];
1021
1022/// What [`by_parts`] calls with the state of each part and the chosen entities in it.
1023pub(crate) type EachPart<'a> = dyn FnMut(&State, &[EntityId]) -> Result<(), NodeError> + 'a;
1024
1025/// Reads what `fields` say of `chosen`, entities ordered by ID, part by part, and calls
1026/// `each` with the state of each part and the chosen entities in it. A part is a range of
1027/// `part` entities of the space, as [`State::excerpt_of_range`] takes it from the state, and
1028/// only the parts that hold a chosen entity are read: each read takes in a part, not an
1029/// entity, and no more than a part sits in memory, however few or spread out the chosen
1030/// entities are.
1031pub(crate) fn by_parts<S: Statements>(
1032	state: &State<S>,
1033	chosen: &[EntityId],
1034	(fields, part): (&[FieldName], usize),
1035	each: &mut EachPart<'_>,
1036) -> Result<(), NodeError>
1037where
1038	NodeError: From<S::Error>,
1039{
1040	// Listing the space's entities takes in the whole space, which no part is wanted from.
1041	if chosen.is_empty() {
1042		return Ok(());
1043	}
1044	let space = state.storage().entities()?;
1045	let merges = state.storage().current_in_field(&fields::MERGED_INTO)?;
1046	let groups = MergeGroups::of(&merges);
1047	let mut bounds: Vec<(EntityId, Option<EntityId>)> = space
1048		.chunks(part.max(1))
1049		.filter_map(|entities| Some((*entities.first()?, Some(*entities.last()?))))
1050		.collect();
1051	// Chosen entities after the last of the space, which no current statement describes.
1052	if let (Some(&chosen_last), Some(&(_, Some(space_last)))) = (chosen.last(), bounds.last())
1053		&& chosen_last > space_last
1054	{
1055		bounds.push((chosen_last, None));
1056	} else if bounds.is_empty() && !chosen.is_empty() {
1057		bounds.push((chosen[0], None));
1058	}
1059	let mut chosen = chosen.iter().copied().peekable();
1060	for (first, last) in bounds {
1061		let mut in_part = Vec::new();
1062		while let Some(entity) = chosen.next_if(|entity| last.is_none_or(|last| *entity <= last)) {
1063			in_part.push(entity);
1064		}
1065		let (Some(&lowest), Some(&highest)) = (in_part.first(), in_part.last()) else {
1066			continue;
1067		};
1068		// Chosen entities between two parts of the space count with the later one; nothing
1069		// else lies between them.
1070		let range = (first.min(lowest), last.unwrap_or(highest).max(highest));
1071		let excerpt = state.excerpt_of_range(range, fields, &groups.touching(range))?;
1072		each(&excerpt, &in_part)?;
1073	}
1074	Ok(())
1075}
1076
1077/// The entities of a space merged together, in groups by the entity each group shows as,
1078/// with the merges of each group, which a part that the group touches needs: merges are
1079/// few, and a part takes only those of the groups it touches.
1080struct MergeGroups<'a> {
1081	merges: &'a [Recorded<'a>],
1082	/// The group of each entity that a merge names.
1083	group_of: BTreeMap<EntityId, EntityId>,
1084	/// The merges of each group, by their place in `merges`.
1085	of_group: BTreeMap<EntityId, Vec<usize>>,
1086}
1087
1088impl<'a> MergeGroups<'a> {
1089	/// The groups that `merges`, the current merges of a space, make.
1090	fn of(merges: &'a [Recorded<'a>]) -> Self {
1091		let mut all = Memory::default();
1092		for recorded in merges {
1093			all.insert(recorded.statement.clone().into_owned(), recorded.origin());
1094		}
1095		let all = State::in_storage(all);
1096		let mut group_of = BTreeMap::new();
1097		let mut of_group: BTreeMap<EntityId, Vec<usize>> = BTreeMap::new();
1098		for (index, recorded) in merges.iter().enumerate() {
1099			let statement = &recorded.statement;
1100			// A merge belongs to the group of the entity it merges, whose canonical entity it
1101			// decides, with that entity's other merges.
1102			let Ok(group) = all.canonical(statement.entity);
1103			of_group.entry(group).or_default().push(index);
1104			group_of.insert(statement.entity, group);
1105			if let Some(into) = statement.value.as_reference() {
1106				let Ok(group) = all.canonical(into);
1107				group_of.insert(into, group);
1108			}
1109		}
1110		Self {
1111			merges,
1112			group_of,
1113			of_group,
1114		}
1115	}
1116
1117	/// The merges of the groups that the entities from `first` to `last` belong to.
1118	fn touching(&self, (first, last): (EntityId, EntityId)) -> Vec<&'a Recorded<'a>> {
1119		let groups: BTreeSet<EntityId> = self
1120			.group_of
1121			.range(first..=last)
1122			.map(|(_, group)| *group)
1123			.collect();
1124		groups
1125			.iter()
1126			.filter_map(|group| self.of_group.get(group))
1127			.flatten()
1128			.map(|&index| &self.merges[index])
1129			.collect()
1130	}
1131}
1132
1133/// The canonical entities that current statements describe, as [`State::entities`] finds
1134/// them, that do not define types and are deleted or not, as `deleted` says: the things of
1135/// the space, or those that can be restored. They are told apart part by part.
1136fn entities_where<S: Statements>(
1137	state: &State<S>,
1138	deleted: bool,
1139	part: usize,
1140) -> Result<BTreeSet<EntityId>, NodeError>
1141where
1142	NodeError: From<S::Error>,
1143{
1144	let entities = state.storage().entities()?;
1145	let mut kept = BTreeSet::new();
1146	by_parts(state, &entities, (&KINDS, part), &mut |kinds, entities| {
1147		for &entity in entities {
1148			let entity = kinds.canonical(entity)?;
1149			if is_listed(kinds, entity, deleted)? {
1150				kept.insert(entity);
1151			}
1152		}
1153		Ok(())
1154	})?;
1155	Ok(kept)
1156}
1157
1158/// What a space holds, counted as [`listing`] and [`entities_where`] tell its entities
1159/// apart, in one pass over the space, `part` entities at a time.
1160fn census<S: Statements>(state: &State<S>, part: usize) -> Result<Census, NodeError>
1161where
1162	NodeError: From<S::Error>,
1163{
1164	let entities = state.storage().entities()?;
1165	// Entities merged together count once, as the one they show as, which may be in
1166	// another part.
1167	let mut seen = BTreeSet::new();
1168	let mut census = Census::default();
1169	by_parts(state, &entities, (&KINDS, part), &mut |kinds, entities| {
1170		for &entity in entities {
1171			let entity = kinds.canonical(entity)?;
1172			if !seen.insert(entity) || kept_apart::<Memory>(kinds, entity)? {
1173				continue;
1174			}
1175			if kinds.is_deleted(entity)? {
1176				census.deleted += 1;
1177			} else {
1178				census.things += 1;
1179				for name in kinds.types(entity)? {
1180					*census.types.entry(name).or_default() += 1;
1181				}
1182			}
1183		}
1184		Ok(())
1185	})?;
1186	Ok(census)
1187}
1188
1189/// Whether an entity is listed among the deleted or the others, as `deleted` says, by what
1190/// a part of the state says: never one that defines types.
1191fn is_listed(kinds: &State, entity: EntityId, deleted: bool) -> Result<bool, NodeError> {
1192	Ok(kinds.is_deleted(entity)? == deleted && !kept_apart(kinds, entity)?)
1193}
1194
1195/// Whether an entity is kept apart from those listed and counted: one that defines types,
1196/// or the record of a space's names in the personal space, which names a space.
1197pub(crate) fn kept_apart<S: Statements>(
1198	state: &State<S>,
1199	entity: EntityId,
1200) -> Result<bool, NodeError>
1201where
1202	NodeError: From<S::Error>,
1203{
1204	Ok(defines_types(state, entity)?
1205		|| state
1206			.types(entity)?
1207			.contains(&nibkeep_governance::SPACE_NAMES))
1208}
1209
1210/// Up to this many entities are listed by reading each from the state, which costs less
1211/// than reading the space part by part, as listing more does.
1212const FEW_LISTED: usize = 64;
1213
1214/// Entities of a stored space in a list, as [`listed`] lists them, read one by one when
1215/// they are few, or else part by part.
1216pub(crate) fn listed_from(
1217	state: &State<Layers<StateFile>>,
1218	types: &Types,
1219	languages: &Languages,
1220	(ids, part): (BTreeSet<EntityId>, usize),
1221) -> Result<Vec<Listed>, NodeError> {
1222	if ids.len() <= FEW_LISTED {
1223		return listed(state, types, languages, ids);
1224	}
1225	let ids: Vec<EntityId> = ids.into_iter().collect();
1226	let fields = naming_fields(state)?;
1227	let mut all = Vec::new();
1228	by_parts(state, &ids, (&fields, part), &mut |part, ids| {
1229		all.extend(listed_in(part, types, languages, ids.iter().copied())?);
1230		Ok(())
1231	})?;
1232	sort_listed(&mut all);
1233	Ok(all)
1234}
1235
1236/// Every thing of a space in a list, as [`listed`] lists them: told apart and named part by
1237/// part, `part` entities at a time, in one pass over the space.
1238fn listing<S: Statements>(
1239	state: &State<S>,
1240	types: &Types,
1241	languages: &Languages,
1242	part: usize,
1243) -> Result<Vec<Listed>, NodeError>
1244where
1245	NodeError: From<S::Error>,
1246{
1247	let entities = state.storage().entities()?;
1248	let fields = naming_fields(state)?;
1249	let mut seen = BTreeSet::new();
1250	let mut all = Vec::new();
1251	by_parts(state, &entities, (&fields, part), &mut |part, entities| {
1252		let mut new = Vec::new();
1253		for &entity in entities {
1254			let entity = part.canonical(entity)?;
1255			if !seen.contains(&entity) && is_listed(part, entity, false)? {
1256				seen.insert(entity);
1257				new.push(entity);
1258			}
1259		}
1260		all.extend(listed_in(part, types, languages, new)?);
1261		Ok(())
1262	})?;
1263	sort_listed(&mut all);
1264	Ok(all)
1265}
1266
1267/// Entities of a part of a space in a list, as [`listed`] lists them.
1268fn listed_in(
1269	part: &State,
1270	types: &Types,
1271	languages: &Languages,
1272	ids: impl IntoIterator<Item = EntityId>,
1273) -> Result<Vec<Listed>, NodeError> {
1274	listed(part, types, languages, ids)
1275}
1276
1277/// The fields that listing entities reads: those that say what an entity is, whether it is
1278/// deleted or merged, and what names it, which [`naming`] looks for in every field whose
1279/// name ends in a naming suffix.
1280fn naming_fields<S: Statements>(state: &State<S>) -> Result<Vec<FieldName>, NodeError>
1281where
1282	NodeError: From<S::Error>,
1283{
1284	let mut fields = KINDS.to_vec();
1285	for field in state.storage().field_names()? {
1286		if fields::can_name(&field) {
1287			fields.push(field);
1288		}
1289	}
1290	Ok(fields)
1291}
1292
1293/// Whether an entity defines a type or a field.
1294pub(crate) fn defines_types<S: Statements>(
1295	state: &State<S>,
1296	entity: EntityId,
1297) -> Result<bool, NodeError>
1298where
1299	NodeError: From<S::Error>,
1300{
1301	let types = state.types(entity)?;
1302	Ok(types.contains(&TYPE_DEFINITION) || types.contains(&FIELD_DEFINITION))
1303}
1304
1305/// Entities in a list, ordered by name without regard to case, unnamed ones last.
1306fn listed<S: Statements>(
1307	state: &State<S>,
1308	types: &Types,
1309	languages: &Languages,
1310	ids: impl IntoIterator<Item = EntityId>,
1311) -> Result<Vec<Listed>, NodeError>
1312where
1313	NodeError: From<S::Error>,
1314{
1315	let mut listed = Vec::new();
1316	for id in ids {
1317		listed.push(Listed {
1318			id,
1319			name: display_name(state, types, languages, id)?,
1320			types: state.types(id)?.into_iter().collect(),
1321			via: None,
1322		});
1323	}
1324	sort_listed(&mut listed);
1325	Ok(listed)
1326}
1327
1328/// Orders a list by name without regard to case, unnamed entities last.
1329fn sort_listed(listed: &mut [Listed]) {
1330	listed.sort_by_cached_key(|entity| {
1331		let name = entity.name.as_deref().map(str::to_lowercase);
1332		(name.is_none(), name, entity.id)
1333	});
1334}
1335
1336/// The operations of one edit of an entity, as the state stands after the edits before it.
1337fn edit_operations<S: Statements>(
1338	state: &State<S>,
1339	types: &Types,
1340	languages: &Languages,
1341	entity: EntityId,
1342	edit: Edit,
1343	dating: &Dating,
1344	rng: &mut impl CryptoRng,
1345) -> Result<Vec<Operation>, NodeError>
1346where
1347	NodeError: From<S::Error>,
1348{
1349	if let Edit::Set(field, _)
1350	| Edit::Add(field, _)
1351	| Edit::Remove(field, _)
1352	| Edit::RemoveForm(field, _)
1353	| Edit::RemoveFormIn { field, .. }
1354	| Edit::AddForm { field, .. } = &edit
1355		&& (fields::is_reserved(field) || policies::is_own_field(field))
1356	{
1357		return Err(NodeError::OwnField(field.clone()));
1358	}
1359	let mut assert =
1360		|field: FieldName, value: Value, qualifiers: Qualifiers, supersedes: Vec<StatementId>| {
1361			let qualifiers = for_field(types, &field, qualifiers);
1362			let statement = Statement::new(StatementId::random(rng), entity, field, value)
1363				.with_qualifiers(qualifiers);
1364			Operation::replace(statement, supersedes)
1365		};
1366	let language = dating.language.as_ref();
1367	let at = (entity, dating.day);
1368	Ok(match edit {
1369		Edit::Set(field, values) => {
1370			let Some(Setting {
1371				mut supersedes,
1372				valid_time,
1373				form,
1374			}) = setting(state, types, languages, entity, &field, &values, dating)?
1375			else {
1376				return Ok(Vec::new());
1377			};
1378			if values.is_empty() {
1379				return Ok(vec![Operation::retract(entity, supersedes)]);
1380			}
1381			values
1382				.into_iter()
1383				.map(|value| {
1384					let qualifiers = corrected(valid_time.clone(), form.as_ref(), &value, language);
1385					assert(
1386						field.clone(),
1387						value,
1388						qualifiers,
1389						std::mem::take(&mut supersedes),
1390					)
1391				})
1392				.collect()
1393		}
1394		Edit::AddForm { field, of, value } => {
1395			let shown = resolve(state, types, languages, entity, &field, dating.day)?.0;
1396			let target = form_of(state, entity, &field, &shown, of.as_ref())?;
1397			// Forms of one value share its valid time.
1398			let group = target.qualifiers.alternative().unwrap_or(target.id);
1399			let qualifiers = dated(target.qualifiers.valid_time().cloned())
1400				.with(fields::ALTERNATIVE, Value::Text(group.to_string()));
1401			let qualifiers = in_language(qualifiers, &value, language);
1402			vec![assert(field, value, qualifiers, Vec::new())]
1403		}
1404		Edit::Add(field, value) => {
1405			// In a field with one value, a value added on another day than today starts on
1406			// that day, and one added today starts now if the field's values are dated.
1407			let definition = types.field(&field);
1408			let one = is_multiplicity(definition.as_ref(), Multiplicity::One);
1409			let starts = match &dating.valid_time {
1410				Some(valid_time) => Some(valid_time.clone()),
1411				None if one
1412					&& (dating.now.is_none()
1413						|| dated_one(state, definition.as_ref(), entity, &field)?) =>
1414				{
1415					Some(dating.start())
1416				}
1417				None => None,
1418			};
1419			let qualifiers = in_language(dated(starts), &value, language);
1420			vec![assert(field, value, qualifiers, Vec::new())]
1421		}
1422		Edit::Remove(..) | Edit::RemoveForm(..) | Edit::RemoveFormIn { .. } => {
1423			removal_of(state, types, languages, at, edit)?
1424		}
1425		Edit::Delete if state.is_deleted(entity)? => Vec::new(),
1426		Edit::Delete => vec![assert(
1427			fields::DELETED,
1428			Value::Boolean(true),
1429			Qualifiers::new(),
1430			Vec::new(),
1431		)],
1432		Edit::Restore => {
1433			let deletions = ids(&state.current(entity, &fields::DELETED)?);
1434			if deletions.is_empty() {
1435				Vec::new()
1436			} else {
1437				vec![Operation::retract(entity, deletions)]
1438			}
1439		}
1440		Edit::AddType(_) | Edit::RemoveType(_) => type_operations(state, entity, edit, rng)?,
1441	})
1442}
1443
1444/// The operations that give an entity a type or take one away.
1445fn type_operations<S: Statements>(
1446	state: &State<S>,
1447	entity: EntityId,
1448	edit: Edit,
1449	rng: &mut impl CryptoRng,
1450) -> Result<Vec<Operation>, NodeError>
1451where
1452	NodeError: From<S::Error>,
1453{
1454	let types = state.types(entity)?;
1455	// The records of users, devices, replicas and spaces keep the types NibKeep gave them.
1456	let record = super::export::OWN_RECORDS
1457		.into_iter()
1458		.find(|own| types.contains(own));
1459	Ok(match edit {
1460		Edit::AddType(name) => {
1461			refuse_own_type(&name)?;
1462			if types.contains(&name) {
1463				Vec::new()
1464			} else if let Some(record) = record {
1465				return Err(NodeError::OwnType(record.clone()));
1466			} else {
1467				let statement = Statement::new(
1468					StatementId::random(rng),
1469					entity,
1470					fields::TYPE,
1471					Value::Text(name.to_string()),
1472				);
1473				vec![Operation::assert(statement)]
1474			}
1475		}
1476		Edit::RemoveType(name) => {
1477			refuse_own_type(&name)?;
1478			if let Some(record) = record {
1479				return Err(NodeError::OwnType(record.clone()));
1480			}
1481			if !types.contains(&name) {
1482				return Err(NodeError::NotOfType(name));
1483			}
1484			if types.len() == 1 {
1485				return Err(NodeError::OnlyType(name));
1486			}
1487			let statements: Vec<StatementId> = state
1488				.current(entity, &fields::TYPE)?
1489				.iter()
1490				.filter(|statement| {
1491					statement
1492						.value
1493						.as_text()
1494						.and_then(|text| text.parse::<TypeName>().ok())
1495						== Some(name.clone())
1496				})
1497				.map(|statement| statement.id)
1498				.collect();
1499			vec![Operation::retract(entity, statements)]
1500		}
1501		_ => unreachable!("only edits of types come here"),
1502	})
1503}
1504
1505/// Refuses a type that only NibKeep's own operations give to entities or take away: those
1506/// that define types and fields, storage policies and rules, and the records of users,
1507/// devices, replicas and spaces.
1508fn refuse_own_type(name: &TypeName) -> Result<(), NodeError> {
1509	if *name == TYPE_DEFINITION
1510		|| *name == FIELD_DEFINITION
1511		|| policies::is_own_type(name)
1512		|| super::export::OWN_RECORDS.contains(name)
1513	{
1514		return Err(NodeError::OwnType(name.clone()));
1515	}
1516	Ok(())
1517}
1518
1519/// The operations of an edit that removes values or forms.
1520fn removal_of<S: Statements>(
1521	state: &State<S>,
1522	types: &Types,
1523	languages: &Languages,
1524	at: (EntityId, Day),
1525	edit: Edit,
1526) -> Result<Vec<Operation>, NodeError>
1527where
1528	NodeError: From<S::Error>,
1529{
1530	match edit {
1531		Edit::Remove(field, value) => {
1532			removal(state, types, languages, at, field, &value, Removing::Whole)
1533		}
1534		Edit::RemoveForm(field, value) => {
1535			removal(state, types, languages, at, field, &value, Removing::Forms)
1536		}
1537		Edit::RemoveFormIn {
1538			field,
1539			value,
1540			language,
1541		} => {
1542			let removing = Removing::FormsIn(language.as_ref());
1543			removal(state, types, languages, at, field, &value, removing)
1544		}
1545		_ => Ok(Vec::new()),
1546	}
1547}
1548
1549/// What a removal takes: whole values, with every form, or forms alone, in any language or
1550/// in one.
1551#[derive(Clone, Copy)]
1552enum Removing<'a> {
1553	Whole,
1554	Forms,
1555	FormsIn(Option<&'a Tag>),
1556}
1557
1558/// The operations that remove `value` from an entity's field as shown on a day: with
1559/// `whole`, every form of the values that it names, in any of their forms; otherwise the
1560/// forms of the values shown that hold it.
1561fn removal<S: Statements>(
1562	state: &State<S>,
1563	types: &Types,
1564	languages: &Languages,
1565	(entity, day): (EntityId, Day),
1566	field: FieldName,
1567	value: &Value,
1568	removing: Removing<'_>,
1569) -> Result<Vec<Operation>, NodeError>
1570where
1571	NodeError: From<S::Error>,
1572{
1573	let shown = resolve(state, types, languages, entity, &field, day)?.0;
1574	let values = values_shown(state, entity, &field, &shown)?;
1575	let whole = matches!(removing, Removing::Whole);
1576	let forms: Vec<Cow<'_, Statement>> = match removing {
1577		Removing::Whole => values
1578			.into_iter()
1579			.filter(|forms| forms.iter().any(|form| removes(&form.value, value)))
1580			.flatten()
1581			.collect(),
1582		Removing::Forms => values
1583			.into_iter()
1584			.flatten()
1585			.filter(|form| removes(&form.value, value))
1586			.collect(),
1587		Removing::FormsIn(language) => values
1588			.into_iter()
1589			.flatten()
1590			.filter(|form| {
1591				removes(&form.value, value)
1592					&& match (form.qualifiers.language(), language) {
1593						(None, None) => true,
1594						(Some(written), Some(language)) => {
1595							Tag::parse(written).as_ref() == Some(language)
1596						}
1597						_ => false,
1598					}
1599			})
1600			.collect(),
1601	};
1602	if forms.is_empty() {
1603		return Err(NodeError::NoValue(field));
1604	}
1605	// A field that shows the value recorded last also has older values, which removing the
1606	// one it shows must not bring back; any other field keeps the value on other days.
1607	let removed =
1608		if whole && is_multiplicity(types.field(&field).as_ref(), Multiplicity::LastWriterWins) {
1609			state.current(entity, &field)?
1610		} else {
1611			with_repeats(state, entity, &field, &forms)?
1612		};
1613	Ok(vec![Operation::retract(entity, ids(&removed))])
1614}
1615
1616/// The value of `of`, in any of its forms, among the values a field shows, or, without it,
1617/// the only value the field shows: the value that a new form is of.
1618fn form_of<'a, S: Statements>(
1619	state: &State<S>,
1620	entity: EntityId,
1621	field: &FieldName,
1622	shown: &'a [Cow<'a, Statement>],
1623	of: Option<&Value>,
1624) -> Result<&'a Statement, NodeError>
1625where
1626	NodeError: From<S::Error>,
1627{
1628	let Some(of) = of else {
1629		return match shown {
1630			[] => Err(NodeError::NoValue(field.clone())),
1631			[one] => Ok(one),
1632			_ => Err(NodeError::WhichValue(field.clone())),
1633		};
1634	};
1635	let values = values_shown(state, entity, field, shown)?;
1636	for statement in shown {
1637		let said = content(statement);
1638		let named = values.iter().any(|forms| {
1639			forms.iter().any(|form| content(form) == said)
1640				&& forms.iter().any(|form| removes(&form.value, of))
1641		});
1642		if named {
1643			return Ok(statement);
1644		}
1645	}
1646	Err(NodeError::NoValue(field.clone()))
1647}
1648
1649/// The values that shown statements stand for, each with every form it has.
1650fn values_shown<'a, S: Statements>(
1651	state: &'a State<S>,
1652	entity: EntityId,
1653	field: &FieldName,
1654	shown: &[Cow<'_, Statement>],
1655) -> Result<Vec<Vec<Cow<'a, Statement>>>, NodeError>
1656where
1657	NodeError: From<S::Error>,
1658{
1659	let said: BTreeSet<(Vec<u8>, Vec<u8>)> = shown.iter().map(|each| content(each)).collect();
1660	Ok(state
1661		.form_groups(entity, field)?
1662		.into_iter()
1663		.filter(|forms| forms.iter().any(|form| said.contains(&content(form))))
1664		.collect())
1665}
1666
1667/// The qualifiers of a value that a person sets: its valid time, and, when it corrects one
1668/// form of a value, the group of forms, which it stays in, and the form's language, unless
1669/// the person gave another.
1670fn corrected(
1671	valid_time: Option<Edtf>,
1672	form: Option<&Form>,
1673	value: &Value,
1674	language: Option<&Tag>,
1675) -> Qualifiers {
1676	let mut qualifiers = dated(valid_time);
1677	if let Some(Form {
1678		group,
1679		language: was,
1680	}) = form
1681	{
1682		qualifiers.insert(fields::ALTERNATIVE, Value::Text(group.to_string()));
1683		if language.is_none()
1684			&& let Some(was) = was
1685		{
1686			qualifiers.insert(fields::LANGUAGE, Value::Text(was.clone()));
1687		}
1688	}
1689	in_language(qualifiers, value, language)
1690}
1691
1692/// Qualifiers with a valid time, if given.
1693fn dated(valid_time: Option<Edtf>) -> Qualifiers {
1694	match valid_time {
1695		Some(valid_time) => Qualifiers::new().with(fields::VALID_TIME, Value::Date(valid_time)),
1696		None => Qualifiers::new(),
1697	}
1698}
1699
1700/// Qualifiers with the language of a value, if it has one: text, names and files can be in
1701/// a language; numbers, dates and references cannot.
1702fn in_language(mut qualifiers: Qualifiers, value: &Value, language: Option<&Tag>) -> Qualifiers {
1703	if let Some(language) = language
1704		&& matches!(value, Value::Text(_) | Value::Name(_) | Value::Blob(_))
1705	{
1706		qualifiers.insert(fields::LANGUAGE, Value::Text(language.to_string()));
1707	}
1708	qualifiers
1709}
1710
1711/// The qualifiers of a value of a field, without a language if the field holds codes, which
1712/// are in no language: a language given for every value written is not theirs.
1713fn for_field(types: &Types, field: &FieldName, mut qualifiers: Qualifiers) -> Qualifiers {
1714	if types
1715		.field(field)
1716		.is_some_and(|definition| definition.is_code())
1717	{
1718		qualifiers.remove(&fields::LANGUAGE);
1719	}
1720	qualifiers
1721}
1722
1723/// The IDs of statements.
1724fn ids(statements: &[Cow<'_, Statement>]) -> Vec<StatementId> {
1725	statements.iter().map(|statement| statement.id).collect()
1726}
1727
1728/// Whether statements hold exactly these values, each as often.
1729fn same_values(statements: &[Cow<'_, Statement>], values: &[Value]) -> bool {
1730	let mut left: Vec<&Value> = statements
1731		.iter()
1732		.map(|statement| &statement.value)
1733		.collect();
1734	for value in values {
1735		match left.iter().position(|held| *held == value) {
1736			Some(index) => {
1737				left.swap_remove(index);
1738			}
1739			None => return false,
1740		}
1741	}
1742	left.is_empty()
1743}
1744
1745/// Whether a field takes one value: one that competes, or the one recorded last.
1746fn has_one_value(types: &Types, field: &FieldName) -> bool {
1747	types.field(field).is_some_and(|definition| {
1748		matches!(
1749			definition.multiplicity(),
1750			Multiplicity::One | Multiplicity::LastWriterWins
1751		)
1752	})
1753}
1754
1755/// What setting a field does.
1756struct Setting {
1757	/// The statements it supersedes.
1758	supersedes: Vec<StatementId>,
1759	/// The valid time of the values it writes.
1760	valid_time: Option<Edtf>,
1761	/// The group of forms that the value it writes joins, when it corrects one form of a
1762	/// value that has others, or one that names its group.
1763	form: Option<Form>,
1764}
1765
1766/// A form of a value that a correction replaces.
1767struct Form {
1768	/// The ID that names the group of forms.
1769	group: StatementId,
1770	/// The language tag of the form, as written.
1771	language: Option<String>,
1772}
1773
1774/// What setting a field to `values` does, or `None` if the field already shows them.
1775fn setting<S: Statements>(
1776	state: &State<S>,
1777	types: &Types,
1778	languages: &Languages,
1779	entity: EntityId,
1780	field: &FieldName,
1781	values: &[Value],
1782	dating: &Dating,
1783) -> Result<Option<Setting>, NodeError>
1784where
1785	NodeError: From<S::Error>,
1786{
1787	if values.len() > 1 && has_one_value(types, field) {
1788		return Err(NodeError::OneValue(field.clone()));
1789	}
1790	let definition = types.field(field);
1791	// A field whose last writer wins hides older values, which setting it replaces too; any
1792	// other field keeps what belongs to other days. One value set in place of the one value
1793	// shown corrects the form shown; other settings replace the values shown, every form.
1794	let shown = resolve(state, types, languages, entity, field, dating.day)?.0;
1795	let last_writer_wins = is_multiplicity(definition.as_ref(), Multiplicity::LastWriterWins);
1796	let correcting = !last_writer_wins && shown.len() == 1 && values.len() == 1;
1797	let replaced = if last_writer_wins {
1798		state.current(entity, field)?
1799	} else if correcting {
1800		with_repeats(state, entity, field, &shown)?
1801	} else {
1802		let forms: Vec<Cow<'_, Statement>> = values_shown(state, entity, field, &shown)?
1803			.into_iter()
1804			.flatten()
1805			.collect();
1806		with_repeats(state, entity, field, &forms)?
1807	};
1808	let unchanged = same_values(&shown, values)
1809		&& dating.valid_time.as_ref().is_none_or(|valid_time| {
1810			shown
1811				.iter()
1812				.all(|statement| statement.qualifiers.valid_time() == Some(valid_time))
1813		});
1814	if unchanged {
1815		return Ok(None);
1816	}
1817	let valid_time = match &dating.valid_time {
1818		Some(valid_time) => Some(valid_time.clone()),
1819		// A correction keeps the date of what it replaces, the last of them in the field's
1820		// order; a value on a day that showed nothing starts on that day.
1821		None if dated_one(state, definition.as_ref(), entity, field)? => match replaced
1822			.iter()
1823			.max_by_key(|statement| statement.qualifiers.valid_time().map(Edtf::start))
1824		{
1825			Some(last) => last.qualifiers.valid_time().cloned(),
1826			None => Some(dating.start()),
1827		},
1828		None => None,
1829	};
1830	// One value that corrects one form keeps it among the others.
1831	let form = match shown.as_slice() {
1832		[corrected] if correcting => {
1833			let group = corrected.qualifiers.alternative();
1834			let others = state.forms(entity, field, corrected.id)?.len() > 1;
1835			(group.is_some() || others).then(|| Form {
1836				group: group.unwrap_or(corrected.id),
1837				language: corrected.qualifiers.language().map(str::to_owned),
1838			})
1839		}
1840		_ => None,
1841	};
1842	Ok(Some(Setting {
1843		supersedes: ids(&replaced),
1844		valid_time,
1845		form,
1846	}))
1847}
1848
1849/// Shown statements, with the current statements of the field that repeat their value and
1850/// qualifiers, which show as one with them and go with them.
1851fn with_repeats<'a, S: Statements>(
1852	state: &'a State<S>,
1853	entity: EntityId,
1854	field: &FieldName,
1855	shown: &[Cow<'a, Statement>],
1856) -> Result<Vec<Cow<'a, Statement>>, NodeError>
1857where
1858	NodeError: From<S::Error>,
1859{
1860	let shown: BTreeSet<(Vec<u8>, Vec<u8>)> =
1861		shown.iter().map(|statement| content(statement)).collect();
1862	Ok(state
1863		.current(entity, field)?
1864		.into_iter()
1865		.filter(|statement| shown.contains(&content(statement)))
1866		.collect())
1867}
1868
1869/// Whether removing `value` removes a value shown: the same value, or, for a name given only
1870/// in full, any name or text written that way, whatever other parts it has.
1871fn removes(shown: &Value, value: &Value) -> bool {
1872	if shown == value {
1873		return true;
1874	}
1875	match value {
1876		Value::Name(name) if name.parts().count() == 1 => shown.as_name_text() == Some(name.full()),
1877		_ => false,
1878	}
1879}
1880
1881/// Whether a field definition has a multiplicity.
1882fn is_multiplicity(definition: Option<&FieldDef>, multiplicity: Multiplicity) -> bool {
1883	definition.is_some_and(|definition| definition.multiplicity() == multiplicity)
1884}
1885
1886/// Whether a field has one value, and some of its values are dated: then a value written
1887/// without a valid time would count as earlier than all of them, and never show, so it
1888/// gets one of its own.
1889fn dated_one<S: Statements>(
1890	state: &State<S>,
1891	definition: Option<&FieldDef>,
1892	entity: EntityId,
1893	field: &FieldName,
1894) -> Result<bool, NodeError>
1895where
1896	NodeError: From<S::Error>,
1897{
1898	Ok(is_multiplicity(definition, Multiplicity::One)
1899		&& state
1900			.current(entity, field)?
1901			.iter()
1902			.any(|statement| statement.qualifiers.valid_time().is_some()))
1903}
1904
1905/// The values of a field to show on `day`, as the field's definition says, each in the form
1906/// that suits a reader of `languages`, and whether they compete.
1907pub(crate) fn resolve<'a, S: Statements>(
1908	state: &'a State<S>,
1909	types: &Types,
1910	languages: &Languages,
1911	entity: EntityId,
1912	field: &FieldName,
1913	day: Day,
1914) -> Result<(Vec<Cow<'a, Statement>>, bool), NodeError>
1915where
1916	NodeError: From<S::Error>,
1917{
1918	Ok(
1919		match state.resolve_for(entity, field, types.field(field).as_ref(), day, languages)? {
1920			Resolution::Values(statements) => (statements, false),
1921			Resolution::Competing(statements) => (statements, true),
1922		},
1923	)
1924}
1925
1926/// The last day there is: names are shown as of it, so that an entity is named by the name
1927/// it has now, the last that started, unless its own period has ended. A name dated in the
1928/// future would show before its day.
1929fn last_day() -> Day {
1930	Day::from_ymd(999_999_999_999_999, 12, 31).expect("the last day of the largest year")
1931}
1932
1933/// The name to show for an entity in lists and searches: its name as of the latest values,
1934/// as [`name_on`] finds it.
1935pub(crate) fn display_name<S: Statements>(
1936	state: &State<S>,
1937	types: &Types,
1938	languages: &Languages,
1939	entity: EntityId,
1940) -> Result<Option<String>, NodeError>
1941where
1942	NodeError: From<S::Error>,
1943{
1944	name_on(state, types, languages, entity, last_day())
1945}
1946
1947/// The entity that a field refers to, as of the latest values: of several, the first that
1948/// the field shows. Of entities merged together, the one they were merged into.
1949pub(crate) fn referred<S: Statements>(
1950	state: &State<S>,
1951	types: &Types,
1952	languages: &Languages,
1953	entity: EntityId,
1954	field: &FieldName,
1955) -> Result<Option<EntityId>, NodeError>
1956where
1957	NodeError: From<S::Error>,
1958{
1959	let referred = resolve(state, types, languages, entity, field, last_day())?
1960		.0
1961		.iter()
1962		.find_map(|statement| statement.value.as_reference());
1963	Ok(match referred {
1964		Some(referred) => Some(state.canonical(referred)?),
1965		None => None,
1966	})
1967}
1968
1969/// A user as history names them, and the person linked to the user in the space, if any
1970/// and not deleted: the name of that person, or else the user's own name.
1971pub(crate) fn user_name<S: Statements>(
1972	state: &State<S>,
1973	types: &Types,
1974	languages: &Languages,
1975	user: EntityId,
1976) -> Result<(Option<String>, Option<EntityId>), NodeError>
1977where
1978	NodeError: From<S::Error>,
1979{
1980	let mut person = referred(state, types, languages, user, &LINKED_PERSON)?;
1981	if let Some(linked) = person
1982		&& state.is_deleted(linked)?
1983	{
1984		person = None;
1985	}
1986	if let Some(person) = person
1987		&& let Some(name) = display_name(state, types, languages, person)?
1988	{
1989		return Ok((Some(name), Some(person)));
1990	}
1991	Ok((display_name(state, types, languages, user)?, person))
1992}
1993
1994/// The field that names an entity, and its statements that show a name.
1995type Naming<'a> = (FieldName, Vec<Cow<'a, Statement>>);
1996
1997/// The field that names an entity on `day`, and the value it shows, in the form that suits
1998/// a reader of `languages`: `org.nibkeep.name`, or else the first field by name that ends
1999/// in `.name`, or else in `.title`, that shows a name written in full, or text, each
2000/// resolved as the field's definition says. Of several values, the first that the field
2001/// shows counts, in the order of `docs/spec/model.md`, section 6.
2002fn naming<'a, S: Statements>(
2003	state: &'a State<S>,
2004	types: &Types,
2005	languages: &Languages,
2006	entity: EntityId,
2007	day: Day,
2008) -> Result<Option<Naming<'a>>, NodeError>
2009where
2010	NodeError: From<S::Error>,
2011{
2012	// The statements of the field that show a name, in the order the field shows them.
2013	let shown = |field: &FieldName| -> Result<Vec<Cow<'a, Statement>>, NodeError> {
2014		Ok(resolve(state, types, languages, entity, field, day)?
2015			.0
2016			.into_iter()
2017			.filter(|statement| statement.value.as_name_text().is_some())
2018			.collect())
2019	};
2020	let named = shown(&NAME)?;
2021	if !named.is_empty() {
2022		return Ok(Some((NAME, named)));
2023	}
2024	let fields = state.fields(entity)?;
2025	for suffix in fields::NAMING_SUFFIXES {
2026		for field in fields
2027			.iter()
2028			.filter(|field| fields::has_suffix(field, suffix))
2029		{
2030			let named = shown(field)?;
2031			if !named.is_empty() {
2032				return Ok(Some((field.clone(), named)));
2033			}
2034		}
2035	}
2036	Ok(None)
2037}
2038
2039/// The name of an entity on `day`, as a reader of `languages` sees it: the name that
2040/// [`naming`] finds, written in full, or text.
2041pub(crate) fn name_on<S: Statements>(
2042	state: &State<S>,
2043	types: &Types,
2044	languages: &Languages,
2045	entity: EntityId,
2046	day: Day,
2047) -> Result<Option<String>, NodeError>
2048where
2049	NodeError: From<S::Error>,
2050{
2051	Ok(naming(state, types, languages, entity, day)?
2052		.and_then(|(_, statements)| statements.into_iter().next())
2053		.and_then(|statement| statement.value.as_name_text().map(str::to_owned)))
2054}
2055
2056/// The names an entity has now, in every form, lowercased, by which it is found: the forms
2057/// of every name that the field [`naming`] finds shows as of the last day, competing names
2058/// included; and of entities merged into it, their own names too, whichever fields name them.
2059fn names_now<S: Statements>(
2060	state: &State<S>,
2061	types: &Types,
2062	entity: EntityId,
2063) -> Result<Vec<String>, NodeError>
2064where
2065	NodeError: From<S::Error>,
2066{
2067	let mut names = Vec::new();
2068	if let Some((field, shown)) = naming(state, types, &Languages::default(), entity, last_day())? {
2069		for statement in shown {
2070			for form in &state.forms(entity, &field, statement.id)? {
2071				if let Some(name) = form.value.as_name_text() {
2072					names.push(name.to_lowercase());
2073				}
2074			}
2075		}
2076	}
2077	for member in state.merged(entity)? {
2078		if member != entity {
2079			names.extend(
2080				super::merge::own_names_in(state, member)?
2081					.iter()
2082					.map(|name| name.to_lowercase()),
2083			);
2084		}
2085	}
2086	Ok(names)
2087}
2088
2089#[cfg(test)]
2090mod tests {
2091	use nibkeep_crypto::PassphraseParams;
2092	use nibkeep_keys::NewProtection;
2093	use nibkeep_testkit::{TestRng, millis_at};
2094
2095	use super::*;
2096	use crate::NewLibrary;
2097
2098	#[test]
2099	fn a_space_read_in_parts_lists_what_it_lists_read_at_once() {
2100		let mut rng = TestRng::new("in parts");
2101		let directory = nibkeep_testkit::empty_directory(
2102			std::env::temp_dir(),
2103			&format!("nibkeep-entities-in-parts-{}", std::process::id()),
2104		);
2105		let now = millis_at("2026-10-24", 12, 0);
2106		let protection = NewProtection::Passphrase(
2107			"correct horse",
2108			PassphraseParams::new(64, 1, 1).expect("valid"),
2109		);
2110		let mut library = Library::create(
2111			&directory,
2112			&NewLibrary::new("Ada", "laptop", "nib"),
2113			&protection,
2114			now,
2115			&mut rng,
2116		)
2117		.expect("creates");
2118		let space = library.personal_space();
2119		let mut made = Vec::new();
2120		for n in 0..90 {
2121			// Every fifth has no name, only a note.
2122			let values = if n % 5 == 4 {
2123				let note: FieldName = "local.note".parse().expect("a field name");
2124				vec![(note, Value::Text(format!("note {n}")))]
2125			} else {
2126				vec![(
2127					fields::NAME,
2128					Value::Name(nibkeep_model::Name::new(format!("thing {n}"))),
2129				)]
2130			};
2131			made.push(
2132				library
2133					.create_entity(space, &[], values, now, &mut rng)
2134					.expect("creates"),
2135			);
2136		}
2137		// Merges between entities far apart by ID, so across parts, a chain of them, and a
2138		// deletion, of a merged entity too.
2139		let mut sorted = made.clone();
2140		sorted.sort();
2141		for (from, into) in [(0, 89), (89, 11), (5, 6), (17, 2), (40, 41)] {
2142			library
2143				.merge_entities(space, sorted[from], sorted[into], now, &mut rng)
2144				.expect("merges");
2145		}
2146		let dating = Dating::today(now, 0).expect("a day");
2147		for deleted in [sorted[11], sorted[8]] {
2148			library
2149				.edit_entity(space, deleted, vec![Edit::Delete], &dating, now, &mut rng)
2150				.expect("deletes");
2151		}
2152		let open = library.space(space).expect("a space");
2153		let state = open.stored.log().state();
2154		let at_once = |part| listing(state, &open.types, &library.languages, part).expect("lists");
2155		assert_eq!(at_once(2), at_once(100_000));
2156		for deleted in [false, true] {
2157			assert_eq!(
2158				entities_where(state, deleted, 3).expect("tells apart"),
2159				entities_where(state, deleted, 100_000).expect("tells apart"),
2160			);
2161		}
2162		assert!(
2163			entities_where(state, true, 3)
2164				.expect("tells apart")
2165				.contains(&state.canonical(sorted[0]).expect("reads")),
2166			"deleted through the entity it is merged into"
2167		);
2168		// More than a few chosen ones, spread over the space, listed part by part as each alone.
2169		let chosen: BTreeSet<EntityId> = entities_where(state, false, 100_000)
2170			.expect("tells apart")
2171			.into_iter()
2172			.enumerate()
2173			.filter(|(n, _)| n % 10 != 3)
2174			.map(|(_, entity)| entity)
2175			.collect();
2176		assert!(chosen.len() > FEW_LISTED);
2177		assert_eq!(
2178			listed_from(state, &open.types, &library.languages, (chosen.clone(), 3))
2179				.expect("lists"),
2180			listed(state, &open.types, &library.languages, chosen).expect("lists"),
2181		);
2182		drop(library);
2183		let _ = std::fs::remove_dir_all(directory);
2184	}
2185}