use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fs;
use std::path::Path;
use std::time::{Duration, Instant, SystemTime};
use nibkeep_base::{EntityId, Hash, SpaceId};
use nibkeep_store::{PlaceCheck, SealedCheck, blobs_starting_with, hash_file};
use super::Library;
use crate::{NodeError, Records};
const DAY: u64 = 86_400_000;
pub const ROUND_MILLIS: u64 = 28 * DAY;
pub const COUNTS_FOR_MILLIS: u64 = 56 * DAY;
const REST_STEP: Duration = Duration::from_millis(100);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Pace {
pub wait: Duration,
pub rest: u32,
pub run_for: Duration,
}
impl Pace {
pub const DEFAULT: Self = Self {
wait: Duration::from_mins(5),
rest: 4,
run_for: Duration::from_secs(60),
};
}
impl Default for Pace {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Round {
pub began: u64,
pub blobs: Part,
pub plain: Part,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Part {
pub total: u64,
pub read: u64,
pub after: Option<Vec<u8>>,
pub done: bool,
}
impl Part {
fn due(&self, elapsed: u64) -> bool {
if self.done {
return false;
}
if elapsed >= ROUND_MILLIS {
return true;
}
let share = u128::from(self.total) * u128::from(elapsed) / u128::from(ROUND_MILLIS);
u128::from(self.read) < share
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CheckRun {
pub blobs: usize,
pub plain: usize,
pub damaged: usize,
pub more: bool,
pub rest: Duration,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DamagedCopy {
pub space: SpaceId,
pub files: Vec<EntityId>,
pub found: u64,
pub copy: Damaged,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Damaged {
Sealed {
sealed: Hash,
replaced: bool,
},
Plain {
path: String,
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CheckStatus {
pub holds: bool,
pub round: Option<Round>,
pub last: Option<u64>,
pub damaged: Vec<DamagedCopy>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PlainPlace {
pub(crate) file: EntityId,
pub(crate) path: String,
pub(crate) content: Hash,
pub(crate) untouched: bool,
pub(crate) size: u64,
pub(crate) seen: Option<(u64, SystemTime)>,
}
pub(crate) fn seen_at(path: &str) -> Option<(u64, SystemTime)> {
let metadata = fs::metadata(path).ok().filter(fs::Metadata::is_file)?;
Some((metadata.len(), metadata.modified().ok()?))
}
pub(crate) struct PlainState {
pub(crate) places: Vec<PlainPlace>,
checks: BTreeMap<(String, Hash), (u64, bool)>,
}
impl PlainState {
pub(crate) fn copies(&self) -> BTreeMap<(EntityId, Hash), u64> {
let mut copies: BTreeMap<(EntityId, Hash), u64> = BTreeMap::new();
for place in self.places.iter().filter(|place| place.untouched) {
let checked = match self.checks.get(&(place.path.clone(), place.content)) {
Some((_, false)) => continue,
Some((checked, true)) => *checked,
None => 0,
};
let latest = copies.entry((place.file, place.content)).or_insert(0);
*latest = (*latest).max(checked);
}
copies
}
fn damaged(&self) -> Vec<(&PlainPlace, u64)> {
let mut seen = BTreeSet::new();
self.places
.iter()
.filter(|place| place.untouched)
.filter_map(
|place| match self.checks.get(&(place.path.clone(), place.content)) {
Some((checked, false)) if seen.insert((place.path.clone(), place.content)) => {
Some((place, *checked))
}
_ => None,
},
)
.collect()
}
}
struct SealedWalk<'a> {
replica: &'a Path,
like: Hash,
pending: VecDeque<(Hash, u64)>,
next: Option<u8>,
after: Option<Hash>,
}
impl<'a> SealedWalk<'a> {
fn new(replica: &'a Path, after: Option<Hash>) -> Self {
Self {
replica,
like: Hash::of(b""),
pending: VecDeque::new(),
next: Some(after.map_or(0, |after| after.digest()[0])),
after,
}
}
fn next(&mut self) -> Option<(Hash, u64)> {
loop {
if let Some(found) = self.pending.pop_front() {
return Some(found);
}
let byte = self.next?;
self.next = byte.checked_add(1);
let after = self.after;
self.pending = blobs_starting_with(self.replica, &self.like, byte)
.unwrap_or_default()
.into_iter()
.filter(|(sealed, _)| after.is_none_or(|after| *sealed > after))
.collect();
}
}
}
#[derive(Default)]
struct Found {
intact: Vec<(Hash, u64)>,
places: Vec<PlaceCheck>,
}
fn rest_until(until: Instant, deadline: Instant, stop: &dyn Fn() -> bool) -> Duration {
let end = until.min(deadline);
while !stop() {
let left = end.saturating_duration_since(Instant::now());
if left.is_zero() {
break;
}
std::thread::sleep(left.min(REST_STEP));
}
if stop() {
return Duration::ZERO;
}
until.saturating_duration_since(Instant::now())
}
fn check_plain(
places: &[PlainPlace],
(now, stop, known): (u64, &dyn Fn() -> bool, &BTreeMap<String, Hash>),
checks: &mut Vec<PlaceCheck>,
run: &mut CheckRun,
) -> u64 {
let mut size = 0_u64;
for place in places.iter().filter(|place| place.untouched) {
let Some(seen) = place.seen else {
continue;
};
if seen_at(&place.path) != Some(seen) {
continue;
}
let hash = match known.get(&place.path) {
Some(hash) => *hash,
None => match hash_file(Path::new(&place.path), stop) {
Ok(Some((hash, _))) => hash,
Ok(None) => break,
Err(_) => continue,
},
};
if seen_at(&place.path) != Some(seen) {
continue;
}
let held = hash == place.content;
run.plain += 1;
run.damaged += usize::from(!held);
size = size.saturating_add(place.size);
checks.push(PlaceCheck {
path: place.path.clone(),
content: place.content,
checked: now,
held,
});
}
size
}
struct Running<'a> {
wall: &'a dyn Fn() -> u64,
pace: Pace,
stop: &'a dyn Fn() -> bool,
deadline: Instant,
}
impl Library {
pub fn check_copies(
&mut self,
records: &Records,
wall: &dyn Fn() -> u64,
pace: Pace,
stop: &dyn Fn() -> bool,
) -> Result<CheckRun, NodeError> {
let running = Running {
wall,
pace,
stop,
deadline: Instant::now() + pace.run_for,
};
let mut round = match records.round()? {
Some(round) => round,
None => self.new_round(wall())?,
};
self.note_aside(wall());
let mut found: BTreeMap<SpaceId, Found> = BTreeMap::new();
let mut run = CheckRun::default();
let checked = self.check_due(&mut round, &running, &mut found, &mut run);
let mut saved = Ok(());
for (space, found) in found {
if let Some(open) = self.spaces.get_mut(&space) {
let recorded = open
.stored
.record_checks(found.intact, Vec::new(), found.places);
saved = saved.and(recorded.map_err(NodeError::from));
}
}
let now = wall();
records.save_round(&round, now)?;
if run.damaged > 0 {
records.ask(None, now)?;
}
checked.and(saved)?;
Ok(run)
}
fn check_due(
&mut self,
round: &mut Round,
running: &Running<'_>,
found: &mut BTreeMap<SpaceId, Found>,
run: &mut CheckRun,
) -> Result<(), NodeError> {
let directory = self.directory().to_path_buf();
let mut sealed_walk = SealedWalk::new(
&directory,
round
.blobs
.after
.as_deref()
.and_then(|after| Hash::from_multihash(after).ok()),
);
let mut plain: Option<VecDeque<(EntityId, SpaceId, Vec<PlainPlace>)>> = None;
let stop = running.stop;
loop {
if stop() {
return Ok(());
}
if !run.rest.is_zero() || Instant::now() >= running.deadline {
run.more = true;
return Ok(());
}
let now = (running.wall)();
let elapsed = now.saturating_sub(round.began);
let began = Instant::now();
if round.blobs.due(elapsed) {
let Some((sealed, size)) = sealed_walk.next() else {
round.blobs.done = true;
continue;
};
match self.check_one_blob(&sealed, now, stop, found)? {
Some(damaged) => {
run.blobs += 1;
run.damaged += usize::from(damaged);
}
None if stop() => return Ok(()),
None => {}
}
round.blobs.after = Some(sealed.to_multihash());
round.blobs.read = round.blobs.read.saturating_add(size);
} else if round.plain.due(elapsed) {
if plain.is_none() {
let after = round
.plain
.after
.as_deref()
.and_then(|after| <[u8; 16]>::try_from(after).ok())
.map(EntityId::from_bytes);
plain = Some(
self.plain_by_file()?
.into_iter()
.filter(|(file, _, _)| after.is_none_or(|after| *file > after))
.collect(),
);
}
let Some((file, space, places)) = plain.as_mut().and_then(VecDeque::pop_front)
else {
round.plain.done = true;
continue;
};
let checks = &mut found.entry(space).or_default().places;
let size = check_plain(&places, (now, stop, &BTreeMap::new()), checks, run);
if stop() {
return Ok(());
}
round.plain.after = Some(file.as_bytes().to_vec());
round.plain.read = round.plain.read.saturating_add(size);
} else {
if round.blobs.done && round.plain.done {
self.recheck_aside(now, stop, found);
*round = self.new_round(now)?;
}
return Ok(());
}
let owed = began.elapsed().saturating_mul(running.pace.rest);
run.rest = rest_until(Instant::now() + owed, running.deadline, stop);
}
}
fn check_one_blob(
&mut self,
sealed: &Hash,
now: u64,
stop: &dyn Fn() -> bool,
found: &mut BTreeMap<SpaceId, Found>,
) -> Result<Option<bool>, NodeError> {
let keyed = self.keeping(sealed);
let Some(first) = keyed.first().copied() else {
return Ok(None);
};
let stored = &self.space(first)?.stored;
match stored.check_sealed_blob(sealed, stop) {
Ok(SealedCheck::Intact(_)) => {
for space in keyed {
found.entry(space).or_default().intact.push((*sealed, now));
}
Ok(Some(false))
}
Ok(SealedCheck::Damaged) => {
if !stored.set_aside_blob(sealed).unwrap_or(false) {
return Ok(None);
}
for space in keyed {
if let Some(open) = self.spaces.get_mut(&space) {
let _ =
open.stored
.record_checks(Vec::new(), vec![(*sealed, now)], Vec::new());
}
}
Ok(Some(true))
}
Ok(SealedCheck::Gone | SealedCheck::Stopped) | Err(_) => Ok(None),
}
}
fn keeping(&self, sealed: &Hash) -> Vec<SpaceId> {
self.spaces
.iter()
.filter(|(_, open)| !open.stored.log().wrapped_blob_keys_of(sealed).is_empty())
.map(|(id, _)| *id)
.collect()
}
pub(crate) fn note_aside(&mut self, now: u64) {
for open in self.spaces.values_mut() {
let Ok(recorded) = open.stored.damaged_blobs() else {
continue;
};
let missing: Vec<(Hash, u64)> = open
.stored
.aside_blobs()
.into_iter()
.filter(|sealed| !recorded.contains_key(sealed))
.map(|sealed| (sealed, now))
.collect();
let _ = open.stored.record_checks(Vec::new(), missing, Vec::new());
}
}
fn recheck_aside(
&self,
now: u64,
stop: &dyn Fn() -> bool,
found: &mut BTreeMap<SpaceId, Found>,
) {
let mut aside = BTreeSet::new();
for open in self.spaces.values() {
aside.extend(open.stored.aside_blobs());
}
for sealed in aside {
let keyed = self.keeping(&sealed);
let Some(open) = keyed.first().and_then(|first| self.spaces.get(first)) else {
continue;
};
if let Ok(SealedCheck::Intact(_)) = open.stored.recheck_aside_blob(&sealed, stop) {
for space in keyed {
found.entry(space).or_default().intact.push((sealed, now));
}
}
}
}
fn new_round(&self, now: u64) -> Result<Round, NodeError> {
let mut blobs = 0_u64;
let mut walk = SealedWalk::new(self.directory(), None);
while let Some((_, size)) = walk.next() {
blobs = blobs.saturating_add(size);
}
let plain = self
.plain_by_file()?
.iter()
.flat_map(|(_, _, places)| places.iter().filter(|place| place.untouched))
.fold(0_u64, |total, place| total.saturating_add(place.size));
Ok(Round {
began: now,
blobs: Part {
total: blobs,
..Part::default()
},
plain: Part {
total: plain,
..Part::default()
},
})
}
pub(crate) fn record_first_check(
&mut self,
space: SpaceId,
(path, content): (String, Hash),
wall_millis: u64,
) {
if let Some(open) = self.spaces.get_mut(&space) {
let _ = open.stored.record_checks(
Vec::new(),
Vec::new(),
vec![PlaceCheck {
path,
content,
checked: wall_millis,
held: true,
}],
);
}
}
pub(crate) fn check_plain_now(
&mut self,
space: SpaceId,
known: &BTreeMap<String, Hash>,
wall_millis: u64,
) -> Result<(), NodeError> {
let places = self.plain_places_here(space)?;
let mut checks = Vec::new();
let mut run = CheckRun::default();
check_plain(
&places,
(wall_millis, &|| false, known),
&mut checks,
&mut run,
);
let open = self
.spaces
.get_mut(&space)
.ok_or(NodeError::NoSpace(space))?;
Ok(open.stored.record_checks(Vec::new(), Vec::new(), checks)?)
}
fn plain_by_file(&self) -> Result<Vec<(EntityId, SpaceId, Vec<PlainPlace>)>, NodeError> {
let mut by_file: BTreeMap<(EntityId, SpaceId), Vec<PlainPlace>> = BTreeMap::new();
for &space in self.spaces.keys() {
for place in self.plain_places_here(space)? {
by_file.entry((place.file, space)).or_default().push(place);
}
}
Ok(by_file
.into_iter()
.map(|((file, space), places)| (file, space, places))
.collect())
}
pub(crate) fn plain_places_here(&self, space: SpaceId) -> Result<Vec<PlainPlace>, NodeError> {
let mut places = self.origin_places_here(space)?;
places.extend(self.checkout_places_here(space)?);
Ok(places)
}
pub(crate) fn plain_state(&self, space: SpaceId) -> Result<PlainState, NodeError> {
let checks = self
.space(space)?
.stored
.place_checks()?
.into_iter()
.map(|check| ((check.path, check.content), (check.checked, check.held)))
.collect();
Ok(PlainState {
places: self.plain_places_here(space)?,
checks,
})
}
pub(crate) fn own_damage(
&self,
space: SpaceId,
plain: &PlainState,
wall_millis: u64,
) -> Result<(u64, u64), NodeError> {
let since = wall_millis.saturating_sub(ROUND_MILLIS);
let mut recent = 0_u64;
let mut still = 0_u64;
for copy in self.damaged_in(space, plain, (wall_millis, false))? {
let unrepaired = match copy.copy {
Damaged::Sealed { replaced, .. } => !replaced,
Damaged::Plain { .. } => true,
};
recent += u64::from(copy.found >= since || unrepaired);
still += u64::from(unrepaired);
}
Ok((recent, still))
}
fn damaged_in(
&self,
space: SpaceId,
plain: &PlainState,
(wall, named): (u64, bool),
) -> Result<Vec<DamagedCopy>, NodeError> {
let open = self.space(space)?;
let log = open.stored.log();
let mut damaged = Vec::new();
for (sealed, found) in open.stored.damaged_blobs()? {
if log.wrapped_blob_keys_of(&sealed).is_empty() {
continue;
}
let replaced = open.stored.holds_sealed(&sealed);
if replaced && found < wall.saturating_sub(ROUND_MILLIS) {
continue;
}
let files = match log.content_of_sealed(&sealed).filter(|_| named) {
Some(content) => self.files_with(space, &content)?,
None => Vec::new(),
};
damaged.push(DamagedCopy {
space,
files,
found,
copy: Damaged::Sealed { sealed, replaced },
});
}
for (place, checked) in plain.damaged() {
damaged.push(DamagedCopy {
space,
files: vec![place.file],
found: checked,
copy: Damaged::Plain {
path: place.path.clone(),
},
});
}
Ok(damaged)
}
fn files_with(&self, space: SpaceId, content: &Hash) -> Result<Vec<EntityId>, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let mut files = Vec::new();
for entity in open
.stored
.find(&nibkeep_std::CONTENT, &nibkeep_model::Value::Blob(*content))?
{
let entity = state.canonical(entity)?;
if !state.is_deleted(entity)?
&& state.types(entity)?.contains(&nibkeep_std::FILE)
&& !files.contains(&entity)
{
files.push(entity);
}
}
Ok(files)
}
pub fn check_status(
&self,
records: &Records,
wall_millis: u64,
) -> Result<CheckStatus, NodeError> {
let (round, last) = match records.round_with_last()? {
Some((round, last)) => (Some(round), last),
None => (None, None),
};
let mut ids: Vec<SpaceId> = self.spaces.keys().copied().collect();
ids.sort_by_key(|&id| (id != self.info.personal, id));
let mut damaged = Vec::new();
let mut holds = SealedWalk::new(self.directory(), None).next().is_some();
for id in ids {
let plain = self.plain_state(id)?;
holds |= !plain.places.is_empty();
damaged.extend(self.damaged_in(id, &plain, (wall_millis, true))?);
}
Ok(CheckStatus {
holds,
round,
last,
damaged,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_plain_copy_that_changed_since_it_was_listed_is_not_read_as_damaged() {
let directory = nibkeep_testkit::empty_directory(
std::env::temp_dir(),
&format!("nibkeep-checking-edited-{}", std::process::id()),
);
let path = directory.join("letter.txt");
fs::write(&path, b"Dear Ada").expect("writes");
let text = path.to_string_lossy().into_owned();
let listed = PlainPlace {
file: EntityId::from_bytes([1; 16]),
path: text.clone(),
content: Hash::of(b"Dear Ada"),
untouched: true,
size: 8,
seen: seen_at(&text),
};
fs::write(&path, b"Dear Ada,\n").expect("edits");
let mut checks = Vec::new();
let mut run = CheckRun::default();
check_plain(
std::slice::from_ref(&listed),
(5, &|| false, &BTreeMap::new()),
&mut checks,
&mut run,
);
assert_eq!(checks, Vec::<PlaceCheck>::new());
assert_eq!(run, CheckRun::default());
let relisted = PlainPlace {
seen: seen_at(&text),
..listed.clone()
};
check_plain(
std::slice::from_ref(&relisted),
(5, &|| false, &BTreeMap::new()),
&mut checks,
&mut run,
);
assert_eq!((run.plain, run.damaged), (1, 1));
assert!(!checks[0].held);
let _ = fs::remove_dir_all(directory);
}
}