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
use std::{
    convert::Infallible,
    future::{ready, Future, Ready},
    ops::Deref,
    pin::Pin,
    task::{Context, Poll},
    {fmt, net::SocketAddr, sync::Arc},
};

use hyper::service::Service;

use viz_core::{
    config::Config,
    http,
    types::{Params, State, StateFactory},
    Context as VizContext, Error, Result,
};
use viz_router::{Method, Router, Tree};
use viz_utils::tracing;

/// Viz App
#[derive(Clone)]
pub struct App {
    tree: Arc<Tree>,
    config: Option<Arc<Config>>,
    state: Option<Vec<Arc<dyn StateFactory>>>,
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    /// Creates a server
    pub fn new() -> Self {
        Self { state: None, config: None, tree: Arc::new(Tree::new()) }
    }

    /// Sets a `State`
    pub fn state<T>(&mut self, state: T) -> &mut Self
    where
        T: Clone + Send + Sync + 'static,
    {
        self.state.get_or_insert_with(Vec::new).push(Arc::new(State::new(state)));
        self
    }

    /// Sets a `Router`
    pub fn routes(&mut self, router: Router) -> &mut Self {
        router.finish(Arc::get_mut(&mut self.tree).unwrap());
        self
    }

    /// Gets the `Config`
    pub async fn config(&mut self) -> Arc<Config> {
        tracing::info!("loading config");
        self.config.replace(Arc::new(Config::load().await.unwrap_or_default()));
        self.config.clone().unwrap()
    }

    /// Into to the Tower Service
    pub fn into_service(self) -> IntoService<Self> {
        IntoService::new(self)
    }
}

/// Serves a request and returns a response.
pub async fn serve(
    req: http::Request,
    mut addr: Option<SocketAddr>,
    tree: Arc<Tree>,
    state: Vec<Arc<dyn StateFactory>>,
    config: Arc<Config>,
) -> Result<http::Response> {
    let mut cx = VizContext::from(req);
    if addr.is_some() {
        cx.extensions_mut().insert(addr.take());
    }
    cx.extensions_mut().insert(config);
    for t in state.iter() {
        t.create(cx.extensions_mut());
    }

    let method = cx.method().to_owned();
    let path = cx.path();

    if let Some((handler, params)) = tree
        .get(&Method::Verb(method.to_owned()))
        .and_then(|t| t.find(path))
        .or_else(|| {
            if method == http::Method::HEAD {
                tree.get(&Method::Verb(http::Method::GET)).and_then(|t| t.find(path))
            } else {
                None
            }
        })
        .or_else(|| tree.get(&Method::Any).and_then(|t| t.find(path)))
    {
        let params: Params = params.into();
        *cx.middleware_mut() = handler.clone();
        cx.extensions_mut().insert(params);
    }

    Ok(cx.next().await?.into())
}

impl fmt::Debug for App {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("App").finish()
    }
}

#[derive(Debug, Clone)]
pub struct AppStream {
    app: App,
    addr: Option<SocketAddr>,
}

impl AppStream {
    pub fn new(app: App, addr: Option<SocketAddr>) -> Self {
        Self { app, addr }
    }
}

impl Deref for AppStream {
    type Target = App;

    fn deref(&self) -> &App {
        &self.app
    }
}

impl Service<http::Request<http::Body>> for AppStream {
    type Response = http::Response;
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<http::Response>> + Send>>;

    #[inline]
    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    #[inline]
    fn call(&mut self, req: http::Request) -> Self::Future {
        Box::pin(serve(
            req,
            self.addr,
            self.tree.clone(),
            self.state.clone().unwrap_or_default(),
            self.config.clone().unwrap_or_default(),
        ))
    }
}

/// Via https://docs.rs/axum/latest/axum/routing/struct.IntoService.html
#[derive(Debug, Clone)]
pub struct IntoService<S> {
    pub(crate) service: S,
}

impl<S> IntoService<S> {
    fn new(service: S) -> Self {
        Self { service }
    }
}

#[cfg(feature = "tcp")]
impl Service<&hyper::server::conn::AddrStream> for IntoService<App> {
    type Response = AppStream;
    type Error = Infallible;
    type Future = Ready<Result<Self::Response, Self::Error>>;

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

    fn call(&mut self, t: &hyper::server::conn::AddrStream) -> Self::Future {
        ready(Ok(AppStream::new(self.service.clone(), Some(t.remote_addr()))))
    }
}

#[cfg(all(unix, feature = "uds"))]
impl Service<&tokio::net::UnixStream> for IntoService<App> {
    type Response = AppStream;
    type Error = Infallible;
    type Future = Ready<Result<Self::Response, Self::Error>>;

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

    fn call(&mut self, _t: &tokio::net::UnixStream) -> Self::Future {
        ready(Ok(AppStream::new(self.service.clone(), None)))
    }
}