use ckb_spawn::Spawn;
use ckb_stop_handler::{SignalSender, StopHandler};
use core::future::Future;
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
use tokio::runtime::Builder;
use tokio::runtime::Handle as TokioHandle;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
pub use tokio;
pub use tokio::runtime::Runtime;
#[derive(Debug, Clone)]
pub struct Handle {
pub(crate) inner: TokioHandle,
}
impl Handle {
pub fn enter<F, R>(&self, f: F) -> R
where
F: FnOnce() -> R,
{
let _enter = self.inner.enter();
f()
}
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.inner.spawn(future)
}
pub fn block_on<F: Future>(&self, future: F) -> F::Output {
self.inner.block_on(future)
}
pub fn spawn_blocking<F, R>(&self, f: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
self.inner.spawn_blocking(f)
}
pub fn into_inner(self) -> TokioHandle {
self.inner
}
}
fn new_runtime() -> Runtime {
Builder::new_multi_thread()
.enable_all()
.thread_name_fn(|| {
static ATOMIC_ID: AtomicU32 = AtomicU32::new(0);
let id = ATOMIC_ID
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
if n >= 999_999 {
Some(0)
} else {
Some(n + 1)
}
})
.expect("impossible since the above closure must return Some(number)");
format!("GlobalRt-{id}")
})
.build()
.expect("ckb runtime initialized")
}
pub fn new_global_runtime() -> (Handle, Runtime) {
let runtime = new_runtime();
let handle = runtime.handle().clone();
(Handle { inner: handle }, runtime)
}
pub fn new_background_runtime() -> (Handle, StopHandler<()>) {
let runtime = new_runtime();
let handle = runtime.handle().clone();
let (tx, rx) = oneshot::channel();
let thread = thread::Builder::new()
.name("GlobalRtBuilder".to_string())
.spawn(move || {
let ret = runtime.block_on(rx);
ckb_logger::debug!("global runtime finish {:?}", ret);
})
.expect("tokio runtime started");
(
Handle { inner: handle },
StopHandler::new(SignalSender::Tokio(tx), Some(thread), "GT".to_string()),
)
}
impl Spawn for Handle {
fn spawn_task<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
{
self.spawn(future);
}
}