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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use crate::{
    errors::HandlerError,
    event::service::{
        factory, fn_service, BoxFuture, BoxService, BoxServiceFactory, Service, ServiceFactory,
    },
};

use std::{future::Future, result::Result as StdResult};

pub type BoxedHandlerService = BoxService<(), (), HandlerError>;
pub type BoxedHandlerServiceFactory = BoxServiceFactory<(), (), (), HandlerError, ()>;

pub type Result = StdResult<(), HandlerError>;

pub trait Handler<Args> {
    type Output;
    type Future: Future<Output = Self::Output>;

    fn call(&self, args: Args) -> Self::Future;
}

#[allow(clippy::module_name_repetitions)]
pub struct HandlerObject {
    service: BoxedHandlerServiceFactory,
}

impl HandlerObject {
    #[must_use]
    pub fn new<H, Args>(handler: H, args: Args) -> Self
    where
        H: Handler<Args> + Clone + Send + Sync + 'static,
        H::Future: Send,
        H::Output: Into<Result>,
        Args: Clone + Send + Sync + 'static,
    {
        Self {
            service: handler_service(handler, args),
        }
    }
}

impl ServiceFactory<()> for HandlerObject {
    type Response = ();
    type Error = HandlerError;
    type Config = ();
    type Service = HandlerObjectService;
    type InitError = ();

    fn new_service(&self, config: Self::Config) -> StdResult<Self::Service, Self::InitError> {
        let service = self.service.new_service(config)?;

        Ok(HandlerObjectService { service })
    }
}

#[allow(clippy::module_name_repetitions)]
pub struct HandlerObjectService {
    service: BoxedHandlerService,
}

impl Service<()> for HandlerObjectService {
    type Response = ();
    type Error = HandlerError;
    type Future = BoxFuture<StdResult<Self::Response, Self::Error>>;

    fn call(&self, request: ()) -> Self::Future {
        self.service.call(request)
    }
}

#[allow(clippy::module_name_repetitions)]
pub fn handler_service<H, Args>(handler: H, args: Args) -> BoxedHandlerServiceFactory
where
    H: Handler<Args> + Clone + Send + Sync + 'static,
    H::Future: Send,
    H::Output: Into<Result>,
    Args: Clone + Send + Sync + 'static,
{
    factory(fn_service(move |()| {
        let handler = handler.clone();
        let args = args.clone();

        async move { handler.call(args).await.into() }
    }))
}

#[doc(hidden)]
mod factory_handlers {
    use super::{Future, Handler};

    // `Handler` implementation for function-like
    macro_rules! factory ({ $($param:ident)* } => {
        impl<Func, Fut, $($param,)*> Handler<($($param,)*)> for Func
        where
            Func: Fn($($param),*) -> Fut,
            Fut: Future,
        {
            type Output = Fut::Output;
            type Future = Fut;

            #[inline]
            #[allow(non_snake_case)]
            fn call(&self, ($($param,)*): ($($param,)*)) -> Self::Future {
                (self)($($param,)*)
            }
        }
    });

    // To be able to use function without arguments
    factory! {}
    // To be able to use function with 1 arguments
    factory! { A }
    // To be able to use function with 2 arguments
    factory! { A B }
    // To be able to use function with 3 arguments
    factory! { A B C }
    // To be able to use function with 4 arguments
    factory! { A B C D }
    // To be able to use function with 5 arguments
    factory! { A B C D E }
    // To be able to use function with 6 arguments
    factory! { A B C D E F }
    // To be able to use function with 7 arguments
    factory! { A B C D E F G }
    // To be able to use function with 8 arguments
    factory! { A B C D E F G H }
    // To be able to use function with 9 arguments
    factory! { A B C D E F G H I }
    // To be able to use function with 10 arguments
    factory! { A B C D E F G H I J }
    // To be able to use function with 11 arguments
    factory! { A B C D E F G H I J K }
    // To be able to use function with 12 arguments
    factory! { A B C D E F G H I J K L }
}

#[cfg(test)]
mod tests {
    use super::*;

    use anyhow::anyhow;
    use tokio;

    #[test]
    fn test_arg_number() {
        fn assert_impl_handler<T>(_: impl Handler<T>) {}

        assert_impl_handler(|| async { unreachable!() });
        assert_impl_handler(
            |_01: (),
             _02: (),
             _03: (),
             _04: (),
             _05: (),
             _06: (),
             _07: (),
             _08: (),
             _09: (),
             _10: (),
             _11: (),
             _12: ()| async { unreachable!() },
        );
    }

    #[tokio::test]
    async fn test_handler_object_service() {
        let handler_object = HandlerObject::new(|| async { Ok(()) }, ());
        let handler_object_service = handler_object.new_service(()).unwrap();

        let response = handler_object_service.call(()).await;

        match response {
            Ok(()) => {}
            _ => panic!("Unexpected result"),
        }
    }

    #[tokio::test]
    async fn test_handler_object_service_error() {
        let handler_object =
            HandlerObject::new(|| async { Err(HandlerError::new(anyhow!("test"))) }, ());
        let handler_object_service = handler_object.new_service(()).unwrap();

        let response = handler_object_service.call(()).await;

        match response {
            Err(_) => {}
            _ => panic!("Unexpected result"),
        }
    }
}