intrepid-core 0.1.6

Manage complex async business logic with ease
Documentation
use tower::Service;

use crate::{Frame, FrameFuture, Handler};

use super::Action;

/// A `Ready` type state represents an action which has a handler and a state, and can be
/// invoked
#[derive(Clone)]
pub struct Stateless<ActionHandler: Clone, Args: Clone> {
    /// The action handler for this ready status struct.
    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,
{
    /// Create a new `Ready` state from an action and a state.
    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,
{
    /// Create a new `Ready` stateless action.
    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(())
}