use std::sync::Arc;
use std::time::{Duration, Instant};
use super::catalog::{Claim, Home};
use super::copy::{self, Copy, Position};
use super::entry::Point;
use super::forward;
use super::log::Log;
use super::message::{In, Out};
use super::node::State;
use crate::sync::lock;
use crate::{Error, ErrorKind, Result, Store};
const TAKEN_WITHIN: Duration = if cfg!(test) { Duration::from_secs(2) } else { Duration::from_secs(60) };
const ASK_AGAIN: Duration = Duration::from_secs(5);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Moved {
pub file: String,
pub sequence: u64,
pub epoch: u64,
}
pub fn move_home(store: &Store, file: &str) -> Result<Moved> {
let what = || format!("move {file} to this node");
let node = store.node().ok_or_else(|| Error::invalid("a store that is no node").within(what()))?;
let copy = node
.copy(file)
.ok_or_else(|| Error::new(ErrorKind::Unavailable, "this node holds no whole copy of it").within(what()))?;
let address = node.address();
if address.is_empty() || !node.uses_catalog() {
let why = "a live move needs a catalog, and a node that serves its address";
return Err(Error::invalid(why).within(what()));
}
let catalog = node.catalog(store).map_err(|error| error.within(what()))?;
let old =
catalog.home_of(file)?.ok_or_else(|| Error::not_found("the catalog names no home of it").within(what()))?;
if old.node == node.id {
return finish(store, node, file, copy, old.epoch).map_err(|error| error.within(what()));
}
let last = match hand_over(store, node, file, ©) {
Ok(last) => last,
Err((error, fenced)) => {
if let Some(last) = fenced {
call_off_for(store, node, &old, file, last);
}
return Err(error.within(what()));
}
};
let epoch = last.epoch.max(old.epoch) + 1;
let claim = Claim { file, node: &node.id, address: &address, epoch };
let unknown = "its claim's outcome is unknown: call move_home again, which finishes a move the catalog names";
let home = catalog.claim(store, &claim).map_err(|error| error.within(unknown).within(what()))?;
if home.node != node.id {
let why = "the old home called the move off before this node's claim reached the catalog";
return Err(Error::new(ErrorKind::Conflict, why).within(what()));
}
finish(store, node, file, copy, epoch).map_err(|error| error.within(what()))
}
fn finish(store: &Store, node: &Arc<State>, file: &str, copy: Arc<Copy>, epoch: u64) -> Result<Moved> {
let sequence = copy.point().sequence;
let again = "the catalog names this node its home: call move_home again to finish";
node.take_over_at(store, file, copy, epoch).map_err(|error| error.within(again))?;
tracing::info!(target: "tinystore", file, sequence, epoch, "a file's home moved to this node");
Ok(Moved { file: file.to_owned(), sequence, epoch })
}
fn call_off_for(store: &Store, node: &State, old: &Home, file: &str, last: Point) {
let epoch = last.epoch.max(old.epoch) + 1;
let claim = Claim { file, node: &old.node, address: &old.address, epoch };
if let Err(error) = node.catalog(store).and_then(|catalog| catalog.claim(store, &claim)) {
tracing::warn!(target: "tinystore", file, %error, "a node could not call a move off: its old home will");
}
}
pub(super) fn hand_over(
store: &Store,
node: &State,
file: &str,
copy: &Copy,
) -> std::result::Result<Point, (Error, Option<Point>)> {
let mut op = Out(vec![forward::HANDOVER]);
op.text(file);
op.text(&node.id);
let (answer, held) = forward::pass_on_held(store, file, op.0).map_err(|error| (error, None))?;
let last = In { bytes: &answer, at: 0 }.point().map_err(|error| (error, None))?;
if !held || copy.point() != last {
let why = format!("this node's copy does not hold the home's last commit, {}: the move stops", last.sequence);
return Err((Error::new(ErrorKind::Unavailable, why), Some(last)));
}
Ok(last)
}
pub(crate) fn run(store: &Store, op: &[u8]) -> Result<(Vec<u8>, String)> {
let mut at = In { bytes: &op[1..], at: 0 };
let (file, to) = (at.text()?, at.text()?);
let state = store.node().ok_or_else(|| Error::invalid("a move asked of a store that is no node"))?;
if copy::is_copy(&state.log_dir(&file)) {
return Ok((forward::pass_on(store, &file, op.to_vec())?, file));
}
let held =
state.point_of(&file).ok_or_else(|| Error::not_found(format!("{file}: this node writes no such file")))?;
state.fence(&file, held.epoch + 1)?;
let last = state.point_of(&file).ok_or_else(|| Error::not_found(format!("{file}: its log")))?;
let watching = Arc::clone(state);
let watched = file.clone();
state.spawn("tinystore node: handover", move || let_go_once_taken(&watching, &watched, &to, last));
let mut answer = Out(Vec::new());
answer.point(&last);
Ok((answer.0, file))
}
fn let_go_once_taken(state: &Arc<State>, file: &str, to: &str, last: Point) {
let mut deadline = Instant::now() + TAKEN_WITHIN;
let mut said = false;
while !state.stopping() {
let Some(store) = state.store() else {
return;
};
let mut home = state.catalog(&store).and_then(|catalog| catalog.home_of(file)).ok().flatten();
if Instant::now() >= deadline && home.as_ref().is_none_or(|home| home.epoch <= last.epoch) {
deadline = Instant::now() + ASK_AGAIN;
let claim = Claim { file, node: &state.id, address: &state.address(), epoch: last.epoch + 1 };
match state.catalog(&store).and_then(|catalog| catalog.claim(&store, &claim)) {
Ok(claimed) => home = Some(claimed),
Err(error) if !said => {
said = true;
tracing::warn!(
target: "tinystore",
file,
%error,
"a move went silent and the catalog cannot be reached: this node stays fenced",
);
}
Err(_) => {}
}
}
if let Some(home) = home.filter(|home| home.epoch > last.epoch && (home.node == to || home.node == state.id)) {
act_on_home(state, &store, file, &home, last);
return;
}
drop(store);
std::thread::sleep(Duration::from_millis(100));
}
}
fn act_on_home(state: &Arc<State>, store: &Store, file: &str, home: &Home, last: Point) {
if home.node != state.id {
if let Err(error) = let_go(state, store, file, &home.address, last) {
tracing::error!(target: "tinystore", file, %error, "a node could not make a file it handed over a copy");
}
return;
}
match state.go_on_at(file, home.epoch) {
Ok(()) => {
tracing::warn!(target: "tinystore", file, epoch = home.epoch, "a move was called off: this node writes the file again")
}
Err(error) => tracing::error!(target: "tinystore", file, %error, "a node could not write a file again"),
}
}
pub(crate) fn let_go(state: &Arc<State>, store: &Store, file: &str, address: &str, last: Point) -> Result<()> {
let dir = state.log_dir(file);
let _rerouting = state.wait_to_reroute(file)?;
let paused = state.pause_readers(file)?;
state.switch_each(file, |switch| switch.become_copy())?;
Log::unfence_in(&dir)?;
super::promote::forget_promotion(&dir)?;
copy::mark(&dir)?;
let wal = crate::sqlite::wal_end(&store.dir().join(file))?;
Position::read(dir.join(Position::FILE))?.keep_durably_at(last, wal)?;
state.keep_copy(file, Arc::new(Copy::open(store, file)?));
drop(paused);
store.applied(file);
let from = lock(&state.upstream_at).clone();
if from.as_deref() != Some(address) {
state.take_directly(store, file, address)?;
}
state.ask_for_what_is_served();
tracing::info!(target: "tinystore", file, to = address, "a node handed a file's home over, and copies it");
Ok(())
}