use std::time::{Duration, Instant};
use super::message::{Message, Refusal};
use super::node::State;
use crate::{Error, ErrorKind, Result, Store};
pub(crate) const MAKE: u8 = 0;
pub(crate) const BATCH: u8 = 6;
pub(crate) const CATALOG: u8 = 7;
pub(crate) const HANDOVER: u8 = 8;
#[cfg(feature = "kv")]
pub(crate) const KV: u8 = 1;
#[cfg(feature = "sql")]
pub(crate) const SQL: u8 = 2;
#[cfg(feature = "search")]
pub(crate) const SEARCH: u8 = 3;
#[cfg(feature = "jobs")]
pub(crate) const JOBS: u8 = 4;
#[cfg(feature = "blobs")]
pub(crate) const BLOBS: u8 = 5;
const ANSWER_WAIT: Duration = Duration::from_secs(30);
const APPLIED_WAIT: Duration = Duration::from_secs(10);
pub(crate) struct Outcome {
pub(crate) result: std::result::Result<Vec<u8>, Error>,
pub(crate) waits: Vec<(String, u64)>,
}
impl Outcome {
pub(crate) fn into_message(self, id: u64) -> Message {
let outcome = self.result.map_err(|error| Refusal::of(&error));
Message::Written { id, outcome, waits: self.waits }
}
}
pub(crate) fn pass_on(store: &Store, file: &str, op: Vec<u8>) -> Result<Vec<u8>> {
pass_on_held(store, file, op).map(|(answer, _)| answer)
}
pub(crate) fn pass_on_held(store: &Store, file: &str, op: Vec<u8>) -> Result<(Vec<u8>, bool)> {
let node = toward_home(store, file)?;
let written = node.write_toward(file, op, ANSWER_WAIT).map_err(|error| error.within(file))?;
let answer = written.outcome.map_err(Refusal::into_error)?;
let mut held = true;
for (name, sequence) in &written.waits {
held &= wait_applied(node, name, *sequence);
}
Ok((answer, held))
}
#[cfg(feature = "kv")]
pub(crate) fn pass_on_then(
store: &Store,
file: &str,
op: Vec<u8>,
answered: impl FnOnce(Option<Result<Vec<u8>>>) + Send + 'static,
) -> Result<()> {
let node = toward_home(store, file)?;
let answered = Box::new(move |written: Option<super::follow::Written>| {
answered(written.map(|written| written.outcome.map_err(Refusal::into_error)));
});
node.write_toward_then(file, op, answered).map_err(|error| error.within(file))
}
#[cfg(feature = "kv")]
pub(crate) fn pass_on_all_then(
store: &Store,
file: &str,
requests: &[Vec<u8>],
answered: impl FnOnce(Option<Result<Vec<u8>>>) + Send + 'static,
) -> Result<()> {
pass_on_then(store, file, batch(requests), answered)
}
fn toward_home<'a>(store: &'a Store, file: &str) -> Result<&'a std::sync::Arc<State>> {
if store.is_beside() {
return Err(Error::invalid(format!(
"{file}: the store is opened beside the process that holds it, and reads only"
)));
}
let Some(node) = store.node() else {
return Err(Error::invalid(format!("{file} is a copy, and the store is no node to pass its writes on")));
};
if node.options.from.is_empty() && !node.follows_directly(file) {
return Err(Error::new(
ErrorKind::Unavailable,
format!("{file} is a copy, and this node takes from no node its writes could go to"),
));
}
Ok(node)
}
pub(crate) fn make(node: &State, name: &str) -> Result<()> {
let written = node.write_toward(name, make_op(name), ANSWER_WAIT)?;
written.outcome.map(drop).map_err(Refusal::into_error)
}
fn make_op(name: &str) -> Vec<u8> {
let mut out = super::Out(vec![MAKE]);
out.text(name);
out.0
}
pub(crate) fn catching_up(store: &Store, file: &str) -> crate::sqlite::CatchUp {
let (store, file) = (store.downgrade(), file.to_owned());
crate::sqlite::CatchUp(std::sync::Arc::new(move || {
let store = store.upgrade().ok_or_else(|| Error::closed(format!("{file}: the node's store")))?;
match pass_on_held(&store, &file, make_op(&file))? {
(_, true) => Ok(()),
(_, false) => Err(Error::new(ErrorKind::Unavailable, format!("{file}: the copy did not reach its home"))),
}
}))
}
pub(crate) fn tag_of(history: &str) -> Option<u8> {
match history {
#[cfg(feature = "kv")]
"kv" => Some(KV),
#[cfg(feature = "jobs")]
"jobs" => Some(JOBS),
_ => None,
}
}
pub(crate) fn make_in(store: &Store, file: &str, tag: u8) -> Result<()> {
let mut out = super::Out(vec![MAKE]);
out.text(file);
out.byte(tag);
pass_on(store, file, out.0).map(drop)
}
#[cfg(any(feature = "kv", feature = "jobs"))]
fn make_in_here(lenders: Lenders<'_>, file: &str, tag: u8) -> Result<()> {
let Some(database) = file.strip_prefix("sql/").and_then(|name| name.strip_suffix(".db")) else {
return Err(Error::invalid(format!("{file} is no database's file to keep an engine's tables")));
};
let home = lenders(database)?;
match tag {
#[cfg(feature = "kv")]
KV => crate::kv::forward::make_in(&home),
#[cfg(feature = "jobs")]
JOBS => crate::jobs::forward::make_in(&home),
_ => {
let _ = home;
Err(Error::invalid(format!("an engine this node keeps in no database's file, tag {tag}")))
}
}
}
fn wait_applied(node: &State, name: &str, sequence: u64) -> bool {
let deadline = Instant::now() + APPLIED_WAIT;
loop {
let seen = node.notify.seen();
match node.copy(name) {
Some(copy) if copy.applied() >= sequence => return true,
None => return true,
Some(_) => {}
}
if node.stopping() {
return false;
}
let now = Instant::now();
if now >= deadline {
tracing::warn!(
target: "tinystore",
file = name,
entry = sequence,
"a write its home committed answered before this node's copy held it: the copy is behind"
);
return false;
}
node.notify.wait_past(seen, deadline - now);
}
}
pub(crate) fn run(state: &State, op: &[u8]) -> Outcome {
let ran = match state.store() {
Some(store) => run_all(&store, op),
None => Err(Error::closed("the node's store")),
};
match ran {
Ok((answer, files)) => {
let waits = files
.into_iter()
.filter_map(|file| state.point_of(&file).map(|point| (file, point.sequence)))
.collect();
Outcome { result: Ok(answer), waits }
}
Err(error) => Outcome { result: Err(error), waits: Vec::new() },
}
}
fn run_all(store: &Store, op: &[u8]) -> Result<(Vec<u8>, Vec<String>)> {
if op.first() != Some(&BATCH) {
return run_on(store, op).map(|(answer, file)| (answer, vec![file]));
}
let mut at = super::In { bytes: &op[1..], at: 0 };
let (mut answers, mut files) = (super::Out(Vec::new()), Vec::new());
let count = at.count()?;
answers.count(count);
for _ in 0..count {
let (answer, file) = run_on(store, at.bytes()?)?;
answers.bytes(&answer);
if !files.contains(&file) {
files.push(file);
}
}
Ok((answers.0, files))
}
pub(crate) fn from_node(mut request: Vec<u8>, node: &str, op: u64) -> Vec<u8> {
let mut tail = super::Out(Vec::new());
tail.text(node);
tail.long(op);
request.extend_from_slice(&tail.0);
request
}
pub(crate) fn pass_on_all(store: &Store, file: &str, requests: &[Vec<u8>]) -> Result<()> {
let (_, held) = pass_on_held(store, file, batch(requests))?;
if held {
return Ok(());
}
Err(Error::new(
ErrorKind::Unavailable,
format!("{file}: its home applied the node's queued writes, and its copy does not hold them yet"),
))
}
pub(crate) fn run_here(store: &Store, requests: &[Vec<u8>]) -> Result<()> {
run_all(store, &batch(requests)).map(drop)
}
fn batch(requests: &[Vec<u8>]) -> Vec<u8> {
let mut out = super::Out(vec![BATCH]);
out.count(requests.len());
for request in requests {
out.bytes(request);
}
out.0
}
pub(crate) fn enqueue(store: &Store, file: &str, subject: Vec<u8>, request: Vec<u8>) -> Result<u64> {
let node = store.node().ok_or_else(|| Error::invalid(format!("{file} is a copy, and the store is no node")))?;
node.queue()?.push(file, subject, request)
}
pub(crate) struct Pending {
pub(crate) node: String,
pub(crate) ops: Vec<super::queue::Queued>,
}
pub(crate) fn queued(store: &Store, file: &str, subject: &[u8]) -> Result<Pending> {
match store.node() {
Some(node) => {
let queue = node.queue()?;
Ok(Pending { node: queue.node.clone(), ops: queue.of_subject(file, subject)? })
}
None => Ok(Pending { node: String::new(), ops: Vec::new() }),
}
}
fn make_here(store: &Store, name: &str) -> Result<()> {
#[cfg(feature = "kv")]
if name == crate::kv::forward::FILE {
return crate::kv::forward::make(store);
}
#[cfg(feature = "jobs")]
if name == crate::jobs::forward::FILE {
return crate::jobs::forward::make(store);
}
#[cfg(feature = "search")]
if name == crate::search::forward::FILE {
return crate::search::forward::make(store);
}
#[cfg(feature = "sql")]
if let Some(database) = name.strip_prefix("sql/").and_then(|name| name.strip_suffix(".db")) {
return store.database(database).open().map(drop);
}
let _ = store;
Err(Error::not_found(format!("{name}: no engine of this node keeps such a file")))
}
#[cfg(any(feature = "kv", feature = "jobs"))]
pub(crate) type Lenders<'a> = &'a dyn Fn(&str) -> Result<crate::engine::Home>;
pub(crate) use crate::engine::database_file;
pub(crate) fn database_of(owner: &str) -> Option<&str> {
owner.strip_prefix("sql ")
}
fn run_on(store: &Store, op: &[u8]) -> Result<(Vec<u8>, String)> {
#[cfg(all(feature = "sql", any(feature = "kv", feature = "jobs")))]
let lenders = |name: &str| -> Result<crate::engine::Home> {
let database = store.database(name).open()?;
Ok(crate::engine::Home::Shared(std::sync::Arc::clone(database.shared())))
};
#[cfg(all(not(feature = "sql"), any(feature = "kv", feature = "jobs")))]
let lenders = |name: &str| -> Result<crate::engine::Home> {
Err(Error::invalid(format!("a write of database {name}'s file, and this node has no sql")))
};
#[cfg(any(feature = "kv", feature = "jobs"))]
let _ = &lenders;
let Some((&tag, body)) = op.split_first() else {
return Err(Error::corrupt("a write passed on holds nothing"));
};
match tag {
MAKE => {
let mut at = super::In { bytes: body, at: 0 };
let file = at.text()?;
if at.done() {
make_here(store, &file)?;
} else {
#[cfg(any(feature = "kv", feature = "jobs"))]
make_in_here(&lenders, &file, at.byte()?)?;
#[cfg(not(any(feature = "kv", feature = "jobs")))]
return Err(Error::invalid(format!("{file}: no engine of this node keeps its tables in a database")));
}
Ok((Vec::new(), file))
}
CATALOG => super::catalog::run(store, body),
HANDOVER => super::handover::run(store, op),
#[cfg(feature = "kv")]
KV => crate::kv::forward::run(store, &lenders, body),
#[cfg(feature = "sql")]
SQL => crate::sql::forward::run(store, body),
#[cfg(feature = "blobs")]
BLOBS => crate::blobs::forward::run(store, body).map(|answer| (answer, crate::blobs::forward::FILE.to_owned())),
#[cfg(feature = "jobs")]
JOBS => crate::jobs::forward::run(store, &lenders, body),
#[cfg(feature = "search")]
SEARCH => {
crate::search::forward::run(store, body).map(|answer| (answer, crate::search::forward::FILE.to_owned()))
}
_ => {
let _ = (store, body);
Err(Error::new(ErrorKind::Invalid, format!("a write of an engine this node does not have, tag {tag}")))
}
}
}