use std::collections::{HashMap, HashSet};
use std::fs;
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use super::catalog::{Catalog, Claim, FILE as CATALOG};
use super::copy::{self, Copy};
use super::entry::Point;
use super::follow::{Direct, Upstream, Written};
use super::links::Follower;
use super::log::{Acks, Bounds, Log, Notify, segments_in};
use super::snapshot::Source;
use super::{DIR, NODE_LOCAL, Node};
use crate::sqlite::{File, Observe, Readers, Switch};
use crate::store::WeakStore;
use crate::sync::lock;
use crate::{Error, ErrorKind, Result, Store};
pub(crate) const READY_WAIT: Duration = Duration::from_secs(30);
const PAUSE_AT_MOST: Duration = Duration::from_secs(5);
pub(crate) struct State {
pub(crate) dir: PathBuf,
pub(crate) options: Node,
store: Mutex<Option<WeakStore>>,
bounds: Bounds,
pub(crate) notify: Arc<Notify>,
pub(crate) acks: Arc<Acks>,
logs: Mutex<HashMap<String, Weak<Log>>>,
copies: Mutex<HashMap<String, Arc<Copy>>>,
copied: Condvar,
routes: Mutex<Routes>,
rerouted: Condvar,
pub(crate) upstream: Upstream,
pub(crate) stopping: AtomicBool,
threads: Mutex<Vec<JoinHandle<()>>>,
links: Mutex<Vec<TcpStream>>,
pub(crate) listening: Mutex<Option<SocketAddr>>,
queue: Mutex<Option<Arc<super::queue::Queue>>>,
pub(crate) tls: super::transport::Tls,
pub(crate) snapshots: std::sync::atomic::AtomicU64,
pub(crate) lost: std::sync::atomic::AtomicU64,
pub(crate) wanted: AtomicBool,
opened: Mutex<HashMap<String, Vec<Switch>>>,
pub(crate) followers: Mutex<HashMap<u64, Follower>>,
next_follower: std::sync::atomic::AtomicU64,
pub(crate) upstream_at: Mutex<Option<String>>,
pub(crate) id: String,
pub(crate) served: Mutex<Option<Vec<String>>>,
catalog: super::catalog::Held,
direct: Mutex<HashMap<String, Arc<Direct>>>,
verifying: Mutex<HashMap<String, Verifying>>,
granted: Mutex<HashMap<String, Instant>>,
epochs: Mutex<HashMap<String, u64>>,
pub(crate) witness: Option<super::witness::Witness>,
}
enum Verifying {
Asked,
Sent,
Done(Result<u64>),
}
pub(super) const DIRECT: &str = "from";
#[derive(Default)]
struct Routes {
opening: HashMap<String, usize>,
rerouting: HashMap<String, usize>,
}
pub(crate) struct Opening<'a> {
state: &'a State,
name: String,
}
impl Drop for Opening<'_> {
fn drop(&mut self) {
release(&mut lock(&self.state.routes).opening, &self.name);
self.state.rerouted.notify_all();
}
}
pub(crate) struct Rerouting<'a> {
state: &'a State,
name: String,
}
impl Drop for Rerouting<'_> {
fn drop(&mut self) {
release(&mut lock(&self.state.routes).rerouting, &self.name);
self.state.rerouted.notify_all();
}
}
fn release(under_way: &mut HashMap<String, usize>, name: &str) {
if let Some(count) = under_way.get_mut(name) {
*count -= 1;
if *count == 0 {
under_way.remove(name);
}
}
}
pub(crate) enum Claimed {
Here,
From,
At(String),
}
pub(crate) struct Following {
state: Arc<State>,
id: u64,
node: String,
address: String,
}
impl Following {
pub(crate) fn node(&self) -> &str {
&self.node
}
pub(crate) fn address(&self) -> &str {
&self.address
}
pub(crate) fn applied(&self, file: &str, sequence: u64) {
if let Some(follower) = lock(&self.state.followers).get_mut(&self.id) {
follower.applied.insert(file.to_owned(), sequence);
}
}
}
impl Drop for Following {
fn drop(&mut self) {
lock(&self.state.followers).remove(&self.id);
}
}
pub(crate) struct Paused(Vec<Arc<Readers>>);
impl Drop for Paused {
fn drop(&mut self) {
self.0.iter().for_each(|readers| readers.resume());
}
}
impl State {
pub(crate) fn new(dir: &Path, options: Node, keep_free: u64) -> Result<State> {
let tls = super::transport::Tls::of(&options)?;
let acks = Arc::new(Acks::waiting_for(options.synchronous_with.clone()));
Ok(State {
id: super::queue::node_id(&dir.join(DIR))?,
acks,
served: Mutex::default(),
catalog: Mutex::default(),
direct: Mutex::default(),
verifying: Mutex::default(),
granted: Mutex::default(),
epochs: Mutex::default(),
witness: if options.witness { Some(super::witness::Witness::open(dir)?) } else { None },
queue: Mutex::default(),
tls,
dir: dir.to_owned(),
options,
store: Mutex::default(),
bounds: Bounds { keep_free, ..Bounds::default() },
notify: Arc::default(),
logs: Mutex::default(),
copies: Mutex::default(),
copied: Condvar::new(),
routes: Mutex::default(),
rerouted: Condvar::new(),
upstream: Upstream::default(),
stopping: AtomicBool::new(false),
threads: Mutex::default(),
links: Mutex::default(),
listening: Mutex::default(),
snapshots: std::sync::atomic::AtomicU64::new(0),
lost: std::sync::atomic::AtomicU64::new(0),
wanted: AtomicBool::new(false),
opened: Mutex::default(),
followers: Mutex::default(),
next_follower: std::sync::atomic::AtomicU64::new(0),
upstream_at: Mutex::default(),
})
}
pub(crate) fn start(self: &Arc<Self>, store: &Store) -> Result<()> {
if self.options.failover.is_some() && self.options.synchronous && self.options.synchronous_with.is_empty() {
return Err(Error::invalid(
"a synchronous node a witness judges names the copies its commits wait for, synchronous_with: only \
they hold every commit it answered, and the witness gives its lease to one of them",
));
}
*lock(&self.store) = Some(store.downgrade());
let _ = self.acks.probe.set(Arc::clone(store.probe()));
let sampler: Weak<dyn crate::probe::Sample> = Arc::downgrade(self) as Weak<State>;
store.probe().sampled(sampler);
if self.options.catalog {
self.catalog(store)?;
}
if let Some(address) = &self.options.serve {
super::serve::start(self, address)?;
}
let direct = self.files_taken_directly()?;
if !self.options.from.is_empty() || !direct.is_empty() {
self.open_copies_held(store)?;
}
if !self.options.from.is_empty() {
super::follow::start(self, store);
}
for (name, address) in direct {
self.take_directly(store, &name, &address)?;
}
let writing = Arc::clone(self);
self.spawn("tinystore node: links", move || super::links::keep_written(&writing));
if let Some(witness) = &self.options.failover {
super::judge::start(self, store, witness.clone());
}
if self.options.catalog || !self.options.from.is_empty() {
let claiming = Arc::clone(self);
self.spawn("tinystore node: catalog", move || claiming.claim_its_files());
}
if self.dir.join(DIR).join(super::queue::FILE).exists() {
self.queue()?;
}
Ok(())
}
pub(crate) fn stop(&self) {
if self.stopping.swap(true, Ordering::SeqCst) {
return;
}
for log in lock(&self.logs).values().filter_map(Weak::upgrade) {
log.stop_waiting();
}
if let Some(mut address) = *lock(&self.listening) {
if address.ip().is_unspecified() {
address.set_ip(match address {
std::net::SocketAddr::V4(_) => std::net::Ipv4Addr::LOCALHOST.into(),
std::net::SocketAddr::V6(_) => std::net::Ipv6Addr::LOCALHOST.into(),
});
}
let _ = TcpStream::connect_timeout(&address, Duration::from_secs(1));
}
for link in lock(&self.links).drain(..) {
let _ = link.shutdown(std::net::Shutdown::Both);
}
self.upstream.stop();
for direct in lock(&self.direct).values() {
direct.upstream.stop();
}
self.notify.appended();
let threads: Vec<_> = lock(&self.threads).drain(..).collect();
for thread in threads {
if thread.thread().id() != thread::current().id() {
let _ = thread.join();
}
}
lock(&self.copies).clear();
if let Some(queue) = lock(&self.queue).take() {
queue.close();
}
if let Some(catalog) = lock(&self.catalog).take() {
catalog.close();
}
}
pub(crate) fn address(&self) -> String {
match &self.options.advertise {
Some(address) => address.clone(),
None => lock(&self.listening).map(|at| at.to_string()).unwrap_or_default(),
}
}
pub(crate) fn catalog(&self, store: &Store) -> Result<Arc<Catalog>> {
let mut held = lock(&self.catalog);
if let Some(catalog) = &*held {
return Ok(Arc::clone(catalog));
}
let catalog = Arc::new(Catalog::open(store)?);
*held = Some(Arc::clone(&catalog));
Ok(catalog)
}
pub(crate) fn uses_catalog(&self) -> bool {
if self.options.catalog || copy::is_copy(&self.log_dir(CATALOG)) {
return true;
}
if self.options.from.is_empty() {
return false;
}
let deadline = Instant::now() + READY_WAIT;
loop {
if let Some(served) = &*lock(&self.served) {
return served.iter().any(|file| file == CATALOG);
}
if Instant::now() >= deadline || self.stopping() {
return false;
}
thread::sleep(Duration::from_millis(20));
}
}
pub(crate) fn is_new(&self, name: &str) -> bool {
if name == CATALOG || self.options.files.is_some() || NODE_LOCAL.contains(&name) {
return false;
}
let dir = self.log_dir(name);
!copy::is_copy(&dir)
&& !dir.join(super::promote::PROMOTED).exists()
&& segments_in(&dir).is_ok_and(|segments| segments.is_empty())
}
pub(crate) fn claim(&self, store: &Store, name: &str) -> Result<Claimed> {
let catalog = self.catalog(store)?;
let (address, epoch) = (self.address(), self.epoch_of(name)?);
let claim = Claim { file: name, node: &self.id, address: &address, epoch };
let home = match catalog.home_of(name)? {
Some(home) if home.node != self.id && epoch > home.epoch && !address.is_empty() => {
catalog.claim(store, &claim)?
}
Some(home) => home,
None if address.is_empty() || self.served_by_from(name) => return Ok(Claimed::From),
None => catalog.claim(store, &claim)?,
};
if home.node == self.id {
return Ok(Claimed::Here);
}
let from = lock(&self.upstream_at).clone();
if self.served_by_from(name) || home.address.is_empty() || from.as_deref() == Some(home.address.as_str()) {
return Ok(Claimed::From);
}
Ok(Claimed::At(home.address))
}
fn epoch_of(&self, name: &str) -> Result<u64> {
let dir = self.log_dir(name);
let last = super::log::Log::last_in(&dir)?.map(|point| point.epoch);
let promoted = super::promote::promoted_at(&dir)?.map(|point| point.epoch);
Ok(last.max(promoted).unwrap_or(1))
}
fn served_by_from(&self, name: &str) -> bool {
lock(&self.served).as_ref().is_some_and(|served| served.iter().any(|file| file == name))
}
pub(crate) fn take_directly(self: &Arc<Self>, store: &Store, name: &str, address: &str) -> Result<()> {
let dir = self.log_dir(name);
fs::create_dir_all(&dir).map_err(|error| Error::io(dir.display().to_string(), error))?;
fs::write(dir.join(DIRECT), address).map_err(|error| Error::io(dir.display().to_string(), error))?;
let direct = {
let mut directs = lock(&self.direct);
match directs.get(address) {
Some(direct) => Arc::clone(direct),
None => {
let direct = Arc::new(Direct::new(address));
directs.insert(address.to_owned(), Arc::clone(&direct));
super::follow::start_direct(self, store, Arc::clone(&direct));
direct
}
}
};
direct.add(name);
Ok(())
}
pub(crate) fn take_over_at(
self: &Arc<Self>,
store: &Store,
name: &str,
copy: Arc<Copy>,
at_least: u64,
) -> Result<()> {
let _rerouting = self.wait_to_reroute(name)?;
let paused = self.pause_readers(name)?;
if let Some(direct) = lock(&self.direct).values().find(|direct| direct.follows(name)) {
direct.remove(name);
}
self.drop_copy(name);
let deadline = Instant::now() + PAUSE_AT_MOST;
while Arc::strong_count(©) > 1 {
if Instant::now() >= deadline {
self.keep_copy(name, copy);
return Err(Error::new(ErrorKind::Unavailable, format!("{name}: a link still applies its copy")));
}
thread::sleep(Duration::from_millis(10));
}
drop(copy);
super::promote::promote_one(name.to_owned(), &self.dir.join(name), &self.log_dir(name), at_least)?;
let log = self.open_log(name)?;
self.switch_each(name, |switch| switch.become_home(Arc::clone(&log)))?;
drop(paused);
store.applied(name);
Ok(())
}
pub(crate) fn wait_to_open(&self, name: &str) -> Result<Opening<'_>> {
let deadline = Instant::now() + READY_WAIT;
let mut routes = lock(&self.routes);
while routes.rerouting.contains_key(name) {
let now = Instant::now();
if now >= deadline || self.stopping() {
return Err(Error::new(ErrorKind::Unavailable, format!("{name}: its route changes still")));
}
let turn = (deadline - now).min(Duration::from_millis(250));
routes = self.rerouted.wait_timeout(routes, turn).unwrap_or_else(PoisonError::into_inner).0;
}
*routes.opening.entry(name.to_owned()).or_default() += 1;
Ok(Opening { state: self, name: name.to_owned() })
}
pub(crate) fn wait_to_reroute(&self, name: &str) -> Result<Rerouting<'_>> {
let deadline = Instant::now() + PAUSE_AT_MOST;
let mut routes = lock(&self.routes);
*routes.rerouting.entry(name.to_owned()).or_default() += 1;
while routes.opening.contains_key(name) {
let now = Instant::now();
if now >= deadline {
release(&mut routes.rerouting, name);
self.rerouted.notify_all();
return Err(Error::new(ErrorKind::Unavailable, format!("{name}: an engine still opens it")));
}
routes = self.rerouted.wait_timeout(routes, deadline - now).unwrap_or_else(PoisonError::into_inner).0;
}
Ok(Rerouting { state: self, name: name.to_owned() })
}
pub(crate) fn go_on_at(&self, name: &str, epoch: u64) -> Result<()> {
match lock(&self.logs).get(name).and_then(Weak::upgrade) {
Some(log) => log.go_on_at(epoch)?,
None => Log::go_on_at_in(&self.log_dir(name), epoch)?,
}
self.unfence(name)
}
pub(crate) fn unfence(&self, name: &str) -> Result<()> {
match lock(&self.logs).get(name).and_then(Weak::upgrade) {
Some(log) => log.unfence(),
None => Log::unfence_in(&self.log_dir(name)),
}
}
pub(crate) fn holding_home<T>(&self, name: &str, read: impl FnOnce(Point) -> Result<T>) -> Result<T> {
if let Some(log) = lock(&self.logs).get(name).and_then(Weak::upgrade) {
return log.holding(read);
}
let point = self.point_of(name).ok_or_else(|| {
Error::new(ErrorKind::Unavailable, format!("{name}: this node holds no log of it it can read now"))
})?;
read(point)
}
pub(crate) fn ask_to_verify(&self, file: &str) {
lock(&self.verifying).insert(file.to_owned(), Verifying::Asked);
}
pub(crate) fn verified(&self, file: &str) -> Option<Result<u64>> {
let mut verifying = lock(&self.verifying);
match verifying.get(file) {
Some(Verifying::Done(_)) => match verifying.remove(file) {
Some(Verifying::Done(done)) => Some(done),
_ => None,
},
_ => None,
}
}
pub(crate) fn forget_verifying(&self, file: &str) {
lock(&self.verifying).remove(file);
}
pub(crate) fn to_verify(&self, held: impl Fn(&str) -> bool) -> Vec<String> {
let mut verifying = lock(&self.verifying);
let asked: Vec<String> = verifying
.iter()
.filter(|(file, state)| matches!(state, Verifying::Asked) && held(file))
.map(|(file, _)| file.clone())
.collect();
for file in &asked {
verifying.insert(file.clone(), Verifying::Sent);
}
asked
}
pub(crate) fn verification(&self, file: &str, done: Result<u64>) {
lock(&self.verifying).insert(file.to_owned(), Verifying::Done(done));
}
pub(crate) fn ask_for_what_is_served(&self) {
self.wanted.store(true, Ordering::SeqCst);
}
pub(crate) fn fence(&self, name: &str, epoch: u64) -> Result<()> {
tracing::error!(
target: "tinystore",
file = name,
epoch,
"another node writes a file this node wrote, at a later epoch: this node takes no more writes of it"
);
let logs = lock(&self.logs);
match logs.get(name).and_then(Weak::upgrade) {
Some(log) => log.fence(epoch),
None => Log::fence_in(&self.log_dir(name), epoch),
}
}
pub(crate) fn follows_directly(&self, name: &str) -> bool {
lock(&self.direct).values().any(|direct| direct.follows(name))
}
pub(crate) fn write_toward(&self, file: &str, op: Vec<u8>, at_most: Duration) -> Result<Written> {
crate::polled::may_wait(|| format!("{file}: a write passed on to its home"))?;
let direct = lock(&self.direct).values().find(|direct| direct.follows(file)).cloned();
match direct {
Some(direct) => direct.upstream.write(op, at_most),
None => self.upstream.write(op, at_most),
}
}
#[cfg(feature = "kv")]
pub(crate) fn write_toward_then(&self, file: &str, op: Vec<u8>, answered: super::follow::Answered) -> Result<()> {
let direct = lock(&self.direct).values().find(|direct| direct.follows(file)).cloned();
match direct {
Some(direct) => direct.upstream.write_then(op, answered),
None => self.upstream.write_then(op, answered),
}
}
fn files_taken_directly(&self) -> Result<Vec<(String, String)>> {
let mut taken = Vec::new();
for name in self.files_logged()? {
let dir = self.log_dir(&name);
if let Ok(address) = fs::read_to_string(dir.join(DIRECT))
&& copy::is_copy(&dir)
{
taken.push((name, address.trim().to_owned()));
}
}
Ok(taken)
}
fn claim_its_files(&self) {
if !self.uses_catalog() {
return;
}
let Some(store) = self.store() else {
return;
};
let (logged, catalog) = match (self.files_logged(), self.catalog(&store)) {
(Ok(logged), Ok(catalog)) => (logged, catalog),
(Err(error), _) | (_, Err(error)) => {
tracing::warn!(target: "tinystore", %error, "a node could not claim its files in the catalog");
return;
}
};
let address = self.address();
for name in logged {
let dir = self.log_dir(&name);
if name == CATALOG || NODE_LOCAL.contains(&name.as_str()) || copy::is_copy(&dir) || self.stopping() {
continue;
}
let epoch = match self.epoch_of(&name) {
Ok(epoch) => epoch,
Err(error) => {
tracing::warn!(
target: "tinystore",
file = %name,
%error,
"a node could not read a file's epoch to claim it",
);
continue;
}
};
let claim = Claim { file: &name, node: &self.id, address: &address, epoch };
match catalog.claim(&store, &claim) {
Ok(home) if home.node == self.id && home.epoch > epoch => {
if let Err(error) = self.go_on_at(&name, home.epoch) {
tracing::warn!(
target: "tinystore",
file = %name,
%error,
"a node could not write a file again",
);
}
}
Ok(home) if home.node == self.id => {}
Ok(home) => self.found_another_home(&name, epoch, home.epoch),
Err(error) => {
tracing::debug!(target: "tinystore", file = %name, %error, "a node could not claim a file")
}
}
}
}
fn found_another_home(&self, name: &str, ours: u64, theirs: u64) {
if theirs <= ours {
tracing::error!(
target: "tinystore",
file = name,
"the catalog names another home of a file this node writes: two homes write it now"
);
return;
}
if let Err(error) = self.fence(name, theirs) {
tracing::warn!(target: "tinystore", file = name, %error, "a node could not fence a file");
}
}
pub(crate) fn queue(self: &Arc<Self>) -> Result<Arc<super::queue::Queue>> {
let mut held = lock(&self.queue);
if let Some(queue) = &*held {
return Ok(Arc::clone(queue));
}
let queue = Arc::new(super::queue::Queue::open(&self.dir, self.id.clone())?);
*held = Some(Arc::clone(&queue));
let (state, sending) = (Arc::clone(self), Arc::clone(&queue));
self.spawn("tinystore node: queue", move || super::queue::send(&state, &sending));
Ok(queue)
}
pub(crate) fn store(&self) -> Option<Store> {
lock(&self.store).as_ref().and_then(WeakStore::upgrade)
}
pub(crate) fn stopping(&self) -> bool {
self.stopping.load(Ordering::SeqCst)
}
pub(crate) fn hello(&self, address: String) -> super::message::Message {
super::message::Message::Hello {
version: super::message::VERSION,
token: self.options.token.clone().unwrap_or_default(),
node: self.id.clone(),
address,
}
}
pub(crate) fn pause(&self, span: Duration) {
let until = Instant::now() + span;
while Instant::now() < until && !self.stopping() {
thread::sleep(Duration::from_millis(50));
}
}
pub(crate) fn spawn(&self, name: &str, work: impl FnOnce() + Send + 'static) {
let inside = tracing::Span::current().metadata().is_some_and(|span| span.name() == "node");
let span = if inside {
tracing::Span::none()
} else {
tracing::info_span!(target: "tinystore", "node", node = %self.id)
};
let thread = thread::Builder::new().name(name.to_owned()).spawn(move || span.in_scope(work));
match thread {
Ok(thread) => {
let mut threads = lock(&self.threads);
threads.retain(|kept| !kept.is_finished());
threads.push(thread);
}
Err(error) => tracing::warn!(target: "tinystore", %error, "a node could not start a thread of its links"),
}
}
pub(crate) fn keep_link(&self, link: &TcpStream) {
if let Ok(link) = link.try_clone() {
let mut links = lock(&self.links);
links.retain(|kept| kept.peer_addr().is_ok());
links.push(link);
}
}
pub(crate) fn open_log(&self, name: &str) -> Result<Arc<dyn Observe>> {
let log = self.kept_log(name, self.log_of(name)?)?;
if self.stopping() {
log.stop_waiting();
}
Ok(log)
}
pub(super) fn log_of(&self, name: &str) -> Result<Log> {
let mut log = Log::open(self.log_dir(name), self.bounds, Arc::clone(&self.notify))?
.followed(name, Arc::clone(&self.acks));
if self.options.failover.is_some() && name != CATALOG {
log = log.judged(lock(&self.granted).remove(name).unwrap_or_else(Instant::now));
}
if self.options.synchronous || !self.options.synchronous_with.is_empty() {
log = log.synchronous();
}
Ok(log)
}
pub(super) fn kept_log(&self, name: &str, log: Log) -> Result<Arc<Log>> {
let log = Arc::new(log);
let mut logs = lock(&self.logs);
logs.insert(name.to_owned(), Arc::downgrade(&log));
log.fenced_as_kept()?;
drop(logs);
Ok(log)
}
pub(crate) fn log_dir(&self, name: &str) -> PathBuf {
self.dir.join(DIR).join(name)
}
pub(crate) fn takes(&self, name: &str) -> bool {
if self.options.from.is_empty() {
return false;
}
if name == CATALOG {
return !self.options.catalog;
}
let dir = self.log_dir(name);
if !copy::is_copy(&dir) && segments_in(&dir).is_ok_and(|segments| !segments.is_empty())
|| dir.join(super::promote::PROMOTED).exists()
{
return false;
}
match &self.options.files {
Some(files) => files.iter().any(|file| file == name),
None => !NODE_LOCAL.contains(&name),
}
}
pub(crate) fn wait_ready(&self, name: &str) -> Result<()> {
let began = Instant::now();
let deadline = began + READY_WAIT;
let mut asked_to_make = false;
let mut copies = lock(&self.copies);
while !copies.contains_key(name) {
if !asked_to_make && began.elapsed() > Duration::from_millis(500) {
asked_to_make = true;
drop(copies);
if let Err(error) = super::forward::make(self, name) {
tracing::debug!(
target: "tinystore",
file = name,
%error,
"a node could not ask its home to make a file",
);
}
copies = lock(&self.copies);
continue;
}
let now = Instant::now();
if now >= deadline || self.stopping() {
return Err(Error::new(
ErrorKind::Unavailable,
format!(
"{name}: no copy of it has come from {} yet: its home has not made it, or no link reaches it",
self.options.from.join(", ")
),
));
}
self.wanted.store(true, Ordering::SeqCst);
let turn = (deadline - now).min(Duration::from_millis(250));
copies = self.copied.wait_timeout(copies, turn).unwrap_or_else(PoisonError::into_inner).0;
}
Ok(())
}
pub(crate) fn following(self: &Arc<Self>, node: String, address: String) -> Following {
let id = self.next_follower.fetch_add(1, Ordering::Relaxed);
lock(&self.followers).insert(id, Follower { address: address.clone(), applied: Default::default() });
Following { state: Arc::clone(self), id, node, address }
}
pub(crate) fn opened(&self, name: &str, file: File) -> File {
let mut held = lock(&self.opened);
let switches = held.entry(name.to_owned()).or_default();
switches.retain(Switch::is_open);
switches.push(file.switch());
file
}
pub(crate) fn switch_each(&self, name: &str, change: impl Fn(&Switch) -> Result<()>) -> Result<()> {
let held = lock(&self.opened);
for switch in held.get(name).into_iter().flatten().filter(|switch| switch.is_open()) {
change(switch)?;
}
Ok(())
}
pub(crate) fn pause_readers(&self, name: &str) -> Result<Paused> {
let open: Vec<Arc<Readers>> = lock(&self.opened)
.get(name)
.map(|switches| switches.iter().filter_map(Switch::readers).collect())
.unwrap_or_default();
let mut paused = Paused(Vec::new());
for readers in open {
readers.pause(PAUSE_AT_MOST)?;
paused.0.push(readers);
}
Ok(paused)
}
pub(crate) fn copy(&self, name: &str) -> Option<Arc<Copy>> {
lock(&self.copies).get(name).cloned()
}
pub(crate) fn keep_copy(&self, name: &str, copy: Arc<Copy>) {
lock(&self.copies).insert(name.to_owned(), copy);
self.copied.notify_all();
self.notify.served_changed();
self.notify.appended();
}
pub(crate) fn bounds(&self) -> Bounds {
self.bounds
}
pub(crate) fn drop_copy(&self, name: &str) {
lock(&self.copies).remove(name);
}
fn open_copies_held(&self, store: &Store) -> Result<()> {
for name in self.files_logged()? {
if copy::is_ready(&self.log_dir(&name), &self.dir.join(&name)) {
match Copy::open(store, &name) {
Ok(copy) => self.keep_copy(&name, Arc::new(copy)),
Err(error) if error.kind() == ErrorKind::Corrupt => self.take_again(&name, &error)?,
Err(error) => return Err(error),
}
}
}
Ok(())
}
fn take_again(&self, name: &str, error: &Error) -> Result<()> {
let position = self.log_dir(name).join(copy::Position::FILE);
fs::remove_file(&position).map_err(|error| Error::io(position.display().to_string(), error))?;
tracing::warn!(target: "tinystore", file = name, %error, "a copy starts again from a snapshot");
Ok(())
}
pub(crate) fn files_served(&self) -> Result<Vec<String>> {
let copies = lock(&self.copies).keys().cloned().collect::<HashSet<_>>();
let mut served = Vec::new();
for name in self.files_logged()? {
let dir = self.log_dir(&name);
if copies.contains(&name) || (!copy::is_copy(&dir) && !segments_in(&dir)?.is_empty()) {
served.push(name);
}
}
Ok(served)
}
pub(crate) fn files_logged_now(&self) -> Result<Vec<String>> {
let mut files = self.files_logged()?;
for name in lock(&self.logs).keys() {
if !files.contains(name) {
files.push(name.clone());
}
}
Ok(files)
}
pub(crate) fn granted(&self, file: &str, until: Instant) {
lock(&self.granted).insert(file.to_owned(), until);
}
pub(crate) fn claim_taken(self: &Arc<Self>, file: &str, epoch: u64) {
let (state, file) = (Arc::clone(self), file.to_owned());
self.spawn("tinystore node: claim", move || {
if !state.uses_catalog() {
return;
}
while !state.stopping() {
let Some(store) = state.store() else { return };
let address = state.address();
let claim = Claim { file: &file, node: &state.id, address: &address, epoch };
match state.catalog(&store).and_then(|catalog| catalog.claim(&store, &claim)) {
Ok(home) if home.node == state.id => return,
Ok(home) => {
tracing::error!(
target: "tinystore",
%file,
epoch,
other = %home.node,
"the catalog names another home of a file this node took by its lease: it becomes that home's copy"
);
state.step_back(&store, &file, &home);
return;
}
Err(error) => tracing::debug!(target: "tinystore", %file, %error, "a node's claim of a file it took waits for the catalog"),
}
drop(store);
state.pause(Duration::from_secs(2));
}
});
}
fn step_back(self: &Arc<Self>, store: &Store, file: &str, home: &super::catalog::Home) {
let stepped = self.fence(file, home.epoch.max(1)).and_then(|()| {
let ours = self.point_of(file).ok_or_else(|| Error::not_found(format!("{file}: its log")))?;
super::handover::let_go(self, store, file, &home.address, ours)
});
if let Err(error) = stepped {
tracing::error!(
target: "tinystore",
file,
%error,
"a node could not become a copy of the home the catalog names",
);
}
}
pub(crate) fn epoch_written(&self, file: &str) -> Option<u64> {
lock(&self.logs).get(file).and_then(Weak::upgrade).map(|log| log.epoch())
}
pub(crate) fn epoch_held(&self, file: &str) -> Option<u64> {
if let Some(epoch) = self.epoch_written(file) {
lock(&self.epochs).insert(file.to_owned(), epoch);
return Some(epoch);
}
if let Some(&epoch) = lock(&self.epochs).get(file) {
return Some(epoch);
}
if !self.log_dir(file).exists() {
return None;
}
let epoch = self.epoch_of(file).ok()?;
lock(&self.epochs).insert(file.to_owned(), epoch);
Some(epoch)
}
pub(crate) fn lease_until(&self, file: &str, until: Instant) {
if let Some(log) = lock(&self.logs).get(file).and_then(Weak::upgrade) {
log.lease_until(until);
}
}
#[cfg(test)]
#[allow(dead_code, reason = "the link tests call it, and they build only with every engine")]
pub(crate) fn lease_of(&self, file: &str) -> Option<Instant> {
lock(&self.logs).get(file).and_then(Weak::upgrade).and_then(|log| log.leased_until())
}
fn files_logged(&self) -> Result<Vec<String>> {
files_logged_in(&self.dir.join(DIR))
}
pub(crate) fn source(&self, name: &str) -> Option<Box<dyn Source>> {
if let Some(copy) = self.copy(name) {
return Some(Box::new(CopySource(copy)));
}
let dir = self.log_dir(name);
if copy::is_copy(&dir) || !dir.exists() {
return None;
}
let log = lock(&self.logs).get(name).and_then(Weak::upgrade);
Some(Box::new(HomeSource { path: self.dir.join(name), dir, log }))
}
pub(crate) fn point_of(&self, name: &str) -> Option<Point> {
self.source(name).and_then(|source| source.stable().ok())
}
}
pub(crate) fn files_logged_in(logs: &Path) -> Result<Vec<String>> {
let mut names = Vec::new();
walk(logs, "", &mut names)?;
names.sort();
Ok(names)
}
fn walk(dir: &Path, prefix: &str, names: &mut Vec<String>) -> Result<()> {
let listed = match fs::read_dir(dir) {
Ok(listed) => listed,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(Error::io(dir.display().to_string(), error)),
};
for found in listed {
let found = found.map_err(|error| Error::io(dir.display().to_string(), error))?;
let Ok(name) = found.file_name().into_string() else { continue };
if !found.file_type().is_ok_and(|kind| kind.is_dir()) {
continue;
}
let path = found.path();
let joined = if prefix.is_empty() { name } else { format!("{prefix}/{name}") };
let holds_a_log =
copy::is_copy(&path) || !segments_in(&path)?.is_empty() || path.join(super::promote::PROMOTED).exists();
if holds_a_log {
names.push(joined);
} else {
walk(&path, &joined, names)?;
}
}
Ok(())
}
struct HomeSource {
path: PathBuf,
dir: PathBuf,
log: Option<Arc<Log>>,
}
impl Source for HomeSource {
fn path(&self) -> &Path {
&self.path
}
fn stable(&self) -> Result<Point> {
if let Some(log) = &self.log {
return Ok(log.stable());
}
if fs::metadata(crate::sqlite::wal_of(&self.path)).is_ok_and(|wal| wal.len() > 0) {
return Err(Error::new(
ErrorKind::Unavailable,
"its WAL holds commits its log may lack until its engine opens it",
));
}
Log::last_in(&self.dir)?.ok_or_else(|| Error::new(ErrorKind::Unavailable, "its log holds no entry yet"))
}
}
struct CopySource(Arc<Copy>);
impl Source for CopySource {
fn path(&self) -> &Path {
self.0.path()
}
fn stable(&self) -> Result<Point> {
Ok(self.0.point())
}
}
impl crate::probe::Sample for State {
fn sample(&self, probe: &crate::probe::Probe) {
let logs: Vec<(String, Arc<Log>)> =
lock(&self.logs).iter().filter_map(|(name, log)| Some((name.clone(), log.upgrade()?))).collect();
for (name, log) in logs {
let file = crate::probe::label(&name);
for (node, behind) in self.acks.behind(&name, log.last()) {
let labels = [("file", file.as_str()), ("node", node.as_str())];
probe.set("tinystore_replication_behind_entries", &labels, behind as f64);
}
}
}
}