motore 0.4.1

Motore is a library of modular and reusable components for building robust clients and servers. Motore is greatly inspired by Tower.
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! 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};

#[cfg(feature = "service_send")]
use futures::future::BoxFuture;
#[cfg(not(feature = "service_send"))]
use futures::future::LocalBoxFuture as 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
/// 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;
///
///     async fn call(
///         &self,
///         _cx: &mut Cx,
///         _req: Request<Vec<u8>>,
///     ) -> Result<Self::Response, Self::Error> {
///         // 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 and return
///         async { Ok(resp) }.await
///     }
/// }
/// ```
///
/// # 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;

    /// Process the request and return the response asynchronously.
    #[cfg(feature = "service_send")]
    fn call(
        &self,
        cx: &mut Cx,
        req: Request,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send;

    /// Process the request and return the response asynchronously.
    #[cfg(not(feature = "service_send"))]
    fn call(
        &self,
        cx: &mut Cx,
        req: Request,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>>;
}

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;

            #[cfg(feature = "service_send")]
            fn call(
                &self,
                cx: &mut Cx,
                req: Req,
            ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
                (&**self).call(cx, req)
            }
            #[cfg(not(feature = "service_send"))]
            fn call(
                &self,
                cx: &mut Cx,
                req: Req,
            ) -> impl Future<Output = Result<Self::Response, Self::Error>> {
                (&**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;

            #[cfg(feature = "service_send")]
            fn call(
                &self,
                req: Req,
            ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
                (&**self).call(req)
            }
            #[cfg(not(feature = "service_send"))]
            fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> {
                (&**self).call(req)
            }
        }
    };
}

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

    #[cfg(feature = "service_send")]
    fn call(
        &self,
        req: Request,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send;
    #[cfg(not(feature = "service_send"))]
    fn call(&self, req: Request) -> impl Future<Output = Result<Self::Response, Self::Error>>;
}

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`.
    #[cfg(feature = "service_send")]
    pub fn new<S>(s: S) -> Self
    where
        S: Service<Cx, T, Response = U, Error = E> + Send + Sync + 'static,
        T: 'static,
    {
        let raw = Box::into_raw(Box::new(s)) as *mut ();
        BoxService {
            raw,
            vtable: ServiceVtable {
                call: call::<Cx, T, S>,
                drop: drop::<S>,
            },
        }
    }

    /// Create a new `BoxService`.
    #[cfg(not(feature = "service_send"))]
    pub fn new<S>(s: S) -> Self
    where
        S: Service<Cx, T, Response = U, Error = E> + 'static,
        T: 'static,
    {
        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;

    #[cfg(feature = "service_send")]
    fn call(
        &self,
        cx: &mut Cx,
        req: T,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        unsafe { (self.vtable.call)(self.raw, cx, req) }
    }
    #[cfg(not(feature = "service_send"))]
    fn call(
        &self,
        cx: &mut Cx,
        req: T,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> {
        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`.
#[cfg(feature = "service_send")]
unsafe impl<Cx, T, U, E> Send for BoxService<Cx, T, U, E> {}
#[cfg(feature = "service_send")]
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`].
#[cfg(feature = "service_send")]
pub struct BoxCloneService<Cx, T, U, E> {
    raw: *mut (),
    vtable: CloneServiceVtable<Cx, T, U, E>,
}

/// A [`Clone`] 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`].
#[cfg(not(feature = "service_send"))]
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`.
    #[cfg(feature = "service_send")]
    pub fn new<S>(s: S) -> Self
    where
        S: Service<Cx, T, Response = U, Error = E> + Clone + Send + Sync + 'static,
        T: 'static,
    {
        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>,
            },
        }
    }

    /// Create a new `BoxCloneService`.
    #[cfg(not(feature = "service_send"))]
    pub fn new<S>(s: S) -> Self
    where
        S: Service<Cx, T, Response = U, Error = E> + Clone + 'static,
        T: 'static,
    {
        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;

    #[cfg(feature = "service_send")]
    fn call(
        &self,
        cx: &mut Cx,
        req: T,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        unsafe { (self.vtable.call)(self.raw, cx, req) }
    }
    #[cfg(not(feature = "service_send"))]
    fn call(
        &self,
        cx: &mut Cx,
        req: T,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> {
        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`.
#[cfg(feature = "service_send")]
unsafe impl<Cx, T, U, E> Send for BoxCloneService<Cx, T, U, E> {}
#[cfg(feature = "service_send")]
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,
{
    let fut = S::call(unsafe { (raw as *mut S).as_mut().unwrap() }, cx, req);
    Box::pin(fut)
}

#[cfg(feature = "service_send")]
fn clone<Cx, Req, S: Clone + Send + Service<Cx, Req> + 'static + Sync>(
    raw: *mut (),
) -> BoxCloneService<Cx, Req, S::Response, S::Error>
where
    Req: 'static,
{
    BoxCloneService::new(S::clone(unsafe { (raw as *mut S).as_ref().unwrap() }))
}

#[cfg(not(feature = "service_send"))]
fn clone<Cx, Req, S: Clone + Service<Cx, Req> + 'static>(
    raw: *mut (),
) -> BoxCloneService<Cx, Req, S::Response, S::Error>
where
    Req: 'static,
{
    BoxCloneService::new(S::clone(unsafe { (raw as *mut S).as_ref().unwrap() }))
}

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