Skip to main content

nibkeep_node/library/
history.rs

1//! History in system time: every value an entity has had, when it was recorded, by whom and
2//! when it was replaced; and an entity, and what links to it, as the library had recorded it
3//! at a moment (`docs/Design.md`, Q18; `docs/spec/time.md`, section 3).
4
5use nibkeep_base::{EntityId, SpaceId, StatementId};
6use std::collections::BTreeMap;
7
8use nibkeep_model::storage::Statements as _;
9use nibkeep_model::{FieldName, Qualifiers, Value, fields};
10use nibkeep_time::{Day, Edtf, Timestamp};
11
12use super::entities::{EntityView, display_name, entity_view};
13use super::links::{Links, links_to};
14use super::{Author, Library};
15use crate::NodeError;
16
17/// Every value an entity has had, by field.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct History {
20	/// The entity, or of entities merged together, the one they were merged into.
21	pub id: EntityId,
22	/// The name to show for it, if it has one.
23	pub name: Option<String>,
24	/// Its fields, those of its types and of its own record included, ordered by name.
25	pub fields: Vec<FieldHistory>,
26}
27
28/// Every value of one field of an entity, in the order they were recorded.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct FieldHistory {
31	/// The field.
32	pub field: FieldName,
33	/// Its values, current and replaced.
34	pub values: Vec<PastValue>,
35}
36
37/// A value an entity had, or has.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct PastValue {
40	/// The statement that holds it.
41	pub statement: StatementId,
42	/// The value.
43	pub value: Value,
44	/// When it was true, if it says.
45	pub valid_time: Option<Edtf>,
46	/// Its language tag, if it has one.
47	pub language: Option<String>,
48	/// When it was first recorded.
49	pub recorded: Timestamp,
50	/// When a purge stated it again, if one did.
51	pub restated: Option<Timestamp>,
52	/// When it was replaced, corrected or removed, if it was.
53	pub replaced: Option<Timestamp>,
54	/// Who recorded it, as far as the space knows.
55	pub author: Option<Author>,
56	/// What the move that carried it from another space noted of it, if one did: the
57	/// mover's account, which only that space proves.
58	pub carried: Option<Carried>,
59}
60
61/// What a move noted of a value that it carried from another space, as its mover's account
62/// of it, not as proof ([technical design: spaces and moves]).
63///
64/// [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Carried {
67	/// The space it came from, if the note names it.
68	pub from: Option<SpaceId>,
69	/// That space's name, if this replica holds it.
70	pub from_name: Option<String>,
71	/// Who recorded it there, as far as this space, or else the personal space, knows the key
72	/// that the note names.
73	pub author: Option<Author>,
74	/// When it was recorded there: milliseconds since 1970.
75	pub recorded: Option<u64>,
76	/// When it was replaced there, if it was: milliseconds since 1970.
77	pub replaced: Option<u64>,
78}
79
80/// The authors and the names of spaces that moves noted, as a history found them, so that
81/// each is found once.
82#[derive(Default)]
83struct Noted {
84	authors: BTreeMap<String, Option<Author>>,
85	spaces: BTreeMap<SpaceId, Option<String>>,
86}
87
88impl Library {
89	/// Every value an entity of a space has had, or one field's, with when each was recorded,
90	/// by whom, and when it was replaced: the history of the record, in system time. Of
91	/// entities merged together, the values of all of them. `None` if the space says nothing
92	/// about the entity. Values that were purged are gone; secret values that this replica
93	/// has not opened are left out.
94	///
95	/// # Errors
96	///
97	/// Returns an error if the library has no such space, or the space cannot be read.
98	pub fn history(
99		&self,
100		space: SpaceId,
101		entity: EntityId,
102		field: Option<&FieldName>,
103	) -> Result<Option<History>, NodeError> {
104		let open = self.space(space)?;
105		open.stored.reading(|stored| {
106			let log = stored.log();
107			let state = log.state();
108			let storage = state.storage();
109			let entity = state.canonical(entity)?;
110			if state.fields(entity)?.is_empty() && state.merged(entity)?.len() <= 1 {
111				let none = storage
112					.of_entity(entity)?
113					.iter()
114					.all(|(_, ids)| ids.is_empty());
115				if none {
116					return Ok(None);
117				}
118			}
119			// Most values have one of a few authors, each found once.
120			let mut authors: BTreeMap<String, Option<Author>> = BTreeMap::new();
121			// And the authors and spaces that moves noted, each found once.
122			let mut noted = Noted::default();
123			let mut by_field: BTreeMap<FieldName, Vec<PastValue>> = BTreeMap::new();
124			for member in state.merged(entity)? {
125				for (name, ids) in storage.of_entity(member)? {
126					if field.is_some_and(|wanted| *wanted != name) {
127						continue;
128					}
129					for id in ids {
130						let Some(recorded) = storage.get(id)? else {
131							continue;
132						};
133						let author = match log.author_of(id)? {
134							Some(key) => {
135								let text = key.to_text();
136								if let Some(author) = authors.get(&text) {
137									author.clone()
138								} else {
139									let author = self.author_with_key(open, stored, &key)?;
140									authors.insert(text, author.clone());
141									author
142								}
143							}
144							None => None,
145						};
146						let statement = recorded.statement;
147						let carried =
148							self.carried(open, stored, &statement.qualifiers, &mut noted)?;
149						by_field.entry(name.clone()).or_default().push(PastValue {
150							statement: statement.id,
151							value: statement.value.clone(),
152							valid_time: statement.qualifiers.valid_time().cloned(),
153							language: statement.qualifiers.language().map(str::to_owned),
154							recorded: recorded.at,
155							restated: recorded.restated,
156							replaced: storage.superseded_at(id)?,
157							author,
158							carried,
159						});
160					}
161				}
162			}
163			let mut fields = Vec::new();
164			for (field, mut values) in by_field {
165				// A carried value goes by when the space it came from recorded it.
166				values.sort_by_key(|value| {
167					let noted = value.carried.as_ref().and_then(|carried| carried.recorded);
168					(
169						noted.unwrap_or_else(|| value.recorded.millis()),
170						value.recorded,
171						value.statement,
172					)
173				});
174				fields.push(FieldHistory { field, values });
175			}
176			Ok(Some(History {
177				id: entity,
178				name: display_name(state, &open.types, &self.languages, entity)?,
179				fields,
180			}))
181		})
182	}
183
184	/// What a move noted of a value it carried, as its qualifiers hold it, if they hold any
185	/// of it.
186	fn carried(
187		&self,
188		open: &super::Space,
189		stored: &nibkeep_store::StoredLog,
190		qualifiers: &Qualifiers,
191		noted: &mut Noted,
192	) -> Result<Option<Carried>, NodeError> {
193		let millis = |field: &FieldName| match qualifiers.get(field) {
194			Some(Value::Integer(millis)) => u64::try_from(*millis).ok(),
195			_ => None,
196		};
197		let from = qualifiers
198			.get(&fields::CARRIED_FROM)
199			.and_then(Value::as_text)
200			.and_then(|text| text.parse::<SpaceId>().ok());
201		let key = qualifiers
202			.get(&fields::CARRIED_BY)
203			.and_then(Value::as_text)
204			.and_then(nibkeep_crypto::VerifyingKey::from_text);
205		let (recorded, replaced) = (
206			millis(&fields::CARRIED_AT),
207			millis(&fields::CARRIED_REPLACED),
208		);
209		if from.is_none() && key.is_none() && recorded.is_none() && replaced.is_none() {
210			return Ok(None);
211		}
212		let mut author = None;
213		if let Some(key) = &key {
214			let text = key.to_text();
215			if let Some(known) = noted.authors.get(&text) {
216				author.clone_from(known);
217			} else {
218				author = self.author_with_key(open, stored, key)?;
219				if author.is_none() {
220					let personal = self.space(self.info.personal)?;
221					author = self.author_with_key(personal, &personal.stored, key)?;
222				}
223				noted.authors.insert(text, author.clone());
224			}
225		}
226		let from_name = match from {
227			Some(space) if self.spaces.contains_key(&space) => {
228				if let Some(name) = noted.spaces.get(&space) {
229					name.clone()
230				} else {
231					let name = self.space_name(space)?;
232					noted.spaces.insert(space, name.clone());
233					name
234				}
235			}
236			_ => None,
237		};
238		Ok(Some(Carried {
239			from,
240			from_name,
241			author,
242			recorded,
243			replaced,
244		}))
245	}
246
247	/// The name an entity of a space had as the library had recorded it at the end of the
248	/// millisecond `millis`, if it had one: what [`Library::name`] gave then.
249	///
250	/// # Errors
251	///
252	/// Returns an error if the library has no such space, or the space cannot be read.
253	pub fn name_as_of(
254		&self,
255		space: SpaceId,
256		entity: EntityId,
257		millis: u64,
258	) -> Result<Option<String>, NodeError> {
259		let open = self.space(space)?;
260		open.stored.reading(|stored| {
261			let state = stored.log().state_as_of(millis);
262			let entity = state.canonical(entity)?;
263			display_name(&state, &open.types, &self.languages, entity)
264		})
265	}
266
267	/// An entity of a space as the library had recorded it at the end of the millisecond
268	/// `millis`, shown as on `day`: what [`Library::entity`] showed then. Changes recorded
269	/// later are left out, and values replaced later are shown. The space's types are those
270	/// it has now. `None` if the library knew nothing of the entity then.
271	///
272	/// # Errors
273	///
274	/// Returns an error if the library has no such space, or the space cannot be read.
275	pub fn entity_as_of(
276		&self,
277		space: SpaceId,
278		entity: EntityId,
279		day: Day,
280		millis: u64,
281	) -> Result<Option<EntityView>, NodeError> {
282		let open = self.space(space)?;
283		open.stored.reading(|stored| {
284			let state = stored.log().state_as_of(millis);
285			entity_view(&state, &open.types, &self.languages, entity, day)
286		})
287	}
288
289	/// The entities that linked to an entity on `day`, as the library had recorded them at
290	/// the end of the millisecond `millis`, as [`Library::links_to`] gives them.
291	///
292	/// # Errors
293	///
294	/// Returns an error if the library has no such space, or the space cannot be read.
295	pub fn links_to_as_of(
296		&self,
297		space: SpaceId,
298		entity: EntityId,
299		day: Day,
300		millis: u64,
301		limit: usize,
302	) -> Result<Vec<Links>, NodeError> {
303		let open = self.space(space)?;
304		open.stored.reading(|stored| {
305			let state = stored.log().state_as_of(millis);
306			links_to(
307				&state,
308				&open.types,
309				&self.languages,
310				(entity, Some(day)),
311				(day, limit),
312			)
313		})
314	}
315}