tii 0.0.6

A Low-Latency Web Server.
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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! Contains the impl of the router.

use crate::functional_traits::{
  HttpEndpoint, RequestFilter, ResponseFilter, Router, RouterFilter,
  RouterWebSocketServingResponse, WebsocketEndpoint,
};
use crate::stream::ConnectionStream;
use crate::tii_builder::{ErrorHandler, NotRouteableHandler};
use crate::tii_error::{InvalidPathError, RequestHeadParsingError, TiiError, TiiResult};
use crate::util::unwrap_some;
use crate::QValue;
use crate::RequestContext;
use crate::{trace_log, util};
use crate::{warn_log, HttpHeaderName};
use crate::{AcceptMimeTypeWithCharset, HttpVersion, MimeCharset, MimeTypeWithCharset};
use crate::{HttpMethod, ResponseContext};
use crate::{Response, StatusCode};
use base64::Engine;
use regex::{Error, Regex};
use sha1::{Digest, Sha1};
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Display, Formatter};
use std::sync::Arc;

#[derive(Debug, Clone)]
enum PathPart {
  Literal(String),
  Variable(String),
  Wildcard,
  RegexVariable(String, Regex),
  RegexTailVariable(String, Regex),
}

impl PathPart {
  fn parse(path: impl AsRef<str>) -> TiiResult<Vec<PathPart>> {
    let mut path = path.as_ref();
    let full_path = path;
    if path == "/" || path.is_empty() {
      return Ok(Vec::new());
    }

    if path.starts_with("/") {
      path = &path[1..];
    }

    let mut parts = Vec::new();
    loop {
      if path.is_empty() || path == "/" {
        return Ok(parts);
      }

      let part = if let Some(idx) = path.find("/") {
        let part = &path[0..idx];
        path = &path[idx + 1..];
        part
      } else {
        let part = path;
        path = "";
        part
      };

      if part == "*" {
        parts.push(PathPart::Wildcard);
        if !path.is_empty() && path != "/" {
          return Err(InvalidPathError::MorePartsAfterWildcard(full_path.to_string()).into());
        }
        return Ok(parts);
      }

      if part.starts_with("{") && part.ends_with("}") {
        let variable = &part[1..part.len() - 1];
        if let Some((name, regex)) = variable.split_once(":") {
          let reg = Regex::new(regex).map_err(|e| match e {
            Error::Syntax(syntax) => {
              InvalidPathError::RegexSyntaxError(full_path.to_string(), regex.to_string(), syntax)
            }
            Error::CompiledTooBig(limit) => {
              InvalidPathError::RegexTooBig(full_path.to_string(), regex.to_string(), limit)
            }
            _ => InvalidPathError::RegexSyntaxError(
              full_path.to_string(),
              regex.to_string(),
              e.to_string(),
            ),
          })?;
          if !path.is_empty() && path != "/" {
            parts.push(PathPart::RegexVariable(name.to_string(), reg));
            continue;
          }

          parts.push(PathPart::RegexTailVariable(name.to_string(), reg));
          continue;
        }

        parts.push(PathPart::Variable(variable.to_string()));
        continue;
      }

      parts.push(PathPart::Literal(part.to_string()));
    }
  }

  const fn is_tail(&self) -> bool {
    matches!(self, PathPart::Wildcard | PathPart::RegexTailVariable(_, _))
  }
  fn matches(
    &self,
    part: &str,
    remaining: &str,
    variables: &mut Option<HashMap<String, String>>,
  ) -> bool {
    match self {
      PathPart::Literal(literal) => part == literal.as_str(),
      PathPart::Variable(var_name) => {
        if variables.is_none() {
          variables.replace(HashMap::new());
        }

        unwrap_some(variables.as_mut()).insert(var_name.to_string(), part.to_string());
        true
      }
      PathPart::Wildcard => true,
      PathPart::RegexVariable(var_name, regex) => {
        if regex.is_match(part) {
          if variables.is_none() {
            variables.replace(HashMap::new());
          }

          unwrap_some(variables.as_mut()).insert(var_name.to_string(), part.to_string());
          return true;
        }
        false
      }
      PathPart::RegexTailVariable(var_name, regex) => {
        if regex.is_match(remaining) {
          if variables.is_none() {
            variables.replace(HashMap::new());
          }

          unwrap_some(variables.as_mut()).insert(var_name.to_string(), remaining.to_string());
          return true;
        }
        false
      }
    }
  }
}

#[derive(Debug, Clone)]
/// Encapsulates a route and its handler.
pub struct Routeable {
  /// The route that this handler will match.
  path: String,

  parts: Vec<PathPart>,

  /// The method this route will handle
  method: HttpMethod,

  /// The mime types this route can consume
  /// EMPTY SET means this route does not expect a request body.
  consumes: HashSet<AcceptMimeTypeWithCharset>,

  /// The mime types this route can produce
  /// EMPTY SET means this route will produce a matching body type.
  produces: HashSet<AcceptMimeTypeWithCharset>,
}

pub(crate) struct HttpRoute {
  pub(crate) routeable: Routeable,

  /// The handler to run when the route is matched.
  pub(crate) handler: Box<dyn HttpEndpoint>,
}

pub(crate) struct WebSocketRoute {
  pub(crate) routeable: Routeable,

  /// The handler to run when the route is matched.
  pub(crate) handler: Box<dyn WebsocketEndpoint>,
}

impl HttpRoute {
  pub(crate) fn new(
    path: impl ToString,
    method: impl Into<HttpMethod>,
    consumes: HashSet<AcceptMimeTypeWithCharset>,
    produces: HashSet<AcceptMimeTypeWithCharset>,
    route: impl HttpEndpoint + 'static,
  ) -> TiiResult<Self> {
    Ok(HttpRoute {
      routeable: Routeable::new(path, method, consumes, produces)?,
      handler: Box::new(route) as Box<dyn HttpEndpoint>,
    })
  }
}

impl WebSocketRoute {
  pub(crate) fn new(
    path: impl ToString,
    method: impl Into<HttpMethod>,
    consumes: HashSet<AcceptMimeTypeWithCharset>,
    produces: HashSet<AcceptMimeTypeWithCharset>,
    route: impl WebsocketEndpoint + 'static,
  ) -> TiiResult<Self> {
    Ok(WebSocketRoute {
      routeable: Routeable::new(path, method, consumes, produces)?,
      handler: Box::new(route) as Box<dyn WebsocketEndpoint>,
    })
  }
}

/// Enum that shows information on how a particular request could be routed on a route.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum RoutingDecision {
  /// Routing matches with the given quality and path params.
  Match(QValue, Option<HashMap<String, String>>),
  /// Path doesnt match.
  PathMismatch,
  /// Path matches, but method doesn't.
  MethodMismatch,
  /// Path and method do match, but the request body cannot be processed by the route.
  MimeMismatch,
  /// Path and method do match, the body can be processed but the response of the endpoint will not be processable by the client.
  AcceptMismatch,
}

impl Display for RoutingDecision {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    //TODO make this not shit
    Debug::fmt(self, f)
  }
}

impl PartialOrd for RoutingDecision {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Ord for RoutingDecision {
  fn cmp(&self, other: &Self) -> Ordering {
    match (self, other) {
      (RoutingDecision::Match(q1, _), RoutingDecision::Match(q2, _)) => q1.cmp(q2),
      (RoutingDecision::Match(_, _), RoutingDecision::PathMismatch) => Ordering::Greater,
      (RoutingDecision::Match(_, _), RoutingDecision::MethodMismatch) => Ordering::Greater,
      (RoutingDecision::Match(_, _), RoutingDecision::MimeMismatch) => Ordering::Greater,
      (RoutingDecision::Match(_, _), RoutingDecision::AcceptMismatch) => Ordering::Greater,

      (RoutingDecision::PathMismatch, RoutingDecision::Match(_, _)) => Ordering::Less,
      (RoutingDecision::PathMismatch, RoutingDecision::PathMismatch) => Ordering::Equal,
      (RoutingDecision::PathMismatch, RoutingDecision::MethodMismatch) => Ordering::Less,
      (RoutingDecision::PathMismatch, RoutingDecision::MimeMismatch) => Ordering::Less,
      (RoutingDecision::PathMismatch, RoutingDecision::AcceptMismatch) => Ordering::Less,

      (RoutingDecision::MethodMismatch, RoutingDecision::Match(_, _)) => Ordering::Less,
      (RoutingDecision::MethodMismatch, RoutingDecision::PathMismatch) => Ordering::Greater,
      (RoutingDecision::MethodMismatch, RoutingDecision::MethodMismatch) => Ordering::Equal,
      (RoutingDecision::MethodMismatch, RoutingDecision::MimeMismatch) => Ordering::Less,
      (RoutingDecision::MethodMismatch, RoutingDecision::AcceptMismatch) => Ordering::Less,

      (RoutingDecision::MimeMismatch, RoutingDecision::Match(_, _)) => Ordering::Less,
      (RoutingDecision::MimeMismatch, RoutingDecision::PathMismatch) => Ordering::Greater,
      (RoutingDecision::MimeMismatch, RoutingDecision::MethodMismatch) => Ordering::Greater,
      (RoutingDecision::MimeMismatch, RoutingDecision::MimeMismatch) => Ordering::Equal,
      (RoutingDecision::MimeMismatch, RoutingDecision::AcceptMismatch) => Ordering::Less,

      (RoutingDecision::AcceptMismatch, RoutingDecision::Match(_, _)) => Ordering::Less,
      (RoutingDecision::AcceptMismatch, RoutingDecision::PathMismatch) => Ordering::Greater,
      (RoutingDecision::AcceptMismatch, RoutingDecision::MethodMismatch) => Ordering::Greater,
      (RoutingDecision::AcceptMismatch, RoutingDecision::MimeMismatch) => Ordering::Greater,
      (RoutingDecision::AcceptMismatch, RoutingDecision::AcceptMismatch) => Ordering::Equal,
    }
  }
}

impl Routeable {
  pub(crate) fn new(
    path: impl ToString,
    method: impl Into<HttpMethod>,
    consumes: HashSet<AcceptMimeTypeWithCharset>,
    produces: HashSet<AcceptMimeTypeWithCharset>,
  ) -> TiiResult<Routeable> {
    let path = path.to_string();
    Ok(Routeable {
      parts: PathPart::parse(path.as_str())?,
      path,
      method: method.into(),
      consumes,
      produces,
    })
  }

  /// The path for this route
  pub fn get_path(&self) -> &str {
    self.path.as_str()
  }

  /// The method for this route
  pub fn get_method(&self) -> &HttpMethod {
    &self.method
  }

  /// The mime types this route can consume
  pub fn get_consumes(&self) -> &HashSet<AcceptMimeTypeWithCharset> {
    &self.consumes
  }

  /// The mime types this route can produce
  pub fn get_produces(&self) -> &HashSet<AcceptMimeTypeWithCharset> {
    &self.produces
  }

  fn matches_path(
    &self,
    route: &RequestContext,
    path_params: &mut Option<HashMap<String, String>>,
  ) -> bool {
    let mut request_path = route.get_path();
    if !request_path.starts_with("/") {
      return false;
    }

    request_path = &request_path[1..];

    if request_path.is_empty() && self.parts.is_empty() {
      return true;
    }

    let mut parts = self.parts.iter();
    loop {
      if let Some((path_part, remaining)) = request_path.split_once("/") {
        if let Some(part) = parts.next() {
          if !part.matches(path_part, request_path, path_params) {
            return false;
          }
          if part.is_tail() {
            return true;
          }

          request_path = remaining;
          continue;
        }

        return false;
      }

      if let Some(part) = parts.next() {
        if !part.matches(request_path, request_path, path_params) {
          return false;
        }

        if part.is_tail() {
          return true;
        }

        request_path = "";
        continue;
      }

      if request_path.is_empty() {
        return true;
      }

      return false;
    }
  }

  /// Checks whether this route matches the given one, respecting its own wildcards only.
  /// For example, `/blog/*` will match `/blog/my-first-post` but not the other way around.
  pub fn matches(&self, route: &RequestContext) -> RoutingDecision {
    let mut path_params = None;

    if !self.matches_path(route, &mut path_params) {
      return RoutingDecision::PathMismatch;
    }

    if &self.method != route.get_method() {
      return RoutingDecision::MethodMismatch;
    }

    if let Some(content_type) = route.get_content_type() {
      let mut found = false;
      for acceptable in &self.consumes {
        if acceptable.mime().permits_specific(content_type)
          && (!acceptable.has_charset() || acceptable.charset() == content_type.charset())
        {
          found = true;
          break;
        }
      }

      if !found {
        return RoutingDecision::MimeMismatch;
      }
    }

    if self.produces.is_empty() {
      //The endpoint either doesn't produce a body or declares that it will produce a matching body...
      return RoutingDecision::Match(QValue::MAX, path_params);
    }

    let acc = route.get_accept();
    if acc.is_empty() {
      //The client doesn't accept a body.
      return RoutingDecision::MimeMismatch;
    }

    // TODO Should we offer this as a map? type -> q?
    // Probably not because requests with more than a few accept charsets are not really... common...
    let accept_charset_from_hdr = route.get_accept();

    let mut current_q = None;
    for accept in acc {
      for mime in &self.produces {
        if !accept.get_type().permits(mime.mime()) {
          continue;
        }

        if accept.charset() != &MimeCharset::Unspecified
          && mime.charset() != &MimeCharset::Unspecified
          && mime.charset() != accept.charset()
        {
          // TODO this is not correct. We have to split q for content type and charset. They have semi independent q.
          // This is likely good enough tho and will only cause issues with seriously retarded requests.
          let mut found = false;
          for accepted_charset in accept_charset_from_hdr.iter().map(|c| c.charset()) {
            if accepted_charset == mime.charset() {
              found = true;
              break;
            }
          }

          if !found {
            continue;
          }
        }

        let qvalue = accept.qvalue();
        if qvalue == QValue::MAX {
          return RoutingDecision::Match(qvalue, path_params);
        }

        match &current_q {
          None => {
            current_q = Some(accept.qvalue());
          }
          Some(current) => {
            if current < &qvalue {
              current_q = Some(accept.qvalue());
            }
          }
        }
      }
    }

    if let Some(qval) = current_q {
      return RoutingDecision::Match(qval, path_params);
    }

    RoutingDecision::AcceptMismatch
  }
}

impl Debug for HttpRoute {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    f.write_fmt(format_args!("HttpRoute({})", self.routeable.path.as_str()))
  }
}

impl Debug for WebSocketRoute {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    f.write_fmt(format_args!("HttpRoute({})", self.routeable.path.as_str()))
  }
}

/// Represents a sub-app to run for a specific host.
pub(crate) struct DefaultRouter {
  /// This filter/predicate will decide if the router should even serve the request at all
  router_filter: Box<dyn RouterFilter>,

  /// Filters that run before the route is matched.
  /// These filters may modify the path of the request to affect routing decision.
  pre_routing_filters: Vec<Box<dyn RequestFilter>>,

  /// Filters that run once the routing decision has been made.
  /// These filters only run if there is an actual endpoint.
  routing_filters: Vec<Box<dyn RequestFilter>>,

  /// These filters run on the response after the actual endpoint (or the error handler) has been called.
  response_filters: Vec<Box<dyn ResponseFilter>>,

  /// Contains all pathing information for websockets and normal http routes.
  /// This is essentially a union of routes and websocket_routes without the handler
  routeables: Vec<Routeable>,

  /// The routes to process requests for and their handlers.
  routes: Vec<HttpRoute>,

  /// The routes to process WebSocket requests for and their handlers.
  websocket_routes: Vec<WebSocketRoute>,

  /// Called when no route has been found in the router.
  not_found_handler: NotRouteableHandler,

  /// Called when no acceptable route has been found
  not_acceptable_handler: NotRouteableHandler,
  /// Called when no route with a handled method has been found.
  method_not_allowed_handler: NotRouteableHandler,
  /// Called when no route with a given media type has been found.
  unsupported_media_type_handler: NotRouteableHandler,

  /// Called when an error in any of the above occurs.
  error_handler: ErrorHandler,
}

impl Debug for DefaultRouter {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    f.write_fmt(format_args!("TiiRouter(pre_routing_filters={}, routing_filters={}, response_filters={}, routes={:?}, websocket_routes={})",
                                 self.pre_routing_filters.len(),
            self.routing_filters.len(),
            self.response_filters.len(),
            self.routes,
            self.websocket_routes.len(),
        ))
  }
}

/// Performs the WebSocket handshake.
fn websocket_handshake(request: &RequestContext) -> TiiResult<Response> {
  const HANDSHAKE_KEY_CONSTANT: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

  // Get the handshake key header
  let handshake_key = request
    .get_header("Sec-WebSocket-Key")
    .ok_or(RequestHeadParsingError::MissingSecWebSocketKeyHeader)?;

  // Calculate the handshake response
  let sha1 =
    Sha1::new().chain_update(handshake_key).chain_update(HANDSHAKE_KEY_CONSTANT).finalize();
  let sec_websocket_accept = base64::prelude::BASE64_STANDARD.encode(sha1);

  //let sec_websocket_accept = sha1.encode();

  // Serialise the handshake response
  let response = Response::new(StatusCode::SwitchingProtocols)
    .with_header(HttpHeaderName::Upgrade, "websocket")?
    .with_header(HttpHeaderName::Connection, "Upgrade")?
    .with_header("Sec-WebSocket-Accept", sec_websocket_accept)?;

  // Oddly enough I think you can establish a WS connection with a POST request that has data.
  // This will consume that data if it has not already been used by a filter.
  // Some beta versions of Web Sockets used the request body to convey the Sec-WebSocket-Key...
  request.consume_request_body()?;
  Ok(response)
}

impl DefaultRouter {
  #[expect(clippy::too_many_arguments)] //Only called by the builder.
  pub(crate) fn new(
    router_filter: Box<dyn RouterFilter>,
    pre_routing_filters: Vec<Box<dyn RequestFilter>>,
    routing_filters: Vec<Box<dyn RequestFilter>>,
    response_filters: Vec<Box<dyn ResponseFilter>>,
    routes: Vec<HttpRoute>,
    websocket_routes: Vec<WebSocketRoute>,
    not_found_handler: NotRouteableHandler,
    not_acceptable_handler: NotRouteableHandler,
    method_not_allowed_handler: NotRouteableHandler,
    unsupported_media_type_handler: NotRouteableHandler,
    error_handler: ErrorHandler,
  ) -> Self {
    let mut routeables = Vec::new();
    for x in routes.iter() {
      routeables.push(x.routeable.clone());
    }
    for x in websocket_routes.iter() {
      routeables.push(x.routeable.clone());
    }

    Self {
      router_filter,
      pre_routing_filters,
      routing_filters,
      response_filters,
      routeables,
      routes,
      websocket_routes,
      not_found_handler,
      not_acceptable_handler,
      method_not_allowed_handler,
      unsupported_media_type_handler,
      error_handler,
    }
  }

  fn serve_ws(
    &self,
    stream: &dyn ConnectionStream,
    request: &mut RequestContext,
  ) -> TiiResult<RouterWebSocketServingResponse> {
    //TODO this fn is too long and has significant duplicate parts with normal http serving.
    //TODO consolidate both impls and split it into smaller sub fn's

    if !self.router_filter.filter(request)? {
      return Ok(RouterWebSocketServingResponse::NotHandled);
    }

    for filter in self.pre_routing_filters.iter() {
      let resp = match filter.filter(request) {
        Ok(Some(res)) => res,
        Ok(None) => continue,
        Err(err) => (self.error_handler)(request, err)?,
      };

      let resp = self.call_response_filters(request, resp)?;
      return Ok(RouterWebSocketServingResponse::HandledWithoutProtocolSwitch(resp));
    }

    let mut best_decision = RoutingDecision::PathMismatch;
    let mut best_handler = None;

    for handler in &self.websocket_routes {
      let decision = handler.routeable.matches(request);
      if best_decision >= decision {
        continue;
      }

      best_decision = decision;
      if let RoutingDecision::Match(qv, _) = &best_decision {
        best_handler = Some(handler);
        if qv == &QValue::MAX {
          break;
        }
      }
    }

    if let Some(handler) = best_handler {
      request.set_routed_path(handler.routeable.path.as_str());
      self.handle_path_parameters(request, &best_decision);

      for filter in self.routing_filters.iter() {
        let resp = match filter.filter(request) {
          Ok(Some(res)) => res,
          Ok(None) => continue,
          Err(err) => (self.error_handler)(request, err)?,
        };

        let resp = self.call_response_filters(request, resp)?;
        return Ok(RouterWebSocketServingResponse::HandledWithoutProtocolSwitch(resp));
      }

      return match websocket_handshake(request) {
        Err(err) => {
          let resp = (self.error_handler)(request, err)?;
          let resp = self.call_response_filters(request, resp)?;
          Ok(RouterWebSocketServingResponse::HandledWithoutProtocolSwitch(resp))
        }
        Ok(resp) => {
          let resp = self.call_response_filters(request, resp)?;
          if resp.status_code != StatusCode::SwitchingProtocols {
            return Ok(RouterWebSocketServingResponse::HandledWithoutProtocolSwitch(resp));
          }

          if let Some(enc) = resp.get_body().and_then(|a| a.get_content_encoding()) {
            if enc == "gzip" && !request.accepts_gzip() {
              warn_log!("Request {} responding with gzip even tho client doesnt indicate that it can understand gzip.", request.id());
            }
          }

          resp.write_to(request.id(), HttpVersion::Http11, stream)?; //Errors here are fatal

          let (sender, receiver) = crate::new_web_socket_stream(stream);
          handler.handler.serve(request, receiver, sender)?;
          Ok(RouterWebSocketServingResponse::HandledWithProtocolSwitch)
        }
      };
    }

    trace_log!("WebsocketConnectionClosed Invoke fallback {}", &best_decision);

    let fallback = self.invoke_appropriate_fallback_handler(request, &best_decision);

    let fallback_resp = match fallback {
      Ok(resp) => self.call_response_filters(request, resp)?,
      Err(err) => {
        let resp = (self.error_handler)(request, err)?;
        self.call_response_filters(request, resp)?
      }
    };
    Ok(RouterWebSocketServingResponse::HandledWithoutProtocolSwitch(fallback_resp))
  }

  fn handle_path_parameters(&self, request: &mut RequestContext, best_decision: &RoutingDecision) {
    match best_decision {
      RoutingDecision::Match(_, path_params) => {
        if let Some(path_params) = path_params {
          for (key, value) in path_params {
            request.set_path_param(key, value);
          }
        }
      }
      _ => util::unreachable(),
    }
  }

  fn call_error_handler(
    &self,
    request: &mut RequestContext,
    error: TiiError,
  ) -> TiiResult<Response> {
    //TODO i am not 100% sure this is a good idea, but it probably is a good idea.
    //The only thing i could consider is having the default impl do this and outsource this responsibility to the user
    //Not doing this on io::Errors when reading the request body will cause stuff to break in a horrific manner.
    //So always doing this is safer, but prevents keepalive in cases where the error is unrelated to the http stream
    //and the user properly handles it.
    request.force_connection_close();

    (self.error_handler)(request, error)
  }

  fn serve_outer(&self, request: &mut RequestContext) -> TiiResult<Option<Response>> {
    if !self.router_filter.filter(request)? {
      return Ok(None);
    }

    let mut resp = self.serve_inner(request).or_else(|e| self.call_error_handler(request, e))?;
    resp = self.call_response_filters(request, resp)?;

    Ok(Some(resp))
  }

  fn call_response_filters(
    &self,
    request: &mut RequestContext,
    resp: Response,
  ) -> TiiResult<Response> {
    let mut resp = ResponseContext::new(request, resp);
    for filter in self.response_filters.iter() {
      filter.filter(&mut resp).or_else(|e| {
        // TODO we should give the error handler
        // TODO a shot at the response now that we dont move ownership into the filter anymore.
        let result = self.call_error_handler(resp.get_request_mut(), e)?;
        resp.set_response(result);
        TiiResult::Ok(())
      })?;
    }
    let (_, resp) = resp.unwrap();
    Ok(resp)
  }

  fn serve_inner(&self, request: &mut RequestContext) -> TiiResult<Response> {
    for filter in self.pre_routing_filters.iter() {
      if let Some(resp) = filter.filter(request)? {
        return Ok(resp);
      }
    }

    let mut best_decision = RoutingDecision::PathMismatch;
    let mut best_handler = None;

    for handler in &self.routes {
      let decision = handler.routeable.matches(request);
      if best_decision >= decision {
        continue;
      }

      best_decision = decision;
      if let RoutingDecision::Match(qv, _) = &best_decision {
        best_handler = Some(handler);
        if qv == &QValue::MAX {
          break;
        }
      }
    }

    if let Some(handler) = best_handler {
      request.set_routed_path(handler.routeable.path.as_str());

      if request.get_request_entity().is_none() {
        if let Some(body) = request.request_body() {
          request.set_request_entity(handler.handler.parse_entity(
            request.get_content_type().unwrap_or(&MimeTypeWithCharset::APPLICATION_OCTET_STREAM),
            body,
          )?);
        }
      }

      self.handle_path_parameters(request, &best_decision);

      for filter in self.routing_filters.iter() {
        if let Some(resp) = filter.filter(request)? {
          return Ok(resp);
        }
      }

      return handler.handler.serve(request);
    }

    self.invoke_appropriate_fallback_handler(request, &best_decision)
  }

  fn invoke_appropriate_fallback_handler(
    &self,
    request: &mut RequestContext,
    best_decision: &RoutingDecision,
  ) -> TiiResult<Response> {
    match best_decision {
      RoutingDecision::PathMismatch => (self.not_found_handler)(request, &self.routeables),
      RoutingDecision::MethodMismatch => {
        (self.method_not_allowed_handler)(request, &self.routeables)
      }
      RoutingDecision::MimeMismatch => {
        (self.unsupported_media_type_handler)(request, &self.routeables)
      }
      RoutingDecision::AcceptMismatch => (self.not_acceptable_handler)(request, &self.routeables),
      // We found a handler! Why are we here?
      RoutingDecision::Match(_, _) => util::unreachable(),
    }
  }
}

impl Router for DefaultRouter {
  fn serve(&self, request: &mut RequestContext) -> TiiResult<Option<Response>> {
    self.serve_outer(request)
  }

  fn serve_websocket(
    &self,
    stream: &dyn ConnectionStream,
    request: &mut RequestContext,
  ) -> TiiResult<RouterWebSocketServingResponse> {
    self.serve_ws(stream, request)
  }
}

impl<T> Router for Arc<T>
where
  T: Router + ?Sized,
{
  fn serve(&self, request: &mut RequestContext) -> TiiResult<Option<Response>> {
    Arc::as_ref(self).serve(request)
  }

  fn serve_websocket(
    &self,
    stream: &dyn ConnectionStream,
    request: &mut RequestContext,
  ) -> TiiResult<RouterWebSocketServingResponse> {
    Arc::as_ref(self).serve_websocket(stream, request)
  }
}