use crate::chan::{self, ChanUd};
use crate::error::{IsleError, LuaErrorKind, LuaFailure};
use crate::runtime::Vm;
use mlua::{AnyUserData, FromLua, IntoLua, Lua, MetaMethod, MultiValue, Table, UserData, Value};
use std::cell::RefCell;
use std::fmt;
use tokio::sync::{mpsc, oneshot};
const MAX_CAP: usize = usize::MAX >> 3;
fn setup_error(message: &str) -> IsleError {
IsleError::Init(LuaFailure::new(LuaErrorKind::External, message))
}
pub fn channel<T>(lua: &Lua, cap: usize) -> Result<(Sender<T>, LuaChannel), IsleError>
where
T: IntoLua + Send + 'static,
{
let vm = Vm::of(lua).ok_or_else(|| {
setup_error("runtime::channel: the VM is not attached (call Vm::attach first)")
})?;
let ctor = vm.channel_ctor()?.ok_or_else(|| {
setup_error(
"runtime::channel: the VM's task library was not created (call Vm::task_lib first)",
)
})?;
if cap == 0 {
return Err(setup_error(
"runtime::channel: cap = 0 (rendezvous) is not supported yet",
));
}
if cap > MAX_CAP {
return Err(setup_error("runtime::channel: cap is too large"));
}
let (tx, rx) = mpsc::channel(cap);
let table: Table = ctor.call(ChanUd(chan::new_host(rx)))?;
Ok((Sender { inner: tx }, LuaChannel(table)))
}
pub fn channel_to_host<T>(lua: &Lua, cap: usize) -> Result<(LuaChannel, Receiver<T>), IsleError>
where
T: FromLua + Send + 'static,
{
let vm = Vm::of(lua).ok_or_else(|| {
setup_error("runtime::channel_to_host: the VM is not attached (call Vm::attach first)")
})?;
let ctor = vm.channel_ctor()?.ok_or_else(|| {
setup_error(
"runtime::channel_to_host: the VM's task library was not created (call Vm::task_lib first)",
)
})?;
if cap == 0 {
return Err(setup_error("runtime::channel_to_host: cap must be >= 1"));
}
if cap > MAX_CAP {
return Err(setup_error("runtime::channel_to_host: cap is too large"));
}
let (tx, rx) = mpsc::channel(cap);
let table: Table = ctor.call((ChanUd(chan::new_to_host(tx)), true))?;
Ok((LuaChannel(table), Receiver { inner: rx }))
}
#[derive(Clone, Debug)]
pub struct LuaChannel(Table);
impl LuaChannel {
pub fn table(&self) -> &Table {
&self.0
}
pub fn into_table(self) -> Table {
self.0
}
}
impl IntoLua for LuaChannel {
fn into_lua(self, _: &Lua) -> mlua::Result<Value> {
Ok(Value::Table(self.0))
}
}
pub struct Sender<T> {
inner: mpsc::Sender<T>,
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Self {
Sender {
inner: self.inner.clone(),
}
}
}
impl<T> fmt::Debug for Sender<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sender")
.field("closed", &self.is_closed())
.finish_non_exhaustive()
}
}
impl<T> Sender<T> {
pub async fn send(&self, value: T) -> Result<(), SendError<T>> {
self.inner.send(value).await.map_err(|e| SendError(e.0))
}
pub fn try_send(&self, value: T) -> Result<(), TrySendError<T>> {
self.inner.try_send(value).map_err(|e| match e {
mpsc::error::TrySendError::Full(v) => TrySendError::Full(v),
mpsc::error::TrySendError::Closed(v) => TrySendError::Closed(v),
})
}
pub fn is_closed(&self) -> bool {
self.inner.is_closed()
}
}
impl<Req, Resp, E> Sender<Request<Req, Resp, E>> {
pub async fn request(&self, req: Req) -> Result<Resp, RequestError<Req, E>> {
let (reply, answer) = oneshot::channel();
self.inner
.send(Request { req, reply })
.await
.map_err(|e| RequestError::Closed(e.0.req))?;
answer
.await
.map_err(|_| RequestError::NoReply)?
.map_err(RequestError::Rejected)
}
}
pub struct Request<Req, Resp, E = String> {
req: Req,
reply: oneshot::Sender<Result<Resp, E>>,
}
impl<Req: fmt::Debug, Resp, E> fmt::Debug for Request<Req, Resp, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Request")
.field("req", &self.req)
.finish_non_exhaustive()
}
}
impl<Req, Resp, E> IntoLua for Request<Req, Resp, E>
where
Req: IntoLua,
Resp: FromLua + 'static,
E: FromLua + 'static,
{
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
let Request { req, reply } = self;
let value = req.into_lua(lua)?;
let ud = lua.create_userdata(RequestUd {
state: RefCell::new(ReplyState::Open(reply)),
})?;
ud.set_user_value(value)?;
Ok(Value::UserData(ud))
}
}
enum ReplyState<Resp, E> {
Open(oneshot::Sender<Result<Resp, E>>),
Answered,
Closed,
}
struct RequestUd<Resp, E> {
state: RefCell<ReplyState<Resp, E>>,
}
impl<Resp, E> RequestUd<Resp, E> {
fn answer(&self, method: &str, answer: Result<Resp, E>) -> mlua::Result<bool> {
let prev = std::mem::replace(&mut *self.state.borrow_mut(), ReplyState::Answered);
match prev {
ReplyState::Open(tx) => Ok(tx.send(answer).is_ok()),
other => {
let e = answered_error(method, &other);
*self.state.borrow_mut() = other;
Err(e.expect("not open"))
}
}
}
}
fn answered_error<Resp, E>(method: &str, state: &ReplyState<Resp, E>) -> Option<mlua::Error> {
match state {
ReplyState::Open(_) => None,
ReplyState::Answered => Some(mlua::Error::runtime(format!(
"req:{method}: request already answered"
))),
ReplyState::Closed => Some(mlua::Error::runtime(format!(
"req:{method}: request is closed"
))),
}
}
impl<Resp: FromLua + 'static, E: FromLua + 'static> UserData for RequestUd<Resp, E> {
fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) {
fields.add_field_function_get("value", |_, ud: AnyUserData| ud.user_value::<Value>());
}
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_method("reply", |lua, this, v: Value| {
if let Some(e) = answered_error("reply", &this.state.borrow()) {
return Err(e);
}
let resp = Resp::from_lua(v, lua)?;
this.answer("reply", Ok(resp))
});
methods.add_method("reject", |lua, this, v: Value| {
if let Some(e) = answered_error("reject", &this.state.borrow()) {
return Err(e);
}
let reason = E::from_lua(v, lua)?;
this.answer("reject", Err(reason))
});
methods.add_method("replied", |_, this, ()| {
Ok(matches!(*this.state.borrow(), ReplyState::Answered))
});
methods.add_meta_method(MetaMethod::Close, |_, this, _: MultiValue| {
let mut state = this.state.borrow_mut();
if matches!(*state, ReplyState::Open(_)) {
*state = ReplyState::Closed;
}
Ok(())
});
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SendError<T>(pub T);
impl<T> fmt::Debug for SendError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SendError").finish_non_exhaustive()
}
}
impl<T> fmt::Display for SendError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("host channel is closed")
}
}
impl<T> std::error::Error for SendError<T> {}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TrySendError<T> {
Full(T),
Closed(T),
}
impl<T> TrySendError<T> {
pub fn into_inner(self) -> T {
match self {
TrySendError::Full(v) | TrySendError::Closed(v) => v,
}
}
}
impl<T> fmt::Debug for TrySendError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TrySendError::Full(_) => f.write_str("Full(..)"),
TrySendError::Closed(_) => f.write_str("Closed(..)"),
}
}
}
impl<T> fmt::Display for TrySendError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TrySendError::Full(_) => f.write_str("host channel is full"),
TrySendError::Closed(_) => f.write_str("host channel is closed"),
}
}
}
impl<T> std::error::Error for TrySendError<T> {}
pub struct Receiver<T> {
inner: mpsc::Receiver<T>,
}
impl<T> fmt::Debug for Receiver<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Receiver")
.field("closed", &self.is_closed())
.finish_non_exhaustive()
}
}
impl<T> Receiver<T> {
pub async fn recv(&mut self) -> Option<T> {
self.inner.recv().await
}
pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
self.inner.try_recv().map_err(|e| match e {
mpsc::error::TryRecvError::Empty => TryRecvError::Empty,
mpsc::error::TryRecvError::Disconnected => TryRecvError::Closed,
})
}
pub fn close(&mut self) {
self.inner.close();
}
pub fn is_closed(&self) -> bool {
self.inner.is_closed()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TryRecvError {
Empty,
Closed,
}
impl fmt::Display for TryRecvError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TryRecvError::Empty => f.write_str("channel to the host is empty"),
TryRecvError::Closed => f.write_str("channel to the host is closed"),
}
}
}
impl std::error::Error for TryRecvError {}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RequestError<Req, E = String> {
Closed(Req),
NoReply,
Rejected(E),
}
impl<Req, E: fmt::Debug> fmt::Debug for RequestError<Req, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RequestError::Closed(_) => f.write_str("Closed(..)"),
RequestError::NoReply => f.write_str("NoReply"),
RequestError::Rejected(e) => f.debug_tuple("Rejected").field(e).finish(),
}
}
}
impl<Req, E: fmt::Display> fmt::Display for RequestError<Req, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RequestError::Closed(_) => f.write_str("host channel is closed"),
RequestError::NoReply => f.write_str("request was not answered"),
RequestError::Rejected(e) => write!(f, "request was rejected: {e}"),
}
}
}
impl<Req, E: fmt::Debug + fmt::Display> std::error::Error for RequestError<Req, E> {}