use std::sync::Arc;
use crate::{Error, ErrorKind, Result};
pub(crate) type Job = Box<dyn FnOnce() + Send>;
pub(crate) type Lead = Arc<dyn Fn(Job) + Send + Sync>;
#[cfg(feature = "async")]
thread_local! {
static LEAD: std::cell::RefCell<Option<Lead>> = const { std::cell::RefCell::new(None) };
static WAITS: std::cell::Cell<Waits> = const { std::cell::Cell::new(Waits::Allowed) };
}
#[cfg(feature = "async")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Waits {
Allowed,
Forbidden,
Refused { met: bool },
}
#[cfg(feature = "async")]
pub(crate) fn leading_on<T>(lead: &Lead, call: impl FnOnce() -> T) -> T {
let _scope = Scope::enter(Some(Arc::clone(lead)), Waits::Forbidden);
call()
}
#[cfg(feature = "async")]
pub(crate) fn without_waiting<T>(call: impl FnOnce() -> T) -> Option<T> {
let scope = Scope::enter(None, Waits::Refused { met: false });
let answer = call();
let met = WAITS.get() == Waits::Refused { met: true };
drop(scope);
(!met).then_some(answer)
}
#[cfg(feature = "async")]
pub(crate) fn lead() -> Option<Lead> {
LEAD.with(|lead| lead.borrow().clone())
}
#[cfg(not(feature = "async"))]
pub(crate) fn lead() -> Option<Lead> {
None
}
#[cfg(feature = "async")]
pub(crate) fn waits_refused() -> bool {
matches!(WAITS.get(), Waits::Refused { .. })
}
#[cfg(not(feature = "async"))]
pub(crate) fn waits_refused() -> bool {
false
}
#[cfg(feature = "async")]
pub(crate) fn may_wait(what: impl FnOnce() -> String) -> Result<()> {
match WAITS.get() {
Waits::Allowed => Ok(()),
Waits::Refused { .. } => Err(refused(what)),
Waits::Forbidden => Err(Error::internal(format!(
"{}: an awaited write's submit would wait on the thread that polls it: \
what reads or waits runs before the submit, on the store's pool",
what()
))),
}
}
#[cfg(not(feature = "async"))]
pub(crate) fn may_wait(_what: impl FnOnce() -> String) -> Result<()> {
Ok(())
}
pub(crate) fn refused(what: impl FnOnce() -> String) -> Error {
#[cfg(feature = "async")]
WAITS.set(Waits::Refused { met: true });
Error::new(ErrorKind::Unavailable, format!("{}: it would wait, and its call runs elsewhere", what()))
}
#[cfg(feature = "async")]
struct Scope {
lead: Option<Lead>,
waits: Waits,
}
#[cfg(feature = "async")]
impl Scope {
fn enter(lead: Option<Lead>, waits: Waits) -> Scope {
let outer = LEAD.with(|scope| std::mem::replace(&mut *scope.borrow_mut(), lead));
Scope { lead: outer, waits: WAITS.replace(waits) }
}
}
#[cfg(feature = "async")]
impl Drop for Scope {
fn drop(&mut self) {
let outer = self.lead.take();
LEAD.with(|scope| *scope.borrow_mut() = outer);
WAITS.set(self.waits);
}
}