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
//! 服务的特征和相关类型的定义。

mod and_then;
pub use and_then::AndThen;

mod boxed;
pub use boxed::{ArcService, BoxCloneService, BoxService};

mod ext;
pub use ext::ServiceExt;

mod map_err;
pub use map_err::MapErr;

mod map_request;
pub use map_request::MapRequest;

mod map_response;
pub use map_response::MapResponse;

mod map_result;
pub use map_result::MapResult;

mod or_else;
pub use or_else::OrElse;

mod service_fn;
pub use service_fn::{service_fn, ServiceFn};

mod then;
pub use then::Then;

use std::future::Future;
use std::sync::Arc;

/// 表示一个接收请求并返回响应的异步函数。
///
/// # 例子
///
/// ```
/// use std::convert::Infallible;
///
/// use boluo_core::request::Request;
/// use boluo_core::response::Response;
/// use boluo_core::service::Service;
///
/// // 回声服务,响应请求主体。
/// struct Echo;
///
/// impl Service<Request> for Echo {
///     type Response = Response;
///     type Error = Infallible;
///
///     async fn call(&self, req: Request) -> Result<Self::Response, Self::Error> {
///         Ok(Response::new(req.into_body()))
///     }
/// }
/// ```
pub trait Service<Req>: Send + Sync {
    /// 服务返回的响应。
    type Response;

    /// 服务产生的错误。
    type Error;

    /// 处理请求并异步返回响应。
    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send;
}

impl<S, Req> Service<Req> for &mut S
where
    S: Service<Req> + ?Sized,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        S::call(self, req)
    }
}

impl<S, Req> Service<Req> for &S
where
    S: Service<Req> + ?Sized,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        S::call(self, req)
    }
}

impl<S, Req> Service<Req> for Box<S>
where
    S: Service<Req> + ?Sized,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        S::call(self, req)
    }
}

impl<S, Req> Service<Req> for Arc<S>
where
    S: Service<Req> + ?Sized,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        S::call(self, req)
    }
}