use std::collections::{HashMap, HashSet};
use std::net::{TcpStream, ToSocketAddrs};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use super::copy::{self, Copy};
use super::entry::{self, Point};
use super::message::{Frames, Message, Refusal, plain_name, timed_out};
use super::node::State;
use super::serve::{Out, PING_EVERY, SILENT_AT_MOST};
use super::snapshot::Taking;
use crate::store::WeakStore;
use crate::sync::lock;
use crate::{Error, ErrorKind, Result, Store};
const LIST_EVERY: Duration = Duration::from_secs(5);
const LINK_WAIT: Duration = Duration::from_secs(10);
pub(crate) struct Written {
pub(crate) outcome: std::result::Result<Vec<u8>, Refusal>,
pub(crate) waits: Vec<(String, u64)>,
}
pub(crate) type Answered = Box<dyn FnOnce(Option<Written>) + Send>;
#[derive(Default)]
pub(crate) struct Upstream {
out: Mutex<Option<Arc<Out>>>,
linked: Condvar,
next_id: AtomicU64,
waiting: Mutex<HashMap<u64, Answered>>,
}
impl Upstream {
pub(crate) fn write(&self, op: Vec<u8>, at_most: Duration) -> Result<Written> {
let out = self.wait_for_link()?;
let (answer, answered): (Sender<Written>, Receiver<Written>) = mpsc::channel();
let id = self.send(
&out,
op,
Box::new(move |written| {
if let Some(written) = written {
let _ = answer.send(written);
}
}),
)?;
answered.recv_timeout(at_most).map_err(|_| {
lock(&self.waiting).remove(&id);
Error::new(ErrorKind::OutcomeUnknown, "the link to the home broke or went silent before the write answered")
})
}
#[cfg(feature = "kv")]
pub(crate) fn write_then(&self, op: Vec<u8>, answered: Answered) -> Result<()> {
let out = lock(&self.out).clone();
let out = out.ok_or_else(|| Error::new(ErrorKind::Unavailable, "no link reaches the home"))?;
self.send(&out, op, answered).map(drop)
}
fn send(&self, out: &Out, op: Vec<u8>, answered: Answered) -> Result<u64> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
lock(&self.waiting).insert(id, answered);
if let Err(error) = out.send(&Message::Write { id, op }) {
lock(&self.waiting).remove(&id);
return Err(Error::new(ErrorKind::Unavailable, "the link to the home broke before the write left")
.with_source(error));
}
Ok(id)
}
fn wait_for_link(&self) -> Result<Arc<Out>> {
let deadline = Instant::now() + LINK_WAIT;
let mut out = lock(&self.out);
loop {
if let Some(out) = &*out {
return Ok(Arc::clone(out));
}
let now = Instant::now();
if now >= deadline {
return Err(Error::new(ErrorKind::Unavailable, "no link reaches the home"));
}
out = self.linked.wait_timeout(out, deadline - now).unwrap_or_else(std::sync::PoisonError::into_inner).0;
}
}
fn linked(&self, out: Option<Arc<Out>>) {
let ended = out.is_none();
*lock(&self.out) = out;
self.linked.notify_all();
if ended {
let unanswered: Vec<Answered> = lock(&self.waiting).drain().map(|(_, answered)| answered).collect();
for answered in unanswered {
answered(None);
}
}
}
fn answered(&self, id: u64, written: Written) {
let answered = lock(&self.waiting).remove(&id);
if let Some(answered) = answered {
answered(Some(written));
}
}
pub(crate) fn stop(&self) {
self.linked(None);
}
}
pub(crate) fn start(state: &Arc<State>, store: &Store) {
let (state, store) = (Arc::clone(state), store.downgrade());
state.clone().spawn("tinystore node: from", move || keep_linked(&state, &store));
}
pub(crate) struct Direct {
pub(crate) address: String,
pub(crate) upstream: Upstream,
files: Mutex<HashSet<String>>,
}
impl Direct {
pub(crate) fn new(address: &str) -> Direct {
Direct { address: address.to_owned(), upstream: Upstream::default(), files: Mutex::default() }
}
pub(crate) fn add(&self, file: &str) {
lock(&self.files).insert(file.to_owned());
}
pub(crate) fn follows(&self, file: &str) -> bool {
lock(&self.files).contains(file)
}
pub(crate) fn remove(&self, file: &str) {
lock(&self.files).remove(file);
}
fn files(&self) -> Vec<String> {
let mut files: Vec<String> = lock(&self.files).iter().cloned().collect();
files.sort_unstable();
files
}
}
#[derive(Clone)]
enum Scope {
From,
Direct(Arc<Direct>),
}
pub(crate) fn start_direct(state: &Arc<State>, store: &Store, direct: Arc<Direct>) {
let (state, store) = (Arc::clone(state), store.downgrade());
state.clone().spawn("tinystore node: direct", move || {
let mut pause = Duration::from_millis(200);
while !state.stopping() {
let began = Instant::now();
if let Err(error) = follow(&state, &store, &direct.address, Scope::Direct(Arc::clone(&direct)))
&& !state.stopping()
{
tracing::debug!(target: "tinystore", to = %direct.address, %error, "a node's direct link to a home");
}
direct.upstream.linked(None);
pause = if began.elapsed() > Duration::from_secs(10) {
Duration::from_millis(200)
} else {
(pause * 2).min(Duration::from_secs(5))
};
state.pause(pause);
}
});
}
fn keep_linked(state: &Arc<State>, store: &WeakStore) {
let mut index = 0;
let mut pause = Duration::from_millis(200);
let mut said = None;
while !state.stopping() {
let address = state.options.from[index % state.options.from.len()].clone();
let began = Instant::now();
match follow(state, store, &address, Scope::From) {
Ok(()) => {}
Err(error) => {
if said.as_deref() != Some(error.to_string().as_str()) && !state.stopping() {
tracing::warn!(target: "tinystore", from = %address, %error, "a node's link to the node it copies");
said = Some(error.to_string());
}
}
}
state.upstream.linked(None);
*lock(&state.upstream_at) = None;
if began.elapsed() > Duration::from_secs(10) {
pause = Duration::from_millis(200);
} else {
index += 1;
pause = (pause * 2).min(Duration::from_secs(5));
}
state.pause(pause);
}
}
enum Held {
Taking(Box<Taking>),
Whole(Arc<Copy>),
Asked,
}
fn follow(state: &Arc<State>, store: &WeakStore, address: &str, scope: Scope) -> Result<()> {
let (mut reading, writing) = dial(state, address)?;
reading.set_timeout(Duration::from_millis(250))?;
writing.set_timeout(SILENT_AT_MOST)?;
let out = Arc::new(Out::new(writing));
out.send(&state.hello(state.address()))?;
let mut link = Link::new(state, store, scope, Arc::clone(&out));
let mut frames = Frames::default();
let (mut heard, mut listed, mut welcomed) = (Instant::now(), Instant::now(), false);
loop {
if state.stopping() {
return Ok(());
}
while let Some(message) = frames.next()? {
heard = Instant::now();
if welcomed {
link.take(message)?;
continue;
}
match message {
Message::Welcome { node, files } => {
welcomed = true;
frames.unpack_from_here()?;
link.welcomed(address, node, &files)?;
}
Message::Refused { why } => return Err(Error::new(ErrorKind::Invalid, format!("refused: {why}"))),
other => return Err(Error::invalid(format!("a link began with {other:?}, not a welcome"))),
}
}
if welcomed {
link.forget_copies_gone();
link.say_applied()?;
link.ask_to_verify()?;
}
match frames.fill(&mut reading) {
Ok(true) => {}
Ok(false) => return Err(Error::new(ErrorKind::Unavailable, "the node closed the link")),
Err(error) if timed_out(&error) => {}
Err(error) => return Err(Error::io("a link", error)),
}
if heard.elapsed() > SILENT_AT_MOST {
return Err(Error::new(ErrorKind::Unavailable, "the node said nothing for too long"));
}
if welcomed {
link.tend(&mut listed)?;
}
}
}
impl<'a> Link<'a> {
fn new(state: &'a Arc<State>, store: &'a WeakStore, scope: Scope, out: Arc<Out>) -> Link<'a> {
Link {
state,
store,
scope,
out,
held: HashMap::new(),
retries: Vec::new(),
said: HashMap::new(),
awaiting: HashMap::new(),
peer: String::new(),
refused: HashSet::new(),
#[cfg(feature = "blobs")]
fetching: Fetching::default(),
}
}
fn welcomed(&mut self, address: &str, node: String, files: &[String]) -> Result<()> {
self.out.pack()?;
self.peer = node;
self.upstream().linked(Some(Arc::clone(&self.out)));
if matches!(self.scope, Scope::From) {
*lock(&self.state.upstream_at) = Some(address.to_owned());
*lock(&self.state.served) = Some(files.to_vec());
}
tracing::info!(target: "tinystore", from = %address, "a node is linked to the node it copies");
self.follow_new(files)
}
fn tend(&mut self, listed: &mut Instant) -> Result<()> {
self.retry_due()?;
#[cfg(feature = "blobs")]
self.fetch_due()?;
if matches!(self.scope, Scope::Direct(_)) {
self.follow_new(&[])?;
}
let state = self.state;
let wanted = matches!(self.scope, Scope::From) && state.wanted.swap(false, Ordering::SeqCst);
if wanted || (state.options.files.is_none() && listed.elapsed() > LIST_EVERY) {
self.out.send(&Message::List)?;
*listed = Instant::now();
} else if self.out.idle_for() >= PING_EVERY {
self.out.send(&Message::Ping)?;
}
Ok(())
}
}
pub(crate) fn dial(state: &State, address: &str) -> Result<(super::transport::Reading, super::transport::Writing)> {
let stream = connect(address)?;
state.keep_link(&stream);
super::transport::connect(state, address, stream)
}
pub(crate) fn connect(address: &str) -> Result<TcpStream> {
let what = || format!("node: from {address}");
let addresses = address.to_socket_addrs().map_err(|error| Error::io(what(), error))?;
let mut last = None;
for resolved in addresses {
match TcpStream::connect_timeout(&resolved, Duration::from_secs(5)) {
Ok(stream) => return Ok(stream),
Err(error) => last = Some(error),
}
}
Err(Error::io(what(), last.unwrap_or_else(|| std::io::Error::other("the address resolves to nothing"))))
}
struct Link<'a> {
state: &'a Arc<State>,
store: &'a WeakStore,
scope: Scope,
out: Arc<Out>,
held: HashMap<String, Held>,
retries: Vec<(String, Instant)>,
said: HashMap<String, u64>,
awaiting: HashMap<String, (Point, Vec<u8>)>,
peer: String,
refused: HashSet<String>,
#[cfg(feature = "blobs")]
fetching: Fetching,
}
#[cfg(feature = "blobs")]
#[derive(Default)]
struct Fetching {
under_way: HashMap<String, Option<std::fs::File>>,
due: bool,
not_before: Option<Instant>,
}
impl Link<'_> {
fn upstream(&self) -> &Upstream {
match &self.scope {
Scope::From => &self.state.upstream,
Scope::Direct(direct) => &direct.upstream,
}
}
fn follow_new(&mut self, served: &[String]) -> Result<()> {
let mut wanted: HashSet<String> = match &self.scope {
Scope::From => served
.iter()
.filter(|name| self.state.takes(name) && !self.state.follows_directly(name))
.cloned()
.collect(),
Scope::Direct(direct) => direct.files().into_iter().collect(),
};
if let (Scope::From, Some(files)) = (&self.scope, &self.state.options.files) {
wanted.extend(files.iter().filter(|name| !self.state.follows_directly(name)).cloned());
}
let mut wanted: Vec<String> = wanted.into_iter().filter(|name| plain_name(name)).collect();
wanted.sort_unstable();
for name in wanted {
if !self.held.contains_key(&name) && self.reaches_its_home(&name)? {
self.ask(&name)?;
}
}
Ok(())
}
fn reaches_its_home(&mut self, name: &str) -> Result<bool> {
let Scope::Direct(direct) = &self.scope else {
return Ok(true);
};
let Some(store) = self.store.upgrade().filter(|_| self.state.uses_catalog()) else {
return Ok(true);
};
let Some(home) = self.state.catalog(&store)?.home_of(name)?.filter(|home| home.node != self.peer) else {
self.refused.remove(name);
return Ok(true);
};
if !home.address.is_empty() && home.address != direct.address {
direct.remove(name);
self.refused.remove(name);
self.state.take_directly(&store, name, &home.address)?;
} else if self.refused.insert(name.to_owned()) {
tracing::warn!(
target: "tinystore",
file = name,
address = %direct.address,
"the node at a file's address is not the home the catalog names: this node takes nothing of it there \
until the catalog names it"
);
}
Ok(false)
}
fn ask(&mut self, name: &str) -> Result<()> {
let at = match self.state.copy(name) {
Some(copy) => {
let at = copy.point();
self.held.insert(name.to_owned(), Held::Whole(copy));
self.blobs_changed(name);
at
}
None => {
self.held.insert(name.to_owned(), Held::Asked);
Point::default()
}
};
self.out.send(&Message::Follow { file: name.to_owned(), at })
}
fn blobs_changed(&mut self, file: &str) {
#[cfg(feature = "blobs")]
if file == crate::blobs::FILE_IN_STORE {
self.fetching.due = true;
}
let _ = file;
}
#[cfg(feature = "blobs")]
fn fetch_due(&mut self) -> Result<()> {
let now = Instant::now();
if !self.fetching.due || self.fetching.not_before.is_some_and(|not_before| now < not_before) {
return Ok(());
}
(self.fetching.due, self.fetching.not_before) = (false, Some(now + Duration::from_millis(300)));
for path in crate::blobs::objects_missing(&self.state.dir)? {
if !self.fetching.under_way.contains_key(&path) {
self.out.send(&Message::Fetch { path: path.clone() })?;
self.fetching.under_way.insert(path, None);
}
}
Ok(())
}
#[cfg(feature = "blobs")]
fn object(&mut self, path: &str, offset: u64, bytes: &[u8], last: bool) -> Result<()> {
use std::io::Write;
let target = self.state.dir.join(path);
if offset == 0 && crate::blobs::is_object(path) && !target.exists() {
self.fetching.under_way.entry(path.to_owned()).or_insert(None);
}
let Some(written) = self.fetching.under_way.get_mut(path) else {
return Ok(());
};
let mut temp = target.as_os_str().to_owned();
temp.push(".part");
let temp = std::path::PathBuf::from(temp);
let io = |error| Error::io(temp.display().to_string(), error);
if offset == 0 {
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(io)?;
}
*written = Some(std::fs::File::create(&temp).map_err(io)?);
}
let Some(file) = written.as_mut() else {
return Err(Error::corrupt(format!("{path}: a piece of a file whose first never came")));
};
file.write_all(bytes).map_err(io)?;
if last {
file.sync_all().map_err(io)?;
self.fetching.under_way.remove(path);
std::fs::rename(&temp, &target).map_err(io)?;
}
Ok(())
}
fn ask_to_verify(&mut self) -> Result<()> {
let held = &self.held;
for file in self.state.to_verify(|file| matches!(held.get(file), Some(Held::Whole(_)))) {
self.out.send(&Message::Verify { file })?;
}
Ok(())
}
fn verified(&mut self, file: &str, at: Point, sum: Vec<u8>, why: &str) {
let stands = match self.held.get(file) {
Some(Held::Whole(copy)) => copy.point(),
_ => return self.state.verification(file, Err(Error::new(ErrorKind::Unavailable, "no whole copy"))),
};
if sum.is_empty() {
return self.state.verification(file, Err(Error::new(ErrorKind::Unavailable, why.to_owned())));
}
if stands.sequence < at.sequence {
self.awaiting.insert(file.to_owned(), (at, sum));
return;
}
self.compare(file, at, &sum, stands);
}
fn compare(&mut self, file: &str, at: Point, sum: &[u8], stands: Point) {
let done = if stands.sequence != at.sequence {
Err(Error::new(
ErrorKind::Conflict,
format!("the copy stands at entry {}, past those checked", stands.sequence),
))
} else if stands.check != at.check {
Err(Error::new(
ErrorKind::Conflict,
format!("the copy's entry {} is not its source's: another home wrote it", stands.sequence),
))
} else {
super::verify::of_copy(self.state, file)
.and_then(|ours| super::verify::compare(file, at.sequence, ours, sum))
};
self.state.verification(file, done);
}
fn forget_copies_gone(&mut self) {
let state = self.state;
self.held.retain(|name, held| !matches!(held, Held::Whole(_)) || state.copy(name).is_some());
}
fn say_applied(&mut self) -> Result<()> {
for (file, held) in &self.held {
if let Held::Whole(copy) = held {
let applied = copy.applied();
if self.said.get(file).is_none_or(|said| *said < applied) {
self.out.send(&Message::Applied { file: file.clone(), sequence: applied })?;
self.said.insert(file.clone(), applied);
}
}
}
Ok(())
}
fn retry_due(&mut self) -> Result<()> {
let now = Instant::now();
let due: Vec<String> = self.retries.iter().filter(|(_, at)| *at <= now).map(|(name, _)| name.clone()).collect();
self.retries.retain(|(_, at)| *at > now);
for name in due {
self.ask(&name)?;
}
Ok(())
}
fn take(&mut self, message: Message) -> Result<()> {
match message {
Message::SnapshotBegin { file, page_size, at } => self.begin(&file, page_size, at),
Message::SnapshotPages { file, pages } => match self.held.get_mut(&file) {
Some(Held::Taking(taking)) => taking.pages(&pages),
_ => Err(Error::invalid(format!("{file}: pages of no snapshot under way"))),
},
Message::SnapshotEnd { file, ready_at } => {
if let Some(Held::Taking(taking)) = self.held.get_mut(&file) {
taking.end(ready_at);
}
self.finish_when_whole(&file)
}
Message::Entry { file, bytes } => self.apply(&file, &bytes),
#[cfg(feature = "blobs")]
Message::Failed { file, .. } if crate::blobs::is_object(&file) => {
self.fetching.under_way.remove(&file);
(self.fetching.due, self.fetching.not_before) = (true, Some(Instant::now() + Duration::from_secs(2)));
Ok(())
}
#[cfg(feature = "blobs")]
Message::Object { path, offset, bytes, last } => self.object(&path, offset, &bytes, last),
Message::Failed { kind: ErrorKind::Conflict, why, .. } => Err(Error::new(ErrorKind::Conflict, why)),
Message::Failed { file, kind, why } => {
tracing::debug!(target: "tinystore", %file, %kind, %why, "a node's file could not be sent yet");
self.held.remove(&file);
self.retries.push((file, Instant::now() + Duration::from_secs(2)));
Ok(())
}
Message::Written { id, outcome, waits } => {
self.upstream().answered(id, Written { outcome, waits });
Ok(())
}
Message::Verified { file, at, sum, why } => {
self.verified(&file, at, sum, &why);
Ok(())
}
Message::Listed { files } => {
if matches!(self.scope, Scope::From) {
*lock(&self.state.served) = Some(files.clone());
}
self.follow_new(&files)
}
Message::Ping => Ok(()),
other => Err(Error::invalid(format!("a link said {other:?}, which a follower is not sent"))),
}
}
fn begin(&mut self, file: &str, page_size: u32, at: Point) -> Result<()> {
if !plain_name(file) {
return Err(Error::invalid(format!("a link sent {file:?}, which is no file's name")));
}
let applied = self.epoch_applied(file)?;
if at.epoch < applied {
return Err(Error::new(
ErrorKind::Conflict,
format!(
"{file}: a snapshot at epoch {} from a node, and this copy applied epoch {applied}: an old home's file",
at.epoch
),
));
}
self.state.snapshots.fetch_add(1, Ordering::Relaxed);
let dir = self.state.log_dir(file);
let taking = Box::new(Taking::begin(&dir, &self.state.dir.join(file), page_size, at)?);
self.held.insert(file.to_owned(), Held::Taking(taking));
Ok(())
}
fn epoch_applied(&self, file: &str) -> Result<u64> {
let kept = copy::Position::read_point(&self.state.log_dir(file).join(copy::Position::FILE))?;
Ok(kept.map_or(0, |point| point.epoch))
}
fn apply(&mut self, file: &str, bytes: &[u8]) -> Result<()> {
let Some((entry, _)) = entry::decode(bytes)? else {
return Err(Error::corrupt(format!("{file}: an entry cut short")));
};
let applied = match self.held.get_mut(file) {
Some(Held::Taking(taking)) => taking.apply(&entry),
Some(Held::Whole(copy)) => copy.apply(&entry, Some(bytes)),
Some(Held::Asked) | None => return Ok(()),
};
match applied {
Ok(()) => {
self.blobs_changed(file);
if let (Some((at, _)), Some(Held::Whole(copy))) = (self.awaiting.get(file), self.held.get(file))
&& copy.point().sequence >= at.sequence
{
let stands = copy.point();
if let Some((at, sum)) = self.awaiting.remove(file) {
self.compare(file, at, &sum, stands);
}
}
self.finish_when_whole(file)
}
Err(error) if matches!(error.kind(), ErrorKind::Conflict | ErrorKind::Invalid) => {
tracing::warn!(target: "tinystore", %file, %error, "a copy starts again from a snapshot");
self.held.insert(file.to_owned(), Held::Asked);
self.out.send(&Message::Follow { file: file.to_owned(), at: Point::default() })
}
Err(error) => Err(error),
}
}
fn finish_when_whole(&mut self, file: &str) -> Result<()> {
let whole = matches!(self.held.get(file), Some(Held::Taking(taking)) if taking.whole());
if !whole {
return Ok(());
}
let store = self.store.upgrade().ok_or_else(|| Error::closed("the node's store"))?;
let state = self.state;
let _rerouting = state.copy(file).map(|_| state.wait_to_reroute(file)).transpose()?;
let paused = self.state.pause_readers(file)?;
let Some(Held::Taking(taking)) = self.held.remove(file) else {
return Ok(());
};
self.state.drop_copy(file);
if let Err(error) = (*taking).finish() {
if copy::is_ready(&self.state.log_dir(file), &self.state.dir.join(file)) {
self.state.keep_copy(file, Arc::new(Copy::open(&store, file)?));
}
return Err(error);
}
let copy = Arc::new(Copy::open(&store, file)?);
self.state.keep_copy(file, Arc::clone(©));
drop(paused);
store.applied(file);
drop(store);
self.held.insert(file.to_owned(), Held::Whole(copy));
self.said.remove(file);
tracing::info!(target: "tinystore", %file, "a node holds a whole copy of a file");
self.blobs_changed(file);
Ok(())
}
}