Skip to main content

nibkeep_node/library/trees/
history.rs

1//! The history of a tree, read from the library's history and storing nothing: the log of
2//! its changes, newest first, with who made them and their revisions' messages; blame, line
3//! by line; and the tree as it is, as a revision's author had it, or as the library had
4//! recorded it by a moment ([technical design: trees]).
5//!
6//! [technical design: trees]: ../../../../../docs/Technical-design.md#15-trees
7
8use std::collections::{BTreeMap, BTreeSet};
9
10use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
11use nibkeep_log::ChangeId;
12use nibkeep_model::storage::Statements;
13use nibkeep_model::{FieldName, Operation, State, Value, fields};
14use nibkeep_std::{
15	COMMITTED_IN, CONTENT, EXECUTABLE, IN_TREE, LINK_TARGET, MESSAGE, PARTS, REVISION,
16	SECRET_CONTENT, SIZE, TREE_PATH,
17};
18use nibkeep_time::Timestamp;
19
20use super::{Change, Changes, TreeChange, TreeState, read_tree_state, tree_entities};
21use crate::NodeError;
22use crate::library::{Author, Library, Space};
23
24/// How large a file's content may be for a diff or blame to read it whole: 64 MiB.
25pub(super) const READ_LIMIT: u64 = 64 * 1024 * 1024;
26
27/// A point of a tree's history to read it at.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum TreePoint {
30	/// As the library has it now.
31	Now,
32	/// As a revision's author had it: the state of its commit's parts and of the changes
33	/// they build on, so that changes made meanwhile on other devices do not slip in.
34	Revision(EntityId),
35	/// As the library had recorded it by a moment, in milliseconds since 1970; or, if a
36	/// commit's parts were recorded both by it and after it, as it had by the moment before
37	/// that commit, which a view of a moment never shows in part.
38	AsOf(u64),
39}
40
41/// A change to a tree, as its log lists it.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct TreeLogEntry {
44	/// The change, by its ID: of a commit, its first part's, which made its revision.
45	pub change: String,
46	/// When it was made, in milliseconds since 1970.
47	pub at: u64,
48	/// Who made it, as far as the space knows.
49	pub author: Option<Author>,
50	/// The commit's revision, if it was a commit.
51	pub revision: Option<EntityId>,
52	/// The revision's message, if it has one.
53	pub message: Option<String>,
54	/// Of a commit whose parts have not all arrived: how many have, and how many it has.
55	pub part: Option<(u64, u64)>,
56	/// What it did to the tree's files and links, by path.
57	pub changes: Vec<TreeChange>,
58}
59
60/// A line of a file of a tree, with what last changed it.
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct BlameLine {
63	/// The line, without its end.
64	pub text: String,
65	/// The revision that last changed it, if a commit did.
66	pub revision: Option<EntityId>,
67	/// Who did, as far as the space knows.
68	pub author: Option<Author>,
69	/// When, in milliseconds since 1970.
70	pub at: u64,
71}
72
73/// What one change said of one entity of a tree.
74#[derive(Clone, Debug, Default)]
75struct Said {
76	fields: BTreeMap<FieldName, Value>,
77}
78
79/// A revision of a tree, as its statements say.
80#[derive(Clone, Debug)]
81struct Revision {
82	message: Option<String>,
83	/// How many parts its commit has, its first included.
84	parts: Option<u64>,
85}
86
87/// A part of a commit that is here, or its first part, by the statement that counts it.
88#[derive(Clone, Copy, Debug)]
89pub(super) struct PartHere {
90	statement: StatementId,
91	at: Timestamp,
92	/// The change that made it, or the purge that stated it again.
93	change: Option<Hash>,
94	restated: bool,
95}
96
97impl Library {
98	/// The tree as it is at a point of its history: as the library has it now, as a
99	/// revision's author had it, or as the library had recorded it by a moment.
100	pub(super) fn tree_state_at(
101		&self,
102		space: SpaceId,
103		tree: EntityId,
104		point: TreePoint,
105	) -> Result<TreeState, NodeError> {
106		let tree = self.check_tree(space, tree)?;
107		match point {
108			TreePoint::Now => self.tree_state(space, tree),
109			TreePoint::AsOf(millis) => {
110				let open = self.space(space)?;
111				open.stored.reading(|stored| {
112					let state = stored.log().state();
113					let entities = tree_entities(state, tree)?;
114					let millis = before_commits_under_way(stored, state, tree, millis)?;
115					let log = stored.log();
116					let changes = Changes::of(log);
117					let readable = self.secrets_unlocked(space);
118					let then = log.state_as_of(millis);
119					read_tree_state(&then, tree, &entities, (Some(&changes), readable))
120				})
121			}
122			TreePoint::Revision(revision) => {
123				let changes = self.revision_changes(space, tree, revision)?;
124				let last = *changes
125					.last()
126					.ok_or_else(|| NodeError::from(NoRevision(revision)))?;
127				Ok(self
128					.tree_states_of_changes(space, tree, last, &BTreeSet::new())?
129					.0)
130			}
131		}
132	}
133
134	/// The tree as the changes `last` builds on, and `last` itself, leave it, and as they
135	/// leave it without those of `without`: replayed from their payloads, in one pass, as the
136	/// author of `last` had it. Only what the space counts is replayed: changes it set aside,
137	/// as a revoked replica's, or whose payloads it cannot apply, add nothing, and of a purged
138	/// change, what its purge stated again.
139	pub(super) fn tree_states_of_changes(
140		&self,
141		space: SpaceId,
142		tree: EntityId,
143		last: ChangeId,
144		without: &BTreeSet<ChangeId>,
145	) -> Result<(TreeState, TreeState), NodeError> {
146		self.tree_states_from(space, tree, &[last], without)
147	}
148
149	/// The tree as the changes that `heads` are or build on leave it, and as they leave it
150	/// without those of `without`, as [`Library::tree_states_of_changes`] replays them.
151	pub(super) fn tree_states_from(
152		&self,
153		space: SpaceId,
154		tree: EntityId,
155		heads: &[ChangeId],
156		without: &BTreeSet<ChangeId>,
157	) -> Result<(TreeState, TreeState), NodeError> {
158		let open = self.space(space)?;
159		let log = open.stored.log();
160		let entities: BTreeSet<EntityId> = open
161			.stored
162			.reading(|stored| tree_entities(stored.log().state(), tree))?
163			.into_iter()
164			.collect();
165		// The changes it builds on, in the order of their times, which follow the order in
166		// which they build on each other.
167		let mut ancestors = Vec::new();
168		let mut seen = BTreeSet::new();
169		let mut waiting = heads.to_vec();
170		while let Some(id) = waiting.pop() {
171			if !seen.insert(id) {
172				continue;
173			}
174			let Some(change) = log.change(id)? else {
175				continue;
176			};
177			waiting.extend(change.parents().iter().copied());
178			ancestors.push((change.timestamp(), id));
179		}
180		ancestors.sort();
181		let mut restated: Option<BTreeMap<ChangeId, Vec<Operation>>> = None;
182		let mut with: State = State::new();
183		let mut apart: State = State::new();
184		for (at, id) in ancestors {
185			let status = nibkeep_log::History::status(log.history(), id)?;
186			let operations = match status {
187				Some(nibkeep_log::Status::Applied) => {
188					log.payload(id, &open.keys)?.map_or_default(|payload| {
189						let mut operations = payload.operations;
190						operations.extend(opened(log, payload.sealed.keys()));
191						operations
192					})
193				}
194				// A change that a purge took away: what the purge stated again of it.
195				Some(nibkeep_log::Status::Ignored) => {
196					let restated = match &mut restated {
197						Some(restated) => restated,
198						None => restated.insert(restated_by_purges(open)?),
199					};
200					restated.get(&id).cloned().unwrap_or_default()
201				}
202				_ => continue,
203			};
204			for operation in &operations {
205				let about_tree = match operation {
206					Operation::Assert { statement, .. } => entities.contains(&statement.entity),
207					Operation::Retract { .. } | Operation::RetractSecret { .. } => true,
208					Operation::Unknown(_) => false,
209				};
210				if about_tree {
211					let Ok(()) = with.apply_in(operation, at, Some(*id.hash()));
212					if !without.contains(&id) {
213						let Ok(()) = apart.apply_in(operation, at, Some(*id.hash()));
214					}
215				}
216			}
217		}
218		let entities: Vec<EntityId> = entities.into_iter().collect();
219		let changes = Changes::of(log);
220		let readable = self.secrets_unlocked(space);
221		Ok((
222			read_tree_state(&with, tree, &entities, (Some(&changes), readable))?,
223			read_tree_state(&apart, tree, &entities, (Some(&changes), readable))?,
224		))
225	}
226
227	/// The tree as the library has it now, without the changes of `without`, such as the
228	/// parts of a commit whose other parts have not arrived.
229	pub(super) fn tree_state_without(
230		&self,
231		space: SpaceId,
232		tree: EntityId,
233		without: &BTreeSet<ChangeId>,
234	) -> Result<TreeState, NodeError> {
235		let heads: Vec<ChangeId> = self
236			.space(space)?
237			.stored
238			.log()
239			.heads()?
240			.into_iter()
241			.collect();
242		Ok(self.tree_states_from(space, tree, &heads, without)?.1)
243	}
244
245	/// The tree that a revision is of, if `revision` is one.
246	pub(super) fn tree_of_revision(
247		&self,
248		space: SpaceId,
249		revision: EntityId,
250	) -> Result<Option<EntityId>, NodeError> {
251		let open = self.space(space)?;
252		open.stored.reading(|stored| {
253			let state = stored.log().state();
254			let revision = state.canonical(revision)?;
255			if !state.types(revision)?.contains(&REVISION) {
256				return Ok(None);
257			}
258			for statement in state.current(revision, &IN_TREE)? {
259				if let Value::Reference(tree) = statement.value {
260					return Ok::<_, NodeError>(Some(state.canonical(tree)?));
261				}
262			}
263			Ok(None)
264		})
265	}
266
267	/// The changes of a revision's commit that are here, in order: of its first part, which
268	/// made the revision, and of each other part. Of a part that a purge stated again, the
269	/// change it came from, which the purge took away.
270	pub(super) fn revision_changes(
271		&self,
272		space: SpaceId,
273		tree: EntityId,
274		revision: EntityId,
275	) -> Result<Vec<ChangeId>, NodeError> {
276		let open = self.space(space)?;
277		let parts = open.stored.reading(|stored| {
278			let state = stored.log().state();
279			let revision = state.canonical(revision)?;
280			if !is_revision_of(state, revision, tree)? {
281				return Err(NoRevision(revision).into());
282			}
283			let mut parts: Vec<PartHere> = first_part(state, revision)?.into_iter().collect();
284			parts.extend(parts_here(state, revision)?);
285			Ok::<_, NodeError>(parts)
286		})?;
287		let mut restated = None;
288		let mut changes = Vec::new();
289		for part in parts {
290			let change = if part.restated {
291				let restated = match &mut restated {
292					Some(restated) => restated,
293					None => restated.insert(restated_by_purges(open)?),
294				};
295				restated
296					.iter()
297					.find(|(_, operations)| {
298						operations.iter().any(|operation| {
299							matches!(operation, Operation::Assert { statement, .. }
300								if statement.id == part.statement)
301						})
302					})
303					.map(|(source, _)| *source)
304			} else {
305				part.change.map(ChangeId::from_hash)
306			};
307			changes.extend(change.map(|change| (part.at, change)));
308		}
309		changes.sort();
310		changes.dedup();
311		Ok(changes.into_iter().map(|(_, change)| change).collect())
312	}
313
314	/// The log of a tree, newest first: each change that touched its files and links, with
315	/// who made it, its revision and the revision's message, and what it did, by path. With
316	/// `path`, only the changes to the file or link there, also when it was elsewhere then.
317	///
318	/// # Errors
319	///
320	/// Returns [`NodeError::NotInTree`] if the tree holds nothing at `path`, and an error if
321	/// the space cannot be read.
322	pub fn tree_log(
323		&self,
324		space: SpaceId,
325		tree: EntityId,
326		path: Option<&str>,
327	) -> Result<Vec<TreeLogEntry>, NodeError> {
328		let tree = self.check_tree(space, tree)?;
329		let chosen = match path {
330			Some(path) => {
331				let state = self.tree_state(space, tree)?;
332				let current = state
333					.by_path
334					.get(path)
335					.or_else(|| state.deleted.get(path))
336					.ok_or_else(|| NodeError::NotInTree(path.to_owned()))?;
337				Some(current.entity)
338			}
339			None => None,
340		};
341		let open = self.space(space)?;
342		open.stored.reading(|stored| {
343			let state = stored.log().state();
344			let entities = tree_entities(state, tree)?;
345			let revisions = revisions_of(stored, state, tree)?;
346			let told = told_by_changes(state, tree, &entities, &revisions)?;
347			let Commits {
348				by_change: by_change_revision,
349				made,
350			} = commits(state, &revisions, &told.parts)?;
351			let paths = &told.paths;
352			let what_changed = |about: &BTreeMap<EntityId, Said>, at: Timestamp| {
353				about
354					.iter()
355					.filter_map(|(entity, said)| {
356						let path_then = |before: bool| {
357							paths.get(entity).and_then(|list| {
358								list.iter()
359									.rev()
360									.find(|(when, _)| if before { *when < at } else { *when <= at })
361									.map(|(_, path)| path.clone())
362							})
363						};
364						what_it_did(said, path_then(false), path_then(true))
365					})
366					.collect::<Vec<TreeChange>>()
367			};
368			// Each commit once, however many parts it has (technical design: one entity per change), and each other
369			// change once: what each part said goes into its commit's entry.
370			let mut grouped: Vec<Grouped> = Vec::new();
371			let mut at_entry: BTreeMap<Result<EntityId, Hash>, usize> = BTreeMap::new();
372			for ((change, recorded), about) in told.by_change {
373				let about_chosen = chosen.is_none_or(|chosen| about.contains_key(&chosen));
374				let commit = by_change_revision.get(&(change, recorded)).copied();
375				let changes = what_changed(&about, recorded);
376				match at_entry.entry(commit.ok_or(change)) {
377					std::collections::btree_map::Entry::Occupied(entry) => {
378						let entry = &mut grouped[*entry.get()];
379						entry.changes.extend(changes);
380						entry.chosen |= about_chosen;
381					}
382					std::collections::btree_map::Entry::Vacant(entry) => {
383						entry.insert(grouped.len());
384						grouped.push(Grouped {
385							change,
386							commit,
387							changes,
388							chosen: about_chosen,
389						});
390					}
391				}
392			}
393			// Only the entries kept are read further: who made each, and when.
394			let mut entries: Vec<(Timestamp, TreeLogEntry)> = Vec::new();
395			for grouped in grouped.into_iter().filter(|grouped| grouped.chosen) {
396				let reading = (open, stored, state);
397				if let Some(entry) = self.log_entry(reading, grouped, (&revisions, &made))? {
398					entries.push(entry);
399				}
400			}
401			// Newest first, by the changes' full times, which order changes made in one
402			// millisecond too.
403			entries.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.change.cmp(&a.1.change)));
404			Ok(entries.into_iter().map(|(_, entry)| entry).collect())
405		})
406	}
407
408	/// The entry of the log for what `grouped` holds, named, of a commit, by its first part,
409	/// which made its revision with the message, and with how many of its parts are here if
410	/// not all are; `None` if its change is not in the log.
411	#[allow(clippy::type_complexity, reason = "what the log read, passed along")]
412	fn log_entry<S: Statements>(
413		&self,
414		(open, stored, state): (&Space, &nibkeep_store::StoredLog, &State<S>),
415		grouped: Grouped,
416		(revisions, made): (&BTreeMap<EntityId, Revision>, &BTreeMap<EntityId, u64>),
417	) -> Result<Option<(Timestamp, TreeLogEntry)>, NodeError>
418	where
419		NodeError: From<S::Error>,
420	{
421		let mut changes = grouped.changes;
422		changes.sort_by(|a, b| a.path.cmp(&b.path));
423		changes.dedup();
424		let first = match grouped.commit {
425			Some(commit) => type_change(state, commit)?,
426			None => None,
427		};
428		let change = first.unwrap_or_else(|| ChangeId::from_hash(grouped.change));
429		let Some(header) = stored.log().change(change)? else {
430			return Ok(None);
431		};
432		let revision = grouped.commit.and_then(|commit| revisions.get(&commit));
433		// Of a commit whose parts have not all arrived, how many have.
434		let part = grouped.commit.and_then(|commit| {
435			let made = made.get(&commit).copied().unwrap_or(0);
436			let of = revision.and_then(|revision| revision.parts).unwrap_or(made);
437			(made < of).then_some((made, of))
438		});
439		let at = header.timestamp();
440		Ok(Some((
441			at,
442			TreeLogEntry {
443				change: change.to_string(),
444				at: at.millis(),
445				author: self.author_with_key(open, stored, header.author())?,
446				revision: grouped.commit,
447				message: revision.and_then(|revision| revision.message.clone()),
448				part,
449				changes,
450			},
451		)))
452	}
453
454	/// Blame for the file at `path` of a tree: for each line of its current version, the
455	/// revision and the author that last changed it, through every version it had, whatever
456	/// its path then.
457	///
458	/// # Errors
459	///
460	/// Returns [`NodeError::NotInTree`] if the tree holds no file at `path`,
461	/// [`NodeError::NotText`] if a version is no text, [`NodeError::NoCopyHere`] if this
462	/// device holds no copy of one, and an error if the space cannot be read.
463	pub fn tree_blame(
464		&self,
465		space: SpaceId,
466		tree: EntityId,
467		path: &str,
468	) -> Result<Vec<BlameLine>, NodeError> {
469		self.tree_blame_with(space, tree, path, false)
470	}
471
472	/// Blame for the file at `path` of a tree, as [`Library::tree_blame`] gives it, and of a
473	/// secret file too if `secrets` says so, with the secrets unlocked.
474	///
475	/// # Errors
476	///
477	/// The errors of [`Library::tree_blame`]; [`NodeError::SecretLines`] if the file is a
478	/// secret one and `secrets` does not ask for it, and [`NodeError::SecretsLocked`] if it
479	/// does while the secrets are locked.
480	pub fn tree_blame_with(
481		&self,
482		space: SpaceId,
483		tree: EntityId,
484		path: &str,
485		secrets: bool,
486	) -> Result<Vec<BlameLine>, NodeError> {
487		let tree = self.check_tree(space, tree)?;
488		let state = self.tree_state(space, tree)?;
489		let entity = match (state.by_path.get(path), state.sealed.get(path)) {
490			(Some(current), _) => current.entity,
491			(None, Some(_)) if !secrets => return Err(NodeError::SecretLines(path.to_owned())),
492			(None, Some(_)) => return Err(NodeError::SecretsLocked),
493			(None, None) => return Err(NodeError::NotInTree(path.to_owned())),
494		};
495		let secret = state.is_secret(entity);
496		if secret && !secrets {
497			return Err(NodeError::SecretLines(path.to_owned()));
498		}
499		if secret && !self.secrets_unlocked(space) {
500			return Err(NodeError::SecretsLocked);
501		}
502		let field = if secret { SECRET_CONTENT } else { CONTENT };
503		let open = self.space(space)?;
504		// Its versions, in the order they were recorded, each with the change that made it.
505		let versions: Vec<(Hash, Hash, Timestamp)> = open.stored.reading(|stored| {
506			let state = stored.log().state();
507			let storage = state.storage();
508			let mut versions = Vec::new();
509			for id in storage.of_field(entity, &field)? {
510				if let Some(recorded) = storage.get(id)?
511					&& let (Value::Blob(content), Some(change)) =
512						(&recorded.statement.value, recorded.change)
513				{
514					versions.push((recorded.at, id, *content, change));
515				}
516			}
517			versions.sort();
518			Ok::<_, NodeError>(
519				versions
520					.into_iter()
521					.map(|(at, _, content, change)| (content, change, at))
522					.collect(),
523			)
524		})?;
525		let mut lines: Vec<(String, Hash, u64)> = Vec::new();
526		let versions: Vec<(Hash, Hash, u64)> = versions
527			.into_iter()
528			.map(|(content, change, at)| (content, change, at.millis()))
529			.collect();
530		let mut previous: Option<String> = None;
531		for (content, change, at) in versions {
532			let bytes = self
533				.version_bytes(space, &content, secret)?
534				.ok_or_else(|| NodeError::NoCopyHere(path.to_owned()))?;
535			if !super::diff::is_text(&bytes) {
536				return Err(NodeError::NotText(path.to_owned()));
537			}
538			let text = String::from_utf8_lossy(&bytes).into_owned();
539			lines = match &previous {
540				None => split_lines(&text)
541					.into_iter()
542					.map(|line| (line, change, at))
543					.collect(),
544				Some(before) => carried(before, &text, &lines, (change, at)),
545			};
546			previous = Some(text);
547		}
548		// A line names the commit that recorded its version, as the part that did names it.
549		let revisions = open.stored.reading(|stored| {
550			let storage = stored.log().state().storage();
551			let mut by_change = BTreeMap::new();
552			for id in storage.of_field(entity, &COMMITTED_IN)? {
553				if let Some(recorded) = storage.get(id)?
554					&& let (Value::Reference(revision), Some(change)) =
555						(&recorded.statement.value, recorded.change)
556				{
557					by_change.insert(change, *revision);
558				}
559			}
560			Ok::<_, NodeError>(by_change)
561		})?;
562		let mut authors: BTreeMap<Hash, Option<Author>> = BTreeMap::new();
563		let mut blamed = Vec::with_capacity(lines.len());
564		for (text, change, at) in lines {
565			let author = if let Some(author) = authors.get(&change) {
566				author.clone()
567			} else {
568				let author = open.stored.reading(|stored| {
569					match stored.log().change(ChangeId::from_hash(change))? {
570						Some(header) => self.author_with_key(open, stored, header.author()),
571						None => Ok(None),
572					}
573				})?;
574				authors.insert(change, author.clone());
575				author
576			};
577			blamed.push(BlameLine {
578				text,
579				revision: revisions.get(&change).copied(),
580				author,
581				at,
582			});
583		}
584		Ok(blamed)
585	}
586}
587
588/// What the log lists as one entry: a commit, by its revision, or another change.
589struct Grouped {
590	/// The change it was first found by.
591	change: Hash,
592	commit: Option<EntityId>,
593	/// What it did to the tree's files and links, by path.
594	changes: Vec<TreeChange>,
595	/// Whether it is about the file or link that the log was asked for, if any.
596	chosen: bool,
597}
598
599/// The commits of a tree's changes, as its log groups them.
600struct Commits {
601	/// The commit of each change, by its revision: of each part of a change, as of a purge,
602	/// which states again parts of several changes, by the time each was recorded.
603	by_change: BTreeMap<(Hash, Timestamp), EntityId>,
604	/// How many parts of each commit are here.
605	made: BTreeMap<EntityId, u64>,
606}
607
608/// The commits of a tree's changes, of its `revisions`: each first part, which made its
609/// revision, and each of `parts`, which names it on what it recorded.
610fn commits<S: Statements>(
611	state: &State<S>,
612	revisions: &BTreeMap<EntityId, Revision>,
613	parts: &[(EntityId, Option<(Hash, Timestamp)>)],
614) -> Result<Commits, NodeError>
615where
616	NodeError: From<S::Error>,
617{
618	let mut commits = Commits {
619		by_change: BTreeMap::new(),
620		made: BTreeMap::new(),
621	};
622	let mut first_parts = Vec::with_capacity(revisions.len());
623	for &revision in revisions.keys() {
624		if let Some(part) = first_part(state, revision)? {
625			first_parts.push((revision, part.change.map(|change| (change, part.at))));
626		}
627	}
628	for &(revision, change) in first_parts.iter().chain(parts) {
629		*commits.made.entry(revision).or_default() += 1;
630		if let Some(change) = change {
631			commits.by_change.insert(change, revision);
632		}
633	}
634	Ok(commits)
635}
636
637/// What the changes to a tree's files and links told, as its log reads them.
638struct Told {
639	/// What each change said of each file and link, by change and when it was recorded: a
640	/// purge states parts of several changes again, each with the time of the change it came
641	/// from.
642	by_change: BTreeMap<(Hash, Timestamp), BTreeMap<EntityId, Said>>,
643	/// Each file's and link's paths over time, in order.
644	paths: BTreeMap<EntityId, Vec<(Timestamp, String)>>,
645	/// The parts of commits that recorded them, or the tree, but their first parts: the
646	/// revision each names, and its change, with when it was recorded.
647	parts: Vec<(EntityId, Option<(Hash, Timestamp)>)>,
648}
649
650/// What each change said of each file and link among `entities`, revisions aside; each one's
651/// paths over time; and the parts of commits that recorded them or `tree`, which name their
652/// revisions on them.
653fn told_by_changes<S: Statements>(
654	state: &State<S>,
655	tree: EntityId,
656	entities: &[EntityId],
657	revisions: &BTreeMap<EntityId, Revision>,
658) -> Result<Told, NodeError>
659where
660	NodeError: From<S::Error>,
661{
662	let storage = state.storage();
663	let mut told = Told {
664		by_change: BTreeMap::new(),
665		paths: BTreeMap::new(),
666		parts: Vec::new(),
667	};
668	let mut part = |recorded: &nibkeep_model::storage::Recorded<'_>| {
669		if recorded.statement.field == COMMITTED_IN
670			&& let Value::Reference(revision) = recorded.statement.value
671		{
672			let change = recorded.change.map(|change| (change, recorded.at));
673			told.parts.push((revision, change));
674		}
675	};
676	for id in storage.of_field(tree, &COMMITTED_IN)? {
677		if let Some(recorded) = storage.get(id)? {
678			part(&recorded);
679		}
680	}
681	for &entity in entities {
682		if revisions.contains_key(&entity) {
683			continue;
684		}
685		for (field, ids) in storage.of_entity(entity)? {
686			for id in ids {
687				let Some(recorded) = storage.get(id)? else {
688					continue;
689				};
690				part(&recorded);
691				if field == TREE_PATH
692					&& let Value::Text(path) = &recorded.statement.value
693				{
694					told.paths
695						.entry(entity)
696						.or_default()
697						.push((recorded.at, path.clone()));
698				}
699				let Some(change) = recorded.change else {
700					continue;
701				};
702				told.by_change
703					.entry((change, recorded.at))
704					.or_default()
705					.entry(entity)
706					.or_default()
707					.fields
708					.insert(field.clone(), recorded.statement.value.clone());
709			}
710		}
711	}
712	for list in told.paths.values_mut() {
713		list.sort();
714	}
715	Ok(told)
716}
717
718/// A revision that the tree does not hold.
719struct NoRevision(EntityId);
720
721impl From<NoRevision> for NodeError {
722	fn from(NoRevision(revision): NoRevision) -> Self {
723		Self::NoRevision(revision.to_string())
724	}
725}
726
727/// What a change that said `said` of a file or link did to it, at the path it had then, or
728/// before it for a move.
729fn what_it_did(said: &Said, now: Option<String>, before: Option<String>) -> Option<TreeChange> {
730	let has = |field: &FieldName| said.fields.contains_key(field);
731	let path = now?;
732	let change = if has(&fields::TYPE) {
733		Change::New
734	} else if said.fields.get(&fields::DELETED) == Some(&Value::Boolean(true)) {
735		Change::Deleted
736	} else if has(&TREE_PATH) {
737		match before {
738			Some(from) if from != path => Change::Moved { from },
739			_ => Change::Edited,
740		}
741	} else if has(&CONTENT) || has(&SECRET_CONTENT) || has(&SIZE) || has(&LINK_TARGET) {
742		// A secret file's new version is sealed, and shows by its size, which is ordinary.
743		Change::Edited
744	} else if let Some(Value::Boolean(executable)) = said.fields.get(&EXECUTABLE) {
745		Change::Executable(*executable)
746	} else {
747		return None;
748	};
749	Some(TreeChange { path, change })
750}
751
752/// The revisions of a tree, by ID.
753fn revisions_of<S: Statements>(
754	stored: &nibkeep_store::StoredLog,
755	state: &State<S>,
756	tree: EntityId,
757) -> Result<BTreeMap<EntityId, Revision>, NodeError>
758where
759	NodeError: From<S::Error>,
760{
761	let tree = state.canonical(tree)?;
762	let mut revisions = BTreeMap::new();
763	for entity in stored.find(&IN_TREE, &Value::Reference(tree))? {
764		let entity = state.canonical(entity)?;
765		if !state.types(entity)?.contains(&REVISION) {
766			continue;
767		}
768		let first_value = |field: &FieldName| -> Result<Option<Value>, NodeError> {
769			let mut current = state.current(entity, field)?;
770			current.sort_by_key(|statement| statement.id);
771			Ok(current.first().map(|statement| statement.value.clone()))
772		};
773		let message = match first_value(&MESSAGE)? {
774			Some(Value::Text(message)) => Some(message),
775			_ => None,
776		};
777		let parts = match first_value(&PARTS)? {
778			Some(Value::Integer(parts)) => u64::try_from(parts).ok(),
779			_ => None,
780		};
781		revisions.insert(entity, Revision { message, parts });
782	}
783	Ok(revisions)
784}
785
786/// The first part of a revision's commit, which made the revision: by the first statement
787/// of its type.
788fn first_part<S: Statements>(
789	state: &State<S>,
790	revision: EntityId,
791) -> Result<Option<PartHere>, NodeError>
792where
793	NodeError: From<S::Error>,
794{
795	let Some(id) = state
796		.storage()
797		.of_field(revision, &fields::TYPE)?
798		.into_iter()
799		.min()
800	else {
801		return Ok(None);
802	};
803	Ok(state.storage().get(id)?.map(|recorded| PartHere {
804		statement: id,
805		at: recorded.at,
806		change: recorded.change,
807		restated: recorded.restated.is_some(),
808	}))
809}
810
811/// The parts of a revision's commit that are here, but its first: each names the revision on
812/// the entity it recorded ([technical design: one entity per change]), a statement that history keeps when a later
813/// commit records the entity again, and that a purge of the entity's other values states
814/// again.
815///
816/// [technical design: one entity per change]: ../../../../../docs/Technical-design.md#62-one-entity-per-change
817pub(super) fn parts_here<S: Statements>(
818	state: &State<S>,
819	revision: EntityId,
820) -> Result<Vec<PartHere>, NodeError>
821where
822	NodeError: From<S::Error>,
823{
824	let storage = state.storage();
825	let mut parts = Vec::new();
826	for id in storage.referring_to(revision)? {
827		if let Some(recorded) = storage.get(id)?
828			&& recorded.statement.field == COMMITTED_IN
829		{
830			parts.push(PartHere {
831				statement: id,
832				at: recorded.at,
833				change: recorded.change,
834				restated: recorded.restated.is_some(),
835			});
836		}
837	}
838	Ok(parts)
839}
840
841/// The moment to read a tree as of, for `millis`: that moment, or, if a commit's parts were
842/// recorded both by it and after it, the moment before the earliest such commit's first, so
843/// that a view of a moment never shows a commit in part ([technical design: one entity per change]). A commit's
844/// parts are made at its moment, but its device takes in what others wrote between batches
845/// of them, and its clock moves past any later change it takes in.
846///
847/// [technical design: one entity per change]: ../../../../../docs/Technical-design.md#62-one-entity-per-change
848fn before_commits_under_way<S: Statements>(
849	stored: &nibkeep_store::StoredLog,
850	state: &State<S>,
851	tree: EntityId,
852	millis: u64,
853) -> Result<u64, NodeError>
854where
855	NodeError: From<S::Error>,
856{
857	// When each part of each commit was recorded.
858	let mut commits: Vec<Vec<u64>> = Vec::new();
859	for &revision in revisions_of(stored, state, tree)?.keys() {
860		let parts: Vec<u64> = first_part(state, revision)?
861			.into_iter()
862			.chain(parts_here(state, revision)?)
863			.map(|part| part.at.millis())
864			.collect();
865		commits.push(parts);
866	}
867	let mut moment = millis;
868	loop {
869		let under_way = commits
870			.iter()
871			.filter(|parts| {
872				parts.iter().any(|&at| at <= moment) && parts.iter().any(|&at| at > moment)
873			})
874			.filter_map(|parts| parts.iter().min().copied())
875			.min();
876		match under_way {
877			Some(first) if first > 0 => moment = first - 1,
878			Some(_) => return Ok(0),
879			None => return Ok(moment),
880		}
881	}
882}
883
884/// Whether `revision` is a revision of `tree`.
885fn is_revision_of<S: Statements>(
886	state: &State<S>,
887	revision: EntityId,
888	tree: EntityId,
889) -> Result<bool, NodeError>
890where
891	NodeError: From<S::Error>,
892{
893	let tree = state.canonical(tree)?;
894	if !state.types(revision)?.contains(&REVISION) {
895		return Ok(false);
896	}
897	for statement in state.current(revision, &IN_TREE)? {
898		if let Value::Reference(of) = statement.value
899			&& state.canonical(of)? == tree
900		{
901			return Ok(true);
902		}
903	}
904	Ok(false)
905}
906
907/// The change that made an entity, by the first statement of its type.
908fn type_change<S: Statements>(
909	state: &State<S>,
910	entity: EntityId,
911) -> Result<Option<ChangeId>, NodeError>
912where
913	NodeError: From<S::Error>,
914{
915	Ok(first_part(state, entity)?.and_then(|part| part.change.map(ChangeId::from_hash)))
916}
917
918/// What the purges of a space stated again of the changes they purged, by change.
919fn restated_by_purges(open: &Space) -> Result<BTreeMap<ChangeId, Vec<Operation>>, NodeError> {
920	let log = open.stored.log();
921	let mut restated: BTreeMap<ChangeId, Vec<Operation>> = BTreeMap::new();
922	for change in log.changes()? {
923		if change.purges().is_empty() {
924			continue;
925		}
926		if let Ok(Some(payload)) = log.payload(change.id(), &open.keys) {
927			for (of, again) in payload.restated {
928				let sealed = opened(log, again.sealed.keys());
929				let operations = restated.entry(of).or_default();
930				operations.extend(again.operations);
931				operations.extend(sealed);
932			}
933		}
934	}
935	Ok(restated)
936}
937
938/// The secret statements of `sealed` that this replica opened, as its secrets are unlocked,
939/// asserted: what a replay of a change's payload adds to its operations.
940fn opened<'a>(
941	log: &nibkeep_log::Log<nibkeep_store::StateFile, nibkeep_store::LogFile>,
942	sealed: impl Iterator<Item = &'a StatementId>,
943) -> Vec<Operation> {
944	let storage = log.state().storage();
945	sealed
946		.filter_map(|id| storage.get(*id).ok().flatten())
947		.map(|recorded| Operation::assert(recorded.statement.into_owned()))
948		.collect()
949}
950
951/// The lines of a text, without their ends.
952pub(super) fn split_lines(text: &str) -> Vec<String> {
953	text.lines().map(str::to_owned).collect()
954}
955
956/// The lines of `after`, each with what last changed it: those that `before` held carry
957/// what they had, and the others what made `after`.
958fn carried(
959	before: &str,
960	after: &str,
961	blamed: &[(String, Hash, u64)],
962	made: (Hash, u64),
963) -> Vec<(String, Hash, u64)> {
964	let patch = diffy::DiffOptions::new()
965		.set_context_len(usize::MAX)
966		.create_patch(before, after);
967	let Some(hunk) = patch.hunks().first() else {
968		return blamed.to_vec();
969	};
970	let mut old = blamed.iter();
971	let mut lines = Vec::new();
972	for line in hunk.lines() {
973		match line {
974			diffy::Line::Context(text) => {
975				let (_, change, at) =
976					old.next()
977						.cloned()
978						.unwrap_or((String::new(), made.0, made.1));
979				lines.push((trimmed(text), change, at));
980			}
981			diffy::Line::Delete(_) => {
982				old.next();
983			}
984			diffy::Line::Insert(text) => lines.push((trimmed(text), made.0, made.1)),
985		}
986	}
987	lines
988}
989
990/// A line without its end.
991fn trimmed(line: &str) -> String {
992	line.trim_end_matches(['\n', '\r']).to_owned()
993}