1use 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
19const DAY: u64 = 86_400_000;
21
22pub const ROUND_MILLIS: u64 = 28 * DAY;
24
25pub const COUNTS_FOR_MILLIS: u64 = 56 * DAY;
27
28const REST_STEP: Duration = Duration::from_millis(100);
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct Pace {
34 pub wait: Duration,
37 pub rest: u32,
40 pub run_for: Duration,
44}
45
46impl Pace {
47 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#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct Round {
65 pub began: u64,
67 pub blobs: Part,
69 pub plain: Part,
71}
72
73#[derive(Clone, Debug, Default, PartialEq, Eq)]
75pub struct Part {
76 pub total: u64,
78 pub read: u64,
80 pub after: Option<Vec<u8>>,
83 pub done: bool,
85}
86
87impl Part {
88 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
105pub struct CheckRun {
106 pub blobs: usize,
108 pub plain: usize,
110 pub damaged: usize,
113 pub more: bool,
115 pub rest: Duration,
118}
119
120#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct DamagedCopy {
123 pub space: SpaceId,
125 pub files: Vec<EntityId>,
127 pub found: u64,
129 pub copy: Damaged,
131}
132
133#[derive(Clone, Debug, PartialEq, Eq)]
135pub enum Damaged {
136 Sealed {
138 sealed: Hash,
140 replaced: bool,
143 },
144 Plain {
148 path: String,
150 },
151}
152
153#[derive(Clone, Debug, Default, PartialEq, Eq)]
155pub struct CheckStatus {
156 pub holds: bool,
159 pub round: Option<Round>,
161 pub last: Option<u64>,
163 pub damaged: Vec<DamagedCopy>,
165}
166
167#[derive(Clone, Debug, PartialEq, Eq)]
170pub(crate) struct PlainPlace {
171 pub(crate) file: EntityId,
173 pub(crate) path: String,
175 pub(crate) content: Hash,
177 pub(crate) untouched: bool,
180 pub(crate) size: u64,
182 pub(crate) seen: Option<(u64, SystemTime)>,
185}
186
187pub(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
193pub(crate) struct PlainState {
195 pub(crate) places: Vec<PlainPlace>,
197 checks: BTreeMap<(String, Hash), (u64, bool)>,
200}
201
202impl PlainState {
203 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 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
238struct SealedWalk<'a> {
242 replica: &'a Path,
243 like: Hash,
245 pending: VecDeque<(Hash, u64)>,
247 next: Option<u8>,
249 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 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#[derive(Default)]
284struct Found {
285 intact: Vec<(Hash, u64)>,
286 places: Vec<PlaceCheck>,
287}
288
289fn 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
306fn 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
350struct 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}