nibkeep_node/library/purge.rs
1//! Purging values for good: every change that asserted them loses its key and payload, and
2//! the purge states again what else they held ([technical design: purging]). A value that refers to
3//! a blob, such as a file's content, takes the blob with it, and the checkouts of its
4//! content ([technical design: checkouts]).
5//!
6//! [technical design: purging]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#64-purging
7//! [technical design: checkouts]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#92-checkouts
8
9use std::collections::BTreeSet;
10use std::path::PathBuf;
11
12use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
13use nibkeep_crypto::rand_core::CryptoRng;
14use nibkeep_model::storage::Statements;
15use nibkeep_model::{FieldName, Value};
16use nibkeep_std::{CHECKOUT, CONTENT, FOUND_ON, ORIGIN, PATH};
17
18use super::Library;
19use crate::NodeError;
20
21/// What a purge takes away: the statements of the values, current or past, and how many
22/// changes lose their keys and payloads; the content they refer to, with its sealed copies
23/// and this device's checkouts of it; and the originals of that content that NibKeep knows
24/// of, which it leaves where they are.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct Purge {
27 /// The statements of the values, and of every other value that holds content that they
28 /// hold.
29 pub statements: Vec<StatementId>,
30 /// How many changes that asserted them lose their keys and payloads, and are stated
31 /// again without them.
32 pub changes: usize,
33 /// How many of the values are secret, and lose only their own keys.
34 pub secret: usize,
35 /// The content hashes of the blobs that the values refer to, which are purged with them.
36 pub contents: Vec<Hash>,
37 /// Whether that content is a secret field's, such as a secret file's, whose secret
38 /// copies are purged; or else an ordinary field's, whose ordinary copies are. The same
39 /// content in fields of the other kind is sealed apart, and stays ([technical design: secret files]).
40 ///
41 /// [technical design: secret files]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#95-secret-files
42 pub of_secrets: bool,
43 /// How many sealed copies of that content lose their keys: those whose keys this replica
44 /// has opened.
45 pub blobs: usize,
46 /// The replica's other spaces that keep that content too, ordered by ID: those that keep
47 /// a key, open or not, for a sealed copy that this space purges, and those that read
48 /// another copy of it with a key of the same kind. A purge destroys only its own space's
49 /// keys, so the content stays there, and an app says so before the purge. Spaces that
50 /// this replica does not hold are not known ([technical design: spaces and moves]).
51 ///
52 /// [technical design: spaces and moves]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#131-spaces-and-moves
53 pub elsewhere: Vec<SpaceId>,
54 /// The entities other than the one purged whose values hold that content, current or
55 /// past, which lose it too, but the origins and checkouts of files, and thumbnails: files
56 /// with the same content, and any other value that refers to it.
57 pub also: Vec<EntityId>,
58 /// The thumbnails made of that content, ordered by ID, which are purged whole, their own
59 /// content too ([technical design: thumbnails]).
60 ///
61 /// [technical design: thumbnails]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#98-thumbnails
62 pub thumbnails: Vec<EntityId>,
63 /// The checkouts on this device of that content, ordered by path.
64 pub checkouts: Vec<PurgedCheckout>,
65 /// The copies on this device of trees' files whose version holds that content, ordered by
66 /// path ([technical design: trees]).
67 ///
68 /// [technical design: trees]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#15-trees
69 pub tree_copies: Vec<PurgedCheckout>,
70 /// Where files with that content were found, on which device, ordered by device and
71 /// path: their originals, which a purge leaves where they are.
72 pub originals: Vec<(EntityId, String)>,
73 /// The person's own copies that wait before they destroy what the purge destroys, as a
74 /// purge says before the person confirms: this device first
75 /// ([technical design: copies that wait]).
76 ///
77 /// [technical design: copies that wait]: https://github.com/nibkeep/nibkeep/blob/main/docs/Technical-design.md#911-copies-that-wait
78 pub waiting: Vec<super::waiting::WaitingCopy>,
79}
80
81/// What a purge of content takes away besides the values named: the content, the entities
82/// whose values hold it, as they show, and the thumbnails made of it.
83struct ContentsPurged {
84 contents: BTreeSet<Hash>,
85 holders: BTreeSet<EntityId>,
86 thumbnails: BTreeSet<EntityId>,
87}
88
89/// A copy on this device of content that a purge takes away: a checkout's, or a tree's file's.
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct PurgedCheckout {
92 /// Where its copy is.
93 pub path: PathBuf,
94 /// Whether its copy was edited, and stays; otherwise it is deleted, or would be.
95 pub edited: bool,
96 /// Whether its copy was deleted.
97 pub deleted: bool,
98}
99
100impl Library {
101 /// What purging an entity's values of a field would take away: every value it has held,
102 /// current or past, or only those equal to `value`, also those of the entities merged
103 /// into it. Content that a value refers to, such as a file's, goes with every value
104 /// that holds it in a field of the same kind, secret or ordinary, of any entity, current
105 /// or past, and with its sealed copies of that kind; finding those values reads the whole
106 /// space, as content is rarely purged, and a value left behind would refer to content
107 /// that nothing can read. Ordinary content takes its thumbnails with it, whole, with
108 /// their own content. The same content in a field of the other kind is sealed apart,
109 /// and stays: purging a file leaves a secret file of the same content, whether the
110 /// secrets are unlocked or not, and the other way round.
111 ///
112 /// # Errors
113 ///
114 /// Returns an error if the library has no such space; if the entity has no such value;
115 /// if the field is secret and the space's secrets are locked while it holds secret
116 /// values, as only unlocked secrets show which values they are; if a value cannot be purged, such as a replica's key; or
117 /// if the space's state cannot be read.
118 pub fn purgeable(
119 &self,
120 space: SpaceId,
121 entity: EntityId,
122 field: &FieldName,
123 value: Option<&Value>,
124 ) -> Result<Purge, NodeError> {
125 let open = self.space(space)?;
126 // Values written before their field was secret are plain, and show; sealed ones
127 // show only once they are unlocked.
128 if open.stored.secret_fields().contains(field)
129 && open.keys.newest_secrets().is_none()
130 && !nibkeep_log::History::sealed(open.stored.log().history())?.is_empty()
131 {
132 return Err(NodeError::SecretsLocked);
133 }
134 let log = open.stored.log();
135 let state = log.state();
136 let mut statements = Vec::new();
137 for entity in state.merged(state.canonical(entity)?)? {
138 for id in state.storage().of_field(entity, field)? {
139 let Some(statement) = state.statement(id)? else {
140 continue;
141 };
142 if value.is_none_or(|value| statement.value == *value) {
143 statements.push(id);
144 }
145 }
146 }
147 if statements.is_empty() {
148 return Err(NodeError::NoValue(field.clone()));
149 }
150 let of_secrets = open.stored.secret_fields().contains(field);
151 let ContentsPurged {
152 contents,
153 holders,
154 thumbnails,
155 } = self.purge_contents(space, &mut statements, of_secrets)?;
156 let mut secret = 0;
157 for &statement in &statements {
158 if log.is_sealed(statement)? {
159 secret += 1;
160 }
161 }
162 let changes = log
163 .changes_to_purge(statements.iter().copied(), &open.keys)?
164 .len();
165 let blobs = contents
166 .iter()
167 .map(|content| {
168 log.blob_keys(content)
169 .filter(|(sealed, _)| log.is_secret_blob(sealed) == of_secrets)
170 .count()
171 })
172 .sum();
173 // Secret files have no checkouts; one of the same content is a file's, which stays.
174 let holding = if of_secrets {
175 Vec::new()
176 } else {
177 self.checkouts_holding(space, &contents)?
178 };
179 let purged_copy = |(path, edited)| PurgedCheckout {
180 path,
181 edited,
182 deleted: false,
183 };
184 let checkouts = holding.into_iter().map(purged_copy).collect();
185 let tree_copies = self.tree_copies_holding(space, &contents, of_secrets)?;
186 let tree_copies = tree_copies.into_iter().map(purged_copy).collect();
187 let purged = state.canonical(entity)?;
188 let (also, originals) = also_and_originals(state, (purged, &holders), &thumbnails)?;
189 let elsewhere = self.spaces_holding(space, &contents, of_secrets)?;
190 Ok(Purge {
191 statements,
192 changes,
193 secret,
194 contents: contents.into_iter().collect(),
195 of_secrets,
196 blobs,
197 elsewhere,
198 also,
199 thumbnails: thumbnails.into_iter().collect(),
200 checkouts,
201 tree_copies,
202 originals: originals.into_iter().collect(),
203 waiting: self.waiting_copies(space)?,
204 })
205 }
206
207 /// The content that the statements to purge refer to, the entities whose values hold
208 /// it, as the entities they show as, and the thumbnails made of it; every value of the
209 /// space that holds it, of any field secret if `of_secrets` says so and ordinary
210 /// otherwise, current or past, is added to `statements`. A value that only names a
211 /// content, as a thumbnail's `std.thumbnail-of` does, takes no content with it. Of
212 /// ordinary content, every value that a thumbnail made of it has held is added too, but
213 /// its marks; and the thumbnail's own content goes with it, unless something else holds
214 /// that content, as the thumbnail of another picture alike may.
215 fn purge_contents(
216 &self,
217 space: SpaceId,
218 statements: &mut Vec<StatementId>,
219 of_secrets: bool,
220 ) -> Result<ContentsPurged, NodeError> {
221 let open = self.space(space)?;
222 let secret_fields = open.stored.secret_fields();
223 let state = open.stored.log().state();
224 let mut contents = BTreeSet::new();
225 for &id in statements.iter() {
226 if let Some(statement) = state.statement(id)?
227 && let Value::Blob(content) = statement.value
228 && !nibkeep_std::names_content_only(&statement.field)
229 {
230 contents.insert(content);
231 }
232 }
233 let mut holders = BTreeSet::new();
234 let mut thumbnails = BTreeSet::new();
235 if contents.is_empty() {
236 return Ok(ContentsPurged {
237 contents,
238 holders,
239 thumbnails,
240 });
241 }
242 let storage = state.storage();
243 let mut seen: BTreeSet<StatementId> = statements.iter().copied().collect();
244 let mut made_of = BTreeSet::new();
245 for entity in storage.described()? {
246 for (field, ids) in storage.of_entity(entity)? {
247 // Content in a field of the other kind is sealed apart, and stays.
248 if secret_fields.contains(&field) != of_secrets {
249 continue;
250 }
251 for id in ids {
252 let Some(recorded) = storage.get(id)? else {
253 continue;
254 };
255 if let Value::Blob(content) = &recorded.statement.value
256 && contents.contains(content)
257 {
258 if nibkeep_std::names_content_only(&field) {
259 made_of.insert(entity);
260 } else {
261 holders.insert(state.canonical(entity)?);
262 }
263 if seen.insert(id) {
264 statements.push(id);
265 }
266 }
267 }
268 }
269 }
270 // A thumbnail goes whole, but its marks of a move or a merge, which lead to where it
271 // went; and its own content, unless another value holds that.
272 let mut theirs = BTreeSet::new();
273 let mut pictures = BTreeSet::new();
274 for thumbnail in made_of {
275 thumbnails.insert(state.canonical(thumbnail)?);
276 for (field, ids) in storage.of_entity(thumbnail)? {
277 if super::behind::is_mark(&field) {
278 continue;
279 }
280 for id in ids {
281 theirs.insert(id);
282 if seen.insert(id) {
283 statements.push(id);
284 }
285 if field == CONTENT
286 && let Some(recorded) = storage.get(id)?
287 && let Value::Blob(picture) = recorded.statement.value
288 {
289 pictures.insert(picture);
290 }
291 }
292 }
293 }
294 if !pictures.is_empty() {
295 for entity in storage.described()? {
296 for (field, ids) in storage.of_entity(entity)? {
297 if secret_fields.contains(&field) {
298 continue;
299 }
300 for id in ids {
301 if !theirs.contains(&id)
302 && let Some(recorded) = storage.get(id)?
303 && let Value::Blob(held) = &recorded.statement.value
304 {
305 pictures.remove(held);
306 }
307 }
308 }
309 }
310 contents.extend(pictures);
311 }
312 Ok(ContentsPurged {
313 contents,
314 holders,
315 thumbnails,
316 })
317 }
318
319 /// Purges an entity's values of a field for good, as [`Library::purgeable`] finds them:
320 /// destroys, on every replica, the keys and payloads of the changes that asserted them,
321 /// or the record keys of secret ones, and states again what else those changes held.
322 /// What a purged value replaced stays replaced. The same change destroys the keys of the
323 /// sealed copies of the content they refer to, and the copies of this device's checkouts
324 /// of it are deleted where they are unchanged, as [`Library::settle_checkouts`] deletes
325 /// them after a sync on other devices. Whoever may purge is decided with roles; the
326 /// person confirms before the call.
327 ///
328 /// # Errors
329 ///
330 /// Returns the errors of [`Library::purgeable`], or an error if a value cannot be purged,
331 /// such as a replica's key, or the purge cannot be saved.
332 pub fn purge(
333 &mut self,
334 space: SpaceId,
335 entity: EntityId,
336 field: &FieldName,
337 value: Option<&Value>,
338 wall_millis: u64,
339 rng: &mut impl CryptoRng,
340 ) -> Result<Purge, NodeError> {
341 let mut purge = self.purgeable(space, entity, field, value)?;
342 self.check_not_revoked(space)?;
343 self.check_not_ai_agent("purge")?;
344 let deleted = self.purge_statements(
345 space,
346 &purge.statements,
347 (&purge.contents, purge.of_secrets),
348 wall_millis,
349 rng,
350 )?;
351 for copy in purge.checkouts.iter_mut().chain(&mut purge.tree_copies) {
352 copy.deleted = deleted.contains(©.path);
353 }
354 Ok(purge)
355 }
356
357 /// Purges statements of a space, and the sealed copies of `contents` of the kind that
358 /// `of_secrets` says, as [`Library::purge`] does once it found them, and returns the
359 /// copies of this device's checkouts that it deleted.
360 pub(crate) fn purge_statements(
361 &mut self,
362 space: SpaceId,
363 statements: &[StatementId],
364 (contents, of_secrets): (&[Hash], bool),
365 wall_millis: u64,
366 rng: &mut impl CryptoRng,
367 ) -> Result<Vec<PathBuf>, NodeError> {
368 // What the checkouts held before, by which their hashes tell what the purge leaves
369 // unchanged.
370 let known = self.checkout_contents_in(space)?;
371 let signing = &self.replica.signing;
372 let code_types = &self.code_types;
373 let open = self
374 .spaces
375 .get_mut(&space)
376 .ok_or(NodeError::NoSpace(space))?;
377 open.stored.purge_with_blobs(
378 signing,
379 &open.keys,
380 statements,
381 (contents, of_secrets),
382 wall_millis,
383 rng,
384 )?;
385 // What was purged may have defined types, or held a list of languages.
386 open.read_types(code_types)?;
387 if space == self.info.personal {
388 self.refresh_languages()?;
389 }
390 // The purge is done; a later settling ends what this one could not. Trees learn the
391 // content first, so that no copy of it anywhere in them is committed again.
392 let contents: BTreeSet<Hash> = contents.iter().copied().collect();
393 let _ = self.note_purged(space, (&contents, of_secrets));
394 Ok(self
395 .settle_checkouts_in(space, &known, wall_millis, rng)
396 .unwrap_or_default())
397 }
398}
399
400/// A place where a file was found: its device, and its path there.
401type Place = (EntityId, String);
402
403/// Of the entities that hold the content a purge takes, `holders`, those that lose it too
404/// besides the one purged, `purged`, and the thumbnails made of it, which a purge names
405/// apart: files with the same content, and any other value that refers to it, but origins
406/// and checkouts; and where files of that content were found, which a purge leaves.
407fn also_and_originals<S: Statements>(
408 state: &nibkeep_model::State<S>,
409 (purged, holders): (EntityId, &BTreeSet<EntityId>),
410 thumbnails: &BTreeSet<EntityId>,
411) -> Result<(Vec<EntityId>, BTreeSet<Place>), NodeError>
412where
413 NodeError: From<S::Error>,
414{
415 let mut also = Vec::new();
416 let mut originals = BTreeSet::new();
417 for &holder in holders {
418 let kinds = state.types(holder)?;
419 if kinds.contains(&ORIGIN) {
420 originals.extend(place_of(state, holder)?);
421 continue;
422 }
423 if kinds.contains(&CHECKOUT) {
424 continue;
425 }
426 if holder != purged && !thumbnails.contains(&holder) {
427 also.push(holder);
428 }
429 }
430 Ok((also, originals))
431}
432
433/// Where an origin of a state says a file was found: each device and path it names.
434fn place_of<S: Statements>(
435 state: &nibkeep_model::State<S>,
436 origin: EntityId,
437) -> Result<Vec<(EntityId, String)>, NodeError>
438where
439 NodeError: From<S::Error>,
440{
441 let mut places = Vec::new();
442 for device in state.current(origin, &FOUND_ON)? {
443 let Some(device) = device.value.as_reference() else {
444 continue;
445 };
446 for path in state.current(origin, &PATH)? {
447 if let Some(path) = path.value.as_text() {
448 places.push((state.canonical(device)?, path.to_owned()));
449 }
450 }
451 }
452 Ok(places)
453}