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
//! Non-blocking implementation, requires the `async` feature.

use crate::{Context, Error, Request, Response, Result};
use async_trait::async_trait;

#[async_trait]
/// Trait for async services that maybe handle a request.
///
/// Only available with the `async` feature.
pub trait Service {
    /// Type of the user data for this service.
    type Data: Send + Sync;

    /// See [Service](crate::Service) for more information.
    async fn handle(
        &self,
        request: &mut Request,
        ctx: &Context<Self::Data>,
    ) -> Result<Option<Response>>;
}

/// Serve requests.
///
/// Requests are passed to each service in turn and the first service 
/// that returns a response wins.
///
/// Only available with the `async` feature.
pub struct Server<'a, T: Send + Sync> {
    /// Services that the server should invoke for every request.
    services: Vec<&'a Box<dyn Service<Data = T>>>,
}

impl<'a, T: Send + Sync> Server<'a, T> {
    /// Create a new server.
    pub fn new(services: Vec<&'a Box<dyn Service<Data = T>>>) -> Self {
        Self {services} 
    }

    /// Call services in order and return the first response message.
    ///
    /// If no services match the incoming request this will
    /// return `Error::MethodNotFound`.
    pub(crate) async fn handle(
        &self,
        request: &mut Request,
        ctx: &Context<T>,
    ) -> Result<Response> {
        for service in self.services.iter() {
            if let Some(result) = service.handle(request, ctx).await? {
                return Ok(result);
            }
        }

        let err = Error::MethodNotFound {
            name: request.method().to_string(),
            id: request.id.clone(),
        };

        Ok((request, err).into())
    }

    /// Infallible service handler, errors are automatically converted to responses.
    pub async fn serve(
        &self,
        request: &mut Request,
        ctx: &Context<T>,
    ) -> Response {
        match self.handle(request, ctx).await {
            Ok(response) => response,
            Err(e) => e.into(),
        }
    }
}