use crate::error::IsleError;
use crate::hook::{CancelToken, EnterGuard};
use crate::hub;
use mlua::{Function, Lua, MultiValue, Value};
use std::cell::{Cell, RefCell};
use std::future::Future;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::time::Instant;
pub(crate) enum Wrap {
Call(crate::protect::Parts),
PCall,
}
pub(crate) const WRAP_PCALL: &str =
"local mark, f = ... return function(...) mark() return pcall(f, ...) end";
type RootMark = Rc<Cell<Option<usize>>>;
thread_local! {
static SCOPE: RefCell<Option<Rc<Scope>>> = const { RefCell::new(None) };
}
pub(crate) fn current() -> Option<Rc<Scope>> {
SCOPE.with(|s| s.borrow().clone())
}
struct ScopeEnterGuard {
prev: Option<Rc<Scope>>,
}
impl ScopeEnterGuard {
fn new(scope: &Rc<Scope>) -> Self {
let prev = SCOPE.with(|s| s.replace(Some(scope.clone())));
Self { prev }
}
}
impl Drop for ScopeEnterGuard {
fn drop(&mut self) {
let prev = self.prev.take();
SCOPE.with(|s| *s.borrow_mut() = prev);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Phase {
Running,
Draining,
Closed,
}
pub(crate) struct Scope {
token: CancelToken,
grace: Duration,
phase: Cell<Phase>,
children: RefCell<Vec<Rc<TaskState>>>,
parent: Option<Weak<Scope>>,
deadline: Cell<Option<Instant>>,
}
impl Scope {
fn new(token: CancelToken, grace: Duration, parent: Option<&Rc<Scope>>) -> Self {
Self {
token,
grace,
phase: Cell::new(Phase::Running),
children: RefCell::new(Vec::new()),
parent: parent.map(Rc::downgrade),
deadline: Cell::new(None),
}
}
pub(crate) fn deadline(&self) -> Option<Instant> {
self.deadline.get()
}
fn ancestors_deadline(&self) -> Option<Instant> {
let mut earliest: Option<Instant> = None;
let mut next = self.parent.as_ref().and_then(Weak::upgrade);
while let Some(scope) = next {
if let Some(d) = scope.deadline() {
earliest = Some(earliest.map_or(d, |e| e.min(d)));
}
next = scope.parent.as_ref().and_then(Weak::upgrade);
}
earliest
}
fn add(&self, child: Rc<TaskState>) {
if self.phase.get() == Phase::Draining {
child.token.cancel();
}
let mut children = self.children.borrow_mut();
children.retain(|c| !c.is_done());
children.push(child);
}
pub(crate) fn spawn<F, T, C>(
self: &Rc<Self>,
grace: Duration,
root: Option<RootMark>,
fut: F,
conv: C,
) -> Spawned<T>
where
F: Future + 'static,
T: 'static,
C: FnOnce(Option<F::Output>, &CancelToken) -> Option<T> + 'static,
{
let token = self.token.child_token();
let state = Rc::new(TaskState::new(token.clone()));
let result = Rc::new(RefCell::new(None));
let out_of_time = match self.phase.get() {
Phase::Running => false,
Phase::Draining => self.deadline().is_some_and(|d| d <= Instant::now()),
Phase::Closed => true,
};
if out_of_time {
token.cancel();
state.finish();
return Spawned { state, result };
}
let child = Rc::new(Scope::new(token.clone(), grace, Some(self)));
let run = run_in(child, root, fut);
let st = state.clone();
let slot = result.clone();
let handle = tokio::task::spawn_local(async move {
let finish = FinishOnDrop(st.clone());
let out = run.await;
*slot.borrow_mut() = conv(out, &token);
st.finish();
drop(finish);
});
*state.abort.borrow_mut() = Some(handle.abort_handle());
self.add(state.clone());
Spawned { state, result }
}
fn cancel_all(&self) {
for c in self.children.borrow().iter() {
c.token.cancel();
}
}
async fn wait_all(&self) {
loop {
let next = self
.children
.borrow()
.iter()
.find(|c| !c.is_done())
.cloned();
match next {
Some(c) => c.wait_done().await,
None => return,
}
}
}
fn abort_all(&self) {
for c in self.children.borrow().iter() {
c.token.cancel();
if let Some(h) = c.abort.borrow_mut().take() {
h.abort();
}
}
}
}
pub(crate) struct Spawned<T> {
pub(crate) state: Rc<TaskState>,
pub(crate) result: Rc<RefCell<Option<T>>>,
}
impl<T> Clone for Spawned<T> {
fn clone(&self) -> Self {
Self {
state: self.state.clone(),
result: self.result.clone(),
}
}
}
pub(crate) struct TaskState {
pub(crate) token: CancelToken,
done: Cell<bool>,
notify: tokio::sync::Notify,
abort: RefCell<Option<tokio::task::AbortHandle>>,
}
impl TaskState {
fn new(token: CancelToken) -> Self {
Self {
token,
done: Cell::new(false),
notify: tokio::sync::Notify::new(),
abort: RefCell::new(None),
}
}
pub(crate) fn is_done(&self) -> bool {
self.done.get()
}
fn finish(&self) {
if self.done.replace(true) {
return;
}
self.abort.borrow_mut().take();
self.notify.notify_waiters();
}
pub(crate) async fn wait_done(&self) {
loop {
let notified = self.notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.done.get() {
return;
}
notified.await;
}
}
}
struct FinishOnDrop(Rc<TaskState>);
impl Drop for FinishOnDrop {
fn drop(&mut self) {
self.0.finish();
}
}
struct Scoped<F> {
token: CancelToken,
scope: Rc<Scope>,
root: Option<RootMark>,
fut: Pin<Box<F>>,
}
impl<F: Future> Future for Scoped<F> {
type Output = F::Output;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<F::Output> {
let _enter = EnterGuard::new(&self.token);
let _scope = ScopeEnterGuard::new(&self.scope);
self.fut.as_mut().poll(cx)
}
}
impl<F> Drop for Scoped<F> {
fn drop(&mut self) {
if let Some(ptr) = self.root.as_ref().and_then(|r| r.take()) {
hub::unmark_root(ptr);
}
}
}
struct AbortOnDrop(Option<Rc<Scope>>);
impl AbortOnDrop {
fn disarm(mut self) {
self.0 = None;
}
}
impl Drop for AbortOnDrop {
fn drop(&mut self) {
if let Some(scope) = self.0.take() {
scope.phase.set(Phase::Closed);
scope.abort_all();
}
}
}
pub(crate) fn lua_body(
lua: &Lua,
wrap: Wrap,
func: Function,
args: MultiValue,
) -> mlua::Result<(RootMark, impl Future<Output = mlua::Result<MultiValue>>)> {
let root = Rc::new(Cell::new(None));
let r = root.clone();
let mark = lua.create_function(move |lua, ()| {
let ptr = lua.current_thread().to_pointer() as usize;
hub::mark_root(ptr);
r.set(Some(ptr));
Ok(())
})?;
let body: Function = match wrap {
Wrap::Call((xpcall, handler, take)) => lua
.load(crate::protect::WRAP_CALL)
.set_name("=mlua_isle.root")
.call((mark, func, xpcall, handler, take))?,
Wrap::PCall => lua.load(WRAP_PCALL).call((mark, func))?,
};
Ok((root, body.call_async::<MultiValue>(args)))
}
fn run_in<F: Future>(
scope: Rc<Scope>,
root: Option<RootMark>,
fut: F,
) -> impl Future<Output = Option<F::Output>> {
let run = Scoped {
token: scope.token.clone(),
scope: scope.clone(),
root,
fut: Box::pin(fut),
};
async move {
let guard = AbortOnDrop(Some(scope.clone()));
let out = with_grace(&scope, run).await;
if scope.deadline.get().is_none() {
let own = Instant::now() + scope.grace;
let deadline = scope.ancestors_deadline().map_or(own, |d| d.min(own));
scope.deadline.set(Some(deadline));
}
scope.phase.set(Phase::Draining);
scope.cancel_all();
scope.wait_all().await;
scope.phase.set(Phase::Closed);
guard.disarm();
out
}
}
async fn with_grace<F: Future>(scope: &Scope, fut: F) -> Option<F::Output> {
tokio::pin!(fut);
tokio::select! {
biased;
_ = scope.token.cancelled() => {}
out = &mut fut => return Some(out),
}
let own = Instant::now() + scope.grace;
let deadline = scope.ancestors_deadline().map_or(own, |d| d.min(own));
scope.deadline.set(Some(deadline));
tokio::time::timeout_at(deadline, fut).await.ok()
}
pub async fn cancellable<F, T>(fut: F) -> mlua::Result<T>
where
F: Future<Output = mlua::Result<T>>,
{
match crate::hook::current_token() {
None => fut.await,
Some(token) => tokio::select! {
biased;
_ = token.cancelled() => Err(crate::error::cancel_error()),
out = fut => out,
},
}
}
pub(crate) async fn run_root(
lua: &Lua,
token: CancelToken,
func: Function,
args: MultiValue,
) -> Result<MultiValue, crate::IsleError> {
hub::ensure_installed(lua)?;
let grace = hub::config(lua).grace;
let parts = crate::protect::parts(lua)?;
let (root, body) = lua_body(lua, Wrap::Call(parts), func, args)?;
let scope = Rc::new(Scope::new(token.clone(), grace, None));
let out = run_in(scope, Some(root), body).await;
if token.is_cancelled() {
return Err(crate::IsleError::Cancelled);
}
match out {
Some(Ok(values)) => crate::protect::unwrap_root(lua, values),
Some(Err(e)) => Err(crate::IsleError::from(e)),
None => Err(crate::IsleError::Cancelled),
}
}
pub(crate) fn error_value(e: mlua::Error) -> Value {
Value::Error(Box::new(e))
}
pub fn current_scope() -> Option<ScopeHandle> {
current().map(|scope| ScopeHandle { scope })
}
#[derive(Clone)]
pub struct ScopeHandle {
scope: Rc<Scope>,
}
impl ScopeHandle {
pub fn spawn_local<F, T>(&self, fut: F) -> ScopedTask<T>
where
F: Future<Output = T> + 'static,
T: 'static,
{
let Spawned { state, result } = self.scope.spawn(self.scope.grace, None, fut, |out, _| out);
ScopedTask {
state,
result,
wait: None,
detached: false,
}
}
pub fn token(&self) -> &CancelToken {
&self.scope.token
}
}
impl std::fmt::Debug for ScopeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScopeHandle")
.field("token", &self.scope.token)
.field("phase", &self.scope.phase.get())
.finish_non_exhaustive()
}
}
#[must_use = "dropping a ScopedTask cancels the task; use .detach() to let it run"]
pub struct ScopedTask<T> {
state: Rc<TaskState>,
result: Rc<RefCell<Option<T>>>,
wait: Option<Pin<Box<dyn Future<Output = ()>>>>,
detached: bool,
}
impl<T> ScopedTask<T> {
pub fn detach(mut self) {
self.detached = true;
}
}
impl<T> Future for ScopedTask<T> {
type Output = Result<T, IsleError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
if !this.state.is_done() {
if this.wait.is_none() {
let state = this.state.clone();
this.wait = Some(Box::pin(async move { state.wait_done().await }));
}
if let Some(wait) = this.wait.as_mut() {
if wait.as_mut().poll(cx).is_pending() {
return Poll::Pending;
}
}
}
this.wait = None;
Poll::Ready(this.result.borrow_mut().take().ok_or(IsleError::Cancelled))
}
}
impl<T> Drop for ScopedTask<T> {
fn drop(&mut self) {
if !self.detached && !self.state.is_done() {
self.state.token.cancel();
}
}
}
impl<T> std::fmt::Debug for ScopedTask<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScopedTask")
.field("token", &self.state.token)
.field("finished", &self.state.is_done())
.field("detached", &self.detached)
.finish_non_exhaustive()
}
}