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
use tower::Service;

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

/// A convenience type for an action ready status.
pub type ReadyAction<ActionHandler, Args, State> = Action<super::Ready<ActionHandler, Args, State>>;

impl<ActionHandler, Args, State> From<super::Ready<ActionHandler, Args, State>>
    for ReadyAction<ActionHandler, Args, State>
where
    ActionHandler: Handler<Args, State> + Clone + Send + 'static,
    Args: Clone + Send + 'static,
    State: Clone + Send + 'static,
{
    fn from(ready: super::Ready<ActionHandler, Args, State>) -> Self {
        Self { action_state: ready }
    }
}

impl<ActionHandler, Args, State> super::Ready<ActionHandler, Args, State>
where
    ActionHandler: Handler<Args, State> + Clone + Send + 'static,
    Args: Clone + Send + 'static,
    State: Clone + Send + 'static,
{
    /// Create a new `Ready` state from an action and a state.
    pub fn new(action: ActionHandler, state: State) -> Self {
        Self {
            action,
            state,
            _args: std::marker::PhantomData,
        }
    }
}

impl<ActionHandler, Args, State, IntoFrame> Service<IntoFrame>
    for ReadyAction<ActionHandler, Args, State>
where
    IntoFrame: Into<Frame>,
    ActionHandler: Handler<Args, State> + Clone + 'static,
    ActionHandler::Future: 'static,
    State: Clone,
    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();
        let future = Handler::invoke(&handler, frame, self.action_state.state.clone());

        FrameFuture::from_async_block(future)
    }
}