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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::convert::Infallible;

use tower::{Layer, Service as TowerService};

use router::Routes;
use service::HrpcService;

use crate::{common::future, request::BoxRequest, response::BoxResponse};

use self::router::RoutesFinalized;

/// Error types used by hRPC.
pub mod error;
/// Layers for hRPC services.
pub mod layer;
/// The router used by hRPC.
pub mod router;
/// Handler type and handlers used by hRPC.
pub mod service;
/// Socket used by hRPC for "streaming" RPCs.
pub mod socket;
/// Transports for hRPC services.
pub mod transport;
/// Other useful types, traits and functions used by hRPC.
pub mod utils;

mod macros;

pub use service::HrpcLayer;

// Prelude used by generated code. It is not meant to be used by users.
#[doc(hidden)]
pub mod gen_prelude {
    pub use super::{
        error::ServerResult,
        router::Routes,
        service::{unary_handler, ws_handler, HrpcLayer, HrpcService},
        socket::Socket,
        transport::Transport,
        MakeRoutes,
    };
    pub use crate::{BoxError, Request as HrpcRequest, Response as HrpcResponse};
    pub use bytes::Bytes;
    pub use futures_util::future::BoxFuture;
    pub use std::{convert::Infallible, future::Future, net::ToSocketAddrs, sync::Arc};
    pub use tower::{layer::util::Identity, Layer, Service as TowerService};
}

/// Prelude that exports commonly used server types.
pub mod prelude {
    pub use super::{
        error::{HrpcError, ServerResult},
        service::{HrpcLayer, HrpcLayerExt},
        socket::Socket,
        transport::Transport,
        MakeRoutes,
    };
    pub use crate::{make_handler, response::IntoResponse, Request, Response};
    pub use hrpc_proc_macro::handler;
}

/// The core trait of `hrpc-rs` servers. This trait acts as a `tower::MakeService`,
/// it can produce a set of [`Routes`] and can be combined with other [`MakeRoutes`]s.
///
/// Not to be confused with [`tower::Service`].
pub trait MakeRoutes: Send + 'static {
    /// Creates a [`Routes`], which will be used to build a [`RoutesFinalized`] instance.
    fn make_routes(&self) -> Routes;

    /// Combines this server with another server.
    fn combine_with<Other>(self, other: Other) -> ServiceStack<Other, Self>
    where
        Other: MakeRoutes,
        Self: Sized,
    {
        ServiceStack {
            outer: other,
            inner: self,
        }
    }

    /// Turns this server into a type that implements `MakeService`, so that
    /// it can be used with [`hyper`].
    fn into_make_service(self) -> IntoMakeService<Self>
    where
        Self: Sized,
    {
        IntoMakeService { mk_router: self }
    }

    /// Layers this server with a layer.
    ///
    /// If your layer does not implement [`Clone`], you can wrap it using
    /// [`HrpcLayer::new`].
    fn layer<S, L>(self, layer: L) -> LayeredService<S, L, Self>
    where
        L: Layer<HrpcService, Service = S> + Clone + Sync + Send + 'static,
        S: tower::Service<BoxRequest, Response = BoxResponse, Error = Infallible> + Send + 'static,
        S::Future: Send,
        Self: Sized,
    {
        LayeredService { inner: self, layer }
    }
}

/// Type that layers the handlers that are produced by a [`MakeRoutes`].
pub struct LayeredService<S, L, M>
where
    L: Layer<HrpcService, Service = S> + Clone + Sync + Send + 'static,
    S: tower::Service<BoxRequest, Response = BoxResponse, Error = Infallible> + Send + 'static,
    S::Future: Send,
    M: MakeRoutes,
{
    inner: M,
    layer: L,
}

impl<S, L, M> Clone for LayeredService<S, L, M>
where
    L: Layer<HrpcService, Service = S> + Clone + Sync + Send + 'static,
    S: tower::Service<BoxRequest, Response = BoxResponse, Error = Infallible> + Send + 'static,
    S::Future: Send,
    M: MakeRoutes + Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            layer: self.layer.clone(),
        }
    }
}

impl<S, L, M> MakeRoutes for LayeredService<S, L, M>
where
    L: Layer<HrpcService, Service = S> + Clone + Sync + Send + 'static,
    S: tower::Service<BoxRequest, Response = BoxResponse, Error = Infallible> + Send + 'static,
    S::Future: Send,
    M: MakeRoutes,
{
    fn make_routes(&self) -> Routes {
        let rb = MakeRoutes::make_routes(&self.inner);
        rb.layer_all(self.layer.clone())
    }
}

/// Type that contains two [`MakeRoutes`]s and stacks (combines) them.
pub struct ServiceStack<Outer, Inner>
where
    Outer: MakeRoutes,
    Inner: MakeRoutes,
{
    outer: Outer,
    inner: Inner,
}

impl<Outer, Inner> Clone for ServiceStack<Outer, Inner>
where
    Outer: MakeRoutes + Clone,
    Inner: MakeRoutes + Clone,
{
    fn clone(&self) -> Self {
        Self {
            outer: self.outer.clone(),
            inner: self.inner.clone(),
        }
    }
}

impl<Outer, Inner> MakeRoutes for ServiceStack<Outer, Inner>
where
    Outer: MakeRoutes,
    Inner: MakeRoutes,
{
    fn make_routes(&self) -> Routes {
        let outer_rb = MakeRoutes::make_routes(&self.outer);
        let inner_rb = MakeRoutes::make_routes(&self.inner);
        outer_rb.combine_with(inner_rb)
    }
}

/// Type that contains a [`MakeRoutes`] and implements `tower::MakeService` to
/// create [`RoutesFinalized`] instances.
pub struct IntoMakeService<S: MakeRoutes> {
    mk_router: S,
}

impl<S: MakeRoutes + Clone> Clone for IntoMakeService<S> {
    fn clone(&self) -> Self {
        Self {
            mk_router: self.mk_router.clone(),
        }
    }
}

impl<T, S: MakeRoutes> TowerService<T> for IntoMakeService<S> {
    type Response = RoutesFinalized;

    type Error = Infallible;

    type Future = future::Ready<Result<RoutesFinalized, Infallible>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        Ok(()).into()
    }

    fn call(&mut self, _req: T) -> Self::Future {
        future::ready(Ok(self.mk_router.make_routes().build()))
    }
}

#[cfg(test)]
mod tests {
    use tower::layer::util::Identity;

    use crate::server::{router::Routes, HrpcLayer, MakeRoutes};

    struct TestServer;

    impl MakeRoutes for TestServer {
        fn make_routes(&self) -> Routes {
            Routes::new()
        }
    }

    #[test]
    fn layered_identity() {
        let s = TestServer;

        // we can't poll it, and we don't want to anyways
        let _ = s.layer(HrpcLayer::new(Identity::new()));
    }
}