Skip to main content

nibkeep_node/library/
import.rs

1//! Imports: an export brought into a space, adding what it holds and the space lacks
2//! (`docs/spec/export.md`, section 7).
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fs::File;
6use std::io;
7use std::path::Path;
8
9use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_governance::{LINKED_PERSON, PERSON, USER};
12use nibkeep_log::History as _;
13use nibkeep_model::schema::{FIELD_DEFINITION, TYPE_DEFINITION};
14use nibkeep_model::storage::Statements as _;
15use nibkeep_model::{FieldName, Operation, State, Statement, TypeName, Types, Value, fields};
16use nibkeep_time::Timestamp;
17use serde_json::Value as Json;
18
19use super::entities::display_name;
20use super::export::{
21	ExportProblem, Manifest, OWN_RECORDS, blake3_of, check_sums, files_of, read_manifest,
22};
23use super::json;
24use super::{Described, Library};
25use crate::NodeError;
26
27/// How many entities' changes an import saves in one batch.
28const BATCH: usize = 1_000;
29
30/// What an import brought in.
31#[derive(Clone, Debug, Default, PartialEq, Eq)]
32pub struct Imported {
33	/// How many entities it read, those left out aside: NibKeep's own records, and the
34	/// definitions of the types left out.
35	pub entities: usize,
36	/// How many statements it added.
37	pub added: usize,
38	/// How many statements it replaced, as the export shows them replaced.
39	pub replaced: usize,
40	/// How many entities it left out: NibKeep's own records of users, devices, replicas and
41	/// spaces.
42	pub skipped: usize,
43	/// How many files it added.
44	pub files: usize,
45	/// The types whose definitions it left out, as the space defines them otherwise, such as
46	/// with a field of another kind.
47	pub types_left_out: Vec<TypeName>,
48	/// The person of the export's user, whom it took for the library's user, in place of the
49	/// person that the new library made, which it deleted.
50	pub person: Option<Described>,
51}
52
53/// A line of an export's entities, as an import reads it: its entity, whether it is one of
54/// NibKeep's own records, and its statements, each with whether the export shows it replaced.
55struct Line {
56	entity: EntityId,
57	own_record: bool,
58	held: Vec<(Statement, bool)>,
59}
60
61/// What an entity of an export defines, if it defines a type or a field.
62enum Definition {
63	/// A type, by its name.
64	Type(TypeName),
65	/// A field of the type that the entity it refers to defines.
66	Field(EntityId),
67}
68
69impl Line {
70	/// The statements of the line that the export shows current.
71	fn current(&self) -> impl Iterator<Item = &Statement> {
72		self.held
73			.iter()
74			.filter(|(_, replaced)| !replaced)
75			.map(|(statement, _)| statement)
76	}
77
78	/// Of a record of a user, the persons that the user is linked to.
79	fn linked_persons(&self) -> Option<BTreeSet<EntityId>> {
80		let user = self.own_record
81			&& self.current().any(|statement| {
82				statement.field == fields::TYPE && statement.value.as_text() == Some(USER.as_str())
83			});
84		user.then(|| {
85			self.current()
86				.filter(|statement| statement.field == LINKED_PERSON)
87				.filter_map(|statement| statement.value.as_reference())
88				.collect()
89		})
90	}
91
92	/// What the entity defines, by its current statements, if it is not one of NibKeep's own
93	/// records and defines a type or a field. Of competing names, the one in the statement
94	/// with the smallest ID counts, as a space reads its definitions.
95	fn definition(&self) -> Option<Definition> {
96		if self.own_record {
97			return None;
98		}
99		let first = |field: &FieldName| {
100			self.current()
101				.filter(|statement| statement.field == *field)
102				.min_by_key(|statement| statement.id)
103		};
104		let is = |kind: &TypeName| {
105			self.current().any(|statement| {
106				statement.field == fields::TYPE && statement.value.as_text() == Some(kind.as_str())
107			})
108		};
109		if is(&TYPE_DEFINITION) {
110			first(&fields::TYPE_NAME)
111				.and_then(|name| name.value.as_text()?.parse().ok())
112				.map(Definition::Type)
113		} else if is(&FIELD_DEFINITION) {
114			first(&fields::FIELD_OF)
115				.and_then(|of| of.value.as_reference())
116				.map(Definition::Field)
117		} else {
118			None
119		}
120	}
121}
122
123impl Library {
124	/// Imports an export into a space, as `docs/spec/export.md` says: its files, and each of
125	/// its statements that the space lacks, with their IDs, replaced as the export shows them;
126	/// never NibKeep's own records of users, devices, replicas and spaces, nor the fields that
127	/// govern a space. Importing an export again adds nothing. Changes are saved in batches.
128	///
129	/// # Errors
130	///
131	/// Returns an error if the library has no such space; if the folder holds no export
132	/// that this version reads, one whose sums or counts do not match, or one of this space
133	/// made before one of its purges, of which nothing is imported; or if a file cannot be
134	/// read or the changes saved, and then how far the import got.
135	pub fn import(
136		&mut self,
137		space: SpaceId,
138		directory: &Path,
139		wall_millis: u64,
140		rng: &mut impl CryptoRng,
141	) -> Result<Imported, NodeError> {
142		let manifest = read_manifest(directory).map_err(NodeError::ExportDamaged)?;
143		self.check_not_purged_since(space, &manifest)?;
144		let unmatched = check_sums(directory)?
145			.into_iter()
146			.find_map(|problem| match problem {
147				ExportProblem::WrongSum(path) | ExportProblem::Unlisted(path) => Some(path),
148				_ => None,
149			});
150		if let Some(path) = unmatched {
151			return Err(NodeError::ExportDamaged(format!(
152				"the sums do not match {path}"
153			)));
154		}
155		// A first reading checks every line, so that a damaged one imports nothing, and keeps
156		// the definitions of types and fields, which are few and come in first; the second
157		// imports the rest, a batch at a time, without holding the export in memory.
158		let path = directory.join("entities.jsonl");
159		let mut lines = 0;
160		let mut definitions = Vec::new();
161		let mut users = Vec::new();
162		for_lines(&path, &mut |number, line| {
163			let line = read_line(line).map_err(|why| damaged_line(number, &why))?;
164			if line.definition().is_some() {
165				definitions.push(line);
166			} else if let Some(persons) = line.linked_persons() {
167				users.push(persons);
168			}
169			lines += 1;
170			Ok(())
171		})?;
172		// The person that the export's user is, of an export of one user, linked to one.
173		let person = match users.as_slice() {
174			[persons] if persons.len() == 1 => persons.first().copied(),
175			_ => None,
176		};
177		if manifest.entities != Some(lines) {
178			return Err(NodeError::ExportDamaged(
179				"its manifest counts another number of entities".to_owned(),
180			));
181		}
182		let mut imported = Imported {
183			files: self.import_files(space, directory, &manifest, wall_millis, rng)?,
184			..Imported::default()
185		};
186		let mut ended =
187			self.import_definitions(space, definitions, &mut imported, wall_millis, rng);
188		if ended.is_ok() {
189			let mut batch = Vec::with_capacity(BATCH);
190			let read = for_lines(&path, &mut |number, line| {
191				let line = read_line(line).map_err(|why| damaged_line(number, &why))?;
192				if line.definition().is_some() {
193					return Ok(());
194				}
195				batch.push(line);
196				if batch.len() == BATCH {
197					let lines = std::mem::take(&mut batch);
198					self.import_batch(space, &lines, &mut imported, wall_millis, rng)?;
199				}
200				Ok(())
201			});
202			ended = read
203				.and_then(|()| self.import_batch(space, &batch, &mut imported, wall_millis, rng));
204		}
205		if ended.is_ok()
206			&& let Some(person) = person
207		{
208			ended = self
209				.take_person(space, person, wall_millis, rng)
210				.map(|taken| imported.person = taken);
211		}
212		// What was saved before a failure stays; importing again brings in the rest.
213		ended.map_err(|error| NodeError::ImportStopped {
214			entities: imported.entities + imported.skipped,
215			error: Box::new(error),
216		})?;
217		Ok(imported)
218	}
219
220	/// Refuses an export of this space made before one of its purges, which may hold what
221	/// the purge destroyed. Statements purged leave no trace of their IDs, so the time
222	/// decides.
223	fn check_not_purged_since(&self, space: SpaceId, manifest: &Manifest) -> Result<(), NodeError> {
224		if manifest.space != space {
225			return Ok(());
226		}
227		let log = self.space(space)?.stored.log();
228		for purge in log.history().purging()? {
229			if log
230				.change(purge)?
231				.is_some_and(|change| change.timestamp().millis() > manifest.as_of)
232			{
233				return Err(NodeError::ExportDamaged(
234					"the space purged values since it was made, which it may hold".to_owned(),
235				));
236			}
237		}
238		Ok(())
239	}
240
241	/// Imports the files of an export that the space does not hold, each checked against
242	/// the hash it is named by, and returns how many it imported.
243	fn import_files(
244		&mut self,
245		space: SpaceId,
246		directory: &Path,
247		manifest: &Manifest,
248		wall_millis: u64,
249		rng: &mut impl CryptoRng,
250	) -> Result<usize, NodeError> {
251		let names = files_of(&directory.join("files"))?;
252		if manifest.files != Some(names.len()) {
253			return Err(NodeError::ExportDamaged(
254				"its manifest counts another number of files".to_owned(),
255			));
256		}
257		let mut imported = 0;
258		for relative in names {
259			let damaged =
260				|| NodeError::ExportDamaged(format!("files/{relative} is named by no hash"));
261			let (algorithm, digest) = relative.split_once('/').ok_or_else(damaged)?;
262			let hash: Hash = format!("{algorithm}:{digest}")
263				.parse()
264				.map_err(|_| damaged())?;
265			if self.space(space)?.stored.holds_ordinary_blob(&hash) {
266				continue;
267			}
268			let path = directory.join("files").join(&relative);
269			if blake3_of(&path).map_err(NodeError::file(&path))? != hash {
270				return Err(NodeError::ExportDamaged(format!(
271					"files/{relative} does not have the hash it is named by"
272				)));
273			}
274			let file = File::open(&path).map_err(NodeError::file(&path))?;
275			self.import_blob(space, file, wall_millis, rng)?;
276			imported += 1;
277		}
278		Ok(imported)
279	}
280
281	/// Imports the definitions of types and fields of an export (`docs/spec/export.md`,
282	/// section 7): as they are, with their IDs, where the space has their type's entity or
283	/// defines no such type; else adding to the space's own definition what they hold and it
284	/// lacks, as defining the type again does, or leaving the type out if the space cannot
285	/// take it as it is.
286	fn import_definitions(
287		&mut self,
288		space: SpaceId,
289		lines: Vec<Line>,
290		imported: &mut Imported,
291		wall_millis: u64,
292		rng: &mut impl CryptoRng,
293	) -> Result<(), NodeError> {
294		// The export's entities of types that the space defines with entities of its own.
295		let mut merged = BTreeMap::new();
296		{
297			let open = self.space(space)?;
298			let storage = open.stored.log().state().storage();
299			for line in &lines {
300				if let Some(Definition::Type(name)) = line.definition()
301					&& open.types.defines_in_space(&name)
302					&& storage.of_entity(line.entity)?.is_empty()
303				{
304					merged.insert(line.entity, name);
305				}
306			}
307		}
308		let (merging, as_they_are): (Vec<Line>, Vec<Line>) =
309			lines.into_iter().partition(|line| match line.definition() {
310				Some(Definition::Type(_)) => merged.contains_key(&line.entity),
311				Some(Definition::Field(of)) => merged.contains_key(&of),
312				None => false,
313			});
314		// Those that come in as they are go together in one change, as definitions do.
315		let mut operations = Vec::new();
316		for line in &as_they_are {
317			operations.extend(self.lacking(space, line, imported)?);
318		}
319		if !operations.is_empty() {
320			self.commit(space, operations, wall_millis, rng)?;
321		}
322		// What the rest define, read as a space reads its own definitions, with how many lines
323		// each type takes.
324		let mut state = State::new();
325		let mut lines_of: BTreeMap<TypeName, usize> = BTreeMap::new();
326		for line in &merging {
327			let name = match line.definition() {
328				Some(Definition::Type(name)) => Some(name),
329				Some(Definition::Field(of)) => merged.get(&of).cloned(),
330				None => None,
331			};
332			if let Some(name) = name {
333				*lines_of.entry(name).or_default() += 1;
334			}
335			for (statement, replaced) in &line.held {
336				if !replaced {
337					let Ok(()) = state.apply(
338						&Operation::assert(statement.clone()),
339						Timestamp::new(wall_millis, 0),
340					);
341				}
342			}
343		}
344		let mut defined = Types::new();
345		let Ok(()) = defined.read(&state);
346		let mut read = merging.len();
347		for definition in defined.defined_by_space() {
348			let careful = {
349				let types = &self.space(space)?.types;
350				let careful = types.careful(definition);
351				types.check(&careful).is_ok().then_some(careful)
352			};
353			let Some(careful) = careful else {
354				read -= lines_of.get(definition.name()).copied().unwrap_or(0);
355				imported.types_left_out.push(definition.name().clone());
356				continue;
357			};
358			imported.added += self.define_lacking(space, &careful, wall_millis, rng)?;
359		}
360		imported.entities += read;
361		Ok(())
362	}
363
364	/// Takes the person of the export's user for the library's user (`docs/spec/export.md`,
365	/// section 7), in the personal space, where a new library links its user to a person:
366	/// links the user to that person, and deletes the one that the user was linked to, if it
367	/// holds only its type and a name, as a new library makes it, and no value refers to it
368	/// but that link. Returns the person taken, if any.
369	fn take_person(
370		&mut self,
371		space: SpaceId,
372		person: EntityId,
373		wall_millis: u64,
374		rng: &mut impl CryptoRng,
375	) -> Result<Option<Described>, NodeError> {
376		if space != self.info.personal {
377			return Ok(None);
378		}
379		let user = self.info.user;
380		let (link, made, name) = {
381			let open = self.space(space)?;
382			let state = open.stored.log().state();
383			let storage = state.storage();
384			if state.fields(person)?.is_empty()
385				|| state.is_deleted(person)?
386				|| state
387					.types(person)?
388					.iter()
389					.any(|kind| OWN_RECORDS.contains(kind))
390			{
391				return Ok(None);
392			}
393			let links = state.current(user, &LINKED_PERSON)?;
394			let [link] = links.as_slice() else {
395				return Ok(None);
396			};
397			let Some(made) = link.value.as_reference() else {
398				return Ok(None);
399			};
400			if link.entity != user || state.canonical(made)? == state.canonical(person)? {
401				return Ok(None);
402			}
403			// Only its type, a person, and a name, never replaced, nor merged with another.
404			let statements = storage.of_entity(made)?;
405			let mut only_named = statements.len() == 2 && state.merged(made)?.len() == 1;
406			for (field, ids) in &statements {
407				let [id] = ids.as_slice() else {
408					only_named = false;
409					break;
410				};
411				only_named &= (*field == fields::NAME
412					|| (*field == fields::TYPE
413						&& storage.get(*id)?.is_some_and(|recorded| {
414							recorded.statement.value.as_text() == Some(PERSON.as_str())
415						})))
416					&& !storage.is_superseded(*id)?;
417			}
418			let referrers = state.referrers(made)?;
419			if !only_named || !matches!(referrers.as_slice(), [only] if only.id == link.id) {
420				return Ok(None);
421			}
422			let name = display_name(state, &open.types, &self.languages, person)?;
423			(link.id, made, name)
424		};
425		let linked = Statement::new(
426			StatementId::random(rng),
427			user,
428			LINKED_PERSON,
429			Value::Reference(person),
430		);
431		let deleted = Statement::new(
432			StatementId::random(rng),
433			made,
434			fields::DELETED,
435			Value::Boolean(true),
436		);
437		// A change for each, saved together: both or neither.
438		let operations = vec![
439			Operation::replace(linked, [link]),
440			Operation::assert(deleted),
441		];
442		self.commit(space, operations, wall_millis, rng)?;
443		Ok(Some(Described { id: person, name }))
444	}
445
446	/// Imports lines of an export in one batch.
447	fn import_batch(
448		&mut self,
449		space: SpaceId,
450		lines: &[Line],
451		imported: &mut Imported,
452		wall_millis: u64,
453		rng: &mut impl CryptoRng,
454	) -> Result<(), NodeError> {
455		if lines.is_empty() {
456			return Ok(());
457		}
458		self.batch(space, |library| {
459			for line in lines {
460				library.import_entity(space, line, imported, wall_millis, rng)?;
461			}
462			Ok(())
463		})
464	}
465
466	/// Imports one entity of an export: the statements of its line that the space lacks,
467	/// and the replacements that it lacks, in one change.
468	fn import_entity(
469		&mut self,
470		space: SpaceId,
471		line: &Line,
472		imported: &mut Imported,
473		wall_millis: u64,
474		rng: &mut impl CryptoRng,
475	) -> Result<(), NodeError> {
476		let operations = self.lacking(space, line, imported)?;
477		if operations.is_empty() {
478			return Ok(());
479		}
480		self.commit(space, operations, wall_millis, rng)
481	}
482
483	/// What the space lacks of a line of an export, counted in `imported`: the assertions of
484	/// the statements it does not hold, and a retraction of those that the export shows
485	/// replaced and it does not; nothing of NibKeep's own records, nor of the fields that
486	/// govern a space.
487	fn lacking(
488		&self,
489		space: SpaceId,
490		line: &Line,
491		imported: &mut Imported,
492	) -> Result<Vec<Operation>, NodeError> {
493		if line.own_record {
494			imported.skipped += 1;
495			return Ok(Vec::new());
496		}
497		imported.entities += 1;
498		let mut operations = Vec::new();
499		let mut retract: Vec<StatementId> = Vec::new();
500		{
501			let storage = self.space(space)?.stored.log().state().storage();
502			for (statement, replaced) in &line.held {
503				if fields::is_governing(&statement.field) {
504					continue;
505				}
506				let known = storage.contains(statement.id)?;
507				if !known {
508					operations.push(Operation::assert(statement.clone()));
509					imported.added += 1;
510				}
511				if *replaced && (!known || !storage.is_superseded(statement.id)?) {
512					retract.push(statement.id);
513				}
514			}
515		}
516		if let Some((statement, _)) = line.held.first()
517			&& !retract.is_empty()
518		{
519			imported.replaced += retract.len();
520			operations.push(Operation::retract(statement.entity, retract));
521		}
522		Ok(operations)
523	}
524}
525
526/// Reads a line of an export's entities.
527fn read_line(line: &str) -> Result<Line, String> {
528	let line: Json = serde_json::from_str(line).map_err(|_| "no JSON".to_owned())?;
529	let entity: EntityId = line["id"]
530		.as_str()
531		.and_then(|id| id.parse().ok())
532		.ok_or("no entity's ID")?;
533	let is_own = |kind: &str| OWN_RECORDS.iter().any(|own| own.as_str() == kind);
534	let mut own_record = line["types"]
535		.as_array()
536		.is_some_and(|types| types.iter().filter_map(Json::as_str).any(is_own));
537	let mut held = Vec::new();
538	for field in line["fields"].as_array().ok_or("no fields")? {
539		let name: FieldName = field["name"]
540			.as_str()
541			.and_then(|name| name.parse().ok())
542			.ok_or("a field without a name")?;
543		for value in field["values"].as_array().ok_or("a field without values")? {
544			let object = value.as_object().ok_or("a value that is no object")?;
545			let id: StatementId = value["statement"]
546				.as_str()
547				.and_then(|id| id.parse().ok())
548				.ok_or("a value without its statement's ID")?;
549			// Qualifiers are left out where there are none; an export may write them empty.
550			let qualifiers = match value.get("qualifiers") {
551				Some(qualifiers) => json::parse_qualifiers(qualifiers)?,
552				None => nibkeep_model::Qualifiers::new(),
553			};
554			let statement = Statement::new(id, entity, name.clone(), json::parse_value(object)?)
555				.with_qualifiers(qualifiers);
556			// A record of who uses a library is one by any type it was given, whatever the
557			// line lists.
558			if statement.field == fields::TYPE && statement.value.as_text().is_some_and(is_own) {
559				own_record = true;
560			}
561			let replaced = value
562				.get("replaced")
563				.is_some_and(|replaced| !replaced.is_null());
564			held.push((statement, replaced));
565		}
566	}
567	Ok(Line {
568		entity,
569		own_record,
570		held,
571	})
572}
573
574/// Calls `each` with every line of a file and its number from 1.
575fn for_lines(
576	path: &Path,
577	each: &mut dyn FnMut(usize, &str) -> Result<(), NodeError>,
578) -> Result<(), NodeError> {
579	let file = File::open(path).map_err(NodeError::file(path))?;
580	for (index, line) in io::BufRead::lines(io::BufReader::new(file)).enumerate() {
581		let line = line.map_err(NodeError::file(path))?;
582		each(index + 1, &line)?;
583	}
584	Ok(())
585}
586
587/// The error of a line of an export's entities that cannot be read.
588fn damaged_line(number: usize, why: &str) -> NodeError {
589	NodeError::ExportDamaged(format!("line {number} of entities.jsonl: {why}"))
590}