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
use futures::future::{self, FutureObj};
use http_service::HttpService;
use std::sync::Arc;

use crate::{
    middleware::{Middleware, Next},
    router::{Router, Selection},
    Context, Route,
};

/// The entry point for building a Tide application.
///
/// Apps are built up as a combination of *state*, *endpoints* and *middleware*:
///
/// - Application state is user-defined, and is provided via the [`App:new`]
/// function. The state is available as a shared reference to all app endpoints.
///
/// - Endpoints provide the actual application-level code corresponding to
/// particular URLs. The [`App::at`] method creates a new *route* (using
/// standard router syntax), which can then be used to register endpoints
/// for particular HTTP request types.
///
/// - Middleware extends the base Tide framework with additional request or
/// response processing, such as compression, default headers, or logging. To
/// add middleware to an app, use the [`App::middleware`] method.
///
/// # Hello, world!
///
/// You can start a simple Tide application that listens for `GET` requests at path `/hello`
/// on `127.0.0.1:8000` with:
///
/// ```rust, no_run
/// #![feature(async_await)]
///
/// let mut app = tide::App::new(());
/// app.at("/hello").get(async move |_| "Hello, world!");
/// app.serve("127.0.0.1:8000");
///```
///
/// # Routing and parameters
///
/// Tide's routing system is simple and similar to many other frameworks. It
/// uses `:foo` for "wildcard" URL segments, and `:foo*` to match the rest of a
/// URL (which may include multiple segments). Here's an example using wildcard
/// segments as parameters to endpoints:
///
/// ```rust, no_run
/// #![feature(async_await, futures_api)]
///
/// use tide::error::ResultExt;
///
/// async fn hello(cx: tide::Context<()>) -> tide::EndpointResult<String> {
///     let user: String = cx.param("user").client_err()?;
///     Ok(format!("Hello, {}!", user))
/// }
///
/// async fn goodbye(cx: tide::Context<()>) -> tide::EndpointResult<String> {
///     let user: String = cx.param("user").client_err()?;
///     Ok(format!("Goodbye, {}.", user))
/// }
///
/// let mut app = tide::App::new(());
///
/// app.at("/hello/:user").get(hello);
/// app.at("/goodbye/:user").get(goodbye);
/// app.at("/").get(async move |_| {
///     "Use /hello/{your name} or /goodbye/{your name}"
/// });
///
/// app.serve("127.0.0.1:8000");
///```
///
/// You can learn more about routing in the [`App::at`] documentation.
///
/// # Application state
///
/// ```rust, no_run, ignore
/// #![feature(async_await, futures_api, await_macro)]
///
/// use tide::{Context, EndpointResult, error::ResultExt, response, App};
/// use http::StatusCode;
/// use std::sync::Mutex;
///
/// #[derive(Default)]
/// struct Database {
///     contents: Mutex<Vec<Message>>,
/// }
///
/// impl Database {
///     fn messages(&self) -> std::sync::MutexGuard<Vec<Message>> {
///         self.contents.lock().unwrap()
///     }
/// }
///
/// #[derive(Serialize, Deserialize, Clone)]
/// struct Message {
///     author: Option<String>,
///     contents: String,
/// }
///
/// async fn new_message(cx: Context<Database>) -> EndpointResult<String> {
///     let msg = await!(cx.body_json()).client_err()?;
///
///     let mut messages = cx.app_data().messages();
///     let id = messages.len();
///     messages.push(msg);
///
///     Ok(id.to_string())
/// }
///
/// async fn get_message(cx: Context<Database>) -> EndpointResult {
///     let id: usize = cx.param("id").client_err()?;
///
///     if let Some(msg) = cx.app_data().messages().get(id) {
///         Ok(response::json(msg))
///     } else {
///         Err(StatusCode::NOT_FOUND)?
///     }
/// }
///
/// fn main() {
///     let mut app = App::new(Database::default());
///     app.at("/message").post(new_message);
///     app.at("/message/:id").get(get_message);
///     app.serve("127.0.0.1:8000").unwrap();
/// }

pub struct App<AppData> {
    router: Router<AppData>,
    middleware: Vec<Arc<dyn Middleware<AppData>>>,
    data: AppData,
}

impl<AppData: Send + Sync + 'static> App<AppData> {
    /// Create an empty `App`, with no initial middleware or configuration.
    pub fn new(data: AppData) -> App<AppData> {
        App {
            router: Router::new(),
            middleware: Vec::new(),
            data,
        }
    }

    /// Add a new route at the given `path`, relative to root.
    ///
    /// Routing means mapping an HTTP request to an endpoint. Here Tide applies
    /// a "table of contents" approach, which makes it easy to see the overall
    /// app structure. Endpoints are selected solely by the path and HTTP method
    /// of a request: the path determines the resource and the HTTP verb the
    /// respective endpoint of the selected resource. Example:
    ///
    /// ```rust,no_run
    /// # #![feature(async_await)]
    /// # let mut app = tide::App::new(());
    /// app.at("/").get(async move |_| "Hello, world!");
    /// ```
    ///
    /// A path is comprised of zero or many segments, i.e. non-empty strings
    /// separated by '/'. There are two kinds of segments: concrete and
    /// wildcard. A concrete segment is used to exactly match the respective
    /// part of the path of the incoming request. A wildcard segment on the
    /// other hand extracts and parses the respective part of the path of the
    /// incoming request to pass it along to the endpoint as an argument. A
    /// wildcard segment is written as `:name`, which creates an endpoint
    /// parameter called `name`. It is not possible to define wildcard segments
    /// with different names for otherwise identical paths.
    ///
    /// Wildcard definitions can be followed by an optional *wildcard
    /// modifier*. Currently, there is only one modifier: `*`, which means that
    /// the wildcard will match to the end of given path, no matter how many
    /// segments are left, even nothing. It is an error to define two wildcard
    /// segments with different wildcard modifiers, or to write other path
    /// segment after a segment with wildcard modifier.
    ///
    /// Here are some examples omitting the HTTP verb based endpoint selection:
    ///
    /// ```rust,no_run
    /// # let mut app = tide::App::new(());
    /// app.at("/");
    /// app.at("/hello");
    /// app.at("add_two/:num");
    /// app.at("static/:path*");
    /// ```
    ///
    /// There is no fallback route matching, i.e. either a resource is a full
    /// match or not, which means that the order of adding resources has no
    /// effect.
    pub fn at<'a>(&'a mut self, path: &'a str) -> Route<'a, AppData> {
        Route::new(&mut self.router, path.to_owned())
    }

    /// Add middleware to an application.
    ///
    /// Middleware provides application-global customization of the
    /// request/response cycle, such as compression, logging, or header
    /// modification. Middleware is invoked when processing a request, and can
    /// either continue processing (possibly modifying the response) or
    /// immediately return a response. See the [`Middleware`] trait for details.
    ///
    /// Middleware can only be added at the "top level" of an application,
    /// and is processed in the order in which it is applied.
    pub fn middleware(&mut self, m: impl Middleware<AppData>) -> &mut Self {
        self.middleware.push(Arc::new(m));
        self
    }

    /// Make this app into an `HttpService`.
    ///
    /// This lower-level method lets you host a Tide application within an HTTP
    /// server of your choice, via the `http_service` interface crate.
    pub fn into_http_service(self) -> Server<AppData> {
        Server {
            router: Arc::new(self.router),
            data: Arc::new(self.data),
            middleware: Arc::new(self.middleware),
        }
    }

    /// Start serving the app at the given address.
    ///
    /// Blocks the calling thread indefinitely.
    #[cfg(feature = "hyper")]
    pub fn serve(self, addr: impl std::net::ToSocketAddrs) -> std::io::Result<()> {
        let addr = addr
            .to_socket_addrs()?
            .next()
            .ok_or(std::io::ErrorKind::InvalidInput)?;

        println!("Server is listening on: http://{}", addr);
        http_service_hyper::serve(self.into_http_service(), addr);
        Ok(())
    }
}

/// An instantiated Tide server.
///
/// This type is useful only in conjunction with the [`HttpService`] trait,
/// i.e. for hosting a Tide app within some custom HTTP server.
#[derive(Clone)]
pub struct Server<AppData> {
    router: Arc<Router<AppData>>,
    data: Arc<AppData>,
    middleware: Arc<Vec<Arc<dyn Middleware<AppData>>>>,
}

impl<AppData: Sync + Send + 'static> HttpService for Server<AppData> {
    type Connection = ();
    type ConnectionFuture = future::Ready<Result<(), std::io::Error>>;
    type Fut = FutureObj<'static, Result<http_service::Response, std::io::Error>>;

    fn connect(&self) -> Self::ConnectionFuture {
        future::ok(())
    }

    fn respond(&self, _conn: &mut (), req: http_service::Request) -> Self::Fut {
        let path = req.uri().path().to_owned();
        let method = req.method().to_owned();
        let router = self.router.clone();
        let middleware = self.middleware.clone();
        let data = self.data.clone();

        box_async! {
            let fut = {
                let Selection { endpoint, params } = router.route(&path, method);
                let cx = Context::new(data, req, params);

                let next = Next {
                    endpoint,
                    next_middleware: &middleware,
                };

                next.run(cx)
            };

            Ok(await!(fut))
        }
    }
}

#[cfg(test)]
mod tests {
    use futures::executor::block_on;
    use std::sync::Arc;

    use super::*;
    use crate::{middleware::Next, router::Selection, Context, Response};

    fn simulate_request<'a, Data: Default + Clone + Send + Sync + 'static>(
        app: &'a App<Data>,
        path: &'a str,
        method: http::Method,
    ) -> FutureObj<'a, Response> {
        let Selection { endpoint, params } = app.router.route(path, method.clone());

        let data = Arc::new(Data::default());
        let req = http::Request::builder()
            .method(method)
            .body(http_service::Body::empty())
            .unwrap();
        let cx = Context::new(data, req, params);
        let next = Next {
            endpoint,
            next_middleware: &app.middleware,
        };

        next.run(cx)
    }

    #[test]
    fn simple_static() {
        let mut router = App::new(());
        router.at("/").get(async move |_| "/");
        router.at("/foo").get(async move |_| "/foo");
        router.at("/foo/bar").get(async move |_| "/foo/bar");

        for path in &["/", "/foo", "/foo/bar"] {
            let res = block_on(simulate_request(&router, path, http::Method::GET));
            let body = block_on(res.into_body().into_vec()).expect("Reading body should succeed");
            assert_eq!(&*body, path.as_bytes());
        }
    }

    #[test]
    fn nested_static() {
        let mut router = App::new(());
        router.at("/a").get(async move |_| "/a");
        router.at("/b").nest(|router| {
            router.at("/").get(async move |_| "/b");
            router.at("/a").get(async move |_| "/b/a");
            router.at("/b").get(async move |_| "/b/b");
            router.at("/c").nest(|router| {
                router.at("/a").get(async move |_| "/b/c/a");
                router.at("/b").get(async move |_| "/b/c/b");
            });
            router.at("/d").get(async move |_| "/b/d");
        });
        router.at("/a/a").nest(|router| {
            router.at("/a").get(async move |_| "/a/a/a");
            router.at("/b").get(async move |_| "/a/a/b");
        });
        router.at("/a/b").nest(|router| {
            router.at("/").get(async move |_| "/a/b");
        });

        for failing_path in &["/", "/a/a", "/a/b/a"] {
            let res = block_on(simulate_request(&router, failing_path, http::Method::GET));
            if !res.status().is_client_error() {
                panic!(
                    "Should have returned a client error when router cannot match with path {}",
                    failing_path
                );
            }
        }

        for path in &[
            "/a", "/a/a/a", "/a/a/b", "/a/b", "/b", "/b/a", "/b/b", "/b/c/a", "/b/c/b", "/b/d",
        ] {
            let res = block_on(simulate_request(&router, path, http::Method::GET));
            let body = block_on(res.into_body().into_vec()).expect("Reading body should succeed");
            assert_eq!(&*body, path.as_bytes());
        }
    }

    #[test]
    fn multiple_methods() {
        let mut router = App::new(());
        router.at("/a").nest(|router| {
            router.at("/b").get(async move |_| "/a/b GET");
        });
        router.at("/a/b").post(async move |_| "/a/b POST");

        for (path, method) in &[("/a/b", http::Method::GET), ("/a/b", http::Method::POST)] {
            let res = block_on(simulate_request(&router, path, method.clone()));
            assert!(res.status().is_success());
            let body = block_on(res.into_body().into_vec()).expect("Reading body should succeed");
            assert_eq!(&*body, format!("{} {}", path, method).as_bytes());
        }
    }
}