Skip to main content

nibkeep_node/library/
deleting_types.rs

1//! Deleting a type that a space defines, and restoring it: its definitions are deleted, as
2//! any entity is, hidden and kept, so that the space's types leave it out, with its fields
3//! where no other type lists them, until it is restored whole
4//! ([data model](../../../../docs/spec/model.md#8-types)).
5
6use std::collections::{BTreeMap, BTreeSet};
7
8use nibkeep_base::{EntityId, SpaceId, StatementId};
9use nibkeep_crypto::rand_core::CryptoRng;
10use nibkeep_model::schema::TYPE_DEFINITION;
11use nibkeep_model::storage::Statements;
12use nibkeep_model::{Operation, State, Statement, TypeName, Value, fields};
13
14use super::{Library, entities};
15use crate::NodeError;
16
17impl Library {
18	/// Deletes a type that a space defines: each of its definitions that is not deleted,
19	/// in one change. The space's types then leave it out, and the fields that only it
20	/// lists; [`Library::restore_type`] brings it back with them. Only a type of the space's
21	/// own is deleted, not one of the standard vocabulary, which comes back as it is
22	/// installed, nor one of NibKeep's, which is defined in code; and only once no entity
23	/// that is not deleted has it, so that no entity is left with a type that no
24	/// definition makes.
25	///
26	/// # Errors
27	///
28	/// Returns [`NodeError::NotOwnType`] for a standard type or one defined in code;
29	/// [`NodeError::NoTypeDefined`] if the space has no definition of it that is not
30	/// deleted; [`NodeError::TypeInUse`] if entities still have it;
31	/// [`NodeError::AiAgentMayNot`] if this replica is an AI agent's; and another error if
32	/// the library has no such space, or the change cannot be saved.
33	pub fn delete_type(
34		&mut self,
35		space: SpaceId,
36		kind: &TypeName,
37		wall_millis: u64,
38		rng: &mut impl CryptoRng,
39	) -> Result<(), NodeError> {
40		self.check_not_ai_agent("delete a type")?;
41		self.check_own_type(kind)?;
42		let operations = {
43			let open = self.space(space)?;
44			let state = open.stored.log().state();
45			let definitions = self.definitions(space, kind, false)?;
46			if definitions.is_empty() {
47				return Err(NodeError::NoTypeDefined(kind.clone()));
48			}
49			let mut having = BTreeSet::new();
50			for entity in entities::with_type(&open.stored, kind)? {
51				let entity = state.canonical(entity)?;
52				if !state.is_deleted(entity)? {
53					having.insert(entity);
54				}
55			}
56			if !having.is_empty() {
57				return Err(NodeError::TypeInUse {
58					kind: kind.clone(),
59					entities: having.len(),
60				});
61			}
62			definitions
63				.into_iter()
64				.map(|definition| {
65					let statement = Statement::new(
66						StatementId::random(rng),
67						definition,
68						fields::DELETED,
69						Value::Boolean(true),
70					);
71					Operation::replace(statement, Vec::new())
72				})
73				.collect::<Vec<_>>()
74		};
75		self.commit(space, operations, wall_millis, rng)
76	}
77
78	/// The types of a space's own that it deleted: those whose definitions are all deleted,
79	/// which [`Library::restore_type`] brings back, ordered by name.
80	///
81	/// # Errors
82	///
83	/// Returns an error if the library has no such space, or the space cannot be read.
84	pub fn deleted_types(&self, space: SpaceId) -> Result<Vec<TypeName>, NodeError> {
85		let types = &self.space(space)?.types;
86		let deleted: BTreeSet<TypeName> = deleted_definitions(self, space)?
87			.into_values()
88			.filter(|kind| types.get(kind).is_none())
89			.collect();
90		Ok(deleted.into_iter().collect())
91	}
92
93	/// Restores a type that a space deleted: each of its deleted definitions, in one change,
94	/// so that it comes back with the fields it had.
95	///
96	/// # Errors
97	///
98	/// Returns [`NodeError::NotOwnType`] for a standard type or one defined in code;
99	/// [`NodeError::NoTypeDefined`] if the space has no deleted definition of it;
100	/// [`NodeError::AiAgentMayNot`] if this replica is an AI agent's; and another error if
101	/// the library has no such space, or the change cannot be saved.
102	pub fn restore_type(
103		&mut self,
104		space: SpaceId,
105		kind: &TypeName,
106		wall_millis: u64,
107		rng: &mut impl CryptoRng,
108	) -> Result<(), NodeError> {
109		self.check_not_ai_agent("restore a type")?;
110		self.check_own_type(kind)?;
111		let operations = {
112			let state = self.space(space)?.stored.log().state();
113			let mut operations = Vec::new();
114			for definition in self.definitions(space, kind, true)? {
115				let deletions: Vec<StatementId> = state
116					.current(definition, &fields::DELETED)?
117					.iter()
118					.map(|statement| statement.id)
119					.collect();
120				if !deletions.is_empty() {
121					operations.push(Operation::retract(definition, deletions));
122				}
123			}
124			operations
125		};
126		if operations.is_empty() {
127			return Err(NodeError::NoTypeDefined(kind.clone()));
128		}
129		self.commit(space, operations, wall_millis, rng)
130	}
131
132	/// Refuses a type that is not the space's own to delete or restore: a standard one, or
133	/// one that NibKeep or an app defines in code.
134	fn check_own_type(&self, kind: &TypeName) -> Result<(), NodeError> {
135		if kind.as_str().starts_with("std.")
136			|| kind.is_nibkeep()
137			|| self.code_types.get(kind).is_some()
138		{
139			return Err(NodeError::NotOwnType(kind.clone()));
140		}
141		Ok(())
142	}
143
144	/// The definitions of a type in a space, those deleted if `deleted`, else the others.
145	fn definitions(
146		&self,
147		space: SpaceId,
148		kind: &TypeName,
149		deleted: bool,
150	) -> Result<Vec<EntityId>, NodeError> {
151		if deleted {
152			return Ok(deleted_definitions(self, space)?
153				.into_iter()
154				.filter(|(_, named)| named == kind)
155				.map(|(definition, _)| definition)
156				.collect());
157		}
158		let open = self.space(space)?;
159		let state = open.stored.log().state();
160		let mut found = BTreeSet::new();
161		for entity in entities::with_type(&open.stored, &TYPE_DEFINITION)? {
162			let entity = state.canonical(entity)?;
163			if !state.is_deleted(entity)? && type_named_in(state, entity)?.as_ref() == Some(kind) {
164				found.insert(entity);
165			}
166		}
167		Ok(found.into_iter().collect())
168	}
169}
170
171/// The deleted entities of a space that define types, with the types they name. The index
172/// of values leaves deleted entities out, so the space's entities are read, in one
173/// transaction, as the deleted entities are listed.
174fn deleted_definitions(
175	library: &Library,
176	space: SpaceId,
177) -> Result<BTreeMap<EntityId, TypeName>, NodeError> {
178	library.space(space)?.stored.reading(|stored| {
179		let state = stored.log().state();
180		let mut found = BTreeMap::new();
181		for entity in state.storage().entities()? {
182			let entity = state.canonical(entity)?;
183			if !found.contains_key(&entity)
184				&& state.is_deleted(entity)?
185				&& state.types(entity)?.contains(&TYPE_DEFINITION)
186				&& let Some(kind) = type_named_in(state, entity)?
187			{
188				found.insert(entity, kind);
189			}
190		}
191		Ok(found)
192	})
193}
194
195/// The type that a definition names, if this version can read its name.
196fn type_named_in<S: Statements>(
197	state: &State<S>,
198	definition: EntityId,
199) -> Result<Option<TypeName>, NodeError>
200where
201	NodeError: From<S::Error>,
202{
203	Ok(state
204		.current(definition, &fields::TYPE_NAME)?
205		.iter()
206		.find_map(|statement| statement.value.as_text()?.parse().ok()))
207}