ratpack 0.1.4

ratpack is a HTTP framework designed around simplicity and ease-of-use
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::{convert::Infallible, net::SocketAddr, sync::Arc};

use http::{HeaderMap, Method, Request, Response, StatusCode};
use hyper::{server::conn::Http, service::service_fn, Body};
use tokio::{net::TcpListener, sync::Mutex};

#[cfg(feature = "unix")]
use std::path::PathBuf;
#[cfg(feature = "unix")]
use tokio::net::UnixListener;

use crate::{handler::Handler, router::Router, Error, ServerError, TransientState};

/// App is used to define application-level functionality and initialize the server. Routes are
/// typically programmed here.
///
/// ```ignore
///   async fn item(
///         req: Request<Body>,
///         resp: Option<Response<Body>>,
///         params: Params,
///         app: App<()>
///   ) -> HTTPResult {
///     Ok((
///        req,
///        Response::builder().
///             status(StatusCode::OK).
///             body(Body::default()).
///             unwrap()
///     ))
///   }
///
///   #[tokio::main]
///   async fn main() -> Result<(), ServerError> {
///     let app = App::new();
///     app.get("/:item", compose_handler!(item));
///     app.serve("localhost:0").await
///   }
/// ```
///
/// Note that App here has _no state_. It will have a type signature of `App<()>`. To carry state,
/// look at the `with_state` method which will change the type signature of the `item` call (and
/// other handlers).
///
/// App routes take a Path: a Path is a URI path component that has the capability to superimpose
/// variables. Paths are really simple but useful for capturing dynamic parts of a routing path.
///
/// Paths should always start with `/`. Paths that are dynamic have member components that start
/// with `:`. For example, `/a/b/c` will always only match one route, while `/a/:b/c` will match
/// any route with `/a/<anything>/c`.
///
/// Variadic path components are accessible through the [crate::Params] implementation. Paths are
/// typically used through [crate::app::App] methods that use a string form of the Path.
///
/// Requests are routed through paths to [crate::handler::HandlerFunc]s.
#[derive(Clone)]
pub struct App<S: Clone + Send, T: TransientState + 'static + Clone + Send> {
    router: Router<S, T>,
    global_state: Option<Arc<Mutex<S>>>,
}

impl<S: 'static + Clone + Send, T: TransientState + 'static + Clone + Send> App<S, T> {
    /// Construct a new App with no state; it will be passed to handlers as `App<()>`.
    pub fn new() -> Self {
        Self {
            router: Router::new(),
            global_state: None,
        }
    }

    /// Construct an App with state.
    ///
    /// This has the type `App<S>` where S is `+ 'static + Clone + Send` and will be passed to
    /// handlers with the appropriate concrete type.
    ///
    pub fn with_state(state: S) -> Self {
        Self {
            router: Router::new(),
            global_state: Some(Arc::new(Mutex::new(state))),
        }
    }

    // FIXME Currently you must await this, seems pointless.
    /// Return the state of the App. This is returned as `Arc<Mutex<S>>` and must be acquired under
    /// lock. In situations where there is no state, [std::option::Option::None] is returned.
    pub async fn state(&self) -> Option<Arc<Mutex<S>>> {
        self.global_state.clone()
    }

    /// Create a route for a GET request. See App's docs and [crate::handler::Handler] for
    /// more information.
    pub fn get(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::GET, path.to_string(), ch);
    }

    /// Create a route for a POST request. See App's docs and [crate::handler::Handler] for
    /// more information.
    pub fn post(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::POST, path.to_string(), ch);
    }

    /// Create a route for a DELETE request. See App's docs and [crate::handler::Handler] for
    /// more information.
    pub fn delete(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::DELETE, path.to_string(), ch);
    }

    /// Create a route for a PUT request. See App's docs and [crate::handler::Handler] for
    /// more information.
    pub fn put(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::PUT, path.to_string(), ch);
    }

    /// Create a route for an OPTIONS request. See App's docs and
    /// [crate::handler::Handler] for more information.
    pub fn options(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::OPTIONS, path.to_string(), ch);
    }

    /// Create a route for a PATCH request. See App's docs and
    /// [crate::handler::Handler] for more information.
    pub fn patch(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::PATCH, path.to_string(), ch);
    }

    /// Create a route for a HEAD request. See App's docs and
    /// [crate::handler::Handler] for more information.
    pub fn head(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::HEAD, path.to_string(), ch);
    }

    /// Create a route for a CONNECT request. See App's docs and
    /// [crate::handler::Handler] for more information.
    pub fn connect(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::CONNECT, path.to_string(), ch);
    }

    /// Create a route for a TRACE request. See App's docs and
    /// [crate::handler::Handler] for more information.
    pub fn trace(&mut self, path: &str, ch: Handler<S, T>) {
        self.router.add(Method::TRACE, path.to_string(), ch);
    }

    /// Dispatch a route based on the request. Returns a response based on the error status of the
    /// handler chain following the normal chain of responsibility rules described elsewhere. Only
    /// needed by server implementors.
    pub async fn dispatch(&self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
        let _uri = req.uri().clone();
        let _method = req.method().clone();

        #[cfg(all(feature = "logging", not(feature = "trace")))]
        log::info!("{} request to {}", _method, _uri);

        #[cfg(feature = "trace")]
        tracing::info!("{} request to {}", _method, _uri);

        match self.router.dispatch(req, self.clone()).await {
            Ok(resp) => {
                let _status = resp.status().clone();

                #[cfg(all(feature = "logging", not(feature = "trace")))]
                log::info!(
                    "{} request to {}: responding with status {}",
                    _method,
                    _uri,
                    _status,
                );

                #[cfg(feature = "trace")]
                tracing::info!(
                    "{} request to {}: responding with status {}",
                    _method,
                    _uri,
                    _status,
                );

                Ok(resp)
            }
            Err(e) => {
                #[cfg(all(feature = "logging", not(feature = "trace")))]
                log::error!(
                    "{} request to {}: responding with error {:?}",
                    _method,
                    _uri,
                    e,
                );

                #[cfg(feature = "trace")]
                tracing::error!(
                    "{} request to {}: responding with error {:?}",
                    _method,
                    _uri,
                    e,
                );
                match e.clone() {
                    Error::StatusCode(sc, msg) => Ok(Response::builder()
                        .status(sc)
                        .body(Body::from(msg))
                        .unwrap()),
                    Error::InternalServerError(e) => Ok(Response::builder()
                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                        .body(Body::from(e.to_string()))
                        .unwrap()),
                }
            }
        }
    }

    #[cfg(feature = "unix")]
    pub async fn serve_unix(self, filename: PathBuf) -> Result<(), ServerError> {
        let unix_listener = UnixListener::bind(filename)?;
        loop {
            let (stream, _) = unix_listener.accept().await?;

            let s = self.clone();
            let sfn = service_fn(move |req: Request<Body>| {
                let s = s.clone();
                async move { s.clone().dispatch(req).await }
            });

            tokio::task::spawn(async move {
                if let Err(http_err) = Http::new()
                    .http1_keep_alive(true)
                    .serve_connection(stream, sfn)
                    .await
                {
                    #[cfg(feature = "logging")]
                    log::error!("Error while serving HTTP connection: {}", http_err);
                    #[cfg(feature = "trace")]
                    tracing::error!("Error while serving HTTP connection: {}", http_err);
                    #[cfg(all(not(feature = "trace"), not(feature = "logging")))]
                    eprintln!("Error while serving HTTP connection: {}", http_err);
                }
            });
        }
    }

    /// Start a TCP/HTTP server with tokio. Performs dispatch on an as-needed basis. This is a more
    /// common path for users to start a server.
    pub async fn serve(self, addr: &str) -> Result<(), ServerError> {
        let socketaddr: SocketAddr = addr.parse()?;

        let tcp_listener = TcpListener::bind(socketaddr).await?;
        loop {
            let (tcp_stream, sa) = tcp_listener.accept().await?;

            let s = self.clone();
            let sfn = service_fn(move |mut req: Request<Body>| {
                let ip = sa.ip();
                req.extensions_mut().insert(ip);
                let s = s.clone();
                async move { s.clone().dispatch(req).await }
            });

            #[cfg(all(feature = "logging", not(feature = "trace")))]
            log::trace!("Request from {}", sa);

            #[cfg(feature = "trace")]
            tracing::trace!("Request from {}", sa);

            tokio::task::spawn(async move {
                if let Err(http_err) = Http::new()
                    .http1_keep_alive(true)
                    .serve_connection(tcp_stream, sfn)
                    .await
                {
                    #[cfg(feature = "logging")]
                    log::error!("Error while serving HTTP connection: {}", http_err);
                    #[cfg(feature = "trace")]
                    tracing::error!("Error while serving HTTP connection: {}", http_err);
                    #[cfg(all(not(feature = "trace"), not(feature = "logging")))]
                    eprintln!("Error while serving HTTP connection: {}", http_err);
                }
            });
        }
    }

    /// Start a TLS-backed TCP/HTTP server with tokio. Performs dispatch on an as-needed basis. This is a more
    /// common path for users to start a server.
    #[cfg(feature = "tls")]
    pub async fn serve_tls(
        self,
        addr: &str,
        config: tokio_rustls::rustls::ServerConfig,
    ) -> Result<(), ServerError> {
        let socketaddr: SocketAddr = addr.parse()?;

        let config = tokio_rustls::TlsAcceptor::from(Arc::new(config));
        let tcp_listener = TcpListener::bind(socketaddr).await?;
        loop {
            let (tcp_stream, sa) = tcp_listener.accept().await?;

            let s = self.clone();
            let sfn = service_fn(move |mut req: Request<Body>| {
                let ip = sa.ip();
                req.extensions_mut().insert(ip);
                let s = s.clone();
                async move { s.clone().dispatch(req).await }
            });

            #[cfg(all(feature = "logging", not(feature = "trace")))]
            log::trace!("Request from {}", sa);

            #[cfg(feature = "trace")]
            tracing::trace!("Request from {}", sa);

            let config = config.clone();
            tokio::task::spawn(async move {
                match config.accept(tcp_stream).await {
                    Ok(tcp_stream) => {
                        if let Err(http_err) = Http::new()
                            .http1_keep_alive(true)
                            .serve_connection(tcp_stream, sfn)
                            .await
                        {
                            #[cfg(feature = "logging")]
                            log::error!("Error while serving HTTP connection: {}", http_err);
                            #[cfg(feature = "trace")]
                            tracing::error!("Error while serving HTTP connection: {}", http_err);
                            #[cfg(all(not(feature = "trace"), not(feature = "logging")))]
                            eprintln!("Error while serving HTTP connection: {}", http_err);
                        }
                    }
                    Err(e) => {
                        #[cfg(feature = "logging")]
                        log::error!("Error while serving TLS: {:?}", e);
                        #[cfg(feature = "trace")]
                        tracing::error!("Error while serving TLS: {:?}", e);
                        #[cfg(all(not(feature = "trace"), not(feature = "logging")))]
                        eprintln!("Error while serving TLS: {:?}", e);
                    }
                }
            });
        }
    }
}

/// TestApp is a testing framework for ratpack applications. Given an App, it can issue mock
/// requests to it without standing up a typical web server.
#[derive(Clone)]
pub struct TestApp<S: Clone + Send + 'static, T: TransientState + 'static + Clone + Send> {
    app: App<S, T>,
    headers: Option<HeaderMap>,
}

impl<S: Clone + Send + 'static, T: TransientState + 'static + Clone + Send> TestApp<S, T> {
    /// Construct a new tested application.
    pub fn new(app: App<S, T>) -> Self {
        Self { app, headers: None }
    }

    /// with_headers applies the headers to any following request, and acts as an alternative
    /// constructor.
    pub fn with_headers(&self, headers: http::HeaderMap) -> Self {
        Self {
            app: self.app.clone(),
            headers: Some(headers),
        }
    }

    /// dispatch a request to the application, this allows for maximum flexibility.
    pub async fn dispatch(&self, req: Request<Body>) -> Response<Body> {
        self.app.dispatch(req).await.unwrap()
    }

    fn populate_headers(&self, mut req: http::request::Builder) -> http::request::Builder {
        if let Some(include_headers) = self.headers.clone() {
            for (header, value) in include_headers.clone() {
                if let Some(header) = header {
                    req = req.header(header, value.clone());
                }
            }
        }

        req
    }

    /// Perform a GET request against the path.
    pub async fn get(&self, path: &str) -> Response<Body> {
        let req = self.populate_headers(Request::builder());

        self.app
            .dispatch(req.uri(path).body(Body::default()).unwrap())
            .await
            .unwrap()
    }

    /// Perform a POST request against the path.
    pub async fn post(&self, path: &str, body: Body) -> Response<Body> {
        let req = self.populate_headers(Request::builder());

        self.app
            .dispatch(req.method(Method::POST).uri(path).body(body).unwrap())
            .await
            .unwrap()
    }

    /// Perform a DELETE request against the path.
    pub async fn delete(&self, path: &str) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(
                req.method(Method::DELETE)
                    .uri(path)
                    .body(Body::default())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    /// Perform a PUT request against the path.
    pub async fn put(&self, path: &str, body: Body) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(req.method(Method::PUT).uri(path).body(body).unwrap())
            .await
            .unwrap()
    }

    /// Perform an OPTIONS request against the path.
    pub async fn options(&self, path: &str) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(
                req.method(Method::OPTIONS)
                    .uri(path)
                    .body(Body::default())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    /// Perform a PATCH request against the path.
    pub async fn patch(&self, path: &str, body: Body) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(req.method(Method::PATCH).uri(path).body(body).unwrap())
            .await
            .unwrap()
    }

    /// Perform a HEAD request against the path.
    pub async fn head(&self, path: &str) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(
                req.method(Method::HEAD)
                    .uri(path)
                    .body(Body::default())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    /// Perform a TRACE request against the path.
    pub async fn trace(&self, path: &str) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(
                req.method(Method::TRACE)
                    .uri(path)
                    .body(Body::default())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    /// Perform a CONNECT request against the path.
    pub async fn connect(&self, path: &str) -> Response<Body> {
        let req = self.populate_headers(Request::builder());
        self.app
            .dispatch(
                req.method(Method::CONNECT)
                    .uri(path)
                    .body(Body::default())
                    .unwrap(),
            )
            .await
            .unwrap()
    }
}