Skip to main content

nibkeep_node/library/
checking.rs

1//! Checking and repair: the holder of the sync role reads every copy that the replica holds
2//! once in a round of 4 weeks, a share at a time; a sealed blob found damaged is moved aside,
3//! so that a sync brings it again, and an original found damaged is reported, never written
4//! over ([technical design: checking and repair]).
5//!
6//! [technical design: checking and repair]: ../../../../docs/Technical-design.md#97-checking-and-repair
7
8use std::collections::{BTreeMap, BTreeSet, VecDeque};
9use std::fs;
10use std::path::Path;
11use std::time::{Duration, Instant, SystemTime};
12
13use nibkeep_base::{EntityId, Hash, SpaceId};
14use nibkeep_store::{PlaceCheck, SealedCheck, blobs_starting_with, hash_file};
15
16use super::Library;
17use crate::{NodeError, Records};
18
19/// A day, in milliseconds.
20const DAY: u64 = 86_400_000;
21
22/// How long a round of checks takes, in which every copy is read once: 4 weeks.
23pub const ROUND_MILLIS: u64 = 28 * DAY;
24
25/// How long a copy counts after its last check: 8 weeks, two rounds.
26pub const COUNTS_FOR_MILLIS: u64 = 56 * DAY;
27
28/// How long a check rests at most before it asks again whether to stop.
29const REST_STEP: Duration = Duration::from_millis(100);
30
31/// How the holder of the sync role paces its checks.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct Pace {
34	/// How long it waits after it takes the role, and after a run that caught up with the
35	/// round, before it looks again whether checks are due.
36	pub wait: Duration,
37	/// How many times as long as reading a file took a check rests after it, so that checks
38	/// take at most a share of the disk's time: 4, a fifth.
39	pub rest: u32,
40	/// How long one run goes on at most, rests included, before it saves where it stands and
41	/// ends, once the file it reads is read; another starts once the rest it owes is over, if
42	/// more is due.
43	pub run_for: Duration,
44}
45
46impl Pace {
47	/// The pace the apps and `nib sync --serve` keep: they look every 5 minutes, rest four
48	/// times as long as they read, and run for a minute at a time.
49	pub const DEFAULT: Self = Self {
50		wait: Duration::from_mins(5),
51		rest: 4,
52		run_for: Duration::from_secs(60),
53	};
54}
55
56impl Default for Pace {
57	fn default() -> Self {
58		Self::DEFAULT
59	}
60}
61
62/// Where a round of checks stands, as the sync records keep it.
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct Round {
65	/// When it began, in milliseconds since 1970.
66	pub began: u64,
67	/// The sealed blobs, in the order of their sealed hashes.
68	pub blobs: Part,
69	/// The plain copies on this device, in the order of their files' IDs.
70	pub plain: Part,
71}
72
73/// Where one kind of copies stands in a round.
74#[derive(Clone, Debug, Default, PartialEq, Eq)]
75pub struct Part {
76	/// How many bytes they took when the round began.
77	pub total: u64,
78	/// How many bytes of them were read since.
79	pub read: u64,
80	/// The last one read: a sealed hash as a multihash, or a file's ID; none before the
81	/// first.
82	pub after: Option<Vec<u8>>,
83	/// Whether every one was read.
84	pub done: bool,
85}
86
87impl Part {
88	/// Whether more of them are due, `elapsed` milliseconds into the round: until as many
89	/// bytes are read as that share of the round's, or every one is read, once the round's
90	/// time is up.
91	fn due(&self, elapsed: u64) -> bool {
92		if self.done {
93			return false;
94		}
95		if elapsed >= ROUND_MILLIS {
96			return true;
97		}
98		let share = u128::from(self.total) * u128::from(elapsed) / u128::from(ROUND_MILLIS);
99		u128::from(self.read) < share
100	}
101}
102
103/// What one run of the regular check did.
104#[derive(Clone, Debug, Default, PartialEq, Eq)]
105pub struct CheckRun {
106	/// How many sealed blobs it read in full.
107	pub blobs: usize,
108	/// How many plain copies it read in full.
109	pub plain: usize,
110	/// How many copies it found damaged: sealed blobs, which it moved aside so that a sync
111	/// brings them again, and originals, which it reports.
112	pub damaged: usize,
113	/// Whether more is due already, as the run ended at its time.
114	pub more: bool,
115	/// How much of its rest after the last file it read the run still owes, as its time
116	/// ended first: the next run waits that long.
117	pub rest: Duration,
118}
119
120/// What checks found damaged in a space, for the person.
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct DamagedCopy {
123	/// The space.
124	pub space: SpaceId,
125	/// The files whose content it holds, if this replica knows them.
126	pub files: Vec<EntityId>,
127	/// When a check last found it damaged, in milliseconds since 1970.
128	pub found: u64,
129	/// What it is, and where it stands.
130	pub copy: Damaged,
131}
132
133/// A copy that checks found damaged.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub enum Damaged {
136	/// A sealed blob, moved aside.
137	Sealed {
138		/// Its sealed hash.
139		sealed: Hash,
140		/// Whether an intact copy is in place again: one that a sync brought, or the copy
141		/// aside, which a later check found intact after all.
142		replaced: bool,
143	},
144	/// A plain copy on this device that holds other content than it should, though its size
145	/// and modification time are those recorded: damaged, or edited within the second its
146	/// time records. NibKeep never writes over it.
147	Plain {
148		/// Its full path.
149		path: String,
150	},
151}
152
153/// Where this replica's checks stand, for the person.
154#[derive(Clone, Debug, Default, PartialEq, Eq)]
155pub struct CheckStatus {
156	/// Whether the replica holds any copy to check: a sealed blob, or a plain copy on this
157	/// device.
158	pub holds: bool,
159	/// The round under way, if one began.
160	pub round: Option<Round>,
161	/// When a check last ran, in milliseconds since 1970, if one did.
162	pub last: Option<u64>,
163	/// What checks found damaged in the last round, and what is damaged still.
164	pub damaged: Vec<DamagedCopy>,
165}
166
167/// A plain copy of a file on this device: an original kept where it was found, or the copy of
168/// a checkout.
169#[derive(Clone, Debug, PartialEq, Eq)]
170pub(crate) struct PlainPlace {
171	/// The file, as the origin or checkout names it.
172	pub(crate) file: EntityId,
173	/// The copy's full path.
174	pub(crate) path: String,
175	/// The content it should hold.
176	pub(crate) content: Hash,
177	/// Whether it is there with the size and modification time recorded, as an unchanged
178	/// copy is.
179	pub(crate) untouched: bool,
180	/// Its size in bytes, as recorded.
181	pub(crate) size: u64,
182	/// The size and modification time found when it was listed, if it was untouched: a check
183	/// reads it only while they stay, so that an edit is not taken for damage.
184	pub(crate) seen: Option<(u64, SystemTime)>,
185}
186
187/// The size and modification time of the file at `path`, if it is one.
188pub(crate) fn seen_at(path: &str) -> Option<(u64, SystemTime)> {
189	let metadata = fs::metadata(path).ok().filter(fs::Metadata::is_file)?;
190	Some((metadata.len(), metadata.modified().ok()?))
191}
192
193/// This device's plain copies of a space's files, with their space's latest checks of them.
194pub(crate) struct PlainState {
195	/// The copies.
196	pub(crate) places: Vec<PlainPlace>,
197	/// The latest check of each copy, by its path and the content it should hold: when, and
198	/// whether it held the content.
199	checks: BTreeMap<(String, Hash), (u64, bool)>,
200}
201
202impl PlainState {
203	/// The unchanged plain copies that the last check did not find damaged, by file and
204	/// content, with when a check last found one of them holding the content, or 0 if none
205	/// did.
206	pub(crate) fn copies(&self) -> BTreeMap<(EntityId, Hash), u64> {
207		let mut copies: BTreeMap<(EntityId, Hash), u64> = BTreeMap::new();
208		for place in self.places.iter().filter(|place| place.untouched) {
209			let checked = match self.checks.get(&(place.path.clone(), place.content)) {
210				Some((_, false)) => continue,
211				Some((checked, true)) => *checked,
212				None => 0,
213			};
214			let latest = copies.entry((place.file, place.content)).or_insert(0);
215			*latest = (*latest).max(checked);
216		}
217		copies
218	}
219
220	/// The unchanged plain copies that the last check found damaged, once each, with when.
221	fn damaged(&self) -> Vec<(&PlainPlace, u64)> {
222		let mut seen = BTreeSet::new();
223		self.places
224			.iter()
225			.filter(|place| place.untouched)
226			.filter_map(
227				|place| match self.checks.get(&(place.path.clone(), place.content)) {
228					Some((checked, false)) if seen.insert((place.path.clone(), place.content)) => {
229						Some((place, *checked))
230					}
231					_ => None,
232				},
233			)
234			.collect()
235	}
236}
237
238/// The sealed blobs of a replica's blob directory in the order of their sealed hashes, read
239/// a directory at a time; a directory that cannot be read is passed over, and read again in
240/// the next round.
241struct SealedWalk<'a> {
242	replica: &'a Path,
243	/// A hash of the algorithm that names the blobs, for its directory.
244	like: Hash,
245	/// The blobs read from the current directory and not yet taken.
246	pending: VecDeque<(Hash, u64)>,
247	/// The first byte of the next directory to read, if any is left.
248	next: Option<u8>,
249	/// The blob after which to start.
250	after: Option<Hash>,
251}
252
253impl<'a> SealedWalk<'a> {
254	fn new(replica: &'a Path, after: Option<Hash>) -> Self {
255		Self {
256			replica,
257			like: Hash::of(b""),
258			pending: VecDeque::new(),
259			next: Some(after.map_or(0, |after| after.digest()[0])),
260			after,
261		}
262	}
263
264	/// The next sealed blob, with its size in bytes, if any is left.
265	fn next(&mut self) -> Option<(Hash, u64)> {
266		loop {
267			if let Some(found) = self.pending.pop_front() {
268				return Some(found);
269			}
270			let byte = self.next?;
271			self.next = byte.checked_add(1);
272			let after = self.after;
273			self.pending = blobs_starting_with(self.replica, &self.like, byte)
274				.unwrap_or_default()
275				.into_iter()
276				.filter(|(sealed, _)| after.is_none_or(|after| *sealed > after))
277				.collect();
278		}
279	}
280}
281
282/// What a run found intact, to save as it ends, for each space.
283#[derive(Default)]
284struct Found {
285	intact: Vec<(Hash, u64)>,
286	places: Vec<PlaceCheck>,
287}
288
289/// Rests until `until`, or until `deadline` or `stop` comes first. Returns how much of the
290/// rest is left: none, unless `deadline` came first.
291fn rest_until(until: Instant, deadline: Instant, stop: &dyn Fn() -> bool) -> Duration {
292	let end = until.min(deadline);
293	while !stop() {
294		let left = end.saturating_duration_since(Instant::now());
295		if left.is_zero() {
296			break;
297		}
298		std::thread::sleep(left.min(REST_STEP));
299	}
300	if stop() {
301		return Duration::ZERO;
302	}
303	until.saturating_duration_since(Instant::now())
304}
305
306/// Checks the plain copies of one file at `now`, those whose size and modification time
307/// are those recorded and stay so while they are read, until `stop` says to stop: notes each
308/// check in `checks` and counts it in `run`. A copy whose hash `known` holds already is not
309/// read again. Returns how many bytes it checked. One that cannot be read now, or changed as
310/// it was read, is read again in the next round.
311fn check_plain(
312	places: &[PlainPlace],
313	(now, stop, known): (u64, &dyn Fn() -> bool, &BTreeMap<String, Hash>),
314	checks: &mut Vec<PlaceCheck>,
315	run: &mut CheckRun,
316) -> u64 {
317	let mut size = 0_u64;
318	for place in places.iter().filter(|place| place.untouched) {
319		let Some(seen) = place.seen else {
320			continue;
321		};
322		if seen_at(&place.path) != Some(seen) {
323			continue;
324		}
325		let hash = match known.get(&place.path) {
326			Some(hash) => *hash,
327			None => match hash_file(Path::new(&place.path), stop) {
328				Ok(Some((hash, _))) => hash,
329				Ok(None) => break,
330				Err(_) => continue,
331			},
332		};
333		if seen_at(&place.path) != Some(seen) {
334			continue;
335		}
336		let held = hash == place.content;
337		run.plain += 1;
338		run.damaged += usize::from(!held);
339		size = size.saturating_add(place.size);
340		checks.push(PlaceCheck {
341			path: place.path.clone(),
342			content: place.content,
343			checked: now,
344			held,
345		});
346	}
347	size
348}
349
350/// How a run goes: the wall clock, its pace, when to stop, and when its time ends.
351struct Running<'a> {
352	wall: &'a dyn Fn() -> u64,
353	pace: Pace,
354	stop: &'a dyn Fn() -> bool,
355	deadline: Instant,
356}
357
358impl Library {
359	/// Runs the regular check of the replica's copies, as the holder of the sync role does
360	/// every few minutes: reads what the round under way says is due, sealed blobs in the
361	/// order of their sealed hashes against their sealed hashes, and this device's unchanged
362	/// plain copies in the order of their files' IDs against their content, each from where
363	/// the last run stopped, resting after each file as `pace` says, for `pace.run_for` at
364	/// most, or until `stop` says to stop. A sealed blob found damaged is moved aside, so
365	/// that the replica no longer holds it, and recorded at once; the run then asks the
366	/// holder to sync with every replica it finds, which brings it again. A plain copy found
367	/// damaged is recorded, and left as it is. As a round begins, the copies kept aside are
368	/// read again, and one found intact after all goes back in place. Where the round
369	/// stands, and what the run found, are saved as it ends, after a failure too
370	/// ([technical design: checking and repair]).
371	///
372	/// [technical design: checking and repair]: ../../../../docs/Technical-design.md#97-checking-and-repair
373	///
374	/// # Errors
375	///
376	/// Returns an error if the records or a space cannot be read, or what the run found
377	/// cannot be saved. A copy that cannot be read is no error: it is read again in the next
378	/// round.
379	pub fn check_copies(
380		&mut self,
381		records: &Records,
382		wall: &dyn Fn() -> u64,
383		pace: Pace,
384		stop: &dyn Fn() -> bool,
385	) -> Result<CheckRun, NodeError> {
386		let running = Running {
387			wall,
388			pace,
389			stop,
390			deadline: Instant::now() + pace.run_for,
391		};
392		let mut round = match records.round()? {
393			Some(round) => round,
394			None => self.new_round(wall())?,
395		};
396		self.note_aside(wall());
397		let mut found: BTreeMap<SpaceId, Found> = BTreeMap::new();
398		let mut run = CheckRun::default();
399		let checked = self.check_due(&mut round, &running, &mut found, &mut run);
400		let mut saved = Ok(());
401		for (space, found) in found {
402			if let Some(open) = self.spaces.get_mut(&space) {
403				let recorded = open
404					.stored
405					.record_checks(found.intact, Vec::new(), found.places);
406				saved = saved.and(recorded.map_err(NodeError::from));
407			}
408		}
409		let now = wall();
410		records.save_round(&round, now)?;
411		if run.damaged > 0 {
412			records.ask(None, now)?;
413		}
414		checked.and(saved)?;
415		Ok(run)
416	}
417
418	/// Reads what the round says is due, as [`Library::check_copies`] says, noting what it
419	/// finds intact in `found` and counting it in `run`.
420	fn check_due(
421		&mut self,
422		round: &mut Round,
423		running: &Running<'_>,
424		found: &mut BTreeMap<SpaceId, Found>,
425		run: &mut CheckRun,
426	) -> Result<(), NodeError> {
427		let directory = self.directory().to_path_buf();
428		let mut sealed_walk = SealedWalk::new(
429			&directory,
430			round
431				.blobs
432				.after
433				.as_deref()
434				.and_then(|after| Hash::from_multihash(after).ok()),
435		);
436		let mut plain: Option<VecDeque<(EntityId, SpaceId, Vec<PlainPlace>)>> = None;
437		let stop = running.stop;
438		loop {
439			if stop() {
440				return Ok(());
441			}
442			if !run.rest.is_zero() || Instant::now() >= running.deadline {
443				run.more = true;
444				return Ok(());
445			}
446			let now = (running.wall)();
447			let elapsed = now.saturating_sub(round.began);
448			let began = Instant::now();
449			if round.blobs.due(elapsed) {
450				let Some((sealed, size)) = sealed_walk.next() else {
451					round.blobs.done = true;
452					continue;
453				};
454				match self.check_one_blob(&sealed, now, stop, found)? {
455					Some(damaged) => {
456						run.blobs += 1;
457						run.damaged += usize::from(damaged);
458					}
459					None if stop() => return Ok(()),
460					None => {}
461				}
462				round.blobs.after = Some(sealed.to_multihash());
463				round.blobs.read = round.blobs.read.saturating_add(size);
464			} else if round.plain.due(elapsed) {
465				if plain.is_none() {
466					let after = round
467						.plain
468						.after
469						.as_deref()
470						.and_then(|after| <[u8; 16]>::try_from(after).ok())
471						.map(EntityId::from_bytes);
472					plain = Some(
473						self.plain_by_file()?
474							.into_iter()
475							.filter(|(file, _, _)| after.is_none_or(|after| *file > after))
476							.collect(),
477					);
478				}
479				let Some((file, space, places)) = plain.as_mut().and_then(VecDeque::pop_front)
480				else {
481					round.plain.done = true;
482					continue;
483				};
484				let checks = &mut found.entry(space).or_default().places;
485				let size = check_plain(&places, (now, stop, &BTreeMap::new()), checks, run);
486				if stop() {
487					return Ok(());
488				}
489				round.plain.after = Some(file.as_bytes().to_vec());
490				round.plain.read = round.plain.read.saturating_add(size);
491			} else {
492				if round.blobs.done && round.plain.done {
493					self.recheck_aside(now, stop, found);
494					*round = self.new_round(now)?;
495				}
496				return Ok(());
497			}
498			let owed = began.elapsed().saturating_mul(running.pace.rest);
499			run.rest = rest_until(Instant::now() + owed, running.deadline, stop);
500		}
501	}
502
503	/// Checks one sealed blob of the replica's blob directory against its sealed hash, for
504	/// each space that keeps a key for it. One found intact is noted in `found`; one found
505	/// damaged is moved aside, and recorded at once in each of those spaces, so that nothing
506	/// that fails later in the run loses the record. Returns whether it was damaged, or
507	/// `None` if it was not read or moved: no space keeps a key for it, it went meanwhile, it
508	/// could not be read or moved, or `stop` said to stop.
509	fn check_one_blob(
510		&mut self,
511		sealed: &Hash,
512		now: u64,
513		stop: &dyn Fn() -> bool,
514		found: &mut BTreeMap<SpaceId, Found>,
515	) -> Result<Option<bool>, NodeError> {
516		let keyed = self.keeping(sealed);
517		let Some(first) = keyed.first().copied() else {
518			return Ok(None);
519		};
520		let stored = &self.space(first)?.stored;
521		match stored.check_sealed_blob(sealed, stop) {
522			Ok(SealedCheck::Intact(_)) => {
523				for space in keyed {
524					found.entry(space).or_default().intact.push((*sealed, now));
525				}
526				Ok(Some(false))
527			}
528			Ok(SealedCheck::Damaged) => {
529				if !stored.set_aside_blob(sealed).unwrap_or(false) {
530					return Ok(None);
531				}
532				// One not recorded now is recorded at the next run (Library::note_aside).
533				for space in keyed {
534					if let Some(open) = self.spaces.get_mut(&space) {
535						let _ =
536							open.stored
537								.record_checks(Vec::new(), vec![(*sealed, now)], Vec::new());
538					}
539				}
540				Ok(Some(true))
541			}
542			Ok(SealedCheck::Gone | SealedCheck::Stopped) | Err(_) => Ok(None),
543		}
544	}
545
546	/// The spaces of the library that keep a key for a sealed blob.
547	fn keeping(&self, sealed: &Hash) -> Vec<SpaceId> {
548		self.spaces
549			.iter()
550			.filter(|(_, open)| !open.stored.log().wrapped_blob_keys_of(sealed).is_empty())
551			.map(|(id, _)| *id)
552			.collect()
553	}
554
555	/// Records, at `now`, the copies kept aside that no space recorded as damaged, in each
556	/// space that keeps a key for them, as when a crash or a failure came between moving one
557	/// and recording it. One that cannot be recorded now is recorded next time.
558	pub(crate) fn note_aside(&mut self, now: u64) {
559		for open in self.spaces.values_mut() {
560			let Ok(recorded) = open.stored.damaged_blobs() else {
561				continue;
562			};
563			let missing: Vec<(Hash, u64)> = open
564				.stored
565				.aside_blobs()
566				.into_iter()
567				.filter(|sealed| !recorded.contains_key(sealed))
568				.map(|sealed| (sealed, now))
569				.collect();
570			let _ = open.stored.record_checks(Vec::new(), missing, Vec::new());
571		}
572	}
573
574	/// Reads the copies kept aside again, and puts each that is intact after all back in
575	/// place, as when the damage was a bad read, noting it in `found` as checked at `now`.
576	fn recheck_aside(
577		&self,
578		now: u64,
579		stop: &dyn Fn() -> bool,
580		found: &mut BTreeMap<SpaceId, Found>,
581	) {
582		let mut aside = BTreeSet::new();
583		for open in self.spaces.values() {
584			aside.extend(open.stored.aside_blobs());
585		}
586		for sealed in aside {
587			let keyed = self.keeping(&sealed);
588			let Some(open) = keyed.first().and_then(|first| self.spaces.get(first)) else {
589				continue;
590			};
591			if let Ok(SealedCheck::Intact(_)) = open.stored.recheck_aside_blob(&sealed, stop) {
592				for space in keyed {
593					found.entry(space).or_default().intact.push((sealed, now));
594				}
595			}
596		}
597	}
598
599	/// A new round of checks, beginning at `now`, with how many bytes each kind of copies
600	/// takes now.
601	fn new_round(&self, now: u64) -> Result<Round, NodeError> {
602		let mut blobs = 0_u64;
603		let mut walk = SealedWalk::new(self.directory(), None);
604		while let Some((_, size)) = walk.next() {
605			blobs = blobs.saturating_add(size);
606		}
607		let plain = self
608			.plain_by_file()?
609			.iter()
610			.flat_map(|(_, _, places)| places.iter().filter(|place| place.untouched))
611			.fold(0_u64, |total, place| total.saturating_add(place.size));
612		Ok(Round {
613			began: now,
614			blobs: Part {
615				total: blobs,
616				..Part::default()
617			},
618			plain: Part {
619				total: plain,
620				..Part::default()
621			},
622		})
623	}
624
625	/// Records that the plain copy at `path` held `content` at `wall_millis`, as it was just
626	/// read whole, where it was found or written: its first check. One that cannot be
627	/// recorded waits for the regular check.
628	pub(crate) fn record_first_check(
629		&mut self,
630		space: SpaceId,
631		(path, content): (String, Hash),
632		wall_millis: u64,
633	) {
634		if let Some(open) = self.spaces.get_mut(&space) {
635			let _ = open.stored.record_checks(
636				Vec::new(),
637				Vec::new(),
638				vec![PlaceCheck {
639					path,
640					content,
641					checked: wall_millis,
642					held: true,
643				}],
644			);
645		}
646	}
647
648	/// Checks the unchanged plain copies of a space on this device at `wall_millis`, as
649	/// `nib verify` does: each is read in full, but those whose hashes `known` holds already,
650	/// and the checks are recorded.
651	///
652	/// # Errors
653	///
654	/// Returns an error if the space cannot be read, or the checks cannot be saved.
655	pub(crate) fn check_plain_now(
656		&mut self,
657		space: SpaceId,
658		known: &BTreeMap<String, Hash>,
659		wall_millis: u64,
660	) -> Result<(), NodeError> {
661		let places = self.plain_places_here(space)?;
662		let mut checks = Vec::new();
663		let mut run = CheckRun::default();
664		check_plain(
665			&places,
666			(wall_millis, &|| false, known),
667			&mut checks,
668			&mut run,
669		);
670		let open = self
671			.spaces
672			.get_mut(&space)
673			.ok_or(NodeError::NoSpace(space))?;
674		Ok(open.stored.record_checks(Vec::new(), Vec::new(), checks)?)
675	}
676
677	/// This device's plain copies of every space's files, by file, in the order of the
678	/// files' IDs.
679	fn plain_by_file(&self) -> Result<Vec<(EntityId, SpaceId, Vec<PlainPlace>)>, NodeError> {
680		let mut by_file: BTreeMap<(EntityId, SpaceId), Vec<PlainPlace>> = BTreeMap::new();
681		for &space in self.spaces.keys() {
682			for place in self.plain_places_here(space)? {
683				by_file.entry((place.file, space)).or_default().push(place);
684			}
685		}
686		Ok(by_file
687			.into_iter()
688			.map(|((file, space), places)| (file, space, places))
689			.collect())
690	}
691
692	/// This device's plain copies of a space's files: the originals kept where they were
693	/// found, and the copies of checkouts, each with the content it should hold.
694	///
695	/// # Errors
696	///
697	/// Returns an error if the space cannot be read.
698	pub(crate) fn plain_places_here(&self, space: SpaceId) -> Result<Vec<PlainPlace>, NodeError> {
699		let mut places = self.origin_places_here(space)?;
700		places.extend(self.checkout_places_here(space)?);
701		Ok(places)
702	}
703
704	/// This device's plain copies of a space's files, with the space's latest checks of them.
705	///
706	/// # Errors
707	///
708	/// Returns an error if the space cannot be read.
709	pub(crate) fn plain_state(&self, space: SpaceId) -> Result<PlainState, NodeError> {
710		let checks = self
711			.space(space)?
712			.stored
713			.place_checks()?
714			.into_iter()
715			.map(|check| ((check.path, check.content), (check.checked, check.held)))
716			.collect();
717		Ok(PlainState {
718			places: self.plain_places_here(space)?,
719			checks,
720		})
721	}
722
723	/// How many of this replica's copies of a space's files its checks found damaged in the
724	/// 4 weeks before `wall_millis`, those damaged still included, and how many are damaged
725	/// still, as its account says; `plain` is its plain copies there.
726	///
727	/// # Errors
728	///
729	/// Returns an error if the space cannot be read.
730	pub(crate) fn own_damage(
731		&self,
732		space: SpaceId,
733		plain: &PlainState,
734		wall_millis: u64,
735	) -> Result<(u64, u64), NodeError> {
736		let since = wall_millis.saturating_sub(ROUND_MILLIS);
737		let mut recent = 0_u64;
738		let mut still = 0_u64;
739		for copy in self.damaged_in(space, plain, (wall_millis, false))? {
740			let unrepaired = match copy.copy {
741				Damaged::Sealed { replaced, .. } => !replaced,
742				Damaged::Plain { .. } => true,
743			};
744			recent += u64::from(copy.found >= since || unrepaired);
745			still += u64::from(unrepaired);
746		}
747		Ok((recent, still))
748	}
749
750	/// What checks found damaged in a space and is still of interest at `wall`: sealed blobs
751	/// whose key the space keeps, found damaged in the 4 weeks before or not yet replaced,
752	/// and plain copies on this device, of `plain`, unchanged, that do not hold their
753	/// content; with the files each holds the content of, where `named` asks for them.
754	fn damaged_in(
755		&self,
756		space: SpaceId,
757		plain: &PlainState,
758		(wall, named): (u64, bool),
759	) -> Result<Vec<DamagedCopy>, NodeError> {
760		let open = self.space(space)?;
761		let log = open.stored.log();
762		let mut damaged = Vec::new();
763		for (sealed, found) in open.stored.damaged_blobs()? {
764			if log.wrapped_blob_keys_of(&sealed).is_empty() {
765				continue;
766			}
767			let replaced = open.stored.holds_sealed(&sealed);
768			if replaced && found < wall.saturating_sub(ROUND_MILLIS) {
769				continue;
770			}
771			let files = match log.content_of_sealed(&sealed).filter(|_| named) {
772				Some(content) => self.files_with(space, &content)?,
773				None => Vec::new(),
774			};
775			damaged.push(DamagedCopy {
776				space,
777				files,
778				found,
779				copy: Damaged::Sealed { sealed, replaced },
780			});
781		}
782		for (place, checked) in plain.damaged() {
783			damaged.push(DamagedCopy {
784				space,
785				files: vec![place.file],
786				found: checked,
787				copy: Damaged::Plain {
788					path: place.path.clone(),
789				},
790			});
791		}
792		Ok(damaged)
793	}
794
795	/// The files of a space whose current content is `content`, deleted ones aside.
796	fn files_with(&self, space: SpaceId, content: &Hash) -> Result<Vec<EntityId>, NodeError> {
797		let open = self.space(space)?;
798		let state = open.stored.log().state();
799		let mut files = Vec::new();
800		for entity in open
801			.stored
802			.find(&nibkeep_std::CONTENT, &nibkeep_model::Value::Blob(*content))?
803		{
804			let entity = state.canonical(entity)?;
805			if !state.is_deleted(entity)?
806				&& state.types(entity)?.contains(&nibkeep_std::FILE)
807				&& !files.contains(&entity)
808			{
809				files.push(entity);
810			}
811		}
812		Ok(files)
813	}
814
815	/// Where this replica's checks stand at `wall_millis`: the round under way, as `records`
816	/// keep it, and what checks found damaged in each space, the personal space first: what
817	/// is damaged still, and what came again in the 4 weeks before.
818	///
819	/// # Errors
820	///
821	/// Returns an error if the records or a space cannot be read.
822	pub fn check_status(
823		&self,
824		records: &Records,
825		wall_millis: u64,
826	) -> Result<CheckStatus, NodeError> {
827		let (round, last) = match records.round_with_last()? {
828			Some((round, last)) => (Some(round), last),
829			None => (None, None),
830		};
831		let mut ids: Vec<SpaceId> = self.spaces.keys().copied().collect();
832		ids.sort_by_key(|&id| (id != self.info.personal, id));
833		let mut damaged = Vec::new();
834		let mut holds = SealedWalk::new(self.directory(), None).next().is_some();
835		for id in ids {
836			let plain = self.plain_state(id)?;
837			holds |= !plain.places.is_empty();
838			damaged.extend(self.damaged_in(id, &plain, (wall_millis, true))?);
839		}
840		Ok(CheckStatus {
841			holds,
842			round,
843			last,
844			damaged,
845		})
846	}
847}
848
849#[cfg(test)]
850mod tests {
851	use super::*;
852
853	#[test]
854	fn a_plain_copy_that_changed_since_it_was_listed_is_not_read_as_damaged() {
855		let directory = nibkeep_testkit::empty_directory(
856			std::env::temp_dir(),
857			&format!("nibkeep-checking-edited-{}", std::process::id()),
858		);
859		let path = directory.join("letter.txt");
860		fs::write(&path, b"Dear Ada").expect("writes");
861		let text = path.to_string_lossy().into_owned();
862		let listed = PlainPlace {
863			file: EntityId::from_bytes([1; 16]),
864			path: text.clone(),
865			content: Hash::of(b"Dear Ada"),
866			untouched: true,
867			size: 8,
868			seen: seen_at(&text),
869		};
870		// Edited after it was listed: another size, so not read.
871		fs::write(&path, b"Dear Ada,\n").expect("edits");
872		let mut checks = Vec::new();
873		let mut run = CheckRun::default();
874		check_plain(
875			std::slice::from_ref(&listed),
876			(5, &|| false, &BTreeMap::new()),
877			&mut checks,
878			&mut run,
879		);
880		assert_eq!(checks, Vec::<PlaceCheck>::new());
881		assert_eq!(run, CheckRun::default());
882		// Listed as it is now, with other content than recorded: damage.
883		let relisted = PlainPlace {
884			seen: seen_at(&text),
885			..listed.clone()
886		};
887		check_plain(
888			std::slice::from_ref(&relisted),
889			(5, &|| false, &BTreeMap::new()),
890			&mut checks,
891			&mut run,
892		);
893		assert_eq!((run.plain, run.damaged), (1, 1));
894		assert!(!checks[0].held);
895		let _ = fs::remove_dir_all(directory);
896	}
897}