use std::{
any::Any,
cell::{Cell, RefCell},
collections::HashSet,
future::Future,
io,
ops::Deref,
panic::AssertUnwindSafe,
rc::Rc,
sync::Arc,
task::{Context, Poll, Waker},
time::Duration,
};
use async_task::Task;
use compio_buf::IntoInner;
use compio_driver::{
AsRawFd, DriverType, Extra, Key, OpCode, Proactor, ProactorBuilder, PushEntry, RawFd,
op::Asyncify,
};
use compio_log::{debug, instrument};
use futures_util::FutureExt;
mod future;
pub use future::Submit;
#[cfg(feature = "time")]
pub(crate) mod time;
mod buffer_pool;
pub use buffer_pool::*;
mod scheduler;
mod opt_waker;
pub use opt_waker::OptWaker;
mod send_wrapper;
use send_wrapper::SendWrapper;
#[cfg(feature = "time")]
use crate::runtime::time::{TimerFuture, TimerKey, TimerRuntime};
use crate::{BufResult, affinity::bind_to_cpu_set, runtime::scheduler::Scheduler};
scoped_tls::scoped_thread_local!(static CURRENT_RUNTIME: Runtime);
pub type JoinHandle<T> = Task<Result<T, Box<dyn Any + Send>>>;
thread_local! {
static RUNTIME_ID: Cell<u64> = const { Cell::new(0) };
}
pub struct RuntimeInner {
driver: RefCell<Proactor>,
scheduler: Scheduler,
#[cfg(feature = "time")]
timer_runtime: RefCell<TimerRuntime>,
id: u64,
}
#[derive(Clone)]
pub struct Runtime(Rc<RuntimeInner>);
impl Deref for Runtime {
type Target = RuntimeInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Runtime {
pub fn new() -> io::Result<Self> {
Self::builder().build()
}
pub fn builder() -> RuntimeBuilder {
RuntimeBuilder::new()
}
pub fn driver_type(&self) -> DriverType {
self.driver.borrow().driver_type()
}
pub fn try_with_current<T, F: FnOnce(&Self) -> T>(f: F) -> Result<T, F> {
if CURRENT_RUNTIME.is_set() {
Ok(CURRENT_RUNTIME.with(f))
} else {
Err(f)
}
}
pub fn with_current<T, F: FnOnce(&Self) -> T>(f: F) -> T {
#[cold]
fn not_in_compio_runtime() -> ! {
panic!("not in a compio runtime")
}
if CURRENT_RUNTIME.is_set() {
CURRENT_RUNTIME.with(f)
} else {
not_in_compio_runtime()
}
}
pub fn enter<T, F: FnOnce() -> T>(&self, f: F) -> T {
CURRENT_RUNTIME.set(self, f)
}
fn spawn_impl<F: Future + 'static>(&self, future: F) -> Task<F::Output> {
unsafe { self.spawn_unchecked(future) }
}
pub unsafe fn spawn_unchecked<F: Future>(&self, future: F) -> Task<F::Output> {
let waker = self.waker();
unsafe { self.scheduler.spawn_unchecked(future, waker) }
}
pub fn run(&self) -> bool {
self.scheduler.run()
}
pub fn waker(&self) -> Waker {
self.driver.borrow().waker()
}
pub fn opt_waker(&self) -> Arc<OptWaker> {
OptWaker::new(self.waker())
}
pub fn block_on<F: Future>(&self, future: F) -> F::Output {
self.enter(|| {
let opt_waker = self.opt_waker();
let waker = Waker::from(opt_waker.clone());
let mut context = Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
loop {
if let Poll::Ready(result) = future.as_mut().poll(&mut context) {
self.run();
return result;
}
let remaining_tasks = self.run() | opt_waker.reset();
if remaining_tasks {
self.poll_with(Some(Duration::ZERO));
} else {
self.poll();
}
}
})
}
pub fn spawn<F: Future + 'static>(&self, future: F) -> JoinHandle<F::Output> {
self.spawn_impl(AssertUnwindSafe(future).catch_unwind())
}
pub fn spawn_blocking<T: Send + 'static>(
&self,
f: impl (FnOnce() -> T) + Send + 'static,
) -> JoinHandle<T> {
let op = Asyncify::new(move || {
let res = std::panic::catch_unwind(AssertUnwindSafe(f));
BufResult(Ok(0), res)
});
self.spawn_impl(self.submit(op).map(|res| res.1.into_inner()))
}
pub fn attach(&self, fd: RawFd) -> io::Result<()> {
self.driver.borrow_mut().attach(fd)
}
fn submit_raw<T: OpCode + 'static>(
&self,
op: T,
extra: Option<Extra>,
) -> PushEntry<Key<T>, BufResult<usize, T>> {
let mut this = self.driver.borrow_mut();
match extra {
Some(e) => this.push_with_extra(op, e),
None => this.push(op),
}
}
fn default_extra(&self) -> Extra {
self.driver.borrow().default_extra()
}
fn submit<T: OpCode + 'static>(&self, op: T) -> Submit<T> {
Submit::new(self.clone(), op)
}
pub(crate) fn cancel<T: OpCode>(&self, op: Key<T>) {
self.driver.borrow_mut().cancel(op);
}
#[cfg(feature = "time")]
pub(crate) fn cancel_timer(&self, key: &TimerKey) {
self.timer_runtime.borrow_mut().cancel(key);
}
pub(crate) fn poll_task<T: OpCode>(
&self,
waker: &Waker,
key: Key<T>,
) -> PushEntry<Key<T>, BufResult<usize, T>> {
instrument!(compio_log::Level::DEBUG, "poll_task", ?key);
let mut driver = self.driver.borrow_mut();
driver.pop(key).map_pending(|mut k| {
driver.update_waker(&mut k, waker);
k
})
}
pub(crate) fn poll_task_with_extra<T: OpCode>(
&self,
cx: &mut Context,
key: Key<T>,
) -> PushEntry<Key<T>, (BufResult<usize, T>, Extra)> {
instrument!(compio_log::Level::DEBUG, "poll_task_with_extra", ?key);
let mut driver = self.driver.borrow_mut();
driver.pop_with_extra(key).map_pending(|mut k| {
driver.update_waker(&mut k, cx.waker());
k
})
}
#[cfg(feature = "time")]
pub(crate) fn poll_timer(&self, cx: &mut Context, key: &TimerKey) -> Poll<()> {
instrument!(compio_log::Level::DEBUG, "poll_timer", ?cx, ?key);
let mut timer_runtime = self.timer_runtime.borrow_mut();
if timer_runtime.is_completed(key) {
debug!("ready");
Poll::Ready(())
} else {
debug!("pending");
timer_runtime.update_waker(key, cx.waker().clone());
Poll::Pending
}
}
pub fn current_timeout(&self) -> Option<Duration> {
#[cfg(not(feature = "time"))]
let timeout = None;
#[cfg(feature = "time")]
let timeout = self.timer_runtime.borrow().min_timeout();
timeout
}
pub fn poll(&self) {
instrument!(compio_log::Level::DEBUG, "poll");
let timeout = self.current_timeout();
debug!("timeout: {:?}", timeout);
self.poll_with(timeout)
}
pub fn poll_with(&self, timeout: Option<Duration>) {
instrument!(compio_log::Level::DEBUG, "poll_with");
let mut driver = self.driver.borrow_mut();
match driver.poll(timeout) {
Ok(()) => {}
Err(e) => match e.kind() {
io::ErrorKind::TimedOut | io::ErrorKind::Interrupted => {
debug!("expected error: {e}");
}
_ => panic!("{e:?}"),
},
}
#[cfg(feature = "time")]
self.timer_runtime.borrow_mut().wake();
}
pub(crate) fn create_buffer_pool(
&self,
buffer_len: u16,
buffer_size: usize,
) -> io::Result<compio_driver::BufferPool> {
self.driver
.borrow_mut()
.create_buffer_pool(buffer_len, buffer_size)
}
pub(crate) unsafe fn release_buffer_pool(
&self,
buffer_pool: compio_driver::BufferPool,
) -> io::Result<()> {
unsafe { self.driver.borrow_mut().release_buffer_pool(buffer_pool) }
}
pub(crate) fn id(&self) -> u64 {
self.id
}
pub fn register_personality(&self) -> io::Result<u16> {
self.driver.borrow_mut().register_personality()
}
pub fn unregister_personality(&self, personality: u16) -> io::Result<()> {
self.driver.borrow_mut().unregister_personality(personality)
}
}
impl Drop for Runtime {
fn drop(&mut self) {
if Rc::strong_count(&self.0) > 1 {
return;
}
self.enter(|| {
self.scheduler.clear();
})
}
}
impl AsRawFd for Runtime {
fn as_raw_fd(&self) -> RawFd {
self.driver.borrow().as_raw_fd()
}
}
#[cfg(feature = "criterion")]
impl criterion::async_executor::AsyncExecutor for Runtime {
fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
self.block_on(future)
}
}
#[cfg(feature = "criterion")]
impl criterion::async_executor::AsyncExecutor for &Runtime {
fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
(**self).block_on(future)
}
}
#[derive(Debug, Clone)]
pub struct RuntimeBuilder {
proactor_builder: ProactorBuilder,
thread_affinity: HashSet<usize>,
event_interval: usize,
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
}
}
impl RuntimeBuilder {
pub fn new() -> Self {
Self {
proactor_builder: ProactorBuilder::new(),
event_interval: 61,
thread_affinity: HashSet::new(),
}
}
pub fn with_proactor(&mut self, builder: ProactorBuilder) -> &mut Self {
self.proactor_builder = builder;
self
}
pub fn thread_affinity(&mut self, cpus: HashSet<usize>) -> &mut Self {
self.thread_affinity = cpus;
self
}
pub fn event_interval(&mut self, val: usize) -> &mut Self {
self.event_interval = val;
self
}
pub fn build(&self) -> io::Result<Runtime> {
let RuntimeBuilder {
proactor_builder,
thread_affinity,
event_interval,
} = self;
let id = RUNTIME_ID.get();
RUNTIME_ID.set(id + 1);
if !thread_affinity.is_empty() {
bind_to_cpu_set(thread_affinity);
}
let inner = RuntimeInner {
driver: RefCell::new(proactor_builder.build()?),
scheduler: Scheduler::new(*event_interval),
#[cfg(feature = "time")]
timer_runtime: RefCell::new(TimerRuntime::new()),
id,
};
Ok(Runtime(Rc::new(inner)))
}
}
pub fn spawn<F: Future + 'static>(future: F) -> JoinHandle<F::Output> {
Runtime::with_current(|r| r.spawn(future))
}
pub fn spawn_blocking<T: Send + 'static>(
f: impl (FnOnce() -> T) + Send + 'static,
) -> JoinHandle<T> {
Runtime::with_current(|r| r.spawn_blocking(f))
}
pub fn submit<T: OpCode + 'static>(op: T) -> Submit<T> {
Runtime::with_current(|r| r.submit(op))
}
#[deprecated(since = "0.8.0", note = "use `submit(op).with_extra()` instead")]
pub fn submit_with_extra<T: OpCode + 'static>(op: T) -> Submit<T, Extra> {
Runtime::with_current(|r| r.submit(op).with_extra())
}
#[cfg(feature = "time")]
pub(crate) async fn create_timer(instant: std::time::Instant) {
let key = Runtime::with_current(|r| r.timer_runtime.borrow_mut().insert(instant));
if let Some(key) = key {
TimerFuture::new(key).await
}
}