Skip to main content

nibkeep_node/library/
dropping.rs

1//! Devices that choose their spaces: dropping a space
2//! ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
3//!
4//! A device drops a space as the person asks there. A drop that would leave the space below
5//! its policies, or on no other device of the person's that remains, is refused, and says
6//! what is missing; so is one while a tree's copy, or an edited checkout, of the space is on
7//! the device. Otherwise the space's folder takes a mark, `dropping`, and the drop waits:
8//! for the device's own changes there to be on other disks, for as many disks as the
9//! space's Critical policy asks for to hold all of the space's changes, for the copies
10//! elsewhere of the blobs it holds to be proven, as the holder of the sync role removes them
11//! a pass at a time, the planner keeping none of the space's blobs while the mark is there,
12//! and for another replica that remains to hold the space's secrets, where this one holds
13//! them. Then it states its choice not to hold the space, and once a device of the person's
14//! that holds the space tells, by its account in the personal space, that it holds that
15//! choice, it deletes the space: its unedited checkouts, the blobs that no other space of the
16//! replica keeps, its key, and its folder, the mark last, so that a deletion that a power cut
17//! stops is finished as the library opens. A space that the person left is dropped the same
18//! way, but at once, without waiting for copies, which are no longer theirs to keep.
19
20use std::fs;
21use std::path::PathBuf;
22
23use nibkeep_base::{EntityId, SpaceId};
24use nibkeep_crypto::rand_core::CryptoRng;
25use nibkeep_governance::Choice;
26use nibkeep_log::ChangeId;
27use nibkeep_model::fields;
28use nibkeep_model::storage::Statements;
29
30use nibkeep_store::log_path;
31
32use super::Library;
33use super::accounts::Copies;
34use super::checkouts::sync_folder_of;
35use super::spaces::Personal;
36use crate::{Needs, NodeError};
37
38/// The name of the mark, in a space's folder, of a drop that this device makes.
39const MARK: &str = "dropping";
40
41/// What the mark of a space that the person left holds.
42const LEFT: &[u8] = b"left";
43
44/// How far a drop of a space on this device has come.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Dropping {
47	/// The space.
48	pub space: SpaceId,
49	/// How far it has come.
50	pub stage: DropStage,
51	/// What it waits for before it states its choice, while it waits.
52	pub waits: Vec<DropWait>,
53}
54
55/// How far a drop has come.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum DropStage {
58	/// This device holds the space still, and waits for what the drop's waits say.
59	Waiting,
60	/// This device stated its choice not to hold the space, and deletes it once a device of
61	/// the person's that holds the space holds that choice.
62	Dropped,
63	/// The space is gone from this device.
64	Deleted,
65}
66
67/// What a drop waits for before this device states its choice.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub enum DropWait {
70	/// The newest of the space's changes that this disk alone holds, as no other disk's
71	/// account says it holds them yet, and whether there may be more of them.
72	OwnChanges {
73		/// How many.
74		changes: usize,
75		/// Whether there may be more, beyond those looked at.
76		more: bool,
77	},
78	/// Fewer disks besides this one hold all of the space's changes than the space's
79	/// Critical policy asks for: how many do, how many of them are away from home, and how
80	/// many are archive nodes'.
81	ChangeCopies {
82		/// The other disks that hold every change.
83		disks: usize,
84		/// How many of them are away from home.
85		away: usize,
86		/// How many of them are archive nodes'.
87		archived: usize,
88		/// What the Critical policy asks.
89		needs: Needs,
90	},
91	/// The sealed blobs of the space that this device holds and no other space of the
92	/// replica keeps: each goes once its copies elsewhere are proven, as the holder of the
93	/// sync role removes copies, a pass at a time.
94	Files(usize),
95	/// This device holds the space's secrets, and no other replica that remains in the
96	/// space does.
97	Secrets,
98}
99
100/// Why a drop of a space is refused now.
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub enum DropRefusal {
103	/// A tree of the space has its folder on this device, which the person deals with first.
104	Tree(PathBuf),
105	/// A checkout of the space was edited since it was written, which the person deals with
106	/// first.
107	EditedCheckout(PathBuf),
108	/// No other device of the person's that remains holds the space, so none could approve
109	/// a request there, nor carry a revocation into it.
110	OnlyDevice,
111	/// The space's changes would be on fewer disks than its Critical policy asks for, as
112	/// the accounts of the other disks say: how many other disks there are, how many of them
113	/// are away from home, and how many are archive nodes'.
114	ChangeCopies {
115		/// The other disks.
116		disks: usize,
117		/// How many of them are away from home.
118		away: usize,
119		/// How many of them are archive nodes'.
120		archived: usize,
121		/// What the Critical policy asks.
122		needs: Needs,
123	},
124	/// Files whose copies on other disks would not meet their policy, as those disks'
125	/// accounts say.
126	Files {
127		/// The policy's name, if it has one.
128		policy: Option<String>,
129		/// What it asks.
130		needs: Needs,
131		/// The files.
132		files: Vec<EntityId>,
133	},
134	/// Blobs held here, besides the files' current contents too, as their older versions,
135	/// thumbnails and pictures, of which other disks' accounts show fewer copies than they
136	/// need: how many, which the device could then never remove.
137	Blobs(usize),
138}
139
140/// The reasons a drop is refused.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct DropRefusals(pub Vec<DropRefusal>);
143
144impl std::fmt::Display for DropRefusals {
145	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146		let mut first = true;
147		for refusal in &self.0 {
148			if !first {
149				f.write_str("; ")?;
150			}
151			first = false;
152			match refusal {
153				DropRefusal::Tree(path) => {
154					write!(f, "a tree's folder is here, at {}", path.display())?;
155				}
156				DropRefusal::EditedCheckout(path) => {
157					write!(f, "a checkout was edited, at {}", path.display())?;
158				}
159				DropRefusal::OnlyDevice => f.write_str("no other device of yours holds it")?,
160				DropRefusal::ChangeCopies { disks, needs, .. } => {
161					write!(
162						f,
163						"its changes would be on {disks} other disks, where its Critical policy \
164						 asks for {}",
165						needs.copies
166					)?;
167					write_marks(f, needs)?;
168				}
169				DropRefusal::Files {
170					policy,
171					needs,
172					files,
173				} => {
174					let count = if files.len() == 1 {
175						"1 file".to_owned()
176					} else {
177						format!("{} files", files.len())
178					};
179					write!(
180						f,
181						"{count} would have fewer copies than {} asks: {}",
182						policy.as_deref().unwrap_or("their policy"),
183						needs.copies
184					)?;
185					write_marks(f, needs)?;
186				}
187				DropRefusal::Blobs(blobs) => {
188					write!(
189						f,
190						"{} held here, of files' older versions, thumbnails or pictures among \
191						 them, would have fewer copies elsewhere than they need",
192						if *blobs == 1 {
193							"1 blob".to_owned()
194						} else {
195							format!("{blobs} blobs")
196						}
197					)?;
198				}
199			}
200		}
201		Ok(())
202	}
203}
204
205/// Writes how many copies away from home and on archive nodes `needs` asks for, where it
206/// asks for any.
207fn write_marks(f: &mut std::fmt::Formatter<'_>, needs: &Needs) -> std::fmt::Result {
208	if needs.away > 0 {
209		write!(f, ", {} away from home", needs.away)?;
210	}
211	if needs.archived > 0 {
212		write!(f, ", {} on archive nodes", needs.archived)?;
213	}
214	Ok(())
215}
216
217impl Library {
218	/// Drops a space on this device, as the person asks here: refuses as [`DropRefusal`]
219	/// says; otherwise marks it, and moves the drop on as far as it can now, as
220	/// [`Library::drop_progress`] then tells. The holder of the sync role goes on with it, a
221	/// pass of removals at a time, and the syncs after, until the space is deleted. A drop
222	/// asked for again tells how far it has come.
223	///
224	/// # Errors
225	///
226	/// Returns [`NodeError::PersonalSpaceHeld`] for the personal space,
227	/// [`NodeError::NoSpace`] for a space that this device does not hold,
228	/// [`NodeError::DropRefused`] with the reasons, and an error if this replica is an AI
229	/// agent's or revoked, or the library cannot be read or changed.
230	pub fn drop_space(
231		&mut self,
232		space: SpaceId,
233		wall_millis: u64,
234		rng: &mut impl CryptoRng,
235	) -> Result<Dropping, NodeError> {
236		if space == self.info.personal {
237			return Err(NodeError::PersonalSpaceHeld);
238		}
239		self.check_not_revoked(self.info.personal)?;
240		self.check_not_ai_agent("choose the spaces it holds")?;
241		// Asked again, also once its choice no longer holds the space.
242		if self.is_dropping(space) {
243			return self.settle_drop(space, wall_millis, rng);
244		}
245		{
246			let open = self.space(space)?;
247			let own = self.replica.signing.verifying_key();
248			if !open.stored.log().holds_space(&own, &open.keys)? {
249				return Err(NodeError::NoSpace(space));
250			}
251		}
252		// A member who left, or was removed, holds the space read only: no longer theirs.
253		let left = self.has_left(space)?;
254		let refused = self.drop_refusals(space, left, wall_millis)?;
255		if !refused.is_empty() {
256			return Err(NodeError::DropRefused(DropRefusals(refused)));
257		}
258		let mark = self.drop_mark(space);
259		fs::write(&mark, if left { LEFT } else { b"" }).map_err(NodeError::file(&mark))?;
260		sync_folder_of(&mark);
261		self.settle_drop(space, wall_millis, rng)
262	}
263
264	/// How far a drop of a space on this device has come, and what it waits for; `None` if
265	/// this device does not drop it, as when it never did, took it back, or deleted it.
266	///
267	/// # Errors
268	///
269	/// Returns an error if the library cannot be read.
270	pub fn drop_progress(&self, space: SpaceId) -> Result<Option<Dropping>, NodeError> {
271		if !self.spaces.contains_key(&space) || !self.is_dropping(space) {
272			return Ok(None);
273		}
274		let read = self.read_personal()?;
275		if self.drop_stated(space, &read) {
276			return Ok(Some(Dropping {
277				space,
278				stage: DropStage::Dropped,
279				waits: Vec::new(),
280			}));
281		}
282		let waits = if self.dropping_left(space) {
283			Vec::new()
284		} else {
285			self.drop_waits(space, self.wall.get())?
286		};
287		Ok(Some(Dropping {
288			space,
289			stage: DropStage::Waiting,
290			waits,
291		}))
292	}
293
294	/// Whether this device drops a space: its folder holds the mark.
295	pub(crate) fn is_dropping(&self, space: SpaceId) -> bool {
296		self.spaces.contains_key(&space) && self.drop_mark(space).exists()
297	}
298
299	/// Takes back a space that this device drops, before it stated its choice: takes the
300	/// mark away. Whether it did.
301	pub(crate) fn take_back_drop(&mut self, space: SpaceId) -> Result<bool, NodeError> {
302		if !self.is_dropping(space) || self.drop_stated(space, &self.read_personal()?) {
303			return Ok(false);
304		}
305		let mark = self.drop_mark(space);
306		fs::remove_file(&mark).map_err(NodeError::file(&mark))?;
307		sync_folder_of(&mark);
308		Ok(true)
309	}
310
311	/// Ends a drop of a space that this device made, whatever its stage, as when it asks for
312	/// the space again: takes the mark away.
313	pub(crate) fn end_drop(&self, space: SpaceId) -> Result<(), NodeError> {
314		if !self.is_dropping(space) {
315			return Ok(());
316		}
317		let mark = self.drop_mark(space);
318		fs::remove_file(&mark).map_err(NodeError::file(&mark))?;
319		sync_folder_of(&mark);
320		Ok(())
321	}
322
323	/// Moves on each drop that this device makes, after a sync or a pass of removals: states
324	/// the choice of each whose waits are over, and deletes each whose choice a device of the
325	/// person's that holds the space holds; then, while the secrets are unlocked, deletes
326	/// those of the spaces deleted while they were locked. Each goes on whatever another's
327	/// error; the first is told at the end.
328	pub(crate) fn settle_drops(
329		&mut self,
330		wall_millis: u64,
331		rng: &mut impl CryptoRng,
332	) -> Result<(), NodeError> {
333		let dropping: Vec<SpaceId> = self
334			.spaces
335			.keys()
336			.copied()
337			.filter(|&space| self.is_dropping(space))
338			.collect();
339		let mut first = Ok(());
340		for space in dropping {
341			let settled = self.settle_drop(space, wall_millis, rng).map(|_| ());
342			if first.is_ok() {
343				first = settled;
344			}
345		}
346		// Tried again after the next sync, which it never fails.
347		let _ = self.forget_secrets_of_dropped(rng);
348		first
349	}
350
351	/// Moves a drop on as far as it can now, as [`Library::settle_drops`] says.
352	fn settle_drop(
353		&mut self,
354		space: SpaceId,
355		wall_millis: u64,
356		rng: &mut impl CryptoRng,
357	) -> Result<Dropping, NodeError> {
358		let left = self.dropping_left(space);
359		let read = self.read_personal()?;
360		if !self.drop_stated(space, &read) {
361			let waits = if left {
362				Vec::new()
363			} else {
364				self.drop_waits(space, wall_millis)?
365			};
366			if !waits.is_empty() {
367				return Ok(Dropping {
368					space,
369					stage: DropStage::Waiting,
370					waits,
371				});
372			}
373			self.state_space_choice(space, false, wall_millis, rng)?;
374		}
375		let read = self.read_personal()?;
376		if (left || self.holder_holds_drop(space, &read)?) && self.delete_dropped(space, rng)? {
377			return Ok(Dropping {
378				space,
379				stage: DropStage::Deleted,
380				waits: Vec::new(),
381			});
382		}
383		Ok(Dropping {
384			space,
385			stage: DropStage::Dropped,
386			waits: Vec::new(),
387		})
388	}
389
390	/// The mark of a drop of a space, in its folder.
391	fn drop_mark(&self, space: SpaceId) -> PathBuf {
392		space_folder(&self.directory, space).join(MARK)
393	}
394
395	/// Whether a drop is of a space that the person left, as its mark says.
396	fn dropping_left(&self, space: SpaceId) -> bool {
397		fs::read(self.drop_mark(space)).is_ok_and(|held| held == LEFT)
398	}
399
400	/// Whether this replica's newest choice of a space, in the personal space, `personal`,
401	/// drops it: its drop is stated.
402	fn drop_stated(&self, space: SpaceId, personal: &Personal) -> bool {
403		self.own_choices(personal)
404			.get(&space)
405			.is_some_and(|(_, holds)| !holds)
406	}
407
408	/// Why a drop of a space would be refused now, as [`DropRefusal`] says; a space that
409	/// the person left, `left`, is refused only for its trees and edited checkouts.
410	fn drop_refusals(
411		&self,
412		space: SpaceId,
413		left: bool,
414		wall_millis: u64,
415	) -> Result<Vec<DropRefusal>, NodeError> {
416		let mut refused = Vec::new();
417		for tree in self.trees(space)? {
418			if let Some(root) = tree.root {
419				refused.push(DropRefusal::Tree(root));
420			}
421		}
422		for checkout in self.checkouts(space)? {
423			if checkout.copy == super::checkouts::CopyState::Edited {
424				refused.push(DropRefusal::EditedCheckout(checkout.path));
425			}
426		}
427		if left {
428			return Ok(refused);
429		}
430		if self.other_holders(space)?.is_empty() {
431			refused.push(DropRefusal::OnlyDevice);
432		}
433		let copies = self.copies_by_disk(space, wall_millis)?;
434		let needs = self.critical_needs(space)?;
435		let others: std::collections::BTreeSet<usize> = (0..copies.disks.len())
436			.filter(|&disk| disk != Copies::OWN)
437			.collect();
438		let (away, archived) = copies.marked(&others);
439		if needs.lacks(others.len(), away, archived).any() {
440			refused.push(DropRefusal::ChangeCopies {
441				disks: others.len(),
442				away,
443				archived,
444				needs,
445			});
446		}
447		for count in self.policies_without_this_disk(space, wall_millis)? {
448			if !count.lacking.is_empty() {
449				refused.push(DropRefusal::Files {
450					policy: count.name,
451					needs: count.needs,
452					files: count.lacking,
453				});
454			}
455		}
456		let short = self.blobs_short_elsewhere(space, &copies)?;
457		if short > 0 {
458			refused.push(DropRefusal::Blobs(short));
459		}
460		Ok(refused)
461	}
462
463	/// What a drop of a space waits for now, as [`DropWait`] says.
464	fn drop_waits(&self, space: SpaceId, wall_millis: u64) -> Result<Vec<DropWait>, NodeError> {
465		let mut waits = Vec::new();
466		let copies = self.copies_by_disk(space, wall_millis)?;
467		let needs = self.critical_needs(space)?;
468		let changes = self.change_copies(space, &copies, needs)?;
469		if changes.here_alone > 0 {
470			waits.push(DropWait::OwnChanges {
471				changes: changes.here_alone,
472				more: changes.here_alone_more,
473			});
474		}
475		let mut holding = self.disks_holding_all(space, &copies)?;
476		holding.remove(&Copies::OWN);
477		let (away, archived) = copies.marked(&holding);
478		if needs.lacks(holding.len(), away, archived).any() {
479			waits.push(DropWait::ChangeCopies {
480				disks: holding.len(),
481				away,
482				archived,
483				needs,
484			});
485		}
486		let stored = &self.space(space)?.stored;
487		let held = stored.sealed_blobs()?;
488		let elsewhere = stored.keyed_elsewhere(&held);
489		let files = held
490			.iter()
491			.filter(|sealed| !elsewhere.contains(sealed))
492			.count();
493		if files > 0 {
494			waits.push(DropWait::Files(files));
495		}
496		if self.alone_holds_secrets(space)? {
497			waits.push(DropWait::Secrets);
498		}
499		Ok(waits)
500	}
501
502	/// The keys of the other devices of the person's that hold a space and remain: by their
503	/// newest choices in the personal space, or with none, as a device with no choice holds
504	/// the space; neither revoked there nor AI agents'; and in the space, listed, neither
505	/// revoked nor ended.
506	fn other_holders(&self, space: SpaceId) -> Result<Vec<[u8; 32]>, NodeError> {
507		let personal = self.info.personal;
508		let read = self.read_personal()?;
509		let roster = self.roster(personal)?;
510		let newest = Self::newest_choices(&read, &roster);
511		let personal_open = self.space(personal)?;
512		let personal_log = personal_open.stored.log();
513		let open = self.space(space)?;
514		let log = open.stored.log();
515		let mut holders = Vec::new();
516		for replica in roster.replicas() {
517			if replica == self.info.replica {
518				continue;
519			}
520			for key in roster.keys_of(replica) {
521				let holds = newest
522					.get(&(space, *key.as_bytes()))
523					.is_none_or(|(_, choice)| choice.holds);
524				if !holds
525					|| holders.contains(key.as_bytes())
526					|| personal_log.is_revoked(key, &personal_open.keys)?
527					|| personal_log.is_ai_agent(key, &personal_open.keys)?
528					|| !log.is_listed(key, &open.keys)?
529					|| log.is_revoked(key, &open.keys)?
530					|| log.is_removed(key, &open.keys)?
531				{
532					continue;
533				}
534				holders.push(*key.as_bytes());
535			}
536		}
537		Ok(holders)
538	}
539
540	/// Whether a device of the person's that holds a space and remains holds this replica's
541	/// stated drop of it: its latest account in the personal space names heads that this
542	/// replica holds whole, and one of which builds on the change that stated the drop.
543	fn holder_holds_drop(&self, space: SpaceId, personal: &Personal) -> Result<bool, NodeError> {
544		let Some(stated) = self.drop_change(space, personal)? else {
545			return Ok(false);
546		};
547		let holders = self.other_holders(space)?;
548		let open = self.space(self.info.personal)?;
549		let log = open.stored.log();
550		for (author, head) in self.other_heads(self.info.personal)? {
551			if !holders.contains(&author) {
552				continue;
553			}
554			for &held in &head.heads {
555				if log.is_complete(held)? && log.builds_on_all(held, &[stated])? {
556					return Ok(true);
557				}
558			}
559		}
560		Ok(false)
561	}
562
563	/// The change of the personal space that stated this replica's newest choice of a space,
564	/// where that choice drops it.
565	fn drop_change(
566		&self,
567		space: SpaceId,
568		personal: &Personal,
569	) -> Result<Option<ChangeId>, NodeError> {
570		let Some((number, false)) = self.own_choices(personal).get(&space).copied() else {
571			return Ok(None);
572		};
573		let own = self.replica.signing.verifying_key();
574		let open = self.space(self.info.personal)?;
575		let state = open.stored.log().state();
576		for statement in state.current(self.info.replica, &fields::SPACE_CHOICE)? {
577			let Some(choice) = statement.value.as_text().and_then(Choice::from_text) else {
578				continue;
579			};
580			if choice.space != space
581				|| choice.key != own
582				|| choice.number != number
583				|| choice.holds
584				|| !choice.verifies()
585			{
586				continue;
587			}
588			if let Some(recorded) = state.storage().get(statement.id)?
589				&& let Some(change) = recorded.change
590			{
591				return Ok(Some(ChangeId::from_hash(change)));
592			}
593		}
594		Ok(None)
595	}
596
597	/// Whether this replica holds a space's secrets, and no other replica that remains in
598	/// the space does, as the space's records say.
599	fn alone_holds_secrets(&self, space: SpaceId) -> Result<bool, NodeError> {
600		let roster = self.roster(space)?;
601		let own = self.own_record(space)?;
602		let holders = roster.secrets_holders();
603		if !holders.contains(&own) {
604			return Ok(false);
605		}
606		for holder in holders {
607			if holder != own && self.is_remaining(space, &roster, holder)? {
608				return Ok(false);
609			}
610		}
611		Ok(true)
612	}
613
614	/// Deletes a space that this device dropped, once it has the space alone, as no other
615	/// program has it open: its unedited checkouts, the blobs that no other space of the
616	/// replica keeps, its secrets keys where they are unlocked, its key, and then its folder,
617	/// the mark last. Whether it did; it tries again after the next sync.
618	fn delete_dropped(
619		&mut self,
620		space: SpaceId,
621		rng: &mut impl CryptoRng,
622	) -> Result<bool, NodeError> {
623		if !self.space(space)?.stored.hold_alone() {
624			return Ok(false);
625		}
626		// Until its key goes, a step that fails lets the others open the space again, and the
627		// next sync tries again.
628		if let Err(error) = self.release_dropped(space, rng) {
629			if let Ok(open) = self.space(space) {
630				open.stored.share_again();
631			}
632			return Err(error);
633		}
634		// The key first: a key without its log would keep the library from opening, and a
635		// folder without its key, with the mark, is deleted as the library opens.
636		let compartment = self.compartment.clone();
637		let mut saved = None;
638		let removed = self.update_key_file(|key_file| {
639			let mut replica = key_file.replica(&compartment)?;
640			replica.spaces.remove(&space);
641			key_file.set_replica(&replica, &compartment, rng)?;
642			saved = Some(replica.spaces);
643			Ok(())
644		});
645		if let Err(error) = removed {
646			if let Ok(open) = self.space(space) {
647				open.stored.share_again();
648			}
649			return Err(error);
650		}
651		if let Some(spaces) = saved {
652			self.replica.spaces = spaces;
653		}
654		self.spaces.remove(&space);
655		self.accounts_refreshed.borrow_mut().remove(&space);
656		if self.chosen == Some(space) {
657			self.chosen = None;
658		}
659		delete_space_folder(&self.directory, space);
660		self.choose_writing_keys()?;
661		Ok(true)
662	}
663
664	/// Deletes what a dropped space leaves beside its folder and key: its unedited checkouts,
665	/// a checkout edited since staying, the person's own file now; the blobs that no other
666	/// space of the replica keeps; and its secrets keys, where they are unlocked.
667	fn release_dropped(
668		&mut self,
669		space: SpaceId,
670		rng: &mut impl CryptoRng,
671	) -> Result<(), NodeError> {
672		self.delete_unedited_checkouts(space)?;
673		self.space(space)?.stored.release_all_blobs()?;
674		if let Some(compartment) = self.secrets_compartment.clone() {
675			self.update_key_file(|key_file| {
676				let mut keys = key_file.secrets(&compartment)?;
677				if keys.spaces.remove(&space).is_some() {
678					key_file.update_secrets(&keys, &compartment, rng)?;
679				}
680				Ok(())
681			})?;
682		}
683		Ok(())
684	}
685
686	/// Deletes the secrets keys of the spaces that this replica dropped and deleted, as a
687	/// deletion leaves them while the secrets are locked: once they are unlocked.
688	pub(crate) fn forget_secrets_of_dropped(
689		&mut self,
690		rng: &mut impl CryptoRng,
691	) -> Result<(), NodeError> {
692		let Some(compartment) = self.secrets_compartment.clone() else {
693			return Ok(());
694		};
695		let read = self.read_personal()?;
696		let dropped: Vec<SpaceId> = self
697			.own_choices(&read)
698			.into_iter()
699			.filter(|(space, (_, holds))| !holds && !self.spaces.contains_key(space))
700			.map(|(space, _)| space)
701			.collect();
702		if dropped.is_empty() {
703			return Ok(());
704		}
705		self.update_key_file(|key_file| {
706			let mut keys = key_file.secrets(&compartment)?;
707			let before = keys.spaces.len();
708			keys.spaces.retain(|space, _| !dropped.contains(space));
709			if keys.spaces.len() != before {
710				key_file.update_secrets(&keys, &compartment, rng)?;
711			}
712			Ok(())
713		})
714	}
715
716	/// Finishes each deletion of a dropped space that a power cut stopped once the space's
717	/// key had gone: deletes each folder of a space that the key file holds no key of, and
718	/// that holds the mark of a drop.
719	pub(crate) fn finish_cut_short_drops(&self) {
720		let Ok(entries) = fs::read_dir(self.directory.join("spaces")) else {
721			return;
722		};
723		for entry in entries.filter_map(Result::ok) {
724			let Some(space) = entry
725				.file_name()
726				.to_str()
727				.and_then(|name| name.parse::<SpaceId>().ok())
728			else {
729				continue;
730			};
731			if !self.replica.spaces.contains_key(&space) && entry.path().join(MARK).exists() {
732				delete_space_folder(&self.directory, space);
733			}
734		}
735	}
736}
737
738/// A space's folder in the replica's folder `directory`.
739fn space_folder(directory: &std::path::Path, space: SpaceId) -> PathBuf {
740	log_path(directory, space).parent().map_or_else(
741		|| directory.join("spaces").join(space.to_string()),
742		ToOwned::to_owned,
743	)
744}
745
746/// Deletes a dropped space's folder in the replica's folder `directory`: everything in it
747/// but the mark, then the mark, then the folder, so that a folder that holds anything holds
748/// the mark until the end. What cannot be deleted now waits for the library's next opening.
749fn delete_space_folder(directory: &std::path::Path, space: SpaceId) {
750	let folder = space_folder(directory, space);
751	let Ok(entries) = fs::read_dir(&folder) else {
752		return;
753	};
754	let mut all = true;
755	for entry in entries.filter_map(Result::ok) {
756		if entry.file_name() == MARK {
757			continue;
758		}
759		let path = entry.path();
760		let deleted = if path.is_dir() {
761			fs::remove_dir_all(&path)
762		} else {
763			fs::remove_file(&path)
764		};
765		all &= deleted.is_ok();
766	}
767	if !all {
768		return;
769	}
770	sync_folder_of(&folder.join(MARK));
771	if fs::remove_file(folder.join(MARK)).is_ok() && fs::remove_dir(&folder).is_ok() {
772		sync_folder_of(&folder);
773	}
774}