Skip to main content

nibkeep_node/library/
export.rs

1//! Exports: a space in ordinary files that stay useful without NibKeep, JSON and SHA-256
2//! sums (`docs/spec/export.md`).
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fs::{self, File};
6use std::io::{self, BufWriter, Write};
7use std::path::Path;
8
9use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
10use nibkeep_model::storage::Statements;
11use nibkeep_model::{FieldName, Languages, State, TypeName, Types, Value};
12use nibkeep_std::CONTENT;
13use nibkeep_store::StoredLog;
14use nibkeep_time::Timestamp;
15use serde_json::{Map, Value as Json, json};
16use sha2::{Digest, Sha256};
17
18use super::entities::display_name;
19use super::{Author, Library, Space, json, policies};
20use crate::NodeError;
21
22/// The version of the format of exports.
23const VERSION: u64 = 1;
24
25/// The types of NibKeep's own records of who uses a library, recovery codes among them: an
26/// export of current values leaves them out, a merge refuses them, and edits neither give
27/// them nor take them away.
28pub const OWN_RECORDS: [TypeName; 5] = [
29	nibkeep_governance::USER,
30	nibkeep_governance::DEVICE,
31	nibkeep_governance::REPLICA,
32	nibkeep_governance::SPACE,
33	nibkeep_governance::RECOVERY_CODE,
34];
35
36/// What an export holds.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum ExportKind {
39	/// Every entity, with every statement, current and replaced, and when each was
40	/// recorded, by whom, and when replaced.
41	Full,
42	/// The current statements, without when or by whom they were recorded, of the entities
43	/// that are not deleted, without NibKeep's own records of users, devices, replicas and
44	/// spaces: for giving a collection to someone.
45	Current,
46}
47
48/// What an export wrote.
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Exported {
51	/// How many entities it holds.
52	pub entities: usize,
53	/// How many files it holds.
54	pub files: usize,
55	/// The files that values refer to but the replica does not hold, ordered by their text.
56	pub missing_files: Vec<Hash>,
57}
58
59impl Library {
60	/// Exports a space into a directory, which must be empty or not exist yet: its
61	/// entities as JSON, the files its values refer to as they were added, a manifest, a
62	/// note for people, and the SHA-256 sums of them all, as `docs/spec/export.md` says.
63	/// Secret values are left out. A space that has not changed since gives the same files.
64	///
65	/// # Errors
66	///
67	/// Returns an error if the library has no such space, the directory holds anything, or
68	/// the space cannot be read, or the files written.
69	pub fn export(
70		&self,
71		space: SpaceId,
72		directory: &Path,
73		kind: ExportKind,
74	) -> Result<Exported, NodeError> {
75		let open = self.space(space)?;
76		if fs::read_dir(directory).is_ok_and(|mut entries| entries.next().is_some()) {
77			return Err(NodeError::ExportExists(directory.display().to_string()));
78		}
79		// The export is written beside the directory and moved into place when it is whole, so
80		// that one cut short leaves nothing that could pass for an export.
81		let Some(name) = directory.file_name() else {
82			return Err(NodeError::Export(format!(
83				"{} is no folder of its own",
84				directory.display()
85			)));
86		};
87		let partial = directory.with_file_name(format!(
88			".{}.partial-{}",
89			name.to_string_lossy(),
90			std::process::id()
91		));
92		let _ = fs::remove_dir_all(&partial);
93		fs::create_dir_all(&partial).map_err(NodeError::file(&partial))?;
94		let device = self.info.device;
95		let written = open
96			.stored
97			.reading(|stored| Self::write_export(open, stored, (space, device), &partial, kind));
98		let moved = written.and_then(|exported| {
99			if directory.exists() {
100				fs::remove_dir(directory).map_err(NodeError::file(directory))?;
101			}
102			fs::rename(&partial, directory).map_err(NodeError::file(directory))?;
103			if let Some(parent) = directory.parent() {
104				sync_directory(parent);
105			}
106			Ok(exported)
107		});
108		if moved.is_err() {
109			let _ = fs::remove_dir_all(&partial);
110		}
111		moved
112	}
113
114	/// Writes an export of a space into a new, empty directory. The files that this device,
115	/// `device`, holds only where they were found are read from there, and checked against
116	/// their hashes.
117	fn write_export(
118		open: &Space,
119		stored: &StoredLog,
120		(space, device): (SpaceId, EntityId),
121		directory: &Path,
122		kind: ExportKind,
123	) -> Result<Exported, NodeError> {
124		let mut sums = Vec::new();
125		let path = directory.join("entities.jsonl");
126		let mut lines = Summed::create(&path).map_err(NodeError::file(&path))?;
127		let written = entities_of(open, stored, stored.log().state(), kind, &mut |line| {
128			lines.write_all(line.as_bytes())?;
129			lines.write_all(b"\n")
130		})?;
131		sums.push((
132			"entities.jsonl".to_owned(),
133			lines.finish().map_err(NodeError::file(&path))?,
134		));
135		if kind == ExportKind::Full {
136			let path = directory.join("changes.jsonl");
137			let mut lines = Summed::create(&path).map_err(NodeError::file(&path))?;
138			for change in &written.changes {
139				lines
140					.write_all(change.as_bytes())
141					.and_then(|()| lines.write_all(b"\n"))
142					.map_err(NodeError::file(&path))?;
143			}
144			sums.push((
145				"changes.jsonl".to_owned(),
146				lines.finish().map_err(NodeError::file(&path))?,
147			));
148		}
149		let mut files = 0;
150		let mut missing = Vec::new();
151		for hash in &written.blobs {
152			let relative = blob_path(hash);
153			let path = directory.join(&relative);
154			let copied = copy_blob(stored, hash, &path).and_then(|copied| match copied {
155				Some(sum) => Ok(Some(sum)),
156				None => copy_in_place(stored, device, hash, &path),
157			});
158			match copied {
159				Ok(Some(sum)) => {
160					sums.push((relative, sum));
161					files += 1;
162				}
163				// A file that the replica does not hold, or cannot read, is listed as missing.
164				Ok(None) => missing.push(*hash),
165				Err(error) => return Err(NodeError::file(&path)(error)),
166			}
167		}
168		for written in [
169			directory.join("files").join("blake3"),
170			directory.join("files"),
171		] {
172			sync_directory(&written);
173		}
174		let manifest = json!({
175			"format": "nibkeep-export",
176			"version": VERSION,
177			"space": {
178				"id": space.to_string(),
179				"name": open.name(&Languages::default())?,
180			},
181			"as_of": written.as_of.map(json::moment),
182			"history": kind == ExportKind::Full,
183			"entities": written.entities,
184			"files": files,
185			"missing_files": missing.iter().map(ToString::to_string).collect::<Vec<_>>(),
186			"secrets": "left out",
187		});
188		let mut text = serde_json::to_string_pretty(&manifest)
189			.map_err(io::Error::from)
190			.map_err(NodeError::file(&directory.join("manifest.json")))?;
191		text.push('\n');
192		for (relative, bytes) in [
193			("manifest.json", text.into_bytes()),
194			("README.txt", readme(kind).into_bytes()),
195		] {
196			let path = directory.join(relative);
197			write_synced(&path, &bytes).map_err(NodeError::file(&path))?;
198			sums.push((relative.to_owned(), hex(&Sha256::digest(&bytes))));
199		}
200		sums.sort();
201		let mut listed = String::new();
202		for (path, sum) in &sums {
203			listed.push_str(sum);
204			listed.push_str("  ");
205			listed.push_str(path);
206			listed.push('\n');
207		}
208		let path = directory.join("SHA256SUMS");
209		write_synced(&path, listed.as_bytes()).map_err(NodeError::file(&path))?;
210		sync_directory(directory);
211		Ok(Exported {
212			entities: written.entities,
213			files,
214			missing_files: missing,
215		})
216	}
217}
218
219/// Writes the lines of an export's entities from a state of a space, one call of `line`
220/// each, in order, with the changes they name and who made them, as the state says. Names
221/// are in no reader's languages, so that every device writes the same.
222fn entities_of<S: Statements>(
223	open: &Space,
224	stored: &StoredLog,
225	state: &State<S>,
226	kind: ExportKind,
227	line: &mut dyn FnMut(&str) -> io::Result<()>,
228) -> Result<Written, NodeError>
229where
230	NodeError: From<S::Error>,
231{
232	let languages = Languages::default();
233	let mut authors = Authors::default();
234	let mut author = |change: Hash| -> Result<Option<Author>, NodeError> {
235		authors.of(open, stored, state, change, &languages)
236	};
237	write_entities(state, &open.types, &languages, kind, &mut author, line)
238}
239
240/// What the lines of an export's entities hold, besides themselves.
241pub(crate) struct Written {
242	/// How many lines were written.
243	pub(crate) entities: usize,
244	/// The blobs that their values refer to.
245	pub(crate) blobs: BTreeSet<Hash>,
246	/// When the last change of the space was recorded, secret values aside, if it has one.
247	pub(crate) as_of: Option<Timestamp>,
248	/// The lines of the changes that they name, in the order they first name them; none in
249	/// an export of current values.
250	pub(crate) changes: Vec<String>,
251}
252
253/// A change as the values of an export name it.
254#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
255enum ChangeKey {
256	/// A change of the log, by its hash.
257	Change(Hash),
258	/// What recorded statements that came in no change, by when they were recorded.
259	Unsigned(Timestamp),
260}
261
262/// The changes that the lines of an export name, numbered in the order they first name
263/// them, each with the line that tells when it was recorded and who made it.
264#[derive(Default)]
265struct Changes {
266	numbers: BTreeMap<ChangeKey, usize>,
267	lines: Vec<String>,
268}
269
270impl Changes {
271	/// The number of a change recorded at `at`, whose author `author` names when the change
272	/// is first seen.
273	fn number(
274		&mut self,
275		key: ChangeKey,
276		at: Timestamp,
277		author: &mut dyn FnMut(Hash) -> Result<Option<Author>, NodeError>,
278	) -> Result<usize, NodeError> {
279		if let Some(&number) = self.numbers.get(&key) {
280			return Ok(number);
281		}
282		let mut line = Map::new();
283		line.insert("recorded".to_owned(), json::moment(at));
284		let author = match key {
285			ChangeKey::Change(hash) => author(hash)?,
286			ChangeKey::Unsigned(_) => None,
287		};
288		if let Some(author) = author {
289			line.insert("replica".to_owned(), json!(author.replica.to_string()));
290			line.insert("user".to_owned(), json!(author.user.id.to_string()));
291			if let Some(person) = author.person {
292				line.insert("person".to_owned(), json!(person.to_string()));
293			}
294			if author.ai_agent.is_some() {
295				line.insert("ai_agent".to_owned(), json!(true));
296			}
297		}
298		let number = self.lines.len();
299		self.lines.push(Json::Object(line).to_string());
300		self.numbers.insert(key, number);
301		Ok(number)
302	}
303}
304
305/// A value of an entity's line, before the line is written and its change numbered.
306struct Pending {
307	/// When it was first recorded, and its statement's ID, which order the values.
308	at: Timestamp,
309	id: StatementId,
310	/// The change that recorded it, or the purge that stated it again, and when.
311	change: ChangeKey,
312	change_at: Timestamp,
313	/// Its JSON, without the change's number.
314	value: Map<String, Json>,
315}
316
317/// Writes the lines of an export's entities from a state, one call of `line` each, ordered
318/// by entity ID; with, in a full export, the changes they name, whose authors `author`
319/// names by their hashes.
320pub(crate) fn write_entities<S: Statements>(
321	state: &State<S>,
322	types: &Types,
323	languages: &Languages,
324	kind: ExportKind,
325	author: &mut dyn FnMut(Hash) -> Result<Option<Author>, NodeError>,
326	line: &mut dyn FnMut(&str) -> io::Result<()>,
327) -> Result<Written, NodeError>
328where
329	NodeError: From<S::Error>,
330{
331	let storage = state.storage();
332	let secret = types.secret_fields();
333	let mut written = Written {
334		entities: 0,
335		blobs: BTreeSet::new(),
336		as_of: None,
337		changes: Vec::new(),
338	};
339	let mut changes = Changes::default();
340	for entity in storage.described()? {
341		// Thumbnails are made again from the originals (technical design: thumbnails).
342		if state.types(entity)?.contains(&nibkeep_std::THUMBNAIL) {
343			continue;
344		}
345		let mut fields: BTreeMap<FieldName, Vec<Pending>> = BTreeMap::new();
346		// The files the entity's line refers to, which count only if the line is written.
347		let mut blobs = BTreeSet::new();
348		for (field, ids) in storage.of_entity(entity)? {
349			let mut values = Vec::new();
350			for id in ids {
351				let Some(recorded) = storage.get(id)? else {
352					continue;
353				};
354				let replaced = storage.superseded_at(id)?;
355				if secret.contains(&field) {
356					continue;
357				}
358				// The moment of the export is that of the space, what it leaves out included,
359				// secret values aside.
360				for at in [Some(recorded.at), recorded.restated, replaced]
361					.into_iter()
362					.flatten()
363				{
364					written.as_of = written.as_of.max(Some(at));
365				}
366				if kind == ExportKind::Current && replaced.is_some() {
367					continue;
368				}
369				let statement = recorded.statement;
370				for value in std::iter::once(&statement.value)
371					.chain(statement.qualifiers.iter().map(|(_, qualifier)| qualifier))
372				{
373					if let Value::Blob(hash) = value {
374						blobs.insert(*hash);
375					}
376				}
377
378				let mut value = Map::new();
379				value.insert("statement".to_owned(), json!(statement.id.to_string()));
380				json::value(&statement.value, &mut value);
381				if !statement.qualifiers.is_empty() {
382					value.insert(
383						"qualifiers".to_owned(),
384						json::qualifiers(&statement.qualifiers),
385					);
386				}
387				if kind == ExportKind::Full {
388					// A value that a purge stated again came in the purge, later than it was
389					// first recorded.
390					if recorded.restated.is_some() {
391						value.insert("recorded".to_owned(), json::moment(recorded.at));
392					}
393					if let Some(replaced) = replaced {
394						value.insert("replaced".to_owned(), json::moment(replaced));
395					}
396				}
397				let change_at = recorded.restated.unwrap_or(recorded.at);
398				values.push(Pending {
399					at: recorded.at,
400					id: statement.id,
401					change: recorded
402						.change
403						.map_or(ChangeKey::Unsigned(change_at), ChangeKey::Change),
404					change_at,
405					value,
406				});
407			}
408			values.sort_by_key(|pending| (pending.at, pending.id));
409			if !values.is_empty() {
410				fields.insert(field, values);
411			}
412		}
413		if fields.is_empty() || (kind == ExportKind::Current && !is_given(state, entity)?) {
414			continue;
415		}
416		written.blobs.append(&mut blobs);
417		let entity_types: Vec<String> = state
418			.types(entity)?
419			.iter()
420			.map(ToString::to_string)
421			.collect();
422		// Changes are numbered as the line names them, once it is written.
423		let numbered = kind == ExportKind::Full;
424		let object = json!({
425			"id": entity.to_string(),
426			"types": entity_types,
427			"name": display_name(state, types, languages, state.canonical(entity)?)?,
428			"fields": fields_of(fields, numbered.then_some(&mut changes), author)?,
429		});
430		line(&object.to_string()).map_err(|error| NodeError::Export(error.to_string()))?;
431		written.entities += 1;
432	}
433	written.changes = changes.lines;
434	Ok(written)
435}
436
437/// The fields of an entity's line, as JSON; with, if `changes` are given, the number of
438/// each value's change, which they number if it is new, its author named by `author`.
439fn fields_of(
440	fields: BTreeMap<FieldName, Vec<Pending>>,
441	mut changes: Option<&mut Changes>,
442	author: &mut dyn FnMut(Hash) -> Result<Option<Author>, NodeError>,
443) -> Result<Vec<Json>, NodeError> {
444	let mut written = Vec::with_capacity(fields.len());
445	for (field, values) in fields {
446		let mut objects = Vec::with_capacity(values.len());
447		for mut pending in values {
448			if let Some(changes) = &mut changes {
449				let number = changes.number(pending.change, pending.change_at, author)?;
450				pending.value.insert("change".to_owned(), json!(number));
451			}
452			objects.push(Json::Object(pending.value));
453		}
454		written.push(json!({ "name": field.to_string(), "values": objects }));
455	}
456	Ok(written)
457}
458
459/// Whether an export of current values holds an entity: one that is not deleted, and not
460/// one of NibKeep's own records.
461fn is_given<S: Statements>(state: &State<S>, entity: EntityId) -> Result<bool, NodeError>
462where
463	NodeError: From<S::Error>,
464{
465	if state.is_deleted(entity)? {
466		return Ok(false);
467	}
468	let held = state.types(entity)?;
469	Ok(!OWN_RECORDS.iter().any(|own| held.contains(own)))
470}
471
472/// The authors of changes, each found once per signing key.
473#[derive(Default)]
474struct Authors {
475	by_key: BTreeMap<String, Option<Author>>,
476}
477
478impl Authors {
479	fn of<S: Statements>(
480		&mut self,
481		open: &Space,
482		stored: &StoredLog,
483		state: &State<S>,
484		change: Hash,
485		languages: &Languages,
486	) -> Result<Option<Author>, NodeError>
487	where
488		NodeError: From<S::Error>,
489	{
490		let Some(key) = stored
491			.log()
492			.change(nibkeep_log::ChangeId::from_hash(change))?
493			.map(|change| *change.author())
494		else {
495			return Ok(None);
496		};
497		let text = key.to_text();
498		if let Some(author) = self.by_key.get(&text) {
499			return Ok(author.clone());
500		}
501		let author = Library::author_in(open, stored, state, &key, languages)?;
502		self.by_key.insert(text, author.clone());
503		Ok(author)
504	}
505}
506
507/// Copies a file that the replica holds into an export, and returns its SHA-256 sum, or
508/// `None`, leaving nothing behind, if the replica does not hold it or cannot read it.
509fn copy_blob(stored: &StoredLog, hash: &Hash, path: &Path) -> io::Result<Option<String>> {
510	if !stored.holds_ordinary_blob(hash) {
511		return Ok(None);
512	}
513	let Ok(mut reader) = stored.open_blob(hash) else {
514		return Ok(None);
515	};
516	if let Some(parent) = path.parent() {
517		fs::create_dir_all(parent)?;
518	}
519	let mut file = Summed::create(path)?;
520	if io::copy(&mut reader, &mut file).is_err() {
521		drop(file);
522		fs::remove_file(path)?;
523		return Ok(None);
524	}
525	file.finish().map(Some)
526}
527
528/// Copies into an export a file that this device holds only where it was found: from the
529/// first place on `device` that holds its content, as its hash tells while it is copied.
530/// Returns its SHA-256 sum, or `None`, leaving nothing behind, if no place does.
531fn copy_in_place(
532	stored: &StoredLog,
533	device: EntityId,
534	hash: &Hash,
535	path: &Path,
536) -> io::Result<Option<String>> {
537	let state = stored.log().state();
538	let Ok(files) = stored.find(&CONTENT, &Value::Blob(*hash)) else {
539		return Ok(None);
540	};
541	let mut places = Vec::new();
542	for file in files {
543		let Ok(origins) = policies::origins_of(state, file) else {
544			continue;
545		};
546		places.extend(
547			origins
548				.into_iter()
549				.filter(|(_, on, _)| *on == device)
550				.map(|(_, _, place)| place),
551		);
552	}
553	for place in places {
554		let Ok(mut original) = File::open(&place) else {
555			continue;
556		};
557		if let Some(parent) = path.parent() {
558			fs::create_dir_all(parent)?;
559		}
560		let mut file = Summed::create(path)?;
561		let mut hasher = nibkeep_base::Hasher::new();
562		let copied = io::copy(&mut original, &mut Both(&mut file, &mut hasher));
563		if copied.is_ok() && hasher.finalize() == *hash {
564			return file.finish().map(Some);
565		}
566		drop(file);
567		fs::remove_file(path)?;
568	}
569	Ok(None)
570}
571
572/// Writes what it is given to two writers.
573struct Both<'a, A, B>(&'a mut A, &'a mut B);
574
575impl<A: Write, B: Write> Write for Both<'_, A, B> {
576	fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
577		let written = self.0.write(bytes)?;
578		self.1.write_all(&bytes[..written])?;
579		Ok(written)
580	}
581
582	fn flush(&mut self) -> io::Result<()> {
583		self.0.flush()?;
584		self.1.flush()
585	}
586}
587
588/// Writes a file and saves it to the disk.
589fn write_synced(path: &Path, bytes: &[u8]) -> io::Result<()> {
590	let mut file = File::create_new(path)?;
591	file.write_all(bytes)?;
592	file.sync_all()
593}
594
595/// Saves a directory's entries to the disk, where the system allows it; a failure leaves
596/// the export as the system keeps it.
597fn sync_directory(directory: &Path) {
598	#[cfg(unix)]
599	if let Ok(opened) = File::open(directory) {
600		let _ = opened.sync_all();
601	}
602	#[cfg(not(unix))]
603	let _ = directory;
604}
605
606/// Where an export keeps a file: `files/blake3/` and the hexadecimal digest.
607fn blob_path(hash: &Hash) -> String {
608	format!("files/{}/{}", hash.algorithm().name(), hex(hash.digest()))
609}
610
611/// Bytes in lowercase hexadecimal.
612fn hex(bytes: &[u8]) -> String {
613	const DIGITS: &[u8; 16] = b"0123456789abcdef";
614	let mut text = String::with_capacity(bytes.len() * 2);
615	for byte in bytes {
616		text.push(char::from(DIGITS[usize::from(byte >> 4)]));
617		text.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
618	}
619	text
620}
621
622/// A file that is summed with SHA-256 as it is written.
623struct Summed {
624	file: BufWriter<File>,
625	sum: Sha256,
626}
627
628impl Summed {
629	fn create(path: &Path) -> io::Result<Self> {
630		Ok(Self {
631			file: BufWriter::new(File::create_new(path)?),
632			sum: Sha256::new(),
633		})
634	}
635
636	/// Saves the file, and returns its sum in hexadecimal.
637	fn finish(self) -> io::Result<String> {
638		let file = self
639			.file
640			.into_inner()
641			.map_err(io::IntoInnerError::into_error)?;
642		file.sync_all()?;
643		Ok(hex(&self.sum.finalize()))
644	}
645}
646
647impl Write for Summed {
648	fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
649		let written = self.file.write(bytes)?;
650		self.sum.update(&bytes[..written]);
651		Ok(written)
652	}
653
654	fn flush(&mut self) -> io::Result<()> {
655		self.file.flush()
656	}
657}
658
659/// The note for people at the top of an export.
660fn readme(kind: ExportKind) -> String {
661	let holds = match kind {
662		ExportKind::Full => {
663			"every value its entities have had, with when each was recorded, by whom, and when it was replaced"
664		}
665		ExportKind::Current => {
666			"the values its entities have now, without who recorded them or when"
667		}
668	};
669	let changes = match kind {
670		ExportKind::Full => {
671			"\n  changes.jsonl    who made each change that its values name, and when"
672		}
673		ExportKind::Current => "",
674	};
675	format!(
676		"This folder is an export of a space of NibKeep, in the format nibkeep-export, version {VERSION}.
677It holds {holds}, as JSON that any program reads, and the files that its values refer to, as they were added.
678
679  manifest.json    what the export holds
680  entities.jsonl   one entity per line, as JSON{changes}
681  files/           the files, named by their BLAKE3 hashes
682  SHA256SUMS       the SHA-256 sum of every other file
683
684To check every file, run:
685
686  sha256sum -c SHA256SUMS
687
688The format is described in docs/spec/export.md of NibKeep's source. This folder is not encrypted: whoever can read it can read everything in it. Secret values are not in it.
689"
690	)
691}
692
693/// What is wrong with an export, compared with the library it came from.
694#[derive(Clone, Debug, PartialEq, Eq)]
695#[non_exhaustive]
696pub enum ExportProblem {
697	/// The folder holds no export that this version reads, for the reason given.
698	NotAnExport(String),
699	/// The export is of a space that the library does not have.
700	OtherSpace(SpaceId),
701	/// A file that `SHA256SUMS` lists is missing, or its sum differs.
702	WrongSum(String),
703	/// A file of the export that `SHA256SUMS` does not list.
704	Unlisted(String),
705	/// An entity that the space held at the export's moment, which the export lacks.
706	MissingEntity(EntityId),
707	/// An entity of the export that the space did not hold at its moment.
708	ExtraEntity(EntityId),
709	/// An entity whose line differs from what the space held at the export's moment.
710	DifferentEntity(EntityId),
711	/// The list of changes, `changes.jsonl`, which differs from the changes that the lines
712	/// should name, or which is missing from a full export or found in one of current values.
713	DifferentChanges,
714	/// A file that the space holds and the export should, but does not.
715	MissingFile(Hash),
716	/// A file of the export whose content does not have the hash it is named by.
717	DifferentFile(Hash),
718	/// A line of `entities.jsonl`, by its number from 1, that is no entity.
719	DamagedLine(usize),
720	/// A file in `files/` that no value of the space referred to at the export's moment.
721	ExtraFile(String),
722	/// A count of the manifest, `entities` or `files`, that is not what the export holds.
723	WrongManifest(String),
724}
725
726/// An export, compared with the library it came from.
727#[derive(Clone, Debug, PartialEq, Eq)]
728pub struct ExportCheck {
729	/// The space it is of, if its manifest says.
730	pub space: Option<SpaceId>,
731	/// The moment it holds the space as of, as its manifest gives it.
732	pub as_of: Option<String>,
733	/// How many entities it holds.
734	pub entities: usize,
735	/// How many files it holds.
736	pub files: usize,
737	/// What is wrong with it: its sums first, by path, then its lines that are no entities,
738	/// its entities, by ID, its list of changes, its files, and its manifest's counts. None
739	/// for an export that holds what the space held at its moment.
740	pub problems: Vec<ExportProblem>,
741}
742
743impl Library {
744	/// Checks an export against the library it came from: every file against `SHA256SUMS`,
745	/// and its entities and files against those that an export of the space as of the
746	/// export's moment holds, so that changes made since do not count. The types the space
747	/// has now decide what is secret and how entities are named, and values purged since are
748	/// gone from the library, so either makes an export differ.
749	///
750	/// # Errors
751	///
752	/// Returns an error if a space cannot be read, or a file of the export.
753	pub fn verify_export(&self, directory: &Path) -> Result<ExportCheck, NodeError> {
754		let mut check = ExportCheck {
755			space: None,
756			as_of: None,
757			entities: 0,
758			files: 0,
759			problems: Vec::new(),
760		};
761		let manifest = match read_manifest(directory) {
762			Ok(manifest) => manifest,
763			Err(why) => {
764				check.problems.push(ExportProblem::NotAnExport(why));
765				return Ok(check);
766			}
767		};
768		check.space = Some(manifest.space);
769		check.as_of.clone_from(&manifest.as_of_text);
770		let Some(open) = self.spaces.get(&manifest.space) else {
771			check
772				.problems
773				.push(ExportProblem::OtherSpace(manifest.space));
774			return Ok(check);
775		};
776		check.problems.extend(check_sums(directory)?);
777		open.stored.reading(|stored| {
778			let then = stored.log().state_as_of(manifest.as_of);
779			let mut expected = Vec::new();
780			let written = entities_of(open, stored, &then, manifest.kind, &mut |line| {
781				expected.push(line.to_owned());
782				Ok(())
783			})?;
784			// A file gone or damaged is told of by the sums; its lines are compared as they are.
785			let held = fs::read(directory.join("entities.jsonl")).unwrap_or_default();
786			let held = String::from_utf8_lossy(&held);
787			let held: Vec<&str> = held.lines().collect();
788			let listed = fs::read(directory.join("changes.jsonl")).ok();
789			let listed = listed.as_deref().map(String::from_utf8_lossy);
790			let listed: Option<Vec<&str>> = listed.as_deref().map(|text| text.lines().collect());
791			let expected_changes: Vec<&str> = written.changes.iter().map(String::as_str).collect();
792			let (problems, entities) = compare_lines(
793				(&expected, &expected_changes),
794				(&held, listed.as_deref().unwrap_or_default()),
795			);
796			check.entities = entities;
797			check.problems.extend(problems);
798			let changes_differ = match (manifest.kind, &listed) {
799				(ExportKind::Full, Some(listed)) => *listed != expected_changes,
800				(ExportKind::Full, None) => true,
801				(ExportKind::Current, listed) => listed.is_some(),
802			};
803			if changes_differ {
804				check.problems.push(ExportProblem::DifferentChanges);
805			}
806			let mut expected_files = BTreeSet::new();
807			for hash in &written.blobs {
808				let relative = blob_path(hash);
809				let path = directory.join(&relative);
810				expected_files.insert(relative);
811				match blake3_of(&path) {
812					Ok(found) => {
813						check.files += 1;
814						if found != *hash {
815							check.problems.push(ExportProblem::DifferentFile(*hash));
816						}
817					}
818					// A file the export says it could not hold, the library may hold since.
819					Err(_) if manifest.missing_files.contains(hash) => {}
820					Err(_) if stored.holds_ordinary_blob(hash) => {
821						check.problems.push(ExportProblem::MissingFile(*hash));
822					}
823					Err(_) => {}
824				}
825			}
826			for relative in files_of(&directory.join("files"))? {
827				let relative = format!("files/{relative}");
828				if !expected_files.contains(&relative) {
829					check.problems.push(ExportProblem::ExtraFile(relative));
830				}
831			}
832			if manifest.entities != Some(check.entities) {
833				check
834					.problems
835					.push(ExportProblem::WrongManifest("entities".to_owned()));
836			}
837			if manifest.files != Some(check.files) {
838				check
839					.problems
840					.push(ExportProblem::WrongManifest("files".to_owned()));
841			}
842			Ok(check)
843		})
844	}
845}
846
847/// What an export's manifest says, as far as a check needs it.
848pub(crate) struct Manifest {
849	pub(crate) space: SpaceId,
850	/// The moment, in milliseconds since 1970; 0 for an export of a space without changes.
851	pub(crate) as_of: u64,
852	pub(crate) as_of_text: Option<String>,
853	pub(crate) kind: ExportKind,
854	/// How many entities and files it says it holds.
855	pub(crate) entities: Option<usize>,
856	pub(crate) files: Option<usize>,
857	/// The files it says the replica did not hold.
858	pub(crate) missing_files: BTreeSet<Hash>,
859}
860
861/// Reads an export's manifest, or says why it is none that this version reads.
862pub(crate) fn read_manifest(directory: &Path) -> Result<Manifest, String> {
863	let text = fs::read_to_string(directory.join("manifest.json"))
864		.map_err(|_| "it has no manifest.json".to_owned())?;
865	let manifest: Json =
866		serde_json::from_str(&text).map_err(|_| "its manifest is no JSON".to_owned())?;
867	if manifest["format"] != "nibkeep-export" {
868		return Err("its manifest names no nibkeep-export".to_owned());
869	}
870	if manifest["version"] != VERSION {
871		return Err(format!(
872			"it is of version {}, which this version does not read",
873			manifest["version"]
874		));
875	}
876	let space = manifest["space"]["id"]
877		.as_str()
878		.and_then(|id| id.parse().ok())
879		.ok_or_else(|| "its manifest names no space".to_owned())?;
880	let kind = match manifest["history"].as_bool() {
881		Some(true) => ExportKind::Full,
882		Some(false) => ExportKind::Current,
883		None => return Err("its manifest does not say whether it holds history".to_owned()),
884	};
885	let as_of_text = manifest["as_of"].as_str().map(str::to_owned);
886	let as_of = match &as_of_text {
887		None => 0,
888		Some(text) => text
889			.parse::<jiff::Timestamp>()
890			.ok()
891			.and_then(|moment| u64::try_from(moment.as_millisecond()).ok())
892			.ok_or_else(|| format!("its moment {text} cannot be read"))?,
893	};
894	let count = |key: &str| {
895		manifest[key]
896			.as_u64()
897			.and_then(|count| usize::try_from(count).ok())
898	};
899	let missing_files = manifest["missing_files"]
900		.as_array()
901		.map_or_default(|hashes| {
902			hashes
903				.iter()
904				.filter_map(|hash| hash.as_str()?.parse().ok())
905				.collect()
906		});
907	Ok(Manifest {
908		space,
909		as_of,
910		as_of_text,
911		kind,
912		entities: count("entities"),
913		files: count("files"),
914		missing_files,
915	})
916}
917
918/// Checks every file of an export against `SHA256SUMS`, and finds the files it does not
919/// list, ordered by path.
920pub(crate) fn check_sums(directory: &Path) -> Result<Vec<ExportProblem>, NodeError> {
921	let path = directory.join("SHA256SUMS");
922	let Ok(sums) = fs::read_to_string(&path) else {
923		return Ok(vec![ExportProblem::WrongSum("SHA256SUMS".to_owned())]);
924	};
925	let mut problems = Vec::new();
926	let mut listed = BTreeSet::new();
927	for line in sums.lines() {
928		let Some((sum, relative)) = line.split_once("  ") else {
929			problems.push(ExportProblem::WrongSum("SHA256SUMS".to_owned()));
930			continue;
931		};
932		listed.insert(relative.to_owned());
933		// A path that leads out of the export, or through a link, names no file of it.
934		let inside = !relative.contains('\\')
935			&& Path::new(relative)
936				.components()
937				.all(|part| matches!(part, std::path::Component::Normal(_)));
938		let path = directory.join(relative);
939		let plain = inside && fs::symlink_metadata(&path).is_ok_and(|found| found.is_file());
940		let matches = plain && sum_of(&path).is_ok_and(|found| found == sum);
941		if !matches {
942			problems.push(ExportProblem::WrongSum(relative.to_owned()));
943		}
944	}
945	for relative in files_of(directory)? {
946		if relative != "SHA256SUMS" && !listed.contains(&relative) {
947			problems.push(ExportProblem::Unlisted(relative));
948		}
949	}
950	problems.sort_by(|one, other| problem_path(one).cmp(problem_path(other)));
951	Ok(problems)
952}
953
954/// The SHA-256 sum of a file, in hexadecimal.
955fn sum_of(path: &Path) -> io::Result<String> {
956	let mut file = File::open(path)?;
957	let mut summing = Sha256::new();
958	let mut buffer = vec![0; 64 * 1024];
959	loop {
960		let read = io::Read::read(&mut file, &mut buffer)?;
961		if read == 0 {
962			return Ok(hex(&summing.finalize()));
963		}
964		summing.update(&buffer[..read]);
965	}
966}
967
968/// The path that a problem with the sums names.
969fn problem_path(problem: &ExportProblem) -> &str {
970	match problem {
971		ExportProblem::WrongSum(path) | ExportProblem::Unlisted(path) => path,
972		_ => "",
973	}
974}
975
976/// Every file under a directory, by its path relative to it, with `/`, ordered.
977pub(crate) fn files_of(directory: &Path) -> Result<Vec<String>, NodeError> {
978	let mut found = Vec::new();
979	let mut to_visit = vec![directory.to_path_buf()];
980	while let Some(next) = to_visit.pop() {
981		let Ok(entries) = fs::read_dir(&next) else {
982			continue;
983		};
984		for entry in entries {
985			let entry = entry.map_err(NodeError::file(&next))?;
986			let path = entry.path();
987			// Links are not followed, so that one cannot lead the walk out or round.
988			if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
989				to_visit.push(path);
990			} else if let Ok(relative) = path.strip_prefix(directory) {
991				let parts: Vec<String> = relative
992					.components()
993					.map(|part| part.as_os_str().to_string_lossy().into_owned())
994					.collect();
995				found.push(parts.join("/"));
996			}
997		}
998	}
999	found.sort();
1000	Ok(found)
1001}
1002
1003/// Compares the lines of entities that an export should hold with those it holds, each
1004/// with the list of changes they name, and says which entities are missing, extra or
1005/// different, and which lines are no entity's; with how many lines are entities. Lines
1006/// that differ only in the numbers of the changes they name, which name the same changes,
1007/// are alike: a change that one list lacks shifts the numbers after it.
1008fn compare_lines(
1009	(expected, expected_changes): (&[String], &[&str]),
1010	(held, held_changes): (&[&str], &[&str]),
1011) -> (Vec<ExportProblem>, usize) {
1012	let id_of = |line: &str| -> Option<EntityId> {
1013		serde_json::from_str::<Json>(line)
1014			.ok()?
1015			.get("id")?
1016			.as_str()?
1017			.parse()
1018			.ok()
1019	};
1020	let mut expected: BTreeMap<EntityId, &str> = expected
1021		.iter()
1022		.filter_map(|line| Some((id_of(line)?, line.as_str())))
1023		.collect();
1024	let mut problems = BTreeMap::new();
1025	let mut damaged = Vec::new();
1026	let mut entities = 0;
1027	for (number, line) in held.iter().enumerate() {
1028		let Some(id) = id_of(line) else {
1029			damaged.push(ExportProblem::DamagedLine(number + 1));
1030			continue;
1031		};
1032		entities += 1;
1033		match expected.remove(&id) {
1034			Some(want)
1035				if want == *line
1036					|| with_changes(want, expected_changes) == with_changes(line, held_changes) => {}
1037			Some(_) => {
1038				problems.insert(id, ExportProblem::DifferentEntity(id));
1039			}
1040			None => {
1041				problems.insert(id, ExportProblem::ExtraEntity(id));
1042			}
1043		}
1044	}
1045	for id in expected.into_keys() {
1046		problems.insert(id, ExportProblem::MissingEntity(id));
1047	}
1048	damaged.extend(problems.into_values());
1049	(damaged, entities)
1050}
1051
1052/// An entity's line with each change it names written out, as its list of changes gives
1053/// it, in place of its number; `None` for a line that is no JSON.
1054fn with_changes(line: &str, changes: &[&str]) -> Option<Json> {
1055	let mut line: Json = serde_json::from_str(line).ok()?;
1056	let values = line
1057		.get_mut("fields")
1058		.and_then(Json::as_array_mut)
1059		.into_iter()
1060		.flatten()
1061		.filter_map(|field| field.get_mut("values").and_then(Json::as_array_mut))
1062		.flatten();
1063	for value in values {
1064		if let Some(number) = value.get("change").and_then(Json::as_u64) {
1065			let change = usize::try_from(number)
1066				.ok()
1067				.and_then(|number| changes.get(number))
1068				.map_or(Json::Null, |change| Json::from(*change));
1069			value["change"] = change;
1070		}
1071	}
1072	Some(line)
1073}
1074
1075/// The BLAKE3 hash of a file, read as a stream.
1076pub(crate) fn blake3_of(path: &Path) -> io::Result<Hash> {
1077	let read = nibkeep_store::hash_file(path, &|| false)?;
1078	read.map(|(hash, _)| hash)
1079		.ok_or_else(|| io::Error::other("stopped"))
1080}