1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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(())
}