Skip to main content

nibkeep_node/library/
backups.rs

1//! Backups: folders on drives and shares that a person's computers fill with the sealed
2//! changes, keys and blobs of the spaces they choose, and take in from, without keys and
3//! without a database ([technical design: backups]).
4//!
5//! [technical design: backups]: ../../../../docs/Technical-design.md#910-backups
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::fs;
9use std::path::{Path, PathBuf};
10use std::time::{Duration, Instant};
11
12use getrandom::SysRng;
13use getrandom::rand_core::UnwrapErr;
14use nibkeep_base::cbor::{self, ToCbor, Value as Cbor};
15use nibkeep_base::{ChangeId, EntityId, Hash, SpaceId, StatementId};
16use nibkeep_crypto::rand_core::CryptoRng;
17use nibkeep_governance::{AWAY, WAITS};
18use nibkeep_log::BackupHead;
19use nibkeep_model::storage::Statements;
20use nibkeep_model::{
21	FieldDef, FieldName, Name, Operation, Statement, TypeDef, TypeName, Value, ValueKind, fields,
22};
23use nibkeep_std::{CONTENT, FILE};
24use nibkeep_sync::{
25	Holder, Holding, MOST_PACK_BLOB, PACK_SIZE, PackItem, PackReader, item_id, pack_header,
26	pack_item,
27};
28
29use super::Library;
30use super::accounts::disk_id;
31use super::holding::HeldElsewhere;
32use super::planner::{Keeps, Moment, gone, moment, taken_of};
33use super::policies::{Kept, answer_policy, default_policies, facts_of, first_name, own_choices};
34use super::recovery::RecoveryFileNeed;
35use super::sync::{MIN_FREE_BYTES, Syncing};
36use crate::backup::{self, BackupFolder, InFileSystem, Record, Updating};
37use crate::{NodeError, place};
38
39/// The type of backups, in the personal space.
40pub(crate) const BACKUP: TypeName = TypeName::from_static("org.nibkeep.backup");
41
42/// A backup's folder, by its path from the folder that its drive or share is mounted at.
43pub(crate) const BACKUP_FOLDER: FieldName = FieldName::from_static("org.nibkeep.backup-folder");
44
45/// A space that a backup holds, by its ID as text: one value for each.
46pub(crate) const BACKUP_SPACE: FieldName = FieldName::from_static("org.nibkeep.backup-space");
47
48/// A policy whose files a backup keeps: one value for each, none for every policy's.
49pub(crate) const BACKUP_POLICY: FieldName = FieldName::from_static("org.nibkeep.backup-policy");
50
51/// The fields of backups, which only the engine's backup functions write.
52const OWN_FIELDS: [FieldName; 3] = [BACKUP_FOLDER, BACKUP_SPACE, BACKUP_POLICY];
53
54/// How old a blob file's last check is before an update reads it again: 4 weeks.
55const CHECK_AGAIN: u64 = 28 * 24 * 60 * 60 * 1000;
56
57/// How long a damaged copy found counts: 4 weeks, as on devices.
58const DAMAGE_COUNTS_FOR: u64 = 28 * 24 * 60 * 60 * 1000;
59
60/// How often an update that checks writes its record, so that a drive pulled out loses
61/// little progress.
62const SAVE_EVERY: Duration = Duration::from_secs(60);
63
64/// A space's packs smaller than this are merged once there are more than
65/// [`MERGE_ABOVE`] of them: 16 MiB.
66const MERGE_BELOW: u64 = 16 * 1024 * 1024;
67
68/// How many small packs a space keeps before they are merged.
69const MERGE_ABOVE: usize = 16;
70
71/// How long a look for backups waits for the drives and shares to answer: 10 seconds.
72const FIND_WITHIN: Duration = Duration::from_secs(10);
73
74/// Whether a field is one of backups', which only the backup functions write.
75pub(crate) fn is_own_field(field: &FieldName) -> bool {
76	OWN_FIELDS.contains(field)
77}
78
79/// The definition of the type of backups, which NibKeep defines in code.
80pub(crate) fn types() -> [TypeDef; 1] {
81	[TypeDef::new(BACKUP, 1)
82		.with_field(fields::NAME, FieldDef::new(ValueKind::Name))
83		.with_field(
84			BACKUP_FOLDER,
85			FieldDef::new(ValueKind::Text).last_writer_wins(),
86		)
87		.with_field(BACKUP_SPACE, FieldDef::new(ValueKind::Text).many())
88		.with_field(BACKUP_POLICY, FieldDef::new(ValueKind::Reference).many())
89		.with_field(AWAY, FieldDef::new(ValueKind::Boolean).last_writer_wins())
90		.with_field(WAITS, FieldDef::new(ValueKind::Integer).last_writer_wins())]
91}
92
93/// One of the person's backups, as their personal space records it.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct Backup {
96	/// Its record's ID, which its folder names.
97	pub id: EntityId,
98	/// Its name.
99	pub name: String,
100	/// Its folder's path from the folder that its drive or share is mounted at.
101	pub folder: String,
102	/// The spaces it holds.
103	pub spaces: Vec<SpaceId>,
104	/// The policies whose files it keeps; none for every policy's.
105	pub policies: Vec<EntityId>,
106	/// Whether it is kept away from home.
107	pub away: bool,
108	/// How many days it waits before it destroys what a purge destroys, if its owner set it,
109	/// 0 for none; without it, 30 ([`super::waiting::backup_wait_days`]).
110	pub waits: Option<u64>,
111}
112
113/// What a new backup holds.
114#[derive(Clone, Debug, Default, PartialEq, Eq)]
115pub struct NewBackup {
116	/// Its name.
117	pub name: String,
118	/// The spaces it holds; none for every space of the library.
119	pub spaces: Vec<SpaceId>,
120	/// The policies whose files it keeps; none for every policy's.
121	pub policies: Vec<EntityId>,
122	/// Whether it is kept away from home.
123	pub away: bool,
124	/// How many days it waits before purging, 0 for none; without it, 30.
125	pub waits: Option<u64>,
126}
127
128/// A backup just made.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct AddedBackup {
131	/// The backup.
132	pub backup: Backup,
133	/// Whether its folder is on a network share, whose drive no system names, so that it
134	/// counts as a disk of its own.
135	pub on_share: bool,
136}
137
138/// What to change of a backup: each value given replaces what it had.
139#[derive(Clone, Debug, Default, PartialEq, Eq)]
140pub struct BackupEdit {
141	/// A new name.
142	pub name: Option<String>,
143	/// The spaces it holds from now on.
144	pub spaces: Option<Vec<SpaceId>>,
145	/// The policies whose files it keeps from now on; none for every policy's.
146	pub policies: Option<Vec<EntityId>>,
147	/// Whether it is kept away from home.
148	pub away: Option<bool>,
149	/// How many days it waits before purging, 0 for none, or `Some(None)` for the default.
150	pub waits: Option<Option<u64>>,
151}
152
153/// How many things went one way in an update of a backup.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155pub struct BackupMoved {
156	/// Changes.
157	pub changes: usize,
158	/// Wrapped record keys and wrapped blob keys.
159	pub keys: usize,
160	/// Sealed blobs.
161	pub blobs: usize,
162	/// The sealed blobs' bytes.
163	pub bytes: u64,
164}
165
166/// What an update of a backup did.
167#[derive(Clone, Debug, Default, PartialEq, Eq)]
168pub struct BackupUpdate {
169	/// The update's number.
170	pub update: u64,
171	/// Whether the backup was pulled out or lost its power during an update before.
172	pub unclean: bool,
173	/// What the replica took in from the backup.
174	pub taken: BackupMoved,
175	/// What it wrote to the backup.
176	pub written: BackupMoved,
177	/// How many items and files of purged content left the backup.
178	pub purged: usize,
179	/// How many purges wait on the backup before what they destroyed leaves it.
180	pub waiting: usize,
181	/// How many sealed blobs that the backup keeps did not fit, and their bytes.
182	pub unfit: usize,
183	/// The bytes of those blobs.
184	pub unfit_bytes: u64,
185	/// How many blob files it read in full and found intact, and their bytes.
186	pub checked: usize,
187	/// The bytes of those files.
188	pub checked_bytes: u64,
189	/// How many copies it found damaged.
190	pub damaged: usize,
191	/// How many of those it wrote again from the replica's copy.
192	pub repaired: usize,
193	/// How many packs and files it set aside as damaged.
194	pub set_aside: usize,
195	/// How many bytes of blob files are left to check, as the update stopped first.
196	pub to_check: u64,
197	/// How many sealed blobs the backup holds, and their bytes.
198	pub held: usize,
199	/// The bytes of those blobs.
200	pub held_bytes: u64,
201	/// The spaces of the backup that this device does not hold, which the update neither
202	/// took in nor wrote, each with the devices of the person's that hold it: one that none
203	/// holds gets no update any more
204	/// ([technical design](../../../../docs/Technical-design.md#910-backups)).
205	pub elsewhere: Vec<HeldElsewhere>,
206}
207
208/// What a backup's folder says of it, without an update: read from its record.
209#[derive(Clone, Debug, Default, PartialEq, Eq)]
210pub struct BackupState {
211	/// The number of its last update; 0 for none.
212	pub update: u64,
213	/// How many sealed blobs it holds.
214	pub held: usize,
215	/// How many bytes of its blob files are due to be read again: not read in full in the
216	/// last 4 weeks.
217	pub to_check: u64,
218	/// How many copies checks found damaged in the 4 weeks before its last update.
219	pub damaged: usize,
220}
221
222/// How a backup waits before purging, as an update applies purges: its record keeps when
223/// the update that first brought each purge ran, and the backup's waits; a purge whose wait
224/// is over, or that its owner ended, applies ([technical design: copies that wait]).
225///
226/// [technical design: copies that wait]: ../../../../docs/Technical-design.md#911-copies-that-wait
227pub(crate) struct Waits<'a> {
228	record: &'a mut Record,
229	now: u64,
230	/// The purges whose wait the owner ended, which apply now.
231	ending: &'a BTreeSet<ChangeId>,
232	/// The purges of which something stays for its wait, with the items and files it keeps,
233	/// each once, by its ID.
234	waiting: BTreeMap<ChangeId, BTreeSet<[u8; 32]>>,
235}
236
237impl<'a> Waits<'a> {
238	pub(crate) fn new(record: &'a mut Record, now: u64, ending: &'a BTreeSet<ChangeId>) -> Self {
239		Self {
240			record,
241			now,
242			ending,
243			waiting: BTreeMap::new(),
244		}
245	}
246
247	/// Whether what `purge` destroyed of the item `item` leaves the backup now: its wait is
248	/// over, or its owner ended it. A purge first seen now begins its wait; an item purged by
249	/// a purge that cannot be told stays, as a copy that waits keeps rather than destroys.
250	fn due(&mut self, purge: Option<&ChangeId>, item: [u8; 32]) -> bool {
251		let Some(&purge) = purge else {
252			return false;
253		};
254		if self.ending.contains(&purge) {
255			return true;
256		}
257		let (seen, _) = *self.record.purges.entry(purge).or_insert((self.now, 0));
258		let due =
259			seen.saturating_add(super::waiting::wait_at(&self.record.waits, seen)) <= self.now;
260		if !due {
261			self.waiting.entry(purge).or_default().insert(item);
262		}
263		due
264	}
265
266	/// Keeps in the record the purges of which something stays, with how much, and those that
267	/// this update could not tell of, as of a space that this computer does not hold.
268	fn settle(self, told: impl Fn(&ChangeId) -> bool) {
269		let waiting = self.waiting;
270		self.record
271			.purges
272			.retain(|purge, _| waiting.contains_key(purge) || !told(purge));
273		for (purge, (_, items)) in &mut self.record.purges {
274			if let Some(kept) = waiting.get(purge) {
275				*items = u64::try_from(kept.len()).unwrap_or(u64::MAX);
276			}
277		}
278	}
279}
280
281/// What an entry of a pack is.
282#[derive(Clone, Debug, PartialEq, Eq)]
283enum What {
284	Change { id: ChangeId, complete: bool },
285	RecordKey(StatementId),
286	BlobKey(Hash),
287	Blob(Hash),
288}
289
290/// An entry of a pack: what it is, its ID as reconciliation knows it (and a blob's by its
291/// sealed hash), and where its encoding is.
292#[derive(Clone, Debug)]
293struct Entry {
294	what: What,
295	id: [u8; 32],
296	start: usize,
297	length: usize,
298	/// A blob's size; 0 for other items.
299	size: u64,
300}
301
302/// A pack of a backup, as read.
303#[derive(Clone, Debug)]
304struct PackFile {
305	space: SpaceId,
306	path: String,
307	size: u64,
308	update: u64,
309	entries: Vec<Entry>,
310}
311
312/// Where a backup keeps a sealed blob.
313#[derive(Clone, Debug)]
314enum BlobAt {
315	File(u64),
316	Pack {
317		path: String,
318		start: usize,
319		length: usize,
320		space: SpaceId,
321		size: u64,
322	},
323}
324
325/// The packs and blob files of a backup.
326struct Packs {
327	files: Vec<PackFile>,
328	blob_files: BTreeMap<Hash, u64>,
329	/// Where the packs hold each sealed blob, as [`Packs::reindex`] found it.
330	blobs_at: BTreeMap<Hash, BlobAt>,
331}
332
333/// What a pack's bytes are.
334enum Indexed {
335	/// A sound pack.
336	Sound(PackFile),
337	/// Not the bytes that its name says: damaged.
338	Damaged,
339	/// The bytes its name says, which this engine does not read, as a pack of a later
340	/// version's: left as they are.
341	Unread,
342}
343
344/// The ID of a sealed blob's entry in a pack.
345fn blob_id(sealed: &Hash) -> [u8; 32] {
346	let digest = Hash::of(&cbor::encode(&Cbor::Array(vec![
347		3_u8.to_cbor(),
348		sealed.to_cbor(),
349	])));
350	digest
351		.digest()
352		.try_into()
353		.unwrap_or_else(|_| unreachable!("BLAKE3 digests are 32 bytes"))
354}
355
356/// What a pack's bytes at `path`, in the folder of `space`, are.
357fn index(space: SpaceId, path: &str, bytes: &[u8]) -> Indexed {
358	if Updating::pack_path(space, &Hash::of(bytes)) != path {
359		return Indexed::Damaged;
360	}
361	read_entries(space, path, bytes).map_or(Indexed::Unread, Indexed::Sound)
362}
363
364/// The entries of a pack of `space`, if it reads as one.
365fn read_entries(space: SpaceId, path: &str, bytes: &[u8]) -> Option<PackFile> {
366	let mut reader = PackReader::new(bytes).ok()?;
367	if reader.space() != space {
368		return None;
369	}
370	let mut entries = Vec::new();
371	while let Some((item, start, length)) = reader.next_item().ok()? {
372		let size = match &item {
373			PackItem::Blob(_, bytes) => u64::try_from(bytes.len()).unwrap_or(u64::MAX),
374			_ => 0,
375		};
376		let (what, id) = match item {
377			PackItem::Change(parcel) => {
378				let complete = parcel.payload.is_some() && !parcel.keys.is_empty();
379				let id = parcel.id();
380				let holding = Holding::Change {
381					id,
382					millis: 0,
383					depth: 0,
384					complete,
385				};
386				(What::Change { id, complete }, item_id(&holding))
387			}
388			PackItem::RecordKey(statement, key) => (
389				What::RecordKey(statement),
390				item_id(&Holding::RecordKey { statement, key }),
391			),
392			PackItem::BlobKey(sealed, key) => (
393				What::BlobKey(sealed),
394				item_id(&Holding::BlobKey { sealed, key }),
395			),
396			PackItem::Blob(sealed, _) => (What::Blob(sealed), blob_id(&sealed)),
397		};
398		entries.push(Entry {
399			what,
400			id,
401			start,
402			length,
403			size,
404		});
405	}
406	Some(PackFile {
407		space,
408		path: path.to_owned(),
409		size: u64::try_from(bytes.len()).unwrap_or(u64::MAX),
410		update: reader.update(),
411		entries,
412	})
413}
414
415impl Packs {
416	/// Reads every pack of the backup, and sets aside those that are damaged.
417	fn read(updating: &Updating<'_>, done: &mut BackupUpdate) -> Result<Self, NodeError> {
418		let mut files = Vec::new();
419		for (space, path, _) in updating.packs()? {
420			// A pack that cannot be read now is tried again at the next update.
421			let Ok(bytes) = updating.read(&path) else {
422				continue;
423			};
424			match index(space, &path, &bytes) {
425				Indexed::Sound(file) => files.push(file),
426				Indexed::Damaged => {
427					updating.set_aside(&path);
428					done.set_aside += 1;
429				}
430				Indexed::Unread => {}
431			}
432		}
433		let mut packs = Self {
434			files,
435			blob_files: updating.blob_files()?,
436			blobs_at: BTreeMap::new(),
437		};
438		packs.reindex();
439		Ok(packs)
440	}
441
442	/// Orders the packs by the update that wrote them, and notes where they hold each sealed
443	/// blob, after packs came or went.
444	fn reindex(&mut self) {
445		self.files
446			.sort_by(|a, b| (a.update, &a.path).cmp(&(b.update, &b.path)));
447		self.blobs_at.clear();
448		for file in &self.files {
449			for entry in &file.entries {
450				if let What::Blob(sealed) = entry.what {
451					self.blobs_at.entry(sealed).or_insert_with(|| BlobAt::Pack {
452						path: file.path.clone(),
453						start: entry.start,
454						length: entry.length,
455						space: file.space,
456						size: entry.size,
457					});
458				}
459			}
460		}
461	}
462
463	fn of_space(&self, space: SpaceId) -> impl Iterator<Item = &PackFile> {
464		self.files.iter().filter(move |file| file.space == space)
465	}
466
467	/// The IDs of the items that the packs of a space hold.
468	fn ids(&self, space: SpaceId) -> BTreeSet<[u8; 32]> {
469		self.of_space(space)
470			.flat_map(|file| file.entries.iter().map(|entry| entry.id))
471			.collect()
472	}
473
474	/// The changes that the packs of a space hold, each with whether one holds it with its
475	/// payload and a key.
476	fn changes(&self, space: SpaceId) -> BTreeMap<ChangeId, bool> {
477		let mut changes = BTreeMap::new();
478		for file in self.of_space(space) {
479			for entry in &file.entries {
480				if let What::Change { id, complete } = entry.what {
481					*changes.entry(id).or_insert(false) |= complete;
482				}
483			}
484		}
485		changes
486	}
487
488	/// Where the backup keeps a sealed blob, if it holds it.
489	fn blob(&self, sealed: &Hash) -> Option<BlobAt> {
490		if let Some(size) = self.blob_files.get(sealed) {
491			return Some(BlobAt::File(*size));
492		}
493		self.blobs_at.get(sealed).cloned()
494	}
495
496	/// The sealed blobs that the backup holds, with their sizes: in files of their own, and
497	/// in packs.
498	fn blobs(&self) -> BTreeMap<Hash, u64> {
499		let mut blobs = self.blob_files.clone();
500		for (sealed, at) in &self.blobs_at {
501			if let BlobAt::Pack { size, .. } = at {
502				blobs.entry(*sealed).or_insert(*size);
503			}
504		}
505		blobs
506	}
507
508	/// The sealed blobs that the backup holds in packs.
509	fn blobs_in_packs(&self) -> BTreeSet<Hash> {
510		self.blobs_at.keys().copied().collect()
511	}
512
513	/// For each sealed blob, the spaces whose packs hold a key for it.
514	fn keyed(&self) -> BTreeMap<Hash, BTreeSet<SpaceId>> {
515		let mut keyed: BTreeMap<Hash, BTreeSet<SpaceId>> = BTreeMap::new();
516		for file in &self.files {
517			for entry in &file.entries {
518				if let What::BlobKey(sealed) = entry.what {
519					keyed.entry(sealed).or_default().insert(file.space);
520				}
521			}
522		}
523		keyed
524	}
525}
526
527/// A pack being written: its bytes, written whole as it fills, and the packs it wrote.
528struct PackWriter {
529	space: SpaceId,
530	update: u64,
531	buffer: Vec<u8>,
532	items: usize,
533	written: Vec<PackFile>,
534	/// The bytes of the packs it wrote.
535	flushed: u64,
536}
537
538impl PackWriter {
539	fn new(space: SpaceId, update: u64) -> Self {
540		Self {
541			space,
542			update,
543			buffer: pack_header(space, update),
544			items: 0,
545			written: Vec::new(),
546			flushed: 0,
547		}
548	}
549
550	/// Adds an item, from its encoding.
551	fn push_encoded(&mut self, updating: &Updating<'_>, encoded: &[u8]) -> Result<(), NodeError> {
552		if self.items > 0 && self.buffer.len() + encoded.len() > PACK_SIZE {
553			self.flush(updating)?;
554		}
555		self.buffer.extend_from_slice(encoded);
556		self.items += 1;
557		Ok(())
558	}
559
560	fn push(&mut self, updating: &Updating<'_>, item: &PackItem) -> Result<(), NodeError> {
561		self.push_encoded(updating, &pack_item(self.space, item))
562	}
563
564	/// The bytes that it holds, not written yet, and that it wrote.
565	fn used(&self) -> u64 {
566		u64::try_from(self.buffer.len())
567			.unwrap_or(u64::MAX)
568			.saturating_add(self.flushed)
569	}
570
571	/// Writes what it holds as a pack, if it holds any item.
572	fn flush(&mut self, updating: &Updating<'_>) -> Result<(), NodeError> {
573		if self.items == 0 {
574			return Ok(());
575		}
576		let path = updating.write_pack(self.space, &self.buffer)?;
577		let file = read_entries(self.space, &path, &self.buffer).ok_or_else(|| {
578			NodeError::Damaged("a pack written to a backup does not read".to_owned())
579		})?;
580		self.flushed = self.flushed.saturating_add(file.size);
581		self.written.push(file);
582		self.buffer = pack_header(self.space, self.update);
583		self.items = 0;
584		Ok(())
585	}
586
587	/// Writes what is left, and returns the packs it wrote.
588	fn finish(mut self, updating: &Updating<'_>) -> Result<Vec<PackFile>, NodeError> {
589		self.flush(updating)?;
590		Ok(self.written)
591	}
592}
593
594/// Where a sealed blob goes in the order in which an update writes blobs.
595type Rank = (
596	u8,
597	std::cmp::Reverse<u32>,
598	std::cmp::Reverse<Option<Moment>>,
599);
600
601/// What a backup keeps of a space's sealed blobs, and in which order an update writes them.
602struct BackupPlan {
603	/// Whether it keeps no sealed blob of the space, as of the personal space where only a
604	/// recovery code brings it.
605	nothing: bool,
606	keeps: Keeps,
607	/// For each content that a file holds or held: the most copies that the policies of
608	/// its files ask for, and the newest moment of them.
609	order: BTreeMap<Hash, (u32, Option<Moment>)>,
610}
611
612impl BackupPlan {
613	/// Where a sealed blob goes in the order of writing, if the backup keeps it: those that
614	/// every replica keeps first, then the files' of the policies that ask for the most
615	/// copies, then the newest.
616	fn rank(&self, secret: bool, content: Option<Hash>) -> Option<Rank> {
617		if self.nothing {
618			return None;
619		}
620		if secret {
621			return Some((0, std::cmp::Reverse(0), std::cmp::Reverse(None)));
622		}
623		let Some(content) = content else {
624			return Some((0, std::cmp::Reverse(0), std::cmp::Reverse(None)));
625		};
626		if !self.keeps.keeps(&content) {
627			return None;
628		}
629		match self.order.get(&content) {
630			None => Some((0, std::cmp::Reverse(0), std::cmp::Reverse(None))),
631			Some((copies, newest)) => {
632				Some((1, std::cmp::Reverse(*copies), std::cmp::Reverse(*newest)))
633			}
634		}
635	}
636}
637
638impl Library {
639	/// The person's backups, as their personal space records them, by name.
640	///
641	/// # Errors
642	///
643	/// Returns an error if the personal space cannot be read.
644	pub fn backups(&self) -> Result<Vec<Backup>, NodeError> {
645		let open = self.space(self.info.personal)?;
646		let state = open.stored.log().state();
647		let mut found = Vec::new();
648		let mut seen = BTreeSet::new();
649		for entity in open
650			.stored
651			.find(&fields::TYPE, &Value::Text(BACKUP.to_string()))?
652		{
653			let entity = state.canonical(entity)?;
654			if !seen.insert(entity)
655				|| state.is_deleted(entity)?
656				|| !state.types(entity)?.contains(&BACKUP)
657			{
658				continue;
659			}
660			let mut spaces: Vec<SpaceId> = state
661				.current(entity, &BACKUP_SPACE)?
662				.iter()
663				.filter_map(|statement| statement.value.as_text()?.parse().ok())
664				.collect();
665			spaces.sort();
666			spaces.dedup();
667			let mut policies = Vec::new();
668			for statement in state.current(entity, &BACKUP_POLICY)? {
669				if let Some(policy) = statement.value.as_reference() {
670					policies.push(policy);
671				}
672			}
673			policies.sort();
674			policies.dedup();
675			found.push(Backup {
676				id: entity,
677				name: first_name(state, entity)?.unwrap_or_default(),
678				folder: state
679					.last_written(entity, &BACKUP_FOLDER)?
680					.and_then(|statement| statement.value.as_text().map(str::to_owned))
681					.unwrap_or_default(),
682				spaces,
683				policies,
684				away: state
685					.last_written(entity, &AWAY)?
686					.is_some_and(|statement| statement.value == Value::Boolean(true)),
687				waits: state.last_written(entity, &WAITS)?.and_then(|statement| {
688					match statement.value {
689						Value::Integer(days) => u64::try_from(days).ok(),
690						_ => None,
691					}
692				}),
693			});
694		}
695		found.sort_by(|a, b| (&a.name, a.id).cmp(&(&b.name, b.id)));
696		Ok(found)
697	}
698
699	/// Whether the person removed a backup: its record, in the personal space, is deleted.
700	/// Another member's backup, of which the personal space knows nothing, is not.
701	pub(crate) fn backup_forgotten(&self, backup: EntityId) -> Result<bool, NodeError> {
702		let state = self.space(self.info.personal)?.stored.log().state();
703		let backup = state.canonical(backup)?;
704		Ok(state.is_deleted(backup)?)
705	}
706
707	/// The backup that `reference` names, by its ID or its name.
708	///
709	/// # Errors
710	///
711	/// Returns [`NodeError::WhichBackup`] if it names none, or several.
712	pub fn find_backup(&self, reference: &str) -> Result<Backup, NodeError> {
713		let backups = self.backups()?;
714		if let Ok(id) = reference.parse::<EntityId>()
715			&& let Some(backup) = backups.iter().find(|backup| backup.id == id)
716		{
717			return Ok(backup.clone());
718		}
719		let named: Vec<&Backup> = backups
720			.iter()
721			.filter(|backup| backup.name == reference)
722			.collect();
723		let named = if named.is_empty() {
724			backups
725				.iter()
726				.filter(|backup| backup.name.to_lowercase() == reference.to_lowercase())
727				.collect()
728		} else {
729			named
730		};
731		match named.as_slice() {
732			[backup] => Ok((*backup).clone()),
733			[] => Err(NodeError::WhichBackup(format!(
734				"no backup of yours is named {reference}"
735			))),
736			_ => Err(NodeError::WhichBackup(format!(
737				"several backups of yours are named {reference}; name one by its ID"
738			))),
739		}
740	}
741
742	/// Makes a backup in `folder`, which must be new or empty, and records it in the personal
743	/// space ([technical design: backups]).
744	///
745	/// [technical design: backups]: ../../../../docs/Technical-design.md#910-backups
746	///
747	/// # Errors
748	///
749	/// Returns [`NodeError::EmptyName`] for an empty name, [`NodeError::NoSpace`] for a
750	/// space that this replica does not hold, [`NodeError::NoEntity`] for a policy of none
751	/// of them, [`NodeError::BackupFolder`] for a folder that is not empty, lies in a
752	/// library or in a cloud drive's folder, and an error if the folder or the change cannot
753	/// be written.
754	pub fn add_backup(
755		&mut self,
756		folder: &Path,
757		new: &NewBackup,
758		wall_millis: u64,
759		rng: &mut impl CryptoRng,
760	) -> Result<AddedBackup, NodeError> {
761		let name = new.name.trim();
762		if name.is_empty() {
763			return Err(NodeError::EmptyName);
764		}
765		let spaces = self.chosen_spaces(&new.spaces)?;
766		self.check_backup_policies(&spaces, &new.policies)?;
767		let folder = std::path::absolute(folder).map_err(NodeError::file(folder))?;
768		let existing = folder
769			.ancestors()
770			.find(|ancestor| ancestor.exists())
771			.unwrap_or(&folder);
772		// Compared as the file system resolves them, links and all.
773		let resolved = fs::canonicalize(existing)
774			.map_err(NodeError::file(existing))?
775			.join(folder.strip_prefix(existing).unwrap_or(Path::new("")));
776		// The library's directory holds `replicas/`, which holds this replica's folder.
777		let root = self.directory.ancestors().nth(2).unwrap_or(&self.directory);
778		let library = fs::canonicalize(root).unwrap_or_else(|_| root.to_owned());
779		if resolved.components().any(|part| part.as_os_str() == ".nib")
780			|| resolved.starts_with(&library)
781		{
782			return Err(NodeError::BackupFolder(format!(
783				"{} is in a library; a backup is a folder of its own",
784				folder.display()
785			)));
786		}
787		if place::whereabouts(existing).drive.cloud {
788			return Err(NodeError::BackupFolder(format!(
789				"{} is in a cloud drive's folder, which may keep its files in the cloud; backups do not support such folders yet",
790				folder.display()
791			)));
792		}
793		let made_new = !folder.exists();
794		let added = self.record_new_backup(
795			&InFileSystem::new(&folder),
796			(name, spaces),
797			new,
798			wall_millis,
799			rng,
800		);
801		if added.is_err() && made_new {
802			let _ = fs::remove_dir(&folder);
803		}
804		added
805	}
806
807	/// Makes a backup as [`Library::add_backup`] does, in a folder reached through the
808	/// interface of files, as the folder that Android's picker gives: it checks only that the
809	/// folder is empty, and records it by the path that its drive gives.
810	///
811	/// # Errors
812	///
813	/// Returns the errors of [`Library::add_backup`] but those of where the folder is.
814	pub fn add_backup_in(
815		&mut self,
816		folder: &dyn BackupFolder,
817		new: &NewBackup,
818		wall_millis: u64,
819		rng: &mut impl CryptoRng,
820	) -> Result<AddedBackup, NodeError> {
821		let name = new.name.trim();
822		if name.is_empty() {
823			return Err(NodeError::EmptyName);
824		}
825		let spaces = self.chosen_spaces(&new.spaces)?;
826		self.check_backup_policies(&spaces, &new.policies)?;
827		self.record_new_backup(folder, (name, spaces), new, wall_millis, rng)
828	}
829
830	/// Makes a backup's folder and records the backup, once its name, spaces and policies
831	/// are checked.
832	fn record_new_backup(
833		&mut self,
834		folder: &dyn BackupFolder,
835		(name, spaces): (&str, Vec<SpaceId>),
836		new: &NewBackup,
837		wall_millis: u64,
838		rng: &mut impl CryptoRng,
839	) -> Result<AddedBackup, NodeError> {
840		let id = EntityId::random(rng);
841		backup::make(folder, id)?;
842		let drive = folder.drive();
843		let path = drive.path.clone().unwrap_or_default();
844		let backup = Backup {
845			id,
846			name: name.to_owned(),
847			folder: path,
848			spaces,
849			policies: new.policies.clone(),
850			away: new.away,
851			waits: new.waits,
852		};
853		let mut operations = vec![
854			assert(id, fields::TYPE, Value::Text(BACKUP.to_string()), rng),
855			assert(id, fields::NAME, Value::Name(Name::new(name)), rng),
856			assert(id, BACKUP_FOLDER, Value::Text(backup.folder.clone()), rng),
857		];
858		for space in &backup.spaces {
859			operations.push(assert(
860				id,
861				BACKUP_SPACE,
862				Value::Text(space.to_string()),
863				rng,
864			));
865		}
866		for policy in &backup.policies {
867			operations.push(assert(id, BACKUP_POLICY, Value::Reference(*policy), rng));
868		}
869		if backup.away {
870			operations.push(assert(id, AWAY, Value::Boolean(true), rng));
871		}
872		if let Some(days) = backup.waits {
873			let days = Value::Integer(i64::try_from(days).unwrap_or(i64::MAX));
874			operations.push(assert(id, WAITS, days, rng));
875		}
876		if let Err(error) = self.commit(self.info.personal, operations, wall_millis, rng) {
877			backup::unmake(folder);
878			return Err(error);
879		}
880		Ok(AddedBackup {
881			backup,
882			on_share: drive.remote,
883		})
884	}
885
886	/// Changes one of the person's backups.
887	///
888	/// # Errors
889	///
890	/// Returns [`NodeError::WhichBackup`] if `backup` is none of the person's backups, the
891	/// errors of [`Library::add_backup`] for what is given, and an error if the change cannot
892	/// be saved.
893	pub fn edit_backup(
894		&mut self,
895		backup: EntityId,
896		edit: &BackupEdit,
897		wall_millis: u64,
898		rng: &mut impl CryptoRng,
899	) -> Result<(), NodeError> {
900		let Some(before) = self.backups()?.into_iter().find(|known| known.id == backup) else {
901			return Err(NodeError::WhichBackup(format!(
902				"{backup} is no backup of yours"
903			)));
904		};
905		let personal = self.info.personal;
906		let mut values = Vec::new();
907		if let Some(name) = &edit.name {
908			if name.trim().is_empty() {
909				return Err(NodeError::EmptyName);
910			}
911			if name.trim() != before.name {
912				values.push((fields::NAME, Value::Name(Name::new(name.trim()))));
913			}
914		}
915		if let Some(away) = edit.away
916			&& away != before.away
917		{
918			values.push((AWAY, Value::Boolean(away)));
919		}
920		let mut operations = self.replacing(personal, backup, values, rng)?;
921		// The wait, or the default without one: its values go.
922		if let Some(waits) = edit.waits
923			&& waits != before.waits
924		{
925			let days = waits.map(|days| Value::Integer(i64::try_from(days).unwrap_or(i64::MAX)));
926			operations.extend(self.replacing_or_clearing(personal, backup, WAITS, days, rng)?);
927		}
928		let spaces = match &edit.spaces {
929			Some(spaces) => self.chosen_spaces(spaces)?,
930			None => before.spaces.clone(),
931		};
932		if let Some(policies) = &edit.policies {
933			self.check_backup_policies(&spaces, policies)?;
934		}
935		// Spaces taken on keep the files of the policies that the backup keeps, by their
936		// names there, as `policies` gives none.
937		let policies = match &edit.policies {
938			None if edit.spaces.is_some() && !before.policies.is_empty() => {
939				Some(self.policies_in(&before.policies, &before.spaces, &spaces)?)
940			}
941			given => given.clone(),
942		};
943		let state = self.space(personal)?.stored.log().state();
944		// Values of many, each added or retracted as the new list says.
945		let mut many = |field: FieldName, values: Vec<Value>| -> Result<(), NodeError> {
946			let current = state.current(backup, &field)?;
947			let retracted: Vec<StatementId> = current
948				.iter()
949				.filter(|statement| !values.contains(&statement.value))
950				.map(|statement| statement.id)
951				.collect();
952			if !retracted.is_empty() {
953				operations.push(Operation::retract(backup, retracted));
954			}
955			for value in values {
956				if !current.iter().any(|statement| statement.value == value) {
957					operations.push(assert(backup, field.clone(), value, rng));
958				}
959			}
960			Ok(())
961		};
962		if edit.spaces.is_some() {
963			many(
964				BACKUP_SPACE,
965				spaces
966					.iter()
967					.map(|space| Value::Text(space.to_string()))
968					.collect(),
969			)?;
970		}
971		if let Some(policies) = &policies {
972			many(
973				BACKUP_POLICY,
974				policies
975					.iter()
976					.map(|policy| Value::Reference(*policy))
977					.collect(),
978			)?;
979		}
980		if operations.is_empty() {
981			return Ok(());
982		}
983		self.commit(personal, operations, wall_millis, rng)
984	}
985
986	/// Forgets one of the person's backups: its record is deleted, and its folder stays for
987	/// the person to delete.
988	///
989	/// # Errors
990	///
991	/// Returns [`NodeError::WhichBackup`] if `backup` is none of the person's backups, and an
992	/// error if the change cannot be saved.
993	pub fn remove_backup(
994		&mut self,
995		backup: EntityId,
996		wall_millis: u64,
997		rng: &mut impl CryptoRng,
998	) -> Result<(), NodeError> {
999		if !self.backups()?.iter().any(|known| known.id == backup) {
1000			return Err(NodeError::WhichBackup(format!(
1001				"{backup} is no backup of yours"
1002			)));
1003		}
1004		let operations = vec![assert(backup, fields::DELETED, Value::Boolean(true), rng)];
1005		self.commit(self.info.personal, operations, wall_millis, rng)
1006	}
1007
1008	/// The person's backups that hold a space of this replica's and are reachable from this
1009	/// computer, each with its folder: at its path under each folder that a drive or share is
1010	/// mounted at, and where `remembered` says this computer found it last.
1011	///
1012	/// # Errors
1013	///
1014	/// Returns an error if the personal space cannot be read.
1015	pub fn find_backups(
1016		&self,
1017		remembered: &BTreeMap<EntityId, PathBuf>,
1018	) -> Result<Vec<(Backup, PathBuf)>, NodeError> {
1019		let mounts = backup::mounts();
1020		let mut backups = Vec::new();
1021		let mut candidates = Vec::new();
1022		for backup in self.backups()? {
1023			if self.backup_spaces(&backup)?.is_empty() {
1024				continue;
1025			}
1026			if let Some(folder) = remembered.get(&backup.id) {
1027				candidates.push((folder.clone(), folder.clone(), backup.id));
1028			}
1029			if !backup.folder.is_empty() {
1030				let path = backup.folder.replace('/', std::path::MAIN_SEPARATOR_STR);
1031				candidates.extend(
1032					mounts
1033						.iter()
1034						.map(|mount| (mount.clone(), mount.join(&path), backup.id)),
1035				);
1036			}
1037			backups.push(backup);
1038		}
1039		let named = backup::find_named(candidates, FIND_WITHIN);
1040		Ok(backups
1041			.into_iter()
1042			.filter_map(|backup| {
1043				let folder = named
1044					.iter()
1045					.find(|(id, _)| *id == backup.id)
1046					.map(|(_, folder)| folder.clone())?;
1047				Some((backup, folder))
1048			})
1049			.collect())
1050	}
1051
1052	/// What a backup's folder says of it, as of `wall_millis`, without updating it.
1053	///
1054	/// # Errors
1055	///
1056	/// Returns [`NodeError::NotTheBackup`] if the folder is not the backup, and an error if it
1057	/// cannot be read.
1058	pub fn backup_state(
1059		&self,
1060		backup: &Backup,
1061		folder: &Path,
1062		wall_millis: u64,
1063	) -> Result<BackupState, NodeError> {
1064		self.backup_state_in(backup, &InFileSystem::new(folder), wall_millis)
1065	}
1066
1067	/// What a backup's folder, reached through the interface of files, says of it, as
1068	/// [`Library::backup_state`] does.
1069	///
1070	/// # Errors
1071	///
1072	/// Returns [`NodeError::NotTheBackup`] if the folder is not the backup, and an error if it
1073	/// cannot be read.
1074	pub fn backup_state_in(
1075		&self,
1076		backup: &Backup,
1077		folder: &dyn BackupFolder,
1078		wall_millis: u64,
1079	) -> Result<BackupState, NodeError> {
1080		if backup::named_in(folder) != Some(backup.id) {
1081			return Err(NodeError::NotTheBackup {
1082				path: folder.shown(""),
1083				name: backup.name.clone(),
1084			});
1085		}
1086		let record = backup::read_record(folder);
1087		let to_check = backup::blob_files_in(folder)?
1088			.into_iter()
1089			.filter(|(sealed, _)| {
1090				record
1091					.checks
1092					.get(sealed)
1093					.is_none_or(|checked| checked.saturating_add(CHECK_AGAIN) <= wall_millis)
1094			})
1095			.map(|(_, size)| size)
1096			.sum();
1097		Ok(BackupState {
1098			update: record.update,
1099			held: record.checks.len(),
1100			to_check,
1101			damaged: record.damaged.len(),
1102		})
1103	}
1104
1105	/// Updates a backup in `folder` ([technical design: backups]): takes in what the replica
1106	/// lacks, applies its purges, writes what the backup lacks, and checks the backup's
1107	/// copies, until `stop` says to stop. `None` while another program updates it.
1108	///
1109	/// [technical design: backups]: ../../../../docs/Technical-design.md#910-backups
1110	///
1111	/// # Errors
1112	///
1113	/// Returns [`NodeError::NotTheBackup`] if the folder is not the backup, and an error if
1114	/// the library or the backup cannot be read or written.
1115	pub fn update_backup(
1116		&mut self,
1117		backup: &Backup,
1118		folder: &Path,
1119		now: &dyn Fn() -> u64,
1120		stop: &dyn Fn() -> bool,
1121	) -> Result<Option<BackupUpdate>, NodeError> {
1122		self.update_backup_in(backup, &InFileSystem::new(folder), now, stop)
1123	}
1124
1125	/// Updates a backup as [`Library::update_backup`] does, in a folder reached through the
1126	/// interface of files, as the folder that Android's picker gives.
1127	///
1128	/// # Errors
1129	///
1130	/// Returns the errors of [`Library::update_backup`].
1131	pub fn update_backup_in(
1132		&mut self,
1133		backup: &Backup,
1134		folder: &dyn BackupFolder,
1135		now: &dyn Fn() -> u64,
1136		stop: &dyn Fn() -> bool,
1137	) -> Result<Option<BackupUpdate>, NodeError> {
1138		self.update_backup_through(backup, folder, (now, stop), &BTreeSet::new())
1139	}
1140
1141	/// Updates a backup as [`Library::update_backup`] does, ending the wait of the purges
1142	/// `ending`, whose destruction then leaves the backup at once.
1143	pub(crate) fn update_backup_ending(
1144		&mut self,
1145		backup: &Backup,
1146		folder: &Path,
1147		(now, stop): (&dyn Fn() -> u64, &dyn Fn() -> bool),
1148		ending: &BTreeSet<ChangeId>,
1149	) -> Result<Option<BackupUpdate>, NodeError> {
1150		self.update_backup_through(backup, &InFileSystem::new(folder), (now, stop), ending)
1151	}
1152
1153	/// Updates a backup in a folder reached through the interface of files, ending the wait
1154	/// of the purges `ending`.
1155	fn update_backup_through(
1156		&mut self,
1157		backup: &Backup,
1158		folder: &dyn BackupFolder,
1159		(now, stop): (&dyn Fn() -> u64, &dyn Fn() -> bool),
1160		ending: &BTreeSet<ChangeId>,
1161	) -> Result<Option<BackupUpdate>, NodeError> {
1162		let Some(updating) = Updating::hold(folder, backup.id, &backup.name)? else {
1163			return Ok(None);
1164		};
1165		let mut record = updating.record();
1166		let mut done = BackupUpdate {
1167			unclean: updating.unclean,
1168			..BackupUpdate::default()
1169		};
1170		// A drive pulled out while written, on a file system that then may damage other
1171		// files: every copy counts again only once read back.
1172		if updating.unclean && updating.unjournaled {
1173			for checked in record.checks.values_mut() {
1174				*checked = 0;
1175			}
1176		}
1177		let mut spaces = self.backup_spaces(backup)?;
1178		let mut packs = Packs::read(&updating, &mut done)?;
1179		// Past every update that wrote a pack, and that the backup's accounts known here tell
1180		// of, too, so that a record lost to a pulled drive does not start the numbers again,
1181		// by which devices tell the backup's latest account.
1182		let accounted = spaces
1183			.iter()
1184			.filter_map(|space| {
1185				let accounts = self.backup_accounts(*space).ok()?;
1186				accounts.get(&backup.id).map(|account| account.head.update)
1187			})
1188			.max()
1189			.unwrap_or(0);
1190		let update = packs
1191			.files
1192			.iter()
1193			.map(|file| file.update)
1194			.fold(record.update.max(accounted), u64::max)
1195			.saturating_add(1);
1196		// A backup that holds the personal space keeps it, also where this computer has not
1197		// heard yet of the code that put it there: so that it takes the code in, and leaves
1198		// it in the backup's recovery file.
1199		let personal = self.info.personal;
1200		if !spaces.contains(&personal) && packs.of_space(personal).next().is_some() {
1201			spaces.push(personal);
1202			spaces.sort();
1203		}
1204		let read_at = now();
1205		for sealed in packs.blobs_in_packs() {
1206			record.checks.insert(sealed, read_at);
1207		}
1208		self.take_in_backup(&updating, &packs, &spaces, now, &mut done)?;
1209		// The backup's wait, as its owner marks it: a shorter one holds only once the wait
1210		// before it has passed.
1211		let marked = super::waiting::backup_wait_days(backup).saturating_mul(super::waiting::DAY);
1212		if let Some(waits) = super::waiting::waits_marked(&record.waits, marked, read_at) {
1213			record.waits = waits;
1214		}
1215		let mut waits = Waits::new(&mut record, read_at, ending);
1216		self.purge_backup(
1217			&updating, &mut packs, &spaces, update, &mut waits, &mut done,
1218		)?;
1219		done.waiting = waits.waiting.len();
1220		// A purge of a space that this computer does not hold stays as the record has it.
1221		let told = |purge: &ChangeId| {
1222			spaces.iter().any(|space| {
1223				self.spaces
1224					.get(space)
1225					.is_some_and(|open| open.stored.log().contains(*purge).unwrap_or(true))
1226			})
1227		};
1228		waits.settle(told);
1229		let wall = now();
1230		// The personal space, which a backup holds for the person's recovery codes whatever
1231		// spaces it names, gives its files only where it is named.
1232		let keys_only = (!backup.spaces.contains(&personal)).then_some(personal);
1233		self.write_backup(
1234			&updating,
1235			&mut packs,
1236			(&spaces, &backup.policies, keys_only),
1237			(update, wall),
1238			&mut record,
1239			&mut done,
1240		)?;
1241		self.write_backup_recovery(&updating)?;
1242		merge(&updating, &mut packs, &spaces, update)?;
1243		self.check_backup(&updating, &mut record, update, (now, stop), &mut done)?;
1244		// What the record knows, of what the backup holds now.
1245		let held = packs.blobs();
1246		record.checks.retain(|sealed, _| held.contains_key(sealed));
1247		for sealed in held.keys() {
1248			record.checks.entry(*sealed).or_insert(0);
1249		}
1250		let wall = now();
1251		record
1252			.damaged
1253			.retain(|_, found| wall.saturating_sub(*found) < DAMAGE_COUNTS_FOR);
1254		record.update = update;
1255		updating.save_record(&record)?;
1256		self.account_backup(backup, (folder, &packs, &record), &spaces, wall);
1257		// The codes that a newer one replaces, if the backup was the last to carry it: the
1258		// update is done, and the next sync tries again if this fails.
1259		let _ = self.revoke_replaced_recovery_codes(false, wall, &mut UnwrapErr(SysRng));
1260		done.update = update;
1261		done.held = held.len();
1262		done.held_bytes = held.values().sum();
1263		// What it names only, after the update is done.
1264		done.elsewhere = self
1265			.spaces_held_elsewhere(&backup.spaces)
1266			.unwrap_or_default();
1267		Ok(Some(done))
1268	}
1269
1270	/// Takes in what the backup in `folder`, whose record is `backup`, holds of `spaces`, as
1271	/// the first two steps of an update do, holding the backup meanwhile: for a library that a
1272	/// recovery code brings back, which does not read the backup's record yet. `None` while
1273	/// another program updates the backup.
1274	///
1275	/// # Errors
1276	///
1277	/// Returns [`NodeError::NotTheBackup`] if the folder is not the backup, and an error if
1278	/// the backup cannot be read, or what it holds saved.
1279	pub(crate) fn take_in_backup_at(
1280		&mut self,
1281		(folder, backup): (&Path, EntityId),
1282		spaces: &[SpaceId],
1283		now: &dyn Fn() -> u64,
1284	) -> Result<Option<BackupMoved>, NodeError> {
1285		let name = folder
1286			.file_name()
1287			.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
1288		let files = InFileSystem::new(folder);
1289		let Some(updating) = Updating::hold(&files, backup, &name)? else {
1290			return Ok(None);
1291		};
1292		let mut done = BackupUpdate::default();
1293		let packs = Packs::read(&updating, &mut done)?;
1294		self.take_in_backup(&updating, &packs, spaces, now, &mut done)?;
1295		Ok(Some(done.taken))
1296	}
1297
1298	/// What a backup keeps of what a purge of `space` destroyed, as its packs hold it while
1299	/// it waits: the changes with their payloads, the record keys and the blob keys that the
1300	/// purge keeps purged. `None` while another program updates the backup.
1301	///
1302	/// # Errors
1303	///
1304	/// Returns [`NodeError::NotTheBackup`] if the folder is not the backup, and an error if
1305	/// the backup or the space cannot be read.
1306	pub(crate) fn backup_kept_of(
1307		&self,
1308		backup: &Backup,
1309		folder: &Path,
1310		(space, purge): (SpaceId, ChangeId),
1311	) -> Result<Option<nibkeep_log::Restores>, NodeError> {
1312		let files = InFileSystem::new(folder);
1313		let Some(updating) = Updating::hold(&files, backup.id, &backup.name)? else {
1314			return Ok(None);
1315		};
1316		let packs = Packs::read(&updating, &mut BackupUpdate::default())?;
1317		let by = self.space(space)?.stored.log().purged_by()?;
1318		let mut restores = nibkeep_log::Restores::default();
1319		for file in packs.of_space(space) {
1320			for entry in &file.entries {
1321				match &entry.what {
1322					What::Change { id, complete: true } if by.changes.get(id) == Some(&purge) => {
1323						restores.changes.insert(*id);
1324					}
1325					What::RecordKey(statement) if by.statements.get(statement) == Some(&purge) => {
1326						restores.statements.insert(*statement);
1327					}
1328					What::BlobKey(sealed) if by.blobs.get(sealed) == Some(&purge) => {
1329						restores.blobs.insert(*sealed);
1330					}
1331					_ => {}
1332				}
1333			}
1334		}
1335		Ok(Some(restores))
1336	}
1337
1338	/// Issues the account of a backup just updated in each of its spaces where this replica
1339	/// counts: its disk, its mark, the space's changes it holds, which are this replica's,
1340	/// what checks found damaged, the update's number, and the sealed blobs that its packs
1341	/// of the space hold keys for, with when each was last checked. Accounts only count and
1342	/// show copies, so one that cannot be issued now waits for the next update.
1343	fn account_backup(
1344		&mut self,
1345		backup: &Backup,
1346		(folder, packs, record): (&dyn BackupFolder, &Packs, &Record),
1347		spaces: &[SpaceId],
1348		wall_millis: u64,
1349	) {
1350		let own = self.replica.signing.verifying_key();
1351		let name = backup::disk_name(folder, backup.id);
1352		let held = packs.blobs();
1353		let keyed = packs.keyed();
1354		let mut rng = UnwrapErr(SysRng);
1355		for &space in spaces {
1356			if !self.counts_in(space, &own).unwrap_or(false) {
1357				continue;
1358			}
1359			let Ok(heads) = self
1360				.space(space)
1361				.and_then(|open| Ok(open.stored.log().heads()?))
1362			else {
1363				continue;
1364			};
1365			// What checks found damaged of this space's blobs alone, as a replica counts its
1366			// own, so that no space learns of another's.
1367			let damaged: Vec<&Hash> = record
1368				.damaged
1369				.keys()
1370				.filter(|sealed| {
1371					keyed
1372						.get(*sealed)
1373						.is_some_and(|keyed| keyed.contains(&space))
1374				})
1375				.collect();
1376			let blobs: BTreeMap<Hash, u64> = held
1377				.keys()
1378				.filter(|sealed| {
1379					keyed
1380						.get(*sealed)
1381						.is_some_and(|keyed| keyed.contains(&space))
1382				})
1383				.map(|sealed| (*sealed, record.checks.get(sealed).copied().unwrap_or(0)))
1384				.collect();
1385			let account = BackupHead {
1386				disk: disk_id(space, Some(&name), &own),
1387				away: backup.away,
1388				heads: heads.into_iter().collect(),
1389				damaged: u64::try_from(damaged.len()).unwrap_or(u64::MAX),
1390				unrepaired: u64::try_from(
1391					damaged
1392						.iter()
1393						.filter(|sealed| !held.contains_key(**sealed))
1394						.count(),
1395				)
1396				.unwrap_or(u64::MAX),
1397				update: record.update,
1398				waits: super::waiting::wait_at(&record.waits, wall_millis)
1399					.div_ceil(super::waiting::DAY),
1400			};
1401			let _ = self.issue_backup_account(
1402				space,
1403				backup.id,
1404				(account, &blobs),
1405				wall_millis,
1406				&mut rng,
1407			);
1408		}
1409	}
1410
1411	/// Keeps the backup's recovery file as the person's codes call for, as
1412	/// [`Library::recovery_file_anew`] says: written anew only where the codes that stand
1413	/// changed, or where it does not read, as on a damaged drive, so that the computers that
1414	/// update a backup in turn leave it as it is.
1415	fn write_backup_recovery(&self, updating: &Updating<'_>) -> Result<(), NodeError> {
1416		// One that does not read is written anew.
1417		let existing = updating.recovery();
1418		match self.recovery_file_anew(existing.as_ref())? {
1419			RecoveryFileNeed::Kept => Ok(()),
1420			RecoveryFileNeed::Written(file) => updating.save_recovery(&file.to_bytes()),
1421			RecoveryFileNeed::Removed => updating.delete_recovery(),
1422		}
1423	}
1424
1425	/// The spaces whose items a backup takes and gives on this replica: those that it holds
1426	/// and the replica holds, and the groups that they add, at any level; and the personal
1427	/// space, whatever it names, while a recovery code of the person's stands, as a code
1428	/// opens the person's other spaces through it.
1429	pub(crate) fn backup_spaces(&self, backup: &Backup) -> Result<Vec<SpaceId>, NodeError> {
1430		let mut spaces = BTreeSet::new();
1431		let personal = self.info.personal;
1432		if self
1433			.roster(personal)?
1434			.codes()
1435			.any(nibkeep_governance::Code::stands)
1436		{
1437			spaces.insert(personal);
1438		}
1439		for space in &backup.spaces {
1440			if !self.spaces.contains_key(space) {
1441				continue;
1442			}
1443			spaces.insert(*space);
1444			for group in self.inner_groups(*space)? {
1445				if self.spaces.contains_key(&group) {
1446					spaces.insert(group);
1447				}
1448			}
1449		}
1450		Ok(spaces.into_iter().collect())
1451	}
1452
1453	/// The spaces chosen for a backup, checked: every space of the library that is no
1454	/// group's, if none is chosen.
1455	fn chosen_spaces(&self, chosen: &[SpaceId]) -> Result<Vec<SpaceId>, NodeError> {
1456		let mut spaces = BTreeSet::new();
1457		if chosen.is_empty() {
1458			for (&id, open) in &self.spaces {
1459				if !open.is_group()? {
1460					spaces.insert(id);
1461				}
1462			}
1463		}
1464		for space in chosen {
1465			self.space(*space)?;
1466			spaces.insert(*space);
1467		}
1468		Ok(spaces.into_iter().collect())
1469	}
1470
1471	/// The policies of `to` that stand for `policies`, of `from`: each default policy of
1472	/// `to` that is one of them in `from`, whether or not it is installed there, and each
1473	/// other of `to` named as one of them is.
1474	fn policies_in(
1475		&self,
1476		policies: &[EntityId],
1477		from: &[SpaceId],
1478		to: &[SpaceId],
1479	) -> Result<Vec<EntityId>, NodeError> {
1480		let mut labels = BTreeSet::new();
1481		let mut names = BTreeSet::new();
1482		for space in from {
1483			for (label, id) in default_policies(*space).into_iter().enumerate() {
1484				if policies.contains(&id) {
1485					labels.insert(label);
1486				}
1487			}
1488			if self.spaces.contains_key(space) {
1489				for policy in self.policies(*space)? {
1490					if policies.contains(&policy.id)
1491						&& let Some(name) = policy.name
1492					{
1493						names.insert(name);
1494					}
1495				}
1496			}
1497		}
1498		let mut found = BTreeSet::new();
1499		for space in to {
1500			let defaults = default_policies(*space);
1501			found.extend(
1502				labels
1503					.iter()
1504					.filter_map(|label| defaults.get(*label).copied()),
1505			);
1506			for policy in self.policies(*space)? {
1507				if policy
1508					.name
1509					.as_ref()
1510					.is_some_and(|name| names.contains(name))
1511				{
1512					found.insert(policy.id);
1513				}
1514			}
1515		}
1516		Ok(found.into_iter().collect())
1517	}
1518
1519	/// Checks that each policy is one of those spaces'.
1520	fn check_backup_policies(
1521		&self,
1522		spaces: &[SpaceId],
1523		policies: &[EntityId],
1524	) -> Result<(), NodeError> {
1525		for policy in policies {
1526			let mut found = false;
1527			for space in spaces {
1528				found |= default_policies(*space).contains(policy)
1529					|| self
1530						.policies(*space)?
1531						.iter()
1532						.any(|known| known.id == *policy);
1533			}
1534			if !found {
1535				return Err(NodeError::NoEntity(format!(
1536					"{policy} is no policy of the backup's spaces"
1537				)));
1538			}
1539		}
1540		Ok(())
1541	}
1542
1543	/// Takes in what the backup's packs and files hold and the replica lacks, as a sync takes
1544	/// in what another replica sends: changes and keys, then the sealed blobs that the
1545	/// replica keeps and lacks.
1546	fn take_in_backup(
1547		&mut self,
1548		updating: &Updating<'_>,
1549		packs: &Packs,
1550		spaces: &[SpaceId],
1551		now: &dyn Fn() -> u64,
1552		done: &mut BackupUpdate,
1553	) -> Result<(), NodeError> {
1554		let mut syncing = Syncing::new(self, now);
1555		for &space in spaces {
1556			let held: BTreeSet<[u8; 32]> = syncing.holdings(space)?.iter().map(item_id).collect();
1557			for file in packs.of_space(space) {
1558				let wanted: Vec<&Entry> = file
1559					.entries
1560					.iter()
1561					.filter(|entry| {
1562						!matches!(entry.what, What::Blob(_)) && !held.contains(&entry.id)
1563					})
1564					.collect();
1565				if wanted.is_empty() {
1566					continue;
1567				}
1568				let Ok(bytes) = updating.read(&file.path) else {
1569					continue;
1570				};
1571				for entry in wanted {
1572					let Some(Ok(item)) = bytes
1573						.get(entry.start..entry.start + entry.length)
1574						.map(|encoded| PackReader::item_at(space, encoded))
1575					else {
1576						continue;
1577					};
1578					match item {
1579						PackItem::Change(parcel) => {
1580							// Taken as from its author, so that what a replica that the space
1581							// ended made after that is left out, as a sync with it leaves it.
1582							let author = *parcel.change.author();
1583							if syncing.receive_change(space, &author, *parcel)? {
1584								done.taken.changes += 1;
1585							}
1586						}
1587						PackItem::RecordKey(statement, key) => {
1588							if syncing.receive_record_key(space, statement, key)? {
1589								done.taken.keys += 1;
1590							}
1591						}
1592						PackItem::BlobKey(sealed, key) => {
1593							if syncing.receive_blob_key(space, sealed, key)? {
1594								done.taken.keys += 1;
1595							}
1596						}
1597						PackItem::Blob(..) => {}
1598					}
1599				}
1600			}
1601			syncing.pause()?;
1602			let on_backup = |sealed: &Hash| packs.blob(sealed).is_some();
1603			for sealed in syncing.wanted_among(space, &on_backup, &BTreeSet::new(), usize::MAX)? {
1604				let kept = match packs.blob(&sealed) {
1605					Some(BlobAt::File(size)) => {
1606						let Ok(mut file) = updating.open(&backup::blob_path(&sealed)) else {
1607							continue;
1608						};
1609						syncing
1610							.receive_blob(space, sealed, size, &mut file)?
1611							.then_some(size)
1612					}
1613					Some(BlobAt::Pack {
1614						path,
1615						start,
1616						length,
1617						space: of,
1618						..
1619					}) => {
1620						let Some(PackItem::Blob(_, bytes)) =
1621							read_item(updating, &path, of, start, length)
1622						else {
1623							continue;
1624						};
1625						let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
1626						syncing
1627							.receive_blob(space, sealed, size, &mut bytes.as_slice())?
1628							.then_some(size)
1629					}
1630					None => None,
1631				};
1632				if let Some(size) = kept {
1633					done.taken.blobs += 1;
1634					done.taken.bytes += size;
1635				}
1636			}
1637			syncing.finish_space(space)?;
1638		}
1639		Ok(())
1640	}
1641
1642	/// Applies the replica's purges to the backup: what they took away leaves the packs of
1643	/// the spaces that the replica holds, which are written anew without it, and a purged
1644	/// blob goes unless a pack of another space holds a key for it.
1645	fn purge_backup(
1646		&self,
1647		updating: &Updating<'_>,
1648		packs: &mut Packs,
1649		spaces: &[SpaceId],
1650		update: u64,
1651		waits: &mut Waits<'_>,
1652		done: &mut BackupUpdate,
1653	) -> Result<(), NodeError> {
1654		// Which purge keeps each item purged, by space, for the wait it counts from.
1655		let mut purged_by = BTreeMap::new();
1656		for &space in spaces {
1657			if let Some(open) = self.spaces.get(&space) {
1658				purged_by.insert(space, open.stored.log().purged_by()?);
1659			}
1660		}
1661		let gone_blobs = self.purged_blobs_of(packs, spaces, &purged_by, waits)?;
1662		let no_purges = nibkeep_log::PurgedBy::default();
1663		let mut rewritten = Vec::new();
1664		for (at, file) in packs.files.iter().enumerate() {
1665			if !spaces.contains(&file.space) {
1666				continue;
1667			}
1668			let log = self.space(file.space)?.stored.log();
1669			let by = purged_by.get(&file.space).unwrap_or(&no_purges);
1670			// For each entry: kept as it is, kept without its payload, or left out, once the
1671			// wait for its purge is over.
1672			let mut verdicts = Vec::with_capacity(file.entries.len());
1673			for entry in &file.entries {
1674				verdicts.push(match &entry.what {
1675					What::Change { id, complete: true }
1676						if log.is_change_purged(*id)?
1677							&& waits.due(by.changes.get(id), entry.id) =>
1678					{
1679						Verdict::Strip
1680					}
1681					What::RecordKey(statement)
1682						if log.is_purged(*statement)?
1683							&& waits.due(by.statements.get(statement), entry.id) =>
1684					{
1685						Verdict::Drop
1686					}
1687					What::BlobKey(sealed)
1688						if log.is_blob_purged(sealed)?
1689							&& waits.due(by.blobs.get(sealed), entry.id) =>
1690					{
1691						Verdict::Drop
1692					}
1693					What::Blob(sealed) if gone_blobs.contains(sealed) => Verdict::Drop,
1694					_ => Verdict::Keep,
1695				});
1696			}
1697			if verdicts.iter().all(|verdict| *verdict == Verdict::Keep) {
1698				continue;
1699			}
1700			let bytes = updating
1701				.read(&file.path)
1702				.map_err(NodeError::file(&updating.shown(&file.path)))?;
1703			let mut writer = PackWriter::new(file.space, update);
1704			for (entry, verdict) in file.entries.iter().zip(&verdicts) {
1705				let encoded = bytes
1706					.get(entry.start..entry.start + entry.length)
1707					.unwrap_or_default();
1708				match verdict {
1709					Verdict::Keep => writer.push_encoded(updating, encoded)?,
1710					Verdict::Strip => {
1711						if let Ok(PackItem::Change(mut parcel)) =
1712							PackReader::item_at(file.space, encoded)
1713						{
1714							parcel.payload = None;
1715							parcel.keys.clear();
1716							writer.push(updating, &PackItem::Change(parcel))?;
1717						}
1718						done.purged += 1;
1719					}
1720					Verdict::Drop => done.purged += 1,
1721				}
1722			}
1723			rewritten.push((at, writer.finish(updating)?));
1724		}
1725		// The new packs in place of the old, each deleted once its new one is written.
1726		for (at, new) in rewritten.into_iter().rev() {
1727			let old = packs.files.remove(at);
1728			if !new.iter().any(|file| file.path == old.path) {
1729				updating.delete(&old.path)?;
1730			}
1731			packs.files.extend(new);
1732		}
1733		for sealed in &gone_blobs {
1734			if packs.blob_files.remove(sealed).is_some() {
1735				updating.delete(&backup::blob_path(sealed))?;
1736				done.purged += 1;
1737			}
1738		}
1739		packs.reindex();
1740		Ok(())
1741	}
1742
1743	/// The sealed blobs that leave a backup in an update: purged, their wait over, in a space
1744	/// of the replica's, and no pack of a space that kept it holds a key for them.
1745	fn purged_blobs_of(
1746		&self,
1747		packs: &Packs,
1748		spaces: &[SpaceId],
1749		purged_by: &BTreeMap<SpaceId, nibkeep_log::PurgedBy>,
1750		waits: &mut Waits<'_>,
1751	) -> Result<BTreeSet<Hash>, NodeError> {
1752		let keyed = packs.keyed();
1753		// Whether a purged blob leaves the backup: purged, its wait over, in a space of the
1754		// replica's, and no pack of a space that kept it holds a key for it.
1755		let mut purged_in = |sealed: &Hash| -> Result<bool, NodeError> {
1756			let mut purged_here = |space: &SpaceId| -> Result<Option<bool>, NodeError> {
1757				match (self.spaces.get(space), purged_by.get(space)) {
1758					(Some(open), Some(by)) => Ok(Some(
1759						open.stored.log().is_blob_purged(sealed)?
1760							&& waits.due(by.blobs.get(sealed), blob_id(sealed)),
1761					)),
1762					_ => Ok(None),
1763				}
1764			};
1765			let mut purged = false;
1766			match keyed.get(sealed) {
1767				Some(keyed) => {
1768					for space in keyed {
1769						match purged_here(space)? {
1770							Some(true) => purged = true,
1771							_ => return Ok(false),
1772						}
1773					}
1774				}
1775				None => {
1776					for space in spaces {
1777						purged |= purged_here(space)? == Some(true);
1778					}
1779				}
1780			}
1781			Ok(purged)
1782		};
1783		let mut gone_blobs = BTreeSet::new();
1784		for sealed in packs.blobs().keys() {
1785			if purged_in(sealed)? {
1786				gone_blobs.insert(*sealed);
1787			}
1788		}
1789		Ok(gone_blobs)
1790	}
1791
1792	/// Writes what the backup lacks, for each space: a pack of the changes and keys, and the
1793	/// sealed blobs that the backup keeps, while its drive keeps 1 GiB free after each.
1794	fn write_backup(
1795		&self,
1796		updating: &Updating<'_>,
1797		packs: &mut Packs,
1798		(spaces, policies, keys_only): (&[SpaceId], &[EntityId], Option<SpaceId>),
1799		(update, wall): (u64, u64),
1800		record: &mut Record,
1801		done: &mut BackupUpdate,
1802	) -> Result<(), NodeError> {
1803		let mut free = updating.free()?;
1804		let mut written_blobs = BTreeSet::new();
1805		for &space in spaces {
1806			let open = self.space(space)?;
1807			let log = open.stored.log();
1808			let on_backup = packs.ids(space);
1809			let changes_on = packs.changes(space);
1810			let mut writer = PackWriter::new(space, update);
1811			let mut changes: Vec<(u64, ChangeId)> = log
1812				.summaries()?
1813				.into_iter()
1814				.filter(|summary| match changes_on.get(&summary.id) {
1815					None => true,
1816					Some(complete) => !complete && summary.complete,
1817				})
1818				.map(|summary| (summary.depth, summary.id))
1819				.collect();
1820			changes.sort();
1821			for (_, id) in changes {
1822				if let Some(parcel) = log.parcel(id)? {
1823					writer.push(updating, &PackItem::Change(Box::new(parcel)))?;
1824					done.written.changes += 1;
1825				}
1826			}
1827			for (statement, key) in log.wrapped_keys() {
1828				let holding = Holding::RecordKey {
1829					statement,
1830					key: key.clone(),
1831				};
1832				if !on_backup.contains(&item_id(&holding)) {
1833					writer.push(updating, &PackItem::RecordKey(statement, key.clone()))?;
1834					done.written.keys += 1;
1835				}
1836			}
1837			for (sealed, key) in log.wrapped_blob_keys() {
1838				let holding = Holding::BlobKey {
1839					sealed: *sealed,
1840					key: key.clone(),
1841				};
1842				if !on_backup.contains(&item_id(&holding)) {
1843					writer.push(updating, &PackItem::BlobKey(*sealed, key.clone()))?;
1844					done.written.keys += 1;
1845				}
1846			}
1847			let mut plan = self.backup_plan(space, policies)?;
1848			plan.nothing = keys_only == Some(space);
1849			let mut blobs = Vec::new();
1850			for sealed in open.stored.sealed_blobs()? {
1851				if written_blobs.contains(&sealed) || packs.blob(&sealed).is_some() {
1852					continue;
1853				}
1854				if let Some(rank) =
1855					plan.rank(log.is_secret_blob(&sealed), log.content_of_sealed(&sealed))
1856				{
1857					blobs.push((rank, sealed));
1858				}
1859			}
1860			blobs.sort();
1861			for (_, sealed) in blobs {
1862				let Some((size, mut file)) = open.stored.open_sealed_blob(&sealed)? else {
1863					continue;
1864				};
1865				let room = free.saturating_sub(writer.used());
1866				if room < size.saturating_add(MIN_FREE_BYTES) {
1867					done.unfit += 1;
1868					done.unfit_bytes += size;
1869					continue;
1870				}
1871				let kept = if size <= MOST_PACK_BLOB {
1872					let mut bytes = Vec::new();
1873					std::io::Read::read_to_end(&mut file, &mut bytes)
1874						.map_err(NodeError::file(&updating.shown("")))?;
1875					// A copy here that is damaged is not passed on.
1876					if Hash::of(&bytes) == sealed {
1877						writer.push(updating, &PackItem::Blob(sealed, bytes))?;
1878						true
1879					} else {
1880						false
1881					}
1882				} else if updating.write_blob(&sealed, &mut file)? {
1883					free = free.saturating_sub(size);
1884					packs.blob_files.insert(sealed, size);
1885					true
1886				} else {
1887					false
1888				};
1889				if kept {
1890					record.checks.insert(sealed, wall);
1891					written_blobs.insert(sealed);
1892					done.written.blobs += 1;
1893					done.written.bytes += size;
1894				}
1895			}
1896			free = free.saturating_sub(writer.used());
1897			packs.files.extend(writer.finish(updating)?);
1898			packs.reindex();
1899		}
1900		Ok(())
1901	}
1902
1903	/// What a backup keeps of a space's sealed blobs: what an archive node keeps, of the
1904	/// files of `policies` only if any are named; and the order in which it writes them.
1905	fn backup_plan(&self, space: SpaceId, policies: &[EntityId]) -> Result<BackupPlan, NodeError> {
1906		let open = self.space(space)?;
1907		let state = open.stored.log().state();
1908		let storage = state.storage();
1909		let rules = self.read_policies(space)?;
1910		let filter: Option<BTreeSet<EntityId>> =
1911			(!policies.is_empty()).then(|| policies.iter().copied().collect());
1912		let standard = answer_policy(space, false);
1913		let (mut in_store, mut in_place) = (BTreeSet::new(), BTreeSet::new());
1914		let (mut chosen, mut unchosen) = (BTreeSet::new(), BTreeSet::new());
1915		let mut order: BTreeMap<Hash, (u32, Option<Moment>)> = BTreeMap::new();
1916		let mut seen = BTreeSet::new();
1917		for file in open
1918			.stored
1919			.find(&fields::TYPE, &Value::Text(FILE.to_string()))?
1920		{
1921			let file = state.canonical(file)?;
1922			if !seen.insert(file) || !state.types(file)?.contains(&FILE) {
1923				continue;
1924			}
1925			let choice = rules.choose(&own_choices(state, file)?, &facts_of(state, file)?);
1926			let taken = taken_of(state, file)?;
1927			let mut contents = BTreeSet::new();
1928			let mut newest = taken;
1929			for member in state.merged(file)? {
1930				for id in storage.of_field(member, &CONTENT)? {
1931					if let Some(recorded) = storage.get(id)?
1932						&& let Value::Blob(content) = recorded.statement.value
1933					{
1934						contents.insert(content);
1935						if taken.is_none() {
1936							newest = newest.max(moment(recorded.at.millis()));
1937						}
1938					}
1939				}
1940			}
1941			if !gone(state, file)?
1942				&& let Some(current) = state.current(file, &CONTENT)?.iter().find_map(|statement| {
1943					match statement.value {
1944						Value::Blob(content) => Some(content),
1945						_ => None,
1946					}
1947				}) {
1948				if choice.needs.kept == Kept::Store {
1949					in_store.insert(current);
1950				} else {
1951					in_place.insert(current);
1952				}
1953			}
1954			if let Some(filter) = &filter {
1955				if filter.contains(&choice.policy.unwrap_or(standard)) {
1956					chosen.extend(contents.iter().copied());
1957				} else {
1958					unchosen.extend(contents.iter().copied());
1959				}
1960			}
1961			for content in contents {
1962				let entry = order.entry(content).or_insert((0, None));
1963				entry.0 = entry.0.max(choice.needs.copies);
1964				entry.1 = entry.1.max(newest);
1965			}
1966		}
1967		let mut not: BTreeSet<Hash> = in_place.difference(&in_store).copied().collect();
1968		not.extend(unchosen.difference(&chosen).copied());
1969		Ok(BackupPlan {
1970			nothing: false,
1971			keeps: Keeps::AllBut(not),
1972			order,
1973		})
1974	}
1975
1976	/// Checks the backup's blob files that were last read in full 4 weeks before or more,
1977	/// the oldest first, at the drive's full speed, until `stop` says to stop: a damaged one
1978	/// is written again from the replica's copy, or set aside.
1979	fn check_backup(
1980		&self,
1981		updating: &Updating<'_>,
1982		record: &mut Record,
1983		update: u64,
1984		(now, stop): (&dyn Fn() -> u64, &dyn Fn() -> bool),
1985		done: &mut BackupUpdate,
1986	) -> Result<(), NodeError> {
1987		let wall = now();
1988		let mut due: Vec<(u64, Hash, u64)> = updating
1989			.blob_files()?
1990			.into_iter()
1991			.filter_map(|(sealed, size)| {
1992				let last = record.checks.get(&sealed).copied().unwrap_or(0);
1993				(last.saturating_add(CHECK_AGAIN) <= wall).then_some((last, sealed, size))
1994			})
1995			.collect();
1996		due.sort();
1997		let mut saved = Instant::now();
1998		for (at, (_, sealed, size)) in due.iter().enumerate() {
1999			if stop() {
2000				done.to_check = due.iter().skip(at).map(|(_, _, size)| size).sum();
2001				break;
2002			}
2003			let path = backup::blob_path(sealed);
2004			let intact = || updating.hash(&path).ok().map(|hash| hash == *sealed);
2005			match intact() {
2006				Some(true) => {
2007					record.checks.insert(*sealed, now());
2008					done.checked += 1;
2009					done.checked_bytes += size;
2010				}
2011				// Read again before it counts as damaged.
2012				Some(false) if intact() == Some(false) => {
2013					done.damaged += 1;
2014					record.damaged.insert(*sealed, now());
2015					let mut repaired = false;
2016					for open in self.spaces.values() {
2017						if !open.stored.holds_sealed(sealed) {
2018							continue;
2019						}
2020						if let Some((_, mut file)) = open.stored.open_sealed_blob(sealed)? {
2021							repaired = updating.write_blob(sealed, &mut file)?;
2022						}
2023						break;
2024					}
2025					if repaired {
2026						record.checks.insert(*sealed, now());
2027						done.repaired += 1;
2028					} else {
2029						updating.set_aside(&path);
2030						record.checks.remove(sealed);
2031						done.set_aside += 1;
2032					}
2033				}
2034				// One that cannot be read now is read at the next update.
2035				_ => {}
2036			}
2037			if saved.elapsed() >= SAVE_EVERY {
2038				let mut saving = record.clone();
2039				saving.update = update;
2040				updating.save_record(&saving)?;
2041				saved = Instant::now();
2042			}
2043		}
2044		Ok(())
2045	}
2046}
2047
2048/// What to do with an entry of a pack that a purge may reach.
2049#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2050enum Verdict {
2051	Keep,
2052	Strip,
2053	Drop,
2054}
2055
2056/// The item of a pack at `start`, `length` bytes long.
2057fn read_item(
2058	updating: &Updating<'_>,
2059	path: &str,
2060	space: SpaceId,
2061	start: usize,
2062	length: usize,
2063) -> Option<PackItem> {
2064	use std::io::{Read, Seek, SeekFrom};
2065	let mut file = updating.open(path).ok()?;
2066	file.seek(SeekFrom::Start(start as u64)).ok()?;
2067	let mut encoded = vec![0; length];
2068	file.read_exact(&mut encoded).ok()?;
2069	PackReader::item_at(space, &encoded).ok()
2070}
2071
2072/// Merges, in each space of `spaces` whose folder has more than [`MERGE_ABOVE`] packs
2073/// smaller than [`MERGE_BELOW`], those packs into new ones, leaving out what other packs
2074/// hold.
2075fn merge(
2076	updating: &Updating<'_>,
2077	packs: &mut Packs,
2078	spaces: &[SpaceId],
2079	update: u64,
2080) -> Result<(), NodeError> {
2081	for &space in spaces {
2082		let small: Vec<usize> = packs
2083			.files
2084			.iter()
2085			.enumerate()
2086			.filter(|(_, file)| file.space == space && file.size < MERGE_BELOW)
2087			.map(|(at, _)| at)
2088			.collect();
2089		if small.len() <= MERGE_ABOVE {
2090			continue;
2091		}
2092		let mut seen: BTreeSet<[u8; 32]> = packs
2093			.files
2094			.iter()
2095			.enumerate()
2096			.filter(|(at, file)| file.space == space && !small.contains(at))
2097			.flat_map(|(_, file)| file.entries.iter().map(|entry| entry.id))
2098			.collect();
2099		seen.extend(packs.blob_files.keys().map(blob_id));
2100		let complete: BTreeSet<ChangeId> = packs
2101			.changes(space)
2102			.into_iter()
2103			.filter(|(_, complete)| *complete)
2104			.map(|(id, _)| id)
2105			.collect();
2106		let mut writer = PackWriter::new(space, update);
2107		let mut merged = Vec::new();
2108		for &at in &small {
2109			let file = &packs.files[at];
2110			// A pack that cannot be read now stays as it is.
2111			let Ok(bytes) = updating.read(&file.path) else {
2112				continue;
2113			};
2114			for entry in &file.entries {
2115				if let What::Change {
2116					id,
2117					complete: false,
2118				} = entry.what
2119					&& complete.contains(&id)
2120				{
2121					continue;
2122				}
2123				if !seen.insert(entry.id) {
2124					continue;
2125				}
2126				writer.push_encoded(
2127					updating,
2128					bytes
2129						.get(entry.start..entry.start + entry.length)
2130						.unwrap_or_default(),
2131				)?;
2132			}
2133			merged.push(at);
2134		}
2135		let new = writer.finish(updating)?;
2136		for at in merged.into_iter().rev() {
2137			let old = packs.files.remove(at);
2138			if !new.iter().any(|file| file.path == old.path) {
2139				updating.delete(&old.path)?;
2140			}
2141		}
2142		packs.files.extend(new);
2143		packs.reindex();
2144	}
2145	Ok(())
2146}
2147
2148/// The operation that asserts a value.
2149fn assert(entity: EntityId, field: FieldName, value: Value, rng: &mut impl CryptoRng) -> Operation {
2150	Operation::assert(Statement::new(
2151		StatementId::random(rng),
2152		entity,
2153		field,
2154		value,
2155	))
2156}
2157
2158#[cfg(test)]
2159mod tests {
2160	use super::*;
2161
2162	#[test]
2163	fn a_backup_counts_each_item_once_and_keeps_purges_it_could_not_tell_of() {
2164		let day = super::super::waiting::DAY;
2165		let purge = ChangeId::from_hash(Hash::of(b"a purge"));
2166		let elsewhere = ChangeId::from_hash(Hash::of(b"a purge of a space not held here"));
2167		let mut record = Record {
2168			waits: vec![(0, 30 * day)],
2169			purges: [(elsewhere, (5, 4))].into(),
2170			..Record::default()
2171		};
2172		let ending = BTreeSet::new();
2173		let mut waits = Waits::new(&mut record, 10, &ending);
2174		// One item met twice, as a blob and its key in two packs, and another.
2175		assert!(!waits.due(Some(&purge), [1; 32]));
2176		assert!(!waits.due(Some(&purge), [1; 32]));
2177		assert!(!waits.due(Some(&purge), [2; 32]));
2178		// An item whose purge cannot be told stays, untold.
2179		assert!(!waits.due(None, [3; 32]));
2180		waits.settle(|seen| *seen == purge);
2181		assert_eq!(record.purges.get(&purge), Some(&(10, 2)));
2182		assert_eq!(
2183			record.purges.get(&elsewhere),
2184			Some(&(5, 4)),
2185			"kept as it was"
2186		);
2187		// Its wait over, it leaves.
2188		let mut waits = Waits::new(&mut record, 10 + 30 * day, &ending);
2189		assert!(waits.due(Some(&purge), [1; 32]));
2190		waits.settle(|seen| *seen == purge);
2191		assert!(!record.purges.contains_key(&purge));
2192	}
2193}