use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::time::Duration;
use super::oneshot::{Answer, pending};
use crate::cancel::{self, Captured};
use crate::memory::PATIENCE;
use crate::polled::{self, Lead};
use crate::pool::Pool;
use crate::{CancellationToken, Error, Memory, Reservation, Result};
#[allow(dead_code, reason = "the engines' async point reads are built on it")]
pub(crate) fn point<T, R>(
pool: &Arc<Pool>,
what: String,
read: R,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, R>
where
R: Fn() -> Result<T> + Send + 'static,
T: Send + 'static,
{
let (tokens, pool) = (cancel::captured(), Arc::clone(pool));
async move {
if let Some(answer) = polled::without_waiting(|| tokens.run(None, &read)) {
return answer;
}
on_the_pool(pool, tokens, what, read).await
}
}
#[allow(dead_code, reason = "kv's awaited steps in memory are built on it")]
pub(crate) fn step<T, S>(pool: &Arc<Pool>, what: String, step: S) -> impl Future<Output = Result<T>> + Send + 'static
where
S: Fn() -> Result<T> + Send + 'static,
T: Send + 'static,
{
let (tokens, pool) = (cancel::captured(), Arc::clone(pool));
async move {
if let Some(answer) = polled::without_waiting(|| tokens.run(None, &step)) {
return answer;
}
blocking(&pool, None, what, move || tokens.run(None, step)).await
}
}
#[allow(dead_code, reason = "the engines' async reads are built on it")]
pub(crate) fn read<T, R>(
pool: &Arc<Pool>,
what: String,
read: R,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, R>
where
R: FnOnce() -> Result<T> + Send + 'static,
T: Send + 'static,
{
on_the_pool(Arc::clone(pool), cancel::captured(), what, read)
}
async fn on_the_pool<T, R>(pool: Arc<Pool>, tokens: Captured, what: String, read: R) -> Result<T>
where
R: FnOnce() -> Result<T> + Send + 'static,
T: Send + 'static,
{
refuse_inside_a_transaction(&what)?;
let token = CancellationToken::new();
let _dropped = CancelOnDrop(token.clone());
let (answer, answered) = pending(what);
pool.run(Box::new(move || {
if !answer.is_awaited() {
return;
}
match catch_unwind(AssertUnwindSafe(|| tokens.run(Some(&token), read))) {
Ok(outcome) => answer.send(outcome),
Err(payload) => answer.panicked(payload),
}
}));
answered.await
}
struct CancelOnDrop(CancellationToken);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
self.0.cancel();
}
}
#[allow(dead_code, reason = "the engines' async writes that hold memory reserve through it")]
pub(crate) fn reserve(
memory: &Arc<Memory>,
bytes: u64,
what: String,
patience: Duration,
) -> impl Future<Output = Result<Reservation>> + Send + 'static + use<> {
let memory = Arc::clone(memory);
async move {
let (answer, answered) = pending(what.clone());
let _waiting = memory.reserve_then(bytes, &what, patience, move |reserved| answer.send(reserved));
answered.await
}
}
#[allow(dead_code, reason = "the engines' async writes are built on it")]
pub(crate) fn write<T, S>(
pool: &Arc<Pool>,
what: String,
submit: S,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, S>
where
S: FnOnce(Answer<T>) + Send + 'static,
T: Send + 'static,
{
let lead = lead_on(pool);
async move {
let (answer, answered) = pending(what);
polled::leading_on(&lead, || submit(answer));
answered.await
}
}
pub(crate) fn lead_on(pool: &Arc<Pool>) -> Lead {
let pool = Arc::clone(pool);
Arc::new(move |job| pool.run_always(job))
}
#[allow(dead_code, reason = "the store's transactions run on it with kv or jobs, and the engines' blocking work")]
pub(crate) fn blocking<T, F>(
pool: &Arc<Pool>,
line: Option<String>,
what: String,
work: F,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, F>
where
F: FnOnce() -> Result<T> + Send + 'static,
T: Send + 'static,
{
let pool = Arc::clone(pool);
async move {
refuse_inside_a_transaction(&what)?;
let (answer, answered) = pending(what);
let job = Box::new(move || answer_with(answer, work));
match line {
Some(line) => pool.run_in_line(&line, job),
None => pool.run(job),
}
answered.await
}
}
const PASSED_ON: &str = "tinystore-passed-on";
#[allow(dead_code, reason = "the calls of kv and blobs passed on to a copy's home run on it")]
pub(crate) async fn passed_on<T, F>(what: String, call: F) -> Result<T>
where
F: FnOnce() -> Result<T> + Send + 'static,
T: Send + 'static,
{
refuse_inside_a_transaction(&what)?;
let (answer, answered) = pending(what.clone());
let started = own_thread(move || match catch_unwind(AssertUnwindSafe(call)) {
Ok(outcome) => answer.send(outcome),
Err(payload) => answer.panicked(payload),
});
if let Err(error) = started {
return Err(Error::io(format!("{what}: a thread to wait for the home's answer on"), error));
}
answered.await
}
#[cfg(feature = "blobs")]
pub(crate) fn passed_on_in_line<A, T, Take, Call>(
pool: &Arc<Pool>,
line: String,
what: String,
(take, call): (Take, Call),
) -> impl Future<Output = Result<T>> + Send + 'static + use<A, T, Take, Call>
where
Take: FnOnce() -> Result<A> + Send + 'static,
Call: FnOnce(A) -> Result<T> + Send + 'static,
A: Send + 'static,
T: Send + 'static,
{
let pool = Arc::clone(pool);
async move {
refuse_inside_a_transaction(&what)?;
let (answer, answered) = pending(what.clone());
let job = Box::new(move || match catch_unwind(AssertUnwindSafe(take)) {
Ok(Ok(taken)) => pass_on_taken(what, answer, move || call(taken)),
Ok(Err(error)) => answer.send(Err(error)),
Err(payload) => answer.panicked(payload),
});
pool.run_in_line(&line, job);
answered.await
}
}
#[cfg(feature = "blobs")]
fn pass_on_taken<T: Send + 'static>(
what: String,
answer: Answer<T>,
call: impl FnOnce() -> Result<T> + Send + 'static,
) {
let handed = Arc::new(std::sync::Mutex::new(Some(answer)));
let answering = Arc::clone(&handed);
let started = own_thread(move || {
if let Some(answer) = crate::sync::lock(&answering).take() {
answer_with(answer, call);
}
});
if let Err(error) = started
&& let Some(answer) = crate::sync::lock(&handed).take()
{
answer.send(Err(Error::io(format!("{what}: a thread to wait for the home's answer on"), error)));
}
}
#[allow(dead_code, reason = "the calls of kv and blobs passed on to a copy's home run on it")]
pub(crate) fn own_thread(job: impl FnOnce() + Send + 'static) -> std::io::Result<()> {
std::thread::Builder::new().name(PASSED_ON.to_owned()).spawn(job).map(drop)
}
#[allow(dead_code, reason = "metrics' awaited ingest holds its memory through it")]
pub(crate) fn holding<T, P, W>(
pool: &Arc<Pool>,
memory: &Arc<Memory>,
what: String,
prepare: P,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, P, W>
where
P: FnOnce() -> Result<(u64, W)> + Send + 'static,
W: FnOnce(Reservation) -> Result<T> + Send + 'static,
T: Send + 'static,
{
let (pool, memory) = (Arc::clone(pool), Arc::clone(memory));
async move {
refuse_inside_a_transaction(&what)?;
let (answer, answered) = pending(what.clone());
let handing = Arc::clone(&pool);
pool.run(Box::new(move || match catch_unwind(AssertUnwindSafe(prepare)) {
Ok(Ok((bytes, work))) => match memory.try_reserve(bytes, &what) {
Ok(held) => answer_with(answer, || work(held)),
Err(_) => {
let served = move |reserved: Result<Reservation>| match reserved {
Ok(held) => handing.run(Box::new(move || answer_with(answer, || work(held)))),
Err(refused) => answer.send(Err(refused)),
};
memory.reserve_then(bytes, &what, PATIENCE, served).stay();
}
},
Ok(Err(refused)) => answer.send(Err(refused)),
Err(payload) => answer.panicked(payload),
}));
answered.await
}
}
fn answer_with<T>(answer: Answer<T>, work: impl FnOnce() -> Result<T>) {
match catch_unwind(AssertUnwindSafe(work)) {
Ok(outcome) => answer.send(outcome),
Err(payload) => answer.panicked(payload),
}
}
pub(crate) fn refuse_inside_a_transaction(what: &str) -> Result<()> {
if !crate::sqlite::in_a_transaction() {
return Ok(());
}
Err(Error::invalid(format!(
"{what}: an awaited call from inside a transaction would wait for the writer the transaction holds: \
make it through the transaction, tx.with(&handle)"
)))
}
#[cfg(test)]
#[path = "run_tests.rs"]
mod tests;