use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use super::DIR;
use crate::sync::lock;
use crate::{Error, Result};
pub(crate) const TTL: Duration = Duration::from_secs(5);
const GATHER: Duration = Duration::from_secs(1);
const STANDING: Duration = Duration::from_secs(3);
const HOLDERS: &str = "witness";
pub(crate) struct Ask<'a> {
pub(crate) file: &'a str,
pub(crate) node: &'a str,
pub(crate) address: &'a str,
pub(crate) epoch: u64,
pub(crate) position: u64,
pub(crate) holding: bool,
pub(crate) synchronous: &'a [String],
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Holder {
pub(crate) node: String,
pub(crate) address: String,
pub(crate) epoch: u64,
}
#[derive(Clone, Default, PartialEq, Eq)]
struct Kept {
holder: Holder,
synchronous: Vec<String>,
}
#[derive(Clone)]
struct Lease {
kept: Kept,
expires: Instant,
standing: HashMap<String, Standing>,
claimant: Option<Claimant>,
}
#[derive(Clone)]
struct Claimant {
epoch: u64,
asked: Instant,
}
#[derive(Clone)]
struct Standing {
address: String,
position: u64,
seen: Instant,
}
pub(crate) struct Witness {
leases: Mutex<HashMap<String, Lease>>,
kept: Mutex<HashMap<String, Kept>>,
path: PathBuf,
started: Instant,
cut: Mutex<HashSet<String>>,
}
impl Witness {
pub(crate) fn open(dir: &Path) -> Result<Witness> {
let path = dir.join(DIR).join(HOLDERS);
let kept = match std::fs::read_to_string(&path) {
Ok(kept) => kept.lines().filter_map(read_holder).collect(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => HashMap::new(),
Err(error) => return Err(Error::io(path.display().to_string(), error)),
};
Ok(Witness {
leases: Mutex::default(),
kept: Mutex::new(kept),
path,
started: Instant::now(),
cut: Mutex::default(),
})
}
pub(crate) fn ask(&self, ask: &Ask<'_>) -> Result<Option<Holder>> {
if lock(&self.cut).contains(ask.node) {
return Ok(None);
}
let now = Instant::now();
let mut leases = lock(&self.leases);
let mut lease = match leases.get(ask.file) {
Some(lease) => lease.clone(),
None => Lease {
kept: lock(&self.kept).get(ask.file).cloned().unwrap_or_default(),
expires: self.started + TTL,
standing: HashMap::new(),
claimant: None,
},
};
let before = lease.kept.holder.clone();
let changed = if ask.holding { renew(&mut lease, ask, now) } else { stand(&mut lease, ask, now) };
if changed {
self.keep(ask.file, &lease.kept)?;
}
let Holder { node, epoch, .. } = &lease.kept.holder;
if *node != before.node || *epoch != before.epoch {
tracing::info!(
target: "tinystore",
file = ask.file,
holder = %node,
epoch,
"a witness granted a file's lease",
);
}
let holder = lease.kept.holder.clone();
leases.insert(ask.file.to_owned(), lease);
Ok(Some(holder))
}
fn keep(&self, file: &str, lease: &Kept) -> Result<()> {
let mut kept = lock(&self.kept).clone();
kept.insert(file.to_owned(), lease.clone());
let lines: String = kept.iter().map(|(file, kept)| written(file, kept)).collect();
let io = |error| Error::io(self.path.display().to_string(), error);
let parent = self.path.parent().expect("the witness's file lies in log/");
std::fs::create_dir_all(parent).map_err(io)?;
let beside = self.path.with_extension("new");
let mut written = std::fs::File::create(&beside).map_err(io)?;
written.write_all(lines.as_bytes()).and_then(|()| written.sync_all()).map_err(io)?;
drop(written);
std::fs::rename(&beside, &self.path).map_err(io)?;
crate::durable::sync_directory(parent).map_err(io)?;
*lock(&self.kept) = kept;
Ok(())
}
}
fn written(file: &str, kept: &Kept) -> String {
let Holder { node, address, epoch } = &kept.holder;
let copies = if kept.synchronous.is_empty() { "-".to_owned() } else { kept.synchronous.join(",") };
format!("{epoch} {node} {address} {copies} {file}\n")
}
fn read_holder(line: &str) -> Option<(String, Kept)> {
let (epoch, rest) = line.split_once(' ')?;
let (node, rest) = rest.split_once(' ')?;
let (address, rest) = rest.split_once(' ')?;
let (copies, file) = rest.split_once(' ')?;
let holder = Holder { node: node.to_owned(), address: address.to_owned(), epoch: epoch.parse().ok()? };
let synchronous = if copies == "-" { Vec::new() } else { copies.split(',').map(str::to_owned).collect() };
Some((file.to_owned(), Kept { holder, synchronous }))
}
#[cfg(test)]
#[allow(dead_code, reason = "the link tests call them, and they build only with every engine")]
impl Witness {
pub(crate) fn holder(&self, file: &str) -> Option<Holder> {
lock(&self.leases).get(file).map(|lease| lease.kept.holder.clone())
}
pub(crate) fn cut(&self, node: &str) {
lock(&self.cut).insert(node.to_owned());
}
pub(crate) fn heal(&self, node: &str) {
lock(&self.cut).remove(node);
}
}
fn renew(lease: &mut Lease, ask: &Ask<'_>, now: Instant) -> bool {
let holder = &lease.kept.holder;
let renewed = holder.node == ask.node && holder.epoch == ask.epoch;
let first = holder.node.is_empty() && ask.epoch >= holder.epoch;
let moved_in = !holder.node.is_empty() && ask.epoch > holder.epoch;
if moved_in && now < lease.expires {
let epoch = lease.claimant.as_ref().map_or(ask.epoch, |claimant| claimant.epoch.max(ask.epoch));
lease.claimant = Some(Claimant { epoch, asked: now });
return false;
}
if !renewed && !first && !moved_in {
return false;
}
let kept = Kept {
holder: Holder { node: ask.node.to_owned(), address: ask.address.to_owned(), epoch: ask.epoch },
synchronous: ask.synchronous.to_vec(),
};
lease.expires = now + TTL;
if !renewed {
(lease.claimant, lease.standing) = (None, HashMap::new());
}
let changed = kept != lease.kept;
lease.kept = kept;
changed
}
fn stand(lease: &mut Lease, ask: &Ask<'_>, now: Instant) -> bool {
let standing = Standing { address: ask.address.to_owned(), position: ask.position, seen: now };
lease.standing.insert(ask.node.to_owned(), standing);
lease.standing.retain(|_, standing| now.duration_since(standing.seen) < STANDING);
let holder = &lease.kept.holder;
if now < lease.expires + GATHER || holder.node == ask.node || holder.epoch == 0 {
return false;
}
if lease.claimant.as_ref().is_some_and(|claimant| now.duration_since(claimant.asked) < TTL) {
return false;
}
if freshest(lease).as_deref() != Some(ask.node) {
return false;
}
let claimed = lease.claimant.as_ref().map_or(0, |claimant| claimant.epoch);
let epoch = holder.epoch.max(claimed) + 1;
let holder = Holder { node: ask.node.to_owned(), address: ask.address.to_owned(), epoch };
lease.claimant = None;
lease.kept = Kept { holder, synchronous: Vec::new() };
lease.expires = now + TTL;
lease.standing.clear();
true
}
fn freshest(lease: &Lease) -> Option<String> {
let waited = &lease.kept.synchronous;
let names = |node: &str, standing: &Standing, name: &String| *name == node || *name == standing.address;
let candidates: Vec<(&String, &Standing)> = lease
.standing
.iter()
.filter(|(node, standing)| waited.is_empty() || waited.iter().any(|name| names(node, standing, name)))
.collect();
let every_one_stands =
waited.iter().all(|name| candidates.iter().any(|(node, standing)| names(node, standing, name)));
if !every_one_stands {
return None;
}
candidates.into_iter().max_by_key(|(_, standing)| standing.position).map(|(node, _)| node.clone())
}