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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#![deny(missing_docs)]

//! Easy-to-use non-async HTTP 1.1 server.

mod status_code;

use anyhow::{anyhow, Context, Error};
use bufstream::BufStream;
use fehler::{throw, throws};
use log::error;
use serde::{Deserialize, Serialize};
pub use status_code::StatusCode;
use std::collections::HashMap;
use std::convert::Infallible;
use std::fmt::{Debug, Display};
use std::io::{BufRead, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::thread;
use url::Url;

type HeaderName = unicase::UniCase<String>;

/// Requirements for the Server Error type parameter.
//pub trait ErrorTrait: Debug + Display + 'static {}

/// Request type passed to handlers. It provides both the input
/// request and the output response, as well as access to state shared
/// across requests.
pub struct Request {
    method: String,
    path_params: HashMap<String, String>,
    req_headers: HashMap<HeaderName, String>,
    req_body: Vec<u8>,
    url: Url,

    status: StatusCode,
    resp_body: Vec<u8>,
    resp_headers: HashMap<String, String>,
}

impl Request {
    /// Get the request URL.
    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Get the request headers.
    pub fn headers(&self) -> &HashMap<HeaderName, String> {
        &self.req_headers
    }

    /// Deserialize the body as JSON.
    #[throws]
    pub fn read_json<'a, D: Deserialize<'a>>(&'a self) -> D {
        serde_json::from_slice(&self.req_body)?
    }

    /// Write the input as the response body. This also sets the
    /// `Content-Type` to `application/octet-stream`.
    pub fn write_bytes(&mut self, body: &[u8]) {
        self.resp_body = body.to_vec();
        self.set_content_type("application/octet-stream");
    }

    /// Serialize the input as the response body. This also sets the
    /// `Content-Type` to `application/json`.
    #[throws]
    pub fn write_json<S: Serialize>(&mut self, body: &S) {
        self.resp_body = serde_json::to_vec(body)?;
        self.set_content_type("application/json");
    }

    /// Write the input as the response body with utf-8 encoding. This
    /// also sets the `Content-Type` to `text/plain; charset=UTF-8`.
    pub fn write_text(&mut self, body: &str) {
        self.resp_body = body.as_bytes().to_vec();
        self.set_content_type("text/plain; charset=UTF-8");
    }

    /// Set the response status code.
    pub fn set_status(&mut self, status: StatusCode) {
        self.status = status;
    }

    /// Set the response status code to 404 (not found).
    pub fn set_not_found(&mut self) {
        self.set_status(StatusCode::NotFound);
    }

    /// Set a response header.
    pub fn set_header(&mut self, name: &str, value: &str) {
        self.resp_headers.insert(name.into(), value.into());
    }

    /// Set the `Content-Type` response header.
    pub fn set_content_type(&mut self, value: &str) {
        self.set_header("Content-Type", value);
    }

    /// Get a path parameter. For example, if an input route
    /// "/resource/:key" is defined, the handler can get the ":key"
    /// portion by calling `path_param("key")`. The returned type can
    /// be anything that implements `FromStr`.
    #[throws]
    pub fn path_param<F>(&self, name: &str) -> F
    where
        F::Err: std::error::Error + Send + Sync + 'static,
        F: FromStr,
    {
        let value = self
            .path_params
            .get(name)
            .ok_or_else(|| anyhow!("path param {} not found", name))?;
        value
            .parse()
            .with_context(|| format!("failed to parse path param {}", name))?
    }
}

/// Handler function for a route.
pub type Handler<E> = dyn Fn(&mut Request) -> Result<(), E> + Send + Sync;

/// Error handler function.
pub type ErrorHandler<E> = dyn Fn(&mut Request, &RequestError<E>) + Send + Sync;

type ErrorHandlerArc<E> = Arc<RwLock<ErrorHandler<E>>>;

#[derive(Clone)]
struct Path {
    parts: Vec<String>,
}

fn match_path(
    path: &Path,
    route_path: &Path,
) -> Option<HashMap<String, String>> {
    let mut map = HashMap::new();
    for (left, right) in path.parts.iter().zip(route_path.parts.iter()) {
        let is_placeholder = right.starts_with(':');
        if !is_placeholder && left != right {
            return None;
        }
        if is_placeholder {
            map.insert(right[1..].to_string(), left.to_string());
        }
    }
    Some(map)
}

impl FromStr for Path {
    type Err = Infallible;

    #[throws(Self::Err)]
    fn from_str(s: &str) -> Path {
        Path {
            parts: s.split('/').map(|p| p.to_string()).collect(),
        }
    }
}

struct Route<E> {
    method: String,
    path: Path,
    handler: Box<Handler<E>>,
}

type Routes<E> = Arc<RwLock<Vec<Route<E>>>>;

/// Errors that can occur when dispatching an error to a handler.
#[derive(Debug, thiserror::Error)]
pub enum RequestError<E: Debug + Display> {
    /// No matching handler found.
    #[error("not found")]
    NotFound,

    /// Customer error returned by a handler.
    #[error("custom: {0}")]
    Custom(E),
}

fn default_error_handler<E: Debug + Display>(
    req: &mut Request,
    error: &RequestError<E>,
) {
    match error {
        RequestError::NotFound => {
            error!("not found: {}", req.url().path());
            req.set_status(StatusCode::NotFound);
            req.write_text("not found");
        }
        RequestError::Custom(err) => {
            error!("error handling {}: {}", req.url().path(), err);
            req.set_status(StatusCode::InternalServerError);
            req.write_text("internal server error");
        }
    }
}

fn dispatch_request<E: Debug + Display>(
    routes: Routes<E>,
    path: &Path,
    req: &mut Request,
) -> Result<(), RequestError<E>> {
    for route in &*routes.read().unwrap() {
        if req.method != route.method {
            continue;
        }

        if let Some(path_params) = match_path(path, &route.path) {
            req.path_params = path_params;
            (route.handler)(req).map_err(RequestError::Custom)?;
            return Ok(());
        }
    }

    Err(RequestError::NotFound)
}

#[throws]
fn handle_connection<E: Debug + Display>(
    stream: TcpStream,
    routes: Routes<E>,
    error_handler: ErrorHandlerArc<E>,
) {
    let mut stream = BufStream::new(stream);
    let mut line = String::new();
    stream
        .read_line(&mut line)
        .context("missing request header")?;
    let parts = line.split_whitespace().take(3).collect::<Vec<_>>();
    if parts.len() != 3 {
        throw!(anyhow!("invalid request: {}", line));
    }
    let method = parts[0];
    let raw_path = parts[1];
    let path = raw_path.parse::<Path>()?;

    // Parse headers
    // TODO: do duplicate headers accumulate? should be Vec value if so
    let mut headers: HashMap<HeaderName, String> = HashMap::new();
    loop {
        let mut line = String::new();
        stream.read_line(&mut line).context("failed to read line")?;

        let mut parts = line.splitn(2, ':');
        if let Some(name) = parts.next() {
            let value = parts.next().unwrap_or("");
            headers.insert(name.into(), value.trim().to_string());
        }

        if line.trim().is_empty() {
            break;
        }
    }

    let mut req_body = Vec::new();
    if let Some(len) = headers.get(&HeaderName::new("Content-Length".into())) {
        if let Ok(len) = len.parse::<usize>() {
            req_body.resize(len, 0);
            stream.read_exact(&mut req_body)?;
        }
    }

    let host = headers
        .get(&HeaderName::new("host".into()))
        .ok_or_else(|| anyhow!("missing host header"))?;
    let mut url = Url::parse(&format!("http://{}", host))
        .with_context(|| format!("failed to parse host {}", host))?;
    url.set_path(raw_path);

    let mut req = Request {
        method: method.into(),
        path_params: HashMap::new(),
        req_headers: headers,
        req_body,
        url,

        resp_body: Vec::new(),
        status: StatusCode::Ok,
        resp_headers: HashMap::new(),
    };

    if let Err(err) = dispatch_request(routes, &path, &mut req) {
        (error_handler.read().unwrap())(&mut req, &err);
    }

    stream.write_all(
        format!(
            "HTTP/1.1 {} {}\n",
            req.status,
            req.status.canonical_reason(),
        )
        .as_bytes(),
    )?;
    for (name, value) in req.resp_headers {
        stream.write_all(format!("{}: {}\n", name, value).as_bytes())?;
    }
    stream.write_all(
        format!("Content-Length: {}\n", req.resp_body.len()).as_bytes(),
    )?;
    stream.write_all(b"\n")?;
    stream.write_all(&req.resp_body)?;
}

/// Test request for calling Server::test_request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TestRequest {
    body: Vec<u8>,
    method: String,
    url: Url,
    headers: HashMap<String, String>,
}

impl TestRequest {
    /// Create a new test request with the method, URL, and body set.
    ///
    /// The input string should be in the format "METHOD /path". The
    /// path will automatically be expanded to a full URL:
    /// "http://example.com/path".
    #[throws]
    pub fn new_with_body(s: &str, body: &[u8]) -> TestRequest {
        let parts = s.split_whitespace().collect::<Vec<_>>();
        TestRequest {
            body: body.into(),
            method: parts[0].into(),
            url: Url::parse(&format!("http://example.com{}", parts[1]))?,
            headers: HashMap::new(),
        }
    }

    /// Create a new test request with the method, URL, and body set.
    ///
    /// The input string should be in the format "METHOD /path". The
    /// path will automatically be expanded to a full URL:
    /// "http://example.com/path".
    #[throws]
    pub fn new_with_json<S: Serialize>(s: &str, body: &S) -> TestRequest {
        let parts = s.split_whitespace().collect::<Vec<_>>();
        TestRequest {
            body: serde_json::to_vec(body)?,
            method: parts[0].into(),
            url: Url::parse(&format!("http://example.com{}", parts[1]))?,
            headers: HashMap::new(),
        }
    }

    /// Create a new test request with the method and URL set.
    ///
    /// The input string should be in the format "METHOD /path". The
    /// path will automatically be expanded to a full URL:
    /// "http://example.com/path".
    #[throws]
    pub fn new(s: &str) -> TestRequest {
        Self::new_with_body(s, &Vec::new())?
    }

    #[throws]
    fn path(&self) -> Path {
        self.url.path().parse()?
    }
}

/// Response from calling Server::test_request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TestResponse {
    /// Response code.
    pub status: StatusCode,

    /// Response body.
    pub body: Vec<u8>,

    /// Response headers.
    pub headers: HashMap<HeaderName, String>,
}

impl TestResponse {
    /// Parse the test response body as JSON.
    #[throws]
    pub fn json<'a, D: Deserialize<'a>>(&'a self) -> D {
        serde_json::from_slice(&self.body)?
    }
}

fn convert_header_map_to_unicase(
    map: &HashMap<String, String>,
) -> HashMap<HeaderName, String> {
    map.iter()
        .map(|(key, val)| (HeaderName::new(key.clone()), val.clone()))
        .collect()
}

/// HTTP 1.1 server.
///
/// Example usage:
/// ```no_run
/// use anyhow::Error;
/// use fehler::throws;
/// use shs::{Request, Server};
///
/// #[throws]
/// fn handler(req: &mut Request) {
///     todo!();
/// }
///
/// let mut server = Server::new("127.0.0.1:1234")?;
/// server.route("GET /hello", &handler)?;
/// server.launch()?;
/// # Ok::<(), Error>(())
/// ```
pub struct Server<E: Debug + Display> {
    address: SocketAddr,

    // The Routes and ErrorHandlerArc types puts the contents behind
    // an Arc<RwLock>. For the non-test case, the launch() function
    // consumes self, so we could just move a regular Vec<Route> into
    // the Arc with no RwLock needed. But test_request does not
    // consume self, since you want to be able to call test_request
    // multiple times, so a RwLock is needed.
    routes: Routes<E>,
    error_handler: ErrorHandlerArc<E>,
}

impl<E: Debug + Display + 'static> Server<E> {
    /// Create a new Server.
    #[throws]
    pub fn new(address: &str) -> Server<E> {
        Server {
            address: address.parse::<SocketAddr>()?,
            routes: Arc::new(RwLock::new(Vec::new())),
            error_handler: Arc::new(RwLock::new(Box::new(
                default_error_handler,
            ))),
        }
    }

    /// Add a new route. The basic format is `"METHOD /path"`. The
    /// path can contain parameters that start with a colon, for
    /// example `"/resource/:key"`; these parameters act as wild cards
    /// that can match any single path segment.
    #[throws]
    pub fn route(&mut self, route: &str, handler: &'static Handler<E>) {
        let mut iter = route.split_whitespace();
        let method = iter.next().ok_or_else(|| anyhow!("missing method"))?;
        let path = iter.next().ok_or_else(|| anyhow!("missing path"))?;
        let mut routes = self.routes.write().unwrap();
        routes.push(Route {
            method: method.into(),
            path: path.parse()?,
            handler: Box::new(handler),
        });
    }

    /// Set a custom error handler.
    ///
    /// The default error handler:
    /// - Logs the error
    /// - If the error is NotFound, sets the status to NotFound and
    ///   the body to "not found"
    /// - If the error is Custom, sets the status to
    ///   InternalServerError and the body to "internal server error"
    pub fn set_error_handler(
        &mut self,
        error_handler: &'static ErrorHandler<E>,
    ) {
        self.error_handler = Arc::new(RwLock::new(Box::new(error_handler)));
    }

    /// Start the server.
    pub fn launch(self) -> Result<(), Error> {
        let listener = TcpListener::bind(self.address)?;
        loop {
            let (tcp_stream, _addr) = listener.accept()?;
            let routes = self.routes.clone();
            let error_handler = self.error_handler.clone();

            // Handle the request in a new thread
            if let Err(err) = thread::Builder::new()
                .name("shs-handler".into())
                .spawn(move || {
                    if let Err(err) =
                        handle_connection(tcp_stream, routes, error_handler)
                    {
                        error!("{}", err);
                    }
                })
            {
                error!("failed to spawn thread: {}", err);
            }
        }
    }

    /// Send a fake request for testing.
    pub fn test_request(
        &self,
        input: &TestRequest,
    ) -> Result<TestResponse, RequestError<E>> {
        let mut req = Request {
            method: input.method.clone(),
            path_params: HashMap::new(),
            req_headers: convert_header_map_to_unicase(&input.headers),
            req_body: input.body.clone(),
            url: input.url.clone(),

            resp_body: Vec::new(),
            status: StatusCode::Ok,
            resp_headers: HashMap::new(),
        };
        let path = input.path().unwrap();
        dispatch_request(self.routes.clone(), &path, &mut req)?;

        Ok(TestResponse {
            status: req.status,
            body: req.resp_body,
            headers: convert_header_map_to_unicase(&req.resp_headers),
        })
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}