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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Definition of the core `Service` trait to Motore.
//!
//! The [`Service`] trait provides the necessary abstractions for defining
//! request / response clients and servers. It is simple but powerful and is
//! used as the foundation for the rest of Motore.

use std::{fmt, future::Future, sync::Arc};

use futures::future::BoxFuture;

mod ext;
mod service_fn;
#[cfg(feature = "tower")]
mod tower_adapter;

pub use ext::*;
pub use service_fn::{service_fn, ServiceFn};
#[cfg(feature = "tower")]
pub use tower_adapter::*;

/// An asynchronous function from a `Request` to a `Response`.
///
/// The `Service` trait is a simplified interface making it easy to write
/// network applications in a modular and reusable way, decoupled from the
/// underlying protocol. It is one of Tower's fundamental abstractions.
///
/// # Functional
///
/// A `Service` is a function of a `Request`. It immediately returns a
/// `Future` representing the eventual completion of processing the
/// request. The actual request processing may happen at any time in the
/// future, on any thread or executor. The processing may depend on calling
/// other services. At some point in the future, the processing will complete,
/// and the `Future` will resolve to a response or error.
///
/// At a high level, the `Service::call` function represents an RPC request. The
/// `Service` value can be a server or a client.
///
/// # Server
///
/// An RPC server *implements* the `Service` trait. Requests received by the
/// server over the network are deserialized and then passed as an argument to the
/// server value. The returned response is sent back over the network.
///
/// As an example, here is how an HTTP request is processed by a server:
///
/// ```rust
/// #![feature(type_alias_impl_trait)]
///
/// use std::future::Future;
///
/// use http::{Request, Response, StatusCode};
/// use motore::Service;
///
/// struct HelloWorld;
///
/// impl<Cx> Service<Cx, Request<Vec<u8>>> for HelloWorld
/// where
///     Cx: 'static + Send,
/// {
///     type Response = Response<Vec<u8>>;
///     type Error = http::Error;
///     type Future<'cx> = impl Future<Output = Result<Self::Response, Self::Error>> + 'cx;
///
///     fn call<'cx, 's>(&'s self, _cx: &'cx mut Cx, _req: Request<Vec<u8>>) -> Self::Future<'cx>
///     where
///         's: 'cx,
///     {
///         // create the body
///         let body: Vec<u8> = "hello, world!\n".as_bytes().to_owned();
///         // Create the HTTP response
///         let resp = Response::builder()
///             .status(StatusCode::OK)
///             .body(body)
///             .expect("Unable to create `http::Response`");
///         // create a response in a future.
///         async { Ok(resp) }
///     }
/// }
/// ```
///
/// # Middleware / Layer
///
/// More often than not, all the pieces needed for writing robust, scalable
/// network applications are the same no matter the underlying protocol. By
/// unifying the API for both clients and servers in a protocol agnostic way,
/// it is possible to write middleware that provide these pieces in a
/// reusable way.
///
/// For example, you can refer to the [`motore::timeout::Timeout`][crate::timeout::Timeout] Service.
pub trait Service<Cx, Request> {
    /// Responses given by the service.
    type Response;
    /// Errors produced by the service.
    type Error;

    /// The future response value.
    type Future<'cx>: Future<Output = Result<Self::Response, Self::Error>> + Send + 'cx
    where
        Cx: 'cx,
        Self: 'cx;

    /// Process the request and return the response asynchronously.
    fn call<'cx, 's>(&'s self, cx: &'cx mut Cx, req: Request) -> Self::Future<'cx>
    where
        's: 'cx;
}

macro_rules! impl_service_ref {
    ($t: tt) => {
        impl<Cx, Req, T> Service<Cx, Req> for $t<T>
        where
            T: Service<Cx, Req>,
        {
            type Response = T::Response;

            type Error = T::Error;

            type Future<'cx> = T::Future<'cx> where Cx: 'cx, Self: 'cx;

            fn call<'cx, 's>(&'s self, cx: &'cx mut Cx, req: Req) -> Self::Future<'cx>
            where
                's: 'cx,
            {
                (&**self).call(cx, req)
            }
        }
    };
}

impl_service_ref!(Arc);
impl_service_ref!(Box);

macro_rules! impl_unary_service_ref {
    ($t: tt) => {
        impl<Req, T> UnaryService<Req> for $t<T>
        where
            T: UnaryService<Req>,
        {
            type Response = T::Response;

            type Error = T::Error;

            type Future<'s> = T::Future<'s> where Self: 's;

            fn call(&self, req: Req) -> Self::Future<'_> {
                (&**self).call(req)
            }
        }
    };
}

/// [`Service`] without need of Context.
pub trait UnaryService<Request> {
    type Response;
    type Error;

    type Future<'s>: Future<Output = Result<Self::Response, Self::Error>> + Send + 's
    where
        Self: 's;

    fn call(&self, req: Request) -> Self::Future<'_>;
}

impl_unary_service_ref!(Arc);
impl_unary_service_ref!(Box);

/// A [`Send`] + [`Sync`] boxed [`Service`].
///
/// [`BoxService`] turns a service into a trait object, allowing the
/// response future type to be dynamic, and allowing the service to be cloned.
pub struct BoxService<Cx, T, U, E> {
    raw: *mut (),
    vtable: ServiceVtable<Cx, T, U, E>,
}

impl<Cx, T, U, E> BoxService<Cx, T, U, E> {
    /// Create a new `BoxService`.
    pub fn new<S>(s: S) -> Self
    where
        S: Service<Cx, T, Response = U, Error = E> + Send + Sync + 'static,
        T: 'static,
        for<'cx> S::Future<'cx>: Send,
    {
        let raw = Box::into_raw(Box::new(s)) as *mut ();
        BoxService {
            raw,
            vtable: ServiceVtable {
                call: call::<Cx, T, S>,
                drop: drop::<S>,
            },
        }
    }
}

impl<Cx, T, U, E> Drop for BoxService<Cx, T, U, E> {
    fn drop(&mut self) {
        unsafe { (self.vtable.drop)(self.raw) };
    }
}

impl<Cx, T, U, E> fmt::Debug for BoxService<Cx, T, U, E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("BoxService").finish()
    }
}

impl<Cx, T, U, E> Service<Cx, T> for BoxService<Cx, T, U, E> {
    type Response = U;

    type Error = E;

    type Future<'cx> = BoxFuture<'cx, Result<U, E>>
    where
        Self: 'cx;

    fn call<'cx, 's>(&'s self, cx: &'cx mut Cx, req: T) -> Self::Future<'cx>
    where
        's: 'cx,
    {
        unsafe { (self.vtable.call)(self.raw, cx, req) }
    }
}

/// # Safety
///
/// The contained `Service` must be `Send` and `Sync` required by the bounds of `new` and `clone`.
unsafe impl<Cx, T, U, E> Send for BoxService<Cx, T, U, E> {}

unsafe impl<Cx, T, U, E> Sync for BoxService<Cx, T, U, E> {}

struct ServiceVtable<Cx, T, U, E> {
    call: unsafe fn(raw: *mut (), cx: &mut Cx, req: T) -> BoxFuture<'_, Result<U, E>>,
    drop: unsafe fn(raw: *mut ()),
}

/// A [`Clone`] + [`Send`] + [`Sync`] boxed [`Service`].
///
/// [`BoxCloneService`] turns a service into a trait object, allowing the
/// response future type to be dynamic, and allowing the service to be cloned.
///
/// This is similar to [`BoxService`](BoxService) except the resulting
/// service implements [`Clone`].
pub struct BoxCloneService<Cx, T, U, E> {
    raw: *mut (),
    vtable: CloneServiceVtable<Cx, T, U, E>,
}

impl<Cx, T, U, E> BoxCloneService<Cx, T, U, E> {
    /// Create a new `BoxCloneService`.
    pub fn new<S>(s: S) -> Self
    where
        S: Service<Cx, T, Response = U, Error = E> + Clone + Send + Sync + 'static,
        T: 'static,
        for<'cx> S::Future<'cx>: Send,
    {
        let raw = Box::into_raw(Box::new(s)) as *mut ();
        BoxCloneService {
            raw,
            vtable: CloneServiceVtable {
                call: call::<Cx, T, S>,
                clone: clone::<Cx, T, S>,
                drop: drop::<S>,
            },
        }
    }
}

impl<Cx, T, U, E> Drop for BoxCloneService<Cx, T, U, E> {
    fn drop(&mut self) {
        unsafe { (self.vtable.drop)(self.raw) };
    }
}

impl<Cx, T, U, E> Clone for BoxCloneService<Cx, T, U, E> {
    fn clone(&self) -> Self {
        unsafe { (self.vtable.clone)(self.raw) }
    }
}

impl<Cx, T, U, E> fmt::Debug for BoxCloneService<Cx, T, U, E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("BoxCloneService").finish()
    }
}

impl<Cx, T, U, E> Service<Cx, T> for BoxCloneService<Cx, T, U, E> {
    type Response = U;

    type Error = E;

    type Future<'cx> = BoxFuture<'cx, Result<U, E>>
    where
        Self: 'cx;

    fn call<'cx, 's>(&'s self, cx: &'cx mut Cx, req: T) -> Self::Future<'cx>
    where
        's: 'cx,
    {
        unsafe { (self.vtable.call)(self.raw, cx, req) }
    }
}

/// # Safety
///
/// The contained `Service` must be `Send` and `Sync` required by the bounds of `new` and `clone`.
unsafe impl<Cx, T, U, E> Send for BoxCloneService<Cx, T, U, E> {}

unsafe impl<Cx, T, U, E> Sync for BoxCloneService<Cx, T, U, E> {}

struct CloneServiceVtable<Cx, T, U, E> {
    call: unsafe fn(raw: *mut (), cx: &mut Cx, req: T) -> BoxFuture<'_, Result<U, E>>,
    clone: unsafe fn(raw: *mut ()) -> BoxCloneService<Cx, T, U, E>,
    drop: unsafe fn(raw: *mut ()),
}

fn call<Cx, Req, S>(
    raw: *mut (),
    cx: &mut Cx,
    req: Req,
) -> BoxFuture<'_, Result<S::Response, S::Error>>
where
    Req: 'static,
    S: Service<Cx, Req> + 'static,
    for<'cx> S::Future<'cx>: Send,
{
    let fut = S::call(unsafe { (raw as *mut S).as_mut().unwrap() }, cx, req);
    Box::pin(fut)
}

fn clone<Cx, Req, S: Clone + Send + Service<Cx, Req> + 'static + Sync>(
    raw: *mut (),
) -> BoxCloneService<Cx, Req, S::Response, S::Error>
where
    Req: 'static,
    for<'cx> S::Future<'cx>: Send,
{
    BoxCloneService::new(S::clone(unsafe { (raw as *mut S).as_ref().unwrap() }))
}

fn drop<S>(raw: *mut ()) {
    unsafe { Box::from_raw(raw as *mut S) };
}