use std::fmt;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use crate::capability::HNil;
use crate::failure::{Cause, Defect, Exit};
use crate::kernel::{
Effect, Node, cause_from_panic, hnil_env, settle_instr, to_exit, unerase_exit,
};
use crate::runtime::{Executor, FiberContext, FiberHandle, TokioExecutor};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockOnInAsync;
impl fmt::Display for BlockOnInAsync {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(
"id_effect: block_on called inside an async context (tokio task or runtime context); \
use `Runtime::run(..).await` instead",
)
}
}
impl std::error::Error for BlockOnInAsync {}
struct Park(Thread);
impl Wake for Park {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.unpark();
}
}
pub(crate) fn in_async_context() -> bool {
::tokio::task::try_id().is_some() || ::tokio::runtime::Handle::try_current().is_ok()
}
pub(crate) fn park_on<F: Future>(fut: F) -> F::Output {
let waker = Waker::from(Arc::new(Park(thread::current())));
let mut cx = Context::from_waker(&waker);
let mut fut = std::pin::pin!(fut);
loop {
if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
return v;
}
thread::park();
}
}
fn settle<A, E>(eff: Effect<A, E, HNil>) -> Result<Exit<A, E>, Effect<A, E, HNil>>
where
A: Send + 'static,
E: Send + 'static,
{
let mut node = match eff.node {
Node::Pure(r) => return Ok(to_exit(r)),
node => node,
};
let out = catch_unwind(AssertUnwindSafe(move || {
loop {
match node {
Node::Pure(r) => return Ok(r),
Node::Sync(f, _) => node = f(&HNil).node,
Node::Op(i) => return Err(i),
}
}
}));
let instr = match out {
Ok(Ok(r)) => return Ok(to_exit(r)),
Ok(Err(i)) => i,
Err(payload) => return Ok(Exit::Failure(cause_from_panic(payload))),
};
match settle_instr(instr, hnil_env()) {
Ok(exit) => Ok(to_exit(unerase_exit::<A, E>(exit))),
Err(rest) => Err(Effect::from_instr(rest)),
}
}
fn drive_root<A, E>(
exec: Arc<dyn Executor>,
eff: Effect<A, E, HNil>,
) -> impl Future<Output = Exit<A, E>> + Send + 'static
where
A: Send + 'static,
E: Send + 'static,
{
eff.run_fiber(FiberContext::new_root(exec))
}
struct OwnedTokio(Option<::tokio::runtime::Runtime>);
impl Drop for OwnedTokio {
fn drop(&mut self) {
if let Some(rt) = self.0.take() {
rt.shutdown_background();
}
}
}
#[derive(Clone)]
pub struct Runtime {
exec: Arc<dyn Executor>,
owned: Option<Arc<OwnedTokio>>,
}
impl fmt::Debug for Runtime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Runtime")
.field("owns_tokio_runtime", &self.owned.is_some())
.finish_non_exhaustive()
}
}
impl Runtime {
pub fn new() -> std::io::Result<Self> {
let rt = ::tokio::runtime::Builder::new_multi_thread()
.enable_all()
.thread_name("id-effect-next")
.build()?;
Ok(Self {
exec: Arc::new(TokioExecutor::new(rt.handle().clone())),
owned: Some(Arc::new(OwnedTokio(Some(rt)))),
})
}
pub fn from_executor(exec: Arc<dyn Executor>) -> Self {
Self { exec, owned: None }
}
pub fn global() -> &'static Runtime {
static GLOBAL: OnceLock<Runtime> = OnceLock::new();
GLOBAL
.get_or_init(|| Runtime::new().expect("id_effect: cannot start the default tokio runtime"))
}
pub fn executor(&self) -> &Arc<dyn Executor> {
&self.exec
}
pub fn run<A, E>(
&self,
eff: Effect<A, E, HNil>,
) -> impl Future<Output = Exit<A, E>> + Send + 'static
where
A: Send + 'static,
E: Send + 'static,
{
let exec = Arc::clone(&self.exec);
async move {
match eff.node {
Node::Pure(r) => to_exit(r),
node => drive_root(exec, Effect { node }).await,
}
}
}
pub fn try_block_on<A, E>(&self, eff: Effect<A, E, HNil>) -> Result<Exit<A, E>, BlockOnInAsync>
where
A: Send + 'static,
E: Send + 'static,
{
if in_async_context() {
return Err(BlockOnInAsync);
}
Ok(match settle(eff) {
Ok(exit) => exit,
Err(eff) => park_on(drive_root(Arc::clone(&self.exec), eff)),
})
}
#[allow(
clippy::disallowed_methods,
reason = "G-nb: the blocking edge itself, delegating to `try_block_on`"
)]
pub fn block_on<A, E>(&self, eff: Effect<A, E, HNil>) -> Exit<A, E>
where
A: Send + 'static,
E: Send + 'static,
{
self
.try_block_on(eff)
.unwrap_or_else(|e| Exit::Failure(Cause::Die(Defect::new(e.to_string()))))
}
pub fn fork<A, E>(&self, eff: Effect<A, E, HNil>) -> FiberHandle<A, E>
where
A: Send + 'static,
E: Send + 'static,
{
eff.fork_root(Arc::clone(&self.exec))
}
pub fn block_on_future<F: Future>(&self, fut: F) -> Result<F::Output, BlockOnInAsync> {
if in_async_context() {
return Err(BlockOnInAsync);
}
Ok(park_on(fut))
}
}