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
use std::io;

use crate::context::basic_context::{generate_context, BasicContext};
use crate::core::context::Context;
use crate::core::errors::Error;
use crate::core::middleware::MiddlewareChain;
use crate::core::request::{Request, RequestWithParams};
use crate::core::route_parser::{MatchedRoute, RouteParser};
use std::future::Future;

enum Method {
    DELETE,
    GET,
    OPTIONS,
    POST,
    PUT,
    PATCH,
}

// Warning, this method is slow and shouldn't be used for route matching, only for route adding
fn _add_method_to_route(method: &Method, path: &str) -> String {
    let prefix = match method {
        Method::DELETE => "__DELETE__",
        Method::GET => "__GET__",
        Method::OPTIONS => "__OPTIONS__",
        Method::POST => "__POST__",
        Method::PUT => "__PUT__",
        Method::PATCH => "__PATCH__",
    };

    match &path[0..1] {
        "/" => format!("{}{}", prefix, path),
        _ => format!("{}/{}", prefix, path),
    }
}

#[inline]
fn _add_method_to_route_from_str(method: &str, path: &str) -> String {
    templatify!("__" ; method ; "__" ; path ; "")
}

///
/// App, the main component of Thruster. The App is the entry point for your application
/// and handles all incomming requests. Apps are also composeable, that is, via the `subapp`
/// method, you can use all of the methods and middlewares contained within an app as a subset
/// of your app's routes.
///
/// There are three main parts to creating a thruster app:
/// 1. Use `App.create` to create a new app with a custom context generator
/// 2. Add routes and middleware via `.get`, `.post`, etc.
/// 3. Build the app future with `App.build` and spawn it on the executor
///
/// # Examples
/// Subapp
///
/// ```rust, ignore
/// let mut app1 = App::<Request, BasicContext>::new();
///
/// fn test_fn_1(context: BasicContext, next: impl Fn(BasicContext) -> MiddlewareReturnValue<BasicContext>  + Send) -> MiddlewareReturnValue<BasicContext> {
///   Box::new(future::ok(BasicContext {
///     body: context.params.get("id").unwrap().to_owned(),
///     params: context.params,
///     query_params: context.query_params
///   }))
/// };
///
/// app1.get("/:id", middleware![BasicContext => test_fn_1]);
///
/// let mut app2 = App::<Request, BasicContext>::new();
/// app2.use_sub_app("/test", app1);
/// ```
///
/// In the above example, the route `/test/some-id` will return `some-id` in the body of the response.
///
/// The provided start methods are great places to start, but you can also simply use Thruster as a router
/// and create your own version of an HTTP server by directly calling `App.resolve` with a Request object.
/// It will then return a future with the Response object that corresponds to the request. This can be
/// useful if trying to integrate with a different type of load balancing system within the threads of the
/// application.
///
pub struct App<R: RequestWithParams, T: 'static + Context + Send, S: Send> {
    pub _route_parser: RouteParser<T>,
    ///
    /// Generate context is common to all `App`s. It's the function that's called upon receiving a request
    /// that translates an acutal `Request` struct to your custom Context type. It should be noted that
    /// the context_generator should be as fast as possible as this is called with every request, including
    /// 404s.
    pub context_generator: fn(R, &S, &str) -> T,
    pub state: S,

}

impl<R: RequestWithParams, T: Context + Send, S: Send> App<R, T, S> {
    /// Creates a new instance of app with the library supplied `BasicContext`. Useful for trivial
    /// examples, likely not a good solution for real code bases. The advantage is that the
    /// context_generator is already supplied for the developer.
    pub fn new_basic() -> App<Request, BasicContext, ()> {
        App::create(generate_context, ())
    }

    /// Create a new app with the given context generator. The app does not begin listening until start
    /// is called.
    pub fn create(generate_context: fn(R, &S, &str) -> T, state: S) -> App<R, T, S> {
        App {
            _route_parser: RouteParser::new(),
            context_generator: generate_context,
            state,
        }
    }

    /// Add method-agnostic middleware for a route. This is useful for applying headers, logging, and
    /// anything else that might not be sensitive to the HTTP method for the endpoint.
    pub fn use_middleware(
        &mut self,
        path: &str,
        middleware: MiddlewareChain<T>,
    ) -> &mut App<R, T, S> {
        self._route_parser
            .add_method_agnostic_middleware(path, middleware);

        self
    }

    /// Add an app as a predetermined set of routes and middleware. Will prefix whatever string is passed
    /// in to all of the routes. This is a main feature of Thruster, as it allows projects to be extermely
    /// modular and composeable in nature.
    pub fn use_sub_app(&mut self, prefix: &str, app: App<R, T, S>) -> &mut App<R, T, S> {
        self._route_parser
            .route_tree
            .add_route_tree(prefix, app._route_parser.route_tree);

        self
    }

    /// Return the route parser for a given app
    pub fn get_route_parser(&self) -> &RouteParser<T> {
        &self._route_parser
    }

    /// Add a route that responds to `GET`s to a given path
    pub fn get(&mut self, path: &str, middlewares: MiddlewareChain<T>) -> &mut App<R, T, S> {
        self._route_parser
            .add_route(&_add_method_to_route(&Method::GET, path), middlewares);

        self
    }

    /// Add a route that responds to `OPTION`s to a given path
    pub fn options(
        &mut self,
        path: &str,
        middlewares: MiddlewareChain<T>,
    ) -> &mut App<R, T, S> {
        self._route_parser
            .add_route(&_add_method_to_route(&Method::OPTIONS, path), middlewares);

        self
    }

    /// Add a route that responds to `POST`s to a given path
    pub fn post(&mut self, path: &str, middlewares: MiddlewareChain<T>) -> &mut App<R, T, S> {
        self._route_parser
            .add_route(&_add_method_to_route(&Method::POST, path), middlewares);

        self
    }

    /// Add a route that responds to `PUT`s to a given path
    pub fn put(&mut self, path: &str, middlewares: MiddlewareChain<T>) -> &mut App<R, T, S> {
        self._route_parser
            .add_route(&_add_method_to_route(&Method::PUT, path), middlewares);

        self
    }

    /// Add a route that responds to `DELETE`s to a given path
    pub fn delete(
        &mut self,
        path: &str,
        middlewares: MiddlewareChain<T>,
    ) -> &mut App<R, T, S> {
        self._route_parser
            .add_route(&_add_method_to_route(&Method::DELETE, path), middlewares);

        self
    }

    /// Add a route that responds to `PATCH`s to a given path
    pub fn patch(
        &mut self,
        path: &str,
        middlewares: MiddlewareChain<T>,
    ) -> &mut App<R, T, S> {
        self._route_parser
            .add_route(&_add_method_to_route(&Method::PATCH, path), middlewares);

        self
    }

    /// Sets the middleware if no route is successfully matched.
    pub fn set404(&mut self, middlewares: MiddlewareChain<T>) -> &mut App<R, T, S> {
        self._route_parser.add_route(
            &_add_method_to_route(&Method::GET, "/*"),
            middlewares.clone(),
        );
        self._route_parser.add_route(
            &_add_method_to_route(&Method::POST, "/*"),
            middlewares.clone(),
        );
        self._route_parser.add_route(
            &_add_method_to_route(&Method::PUT, "/*"),
            middlewares.clone(),
        );
        self._route_parser.add_route(
            &_add_method_to_route(&Method::PATCH, "/*"),
            middlewares.clone(),
        );
        self._route_parser
            .add_route(&_add_method_to_route(&Method::DELETE, "/*"), middlewares);

        self
    }

    pub fn resolve_from_method_and_path(&self, method: &str, path: &str) -> MatchedRoute<T> {
        let path_with_method = _add_method_to_route_from_str(method, path);

        self._route_parser.match_route(path_with_method)
    }

    /// Resolves a request, returning a future that is processable into a Response
    #[cfg(feature = "hyper_server")]
    pub fn resolve(
        &self,
        request: R,
        matched_route: MatchedRoute<T>,
    ) -> impl Future<Output = Result<T::Response, io::Error>> + Send {
        self._resolve(request, matched_route)
    }

    #[cfg(not(feature = "hyper_server"))]
    pub fn resolve(
        &self,
        request: R,
        matched_route: MatchedRoute<T>,
    ) -> impl Future<Output = Result<T::Response, io::Error>> + Send {
        self._resolve(request, matched_route)
    }

    fn _resolve(
        &self,
        mut request: R,
        matched_route: MatchedRoute<T>,
    ) -> impl Future<Output = Result<T::Response, io::Error>> + Send {
        request.set_params(matched_route.params);

        let context = (self.context_generator)(request, &self.state, matched_route.path);

        let copy = matched_route.middleware.clone();
        async move {
            let ctx = copy.run(context).await;

            let ctx = match ctx {
                Ok(val) => val,
                Err(e) => e.build_context(),
            };

            Ok(ctx.get_response())
        }
    }
}