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

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

use super::{Action, Active, Ready, Stateless};

/// A convenience type for an action candidate
pub type CandidateAction<ActionHandler, Args, State> =
    Action<super::Candidate<ActionHandler, Args, State>>;

impl<ActionHandler, Args, State> CandidateAction<ActionHandler, Args, State>
where
    ActionHandler: Handler<Args, State> + Clone + Send + 'static,
    Args: Clone + Send + 'static,
    State: Clone + Send + 'static,
{
    /// Create an [`Actionable`] [`Candidate`] from a given `ActionHandler`.
    pub fn new(action: ActionHandler) -> Self {
        super::Candidate::new(action).into()
    }

    /// Create a new `Actionable` `Ready` from an action and a state.
    pub fn with_state(self, state: State) -> Action<Ready<ActionHandler, Args, State>> {
        Ready::new(self.action_state.action, state).into()
    }
}

impl<ActionHandler, Args> CandidateAction<ActionHandler, Args, ()>
where
    ActionHandler: Handler<Args, ()> + Clone + Send + 'static,
    Args: Clone + Send + 'static,
{
    /// Create a new `Actionable` `Stateless` from an action, with no state.
    pub fn stateless(self) -> Action<Stateless<ActionHandler, Args>> {
        Stateless::new(self.action_state.action).into()
    }
}

impl<ActionHandler, Args, State> Actionable<State> for CandidateAction<ActionHandler, Args, State>
where
    ActionHandler: Handler<Args, State> + Clone + Send + Sync + 'static,
    Args: Clone + Send + Sync + 'static,
    State: Clone + Send + Sync + 'static,
{
    fn into_actionable(self: Box<Self>, state: State) -> Action<Active> {
        let inner = self.with_state(state);
        let service = ActionService::new(inner);

        Action::active(service)
    }
}

impl<IntoFrame, ActionHandler, Args> Service<IntoFrame> for CandidateAction<ActionHandler, Args, ()>
where
    IntoFrame: Into<Frame> + Clone + Send + 'static,
    ActionHandler: Handler<Args, ()> + Clone + Send + 'static,
    Args: Clone + Send + 'static,
{
    type Response = Frame;
    type Error = crate::Error;
    type Future = FrameFuture;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        let mut action = self.clone().stateless();

        Service::<IntoFrame>::poll_ready(&mut action, cx)
    }

    fn call(&mut self, frame: IntoFrame) -> Self::Future {
        let mut action = self.clone().stateless();

        Service::<IntoFrame>::call(&mut action, frame)
    }
}