use tower::Service;
use crate::{Frame, FrameFuture, Handler};
use super::Action;
#[derive(Clone)]
pub struct Stateless<ActionHandler: Clone, Args: Clone> {
pub action: ActionHandler,
_args: std::marker::PhantomData<Args>,
}
impl<ActionHandler, Args> From<Stateless<ActionHandler, Args>>
for Action<Stateless<ActionHandler, Args>>
where
ActionHandler: Handler<Args, ()> + Clone + Send + 'static,
Args: Clone + Send + 'static,
{
fn from(status: Stateless<ActionHandler, Args>) -> Self {
Self { action_state: status }
}
}
impl<ActionHandler, Args> Stateless<ActionHandler, Args>
where
ActionHandler: Handler<Args, ()> + Clone + Send + 'static,
Args: Clone + Send + 'static,
{
pub fn new(action: ActionHandler) -> Self {
Self {
action,
_args: std::marker::PhantomData,
}
}
}
impl<ActionHandler, Args> Stateless<ActionHandler, Args>
where
ActionHandler: Handler<Args, ()> + Clone + Send + 'static,
Args: Clone + Send + 'static,
{
pub fn new_stateless(action: ActionHandler) -> Self {
Self::new(action)
}
}
impl<ActionHandler, Args, IntoFrame> Service<IntoFrame> for Action<Stateless<ActionHandler, Args>>
where
IntoFrame: Into<Frame>,
ActionHandler: Handler<Args, ()> + Clone + 'static,
ActionHandler::Future: 'static,
Args: Clone,
{
type Response = Frame;
type Error = crate::Error;
type Future = FrameFuture;
fn poll_ready(
&mut self,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn call(&mut self, frame: IntoFrame) -> Self::Future {
let handler = self.action_state.action.clone();
FrameFuture::from_async_block(Handler::invoke(&handler, frame, ()))
}
}
#[tokio::test]
async fn invoking_stateless_actions_directly() -> Result<(), tower::BoxError> {
let action = || async {};
let result = action.invoke((), ()).await?;
assert_eq!(result, ().into());
Ok(())
}