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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
//! Contains all state that's needed to process a request.

use crate::http::headers::HttpHeaderName;
use crate::http::request::HttpVersion;
use crate::http::request_body::RequestBody;
use crate::http::RequestHead;
use crate::stream::ConnectionStream;
use crate::tii_error::{RequestHeadParsingError, TiiError, TiiResult};
use crate::tii_server::ConnectionStreamMetadata;
use crate::util::unwrap_some;
use crate::{
  debug_log, error_log, trace_log, util, warn_log, AcceptMimeCharset, AcceptQualityMimeType,
  Cookie, HttpHeader, HttpMethod, MimeType, MimeTypeWithCharset, TypeSystem, TypeSystemError,
  UserError,
};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::error::Error;
use std::fmt::Debug;
use std::io::ErrorKind;
use std::str::FromStr;
use std::sync::Arc;
use std::time::SystemTime;
use std::{io, mem};

/// This struct contains all information needed to process a request as well as all state
/// for a single request.
#[derive(Debug)]
pub struct RequestContext {
  id: u128,
  timestamp: u128,
  peer_address: String,
  local_address: String,
  request: RequestHead,
  body: Option<RequestBody>,
  request_entity: Option<Box<dyn Any + Send + Sync>>,
  force_connection_close: bool,
  stream_meta: Option<Arc<dyn ConnectionStreamMetadata>>,
  routed_path: Option<String>,
  path_params: Option<HashMap<String, String>>,
  properties: Option<HashMap<String, Box<dyn Any + Send>>>,
  type_system: TypeSystem,
}

impl RequestContext {
  /// Create a new RequestContext programmatically.
  /// This is useful for unit testing endpoints.
  /// # Errors
  /// return Err if the path/query/hears etc. are not valid is not a valid
  #[allow(clippy::too_many_arguments)] //For unit test and mocking only.
  pub fn new(
    id: u128,
    peer_address: impl ToString,
    local_address: impl ToString,
    method: HttpMethod,
    version: HttpVersion,
    path: impl ToString,
    query: Vec<(impl ToString, impl ToString)>,
    headers: Vec<HttpHeader>,
    body: Option<RequestBody>,
    stream_meta: Option<Arc<dyn ConnectionStreamMetadata>>,
    type_system: TypeSystem,
  ) -> TiiResult<Self> {
    Ok(Self {
      id,
      timestamp: SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|a| a.as_millis())
        .unwrap_or(0),
      peer_address: peer_address.to_string(),
      local_address: local_address.to_string(),
      request: RequestHead::new(method, version, path, query, headers)?,
      body,
      request_entity: None,
      force_connection_close: false,
      stream_meta,
      routed_path: None,
      path_params: None,
      properties: None,
      type_system,
    })
  }

  #[allow(clippy::too_many_arguments)]
  fn new_http09(
    id: u128,
    timestamp: u128,
    local_address: String,
    peer_address: String,
    req: RequestHead,
    _stream: &dyn ConnectionStream,
    stream_meta: Option<Arc<dyn ConnectionStreamMetadata>>,
    type_system: TypeSystem,
  ) -> TiiResult<RequestContext> {
    trace_log!("tii: Request {id} is http 0.9");

    Ok(RequestContext {
      id,
      timestamp,
      peer_address,
      local_address,
      request: req,
      body: None,
      request_entity: None,
      force_connection_close: true,
      properties: None,
      routed_path: None,
      stream_meta,
      path_params: None,
      type_system,
    })
  }

  #[allow(clippy::too_many_arguments)]
  fn new_http10(
    id: u128,
    timestamp: u128,
    local_address: String,
    peer_address: String,
    req: RequestHead,
    stream: &dyn ConnectionStream,
    stream_meta: Option<Arc<dyn ConnectionStreamMetadata>>,
    type_system: TypeSystem,
  ) -> TiiResult<RequestContext> {
    trace_log!("tii: Request {id} is http 1.0");

    if let Some(content_length) = req.get_header(&HttpHeaderName::ContentLength) {
      let content_length: u64 = content_length.parse().map_err(|_| {
        TiiError::from(RequestHeadParsingError::InvalidContentLength(content_length.to_string()))
      })?;

      if content_length == 0 {
        trace_log!("tii: Request {id} has no request body");
        return Ok(RequestContext {
          id,
          timestamp,
          peer_address,
          local_address,
          request: req,
          body: None,
          request_entity: None,
          force_connection_close: true,
          properties: None,
          routed_path: None,
          stream_meta,
          path_params: None,
          type_system,
        });
      }

      trace_log!("tii: Request {id} has {content_length} bytes of request body");
      let body = RequestBody::new_with_content_length(stream.new_ref_read(), content_length);
      return Ok(RequestContext {
        id,
        timestamp,
        peer_address,
        local_address,
        request: req,
        body: Some(body),
        request_entity: None,
        force_connection_close: true,
        properties: None,
        routed_path: None,
        stream_meta,
        path_params: None,
        type_system,
      });
    }

    trace_log!(
      "tii: Request {id} did not sent Content-Length header. Assuming that it has no request body"
    );
    Ok(RequestContext {
      id,
      timestamp,
      peer_address,
      local_address,
      request: req,
      body: None,
      request_entity: None,
      force_connection_close: true,
      properties: None,
      routed_path: None,
      stream_meta,
      path_params: None,
      type_system,
    })
  }

  #[allow(clippy::too_many_arguments)]
  fn new_http11(
    id: u128,
    timestamp: u128,
    local_address: String,
    peer_address: String,
    req: RequestHead,
    stream: &dyn ConnectionStream,
    stream_meta: Option<Arc<dyn ConnectionStreamMetadata>>,
    type_system: TypeSystem,
  ) -> TiiResult<RequestContext> {
    trace_log!("tii: Request {id} is http 1.1");

    let content_length =
      if let Some(content_length) = req.get_header(&HttpHeaderName::ContentLength) {
        Some(content_length.parse::<u64>().map_err(|_| {
          TiiError::from(RequestHeadParsingError::InvalidContentLength(content_length.to_string()))
        })?)
      } else {
        None
      };

    match (
      req.get_header(&HttpHeaderName::ContentEncoding),
      req.get_header(&HttpHeaderName::TransferEncoding),
    ) {
      (None, None) => match content_length {
        None => {
          if req.get_header(&HttpHeaderName::Connection) != Some("keep-alive") {
            trace_log!(
              "tii: Request {id} did not sent Content-Length header. Assuming that it has no request body. Connection: keep-alive was not explicitly requested, so will send Connection: close");

            return Ok(RequestContext {
              id,
              timestamp,
              peer_address,
              local_address,
              request: req,
              body: None,
              request_entity: None,
              force_connection_close: true,
              properties: None,
              routed_path: None,
              stream_meta,
              path_params: None,
              type_system,
            });
          }

          if req.get_method().is_likely_to_have_request_body() {
            warn_log!(
            "tii: Request {id} did not sent Content-Length header but did request Connection: keep-alive. Assuming that it has no request body. The request method {} usually has a body, will force Connection: close to be safe.", req.get_method()
            );

            return Ok(RequestContext {
              id,
              timestamp,
              peer_address,
              local_address,
              request: req,
              body: None,
              request_entity: None,
              force_connection_close: true,
              properties: None,
              routed_path: None,
              stream_meta,
              path_params: None,
              type_system,
            });
          }

          trace_log!(
            "tii: Request {id} did not sent Content-Length header. Assuming that it has no request body. Connection: keep-alive was requested, so will trust the client that the request actually has no body.");

          Ok(RequestContext {
            id,
            timestamp,
            peer_address,
            local_address,
            request: req,
            body: None,
            request_entity: None,
            force_connection_close: false,
            properties: None,
            routed_path: None,
            stream_meta,
            path_params: None,
            type_system,
          })
        }
        Some(0) => {
          trace_log!("tii: Request {id} has no request body");
          Ok(RequestContext {
            id,
            timestamp,
            peer_address,
            local_address,
            request: req,
            body: None,
            request_entity: None,
            force_connection_close: false,
            properties: None,
            routed_path: None,
            stream_meta,
            path_params: None,
            type_system,
          })
        }
        Some(content_length) => {
          trace_log!("tii: Request {id} has {content_length} bytes of request body");
          Ok(RequestContext {
            id,
            timestamp,
            peer_address,
            local_address,
            request: req,
            body: Some(RequestBody::new_with_content_length(stream.new_ref_read(), content_length)),
            request_entity: None,
            force_connection_close: false,
            properties: None,
            routed_path: None,
            stream_meta,
            path_params: None,
            type_system,
          })
        }
      },
      (None, Some("chunked")) => {
        trace_log!("tii: Request {id} has chunked request body");
        let body = RequestBody::new_chunked(stream.new_ref_read());
        Ok(RequestContext {
          id,
          timestamp,
          peer_address,
          local_address,
          request: req,
          body: Some(body),
          request_entity: None,
          force_connection_close: false,
          properties: None,
          routed_path: None,
          stream_meta,
          path_params: None,
          type_system,
        })
      }
      (None, Some("x-gzip")) | (None, Some("gzip")) => {
        trace_log!("tii: Request {id} has gzip request body with length of uncompressed content");
        let Some(content_length) = content_length else {
          error_log!("tii: Request {id} not implemented no transfer encoding, Content-Encoding: gzip/x-gzip without Content-Length header");
          return Err(TiiError::from(RequestHeadParsingError::ContentLengthHeaderMissing));
        };

        let body =
          RequestBody::new_gzip_with_uncompressed_length(stream.new_ref_read(), content_length)?;

        Ok(RequestContext {
          id,
          timestamp,
          peer_address,
          local_address,
          request: req,
          body: Some(body),
          //TODO, i have seen gzip produce trailer bytes in the past that are just padding
          //and I am not confident enough that libflate consumes them.
          //Until I have verified that libflate consumes the trailerbytes without fail we should not enable keep alive.
          request_entity: None,
          force_connection_close: true,
          properties: None,
          routed_path: None,
          stream_meta,
          path_params: None,
          type_system,
        })
      }
      (Some("gzip"), None) | (Some("x-gzip"), None) => {
        trace_log!("tii: Request {id} has gzip request body with length of compressed content");
        //gzip+Content-Length of zipped stuff
        let Some(content_length) = content_length else {
          error_log!("tii: Request {id} not implemented Transfer-Encoding: gzip/x-gzip, no Content-Encoding without Content-Length header");
          return Err(TiiError::from(RequestHeadParsingError::ContentLengthHeaderMissing));
        };

        //TODO curl, hyper and several http server implementation disagree on how this should be handled.
        //Its safe to assume that no client will ever send this...
        //We may have to read the full rfc eventually, the rfc only mentions that this exists and
        //This impl is honestly based upon some forum comments of a obscure http proxy.
        let body = RequestBody::new_gzip_with_compressed_content_length(
          stream.new_ref_read(),
          content_length,
        )?;
        Ok(RequestContext {
          id,
          timestamp,
          peer_address,
          local_address,
          request: req,
          body: Some(body),
          request_entity: None,
          force_connection_close: false,
          properties: None,
          routed_path: None,
          stream_meta,
          path_params: None,
          type_system,
        })
      }
      (Some("gzip"), Some("chunked"))
      | (Some("x-gzip"), Some("chunked"))
      | (None, Some("gzip, chunked"))
      | (None, Some("x-gzip, chunked")) => {
        trace_log!("tii: Request {id} has chunked gzip request body");
        let body = RequestBody::new_gzip_chunked(stream.new_ref_read())?;
        Ok(RequestContext {
          id,
          timestamp,
          peer_address,
          local_address,
          request: req,
          body: Some(body),
          request_entity: None,
          force_connection_close: false,
          properties: None,
          routed_path: None,
          stream_meta,
          path_params: None,
          type_system,
        })
      }
      (other_encoding, other_transfer) => {
        match other_transfer {
          Some("chunked") | None => (),
          Some(other) => {
            error_log!("tii: Request {id} has unimplemented transfer encoding: {}", other);
            return Err(TiiError::from(RequestHeadParsingError::TransferEncodingNotSupported(
              other.to_string(),
            )));
          }
        }

        let Some(other_encoding) = other_encoding else {
          error_log!(
            "tii: BUG! Fatal unreachable syntax/encoding reached {:?} {:?}",
            other_encoding,
            other_transfer
          );
          util::unreachable();
        };

        error_log!("tii: Request {id} has unimplemented content encoding: {}", other_encoding);

        Err(TiiError::from(RequestHeadParsingError::ContentEncodingNotSupported(
          other_encoding.to_string(),
        )))
      }
    }
  }

  /// Create a new RequestContext from a stream. This will parse RequestHead but not any part of the potential request body.
  /// Errors on IO-Error or malformed RequestHead.
  pub fn read(
    stream: &dyn ConnectionStream,
    stream_meta: Option<Arc<dyn ConnectionStreamMetadata>>,
    max_head_buffer_size: usize,
    type_system: TypeSystem,
  ) -> TiiResult<RequestContext> {
    let now: u128 =
      SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|a| a.as_millis()).unwrap_or(0);
    let id = util::next_id();
    let peer_address = stream.peer_addr()?;
    let local_address = stream.local_addr()?;
    debug_log!("tii: Request {id} local: {} peer: {}", &local_address, &peer_address);

    let req = RequestHead::read(id, stream, max_head_buffer_size)?;

    match req.get_version() {
      HttpVersion::Http09 => Self::new_http09(
        id,
        now,
        local_address,
        peer_address,
        req,
        stream,
        stream_meta,
        type_system,
      ),
      HttpVersion::Http10 => Self::new_http10(
        id,
        now,
        local_address,
        peer_address,
        req,
        stream,
        stream_meta,
        type_system,
      ),
      HttpVersion::Http11 => Self::new_http11(
        id,
        now,
        local_address,
        peer_address,
        req,
        stream,
        stream_meta,
        type_system,
      ),
    }
  }

  /// unique id for this request.
  pub fn id(&self) -> u128 {
    self.id
  }

  /// returns the timestamp when this request began parsing from the stream.
  /// This timestamp is in unix epoch millis.
  /// Meaning milliseconds passed since Midnight 1. Jan 1970 in UTC timezone (UK/England).
  /// The time source of this timestamp is not monotonic.
  pub fn get_timestamp(&self) -> u128 {
    self.timestamp
  }

  /// address of the peer we are talking to, entirely socket dependant.
  pub fn peer_address(&self) -> &str {
    self.peer_address.as_str()
  }

  /// address of our socket
  pub fn local_address(&self) -> &str {
    self.local_address.as_str()
  }

  /// True if the request contains the specified property.
  pub fn contains_property(&self, key: impl AsRef<str>) -> bool {
    if let Some(prop) = self.properties.as_ref() {
      return prop.contains_key(key.as_ref());
    }
    false
  }

  /// Get the specified property, uses downcast ref. returns none if the downcast didn't succeed.
  pub fn get_property<T: Any + Send>(&self, key: impl AsRef<str>) -> Option<&T> {
    if let Some(prop) = self.properties.as_ref() {
      if let Some(value) = prop.get(key.as_ref()) {
        return value.downcast_ref::<T>();
      }
    }

    None
  }

  /// Gets a downcast to the stream metadata. returns none if the downcast didn't succeed or there is no meta.
  pub fn get_stream_meta<T: ConnectionStreamMetadata>(&self) -> Option<&T> {
    if let Some(arc) = self.stream_meta.as_ref() {
      return arc.as_ref().as_any().downcast_ref::<T>();
    }

    None
  }

  /// Removes a property from the request.
  pub fn remove_property(&mut self, key: impl AsRef<str>) -> Option<Box<dyn Any + Send>> {
    if let Some(prop) = self.properties.as_mut() {
      if let Some(value) = prop.remove(key.as_ref()) {
        return Some(value);
      }
    }
    None
  }

  /// Sets a property into the request.
  pub fn set_property<T: Any + Send>(
    &mut self,
    key: impl ToString,
    value: T,
  ) -> Option<Box<dyn Any + Send>> {
    let boxed = Box::new(value) as Box<dyn Any + Send>;

    let k = key.to_string();
    if let Some(prop) = self.properties.as_mut() {
      if let Some(value) = prop.insert(k, boxed) {
        return Some(value);
      }
      return None;
    }

    //Lazy init the map.
    let mut nmap = HashMap::new();
    nmap.insert(k, boxed);
    self.properties = Some(nmap);
    None
  }

  /// Returns an iterator over property keys.
  pub fn get_property_keys(&self) -> Box<dyn Iterator<Item = &String> + '_> {
    match self.properties.as_ref() {
      Some(props) => Box::new(props.keys()),
      None => Box::new(std::iter::empty()),
    }
  }

  /// Returns the parsed request entity if any
  /// Parsing (if required by Endpoint) happens after the routing decision has been made.
  /// Before that this fn will always return None
  pub fn get_request_entity(&self) -> Option<&(dyn Any + Send + Sync)> {
    self.request_entity.as_ref().map(Box::as_ref)
  }

  /// Returns the mutable parsed request entity if any
  /// Parsing (if required by Endpoint) happens after the routing decision has been made.
  /// Before that this fn will always return None
  pub fn get_request_entity_mut(&mut self) -> Option<&mut (dyn Any + Send + Sync)> {
    self.request_entity.as_mut().map(Box::as_mut)
  }

  /// Replaces the request entity.
  /// Beware that setting the request entity to an incorrect type the endpoint does not expect will cause
  /// UserError before the endpoint is invoked!
  pub fn set_request_entity(
    &mut self,
    entity: Option<Box<dyn Any + Send + Sync>>,
  ) -> Option<Box<dyn Any + Send + Sync>> {
    mem::replace(&mut self.request_entity, entity)
  }

  /// Calls a closure with the cast request entity.
  /// # Errors
  /// If casting fails because the request entity is not of a compatible type
  pub fn cast_request_entity<DST: Any + ?Sized + 'static, RET: Any + 'static>(
    &self,
    receiver: impl FnOnce(&DST) -> RET + 'static,
  ) -> Result<RET, TypeSystemError> {
    let src = self.get_request_entity().ok_or(TypeSystemError::SourceTypeUnknown)?;

    let caster = self.type_system.type_cast_wrapper(src.type_id(), TypeId::of::<DST>())?;

    caster.call(src, receiver)
  }

  /// Calls a closure with the cast mutable request entity.
  /// # Errors
  /// If casting fails because the request entity is not of a compatible type
  pub fn cast_request_entity_mut<DST: Any + ?Sized + 'static, RET: Any + 'static>(
    &mut self,
    receiver: impl FnOnce(&mut DST) -> RET + 'static,
  ) -> Result<RET, TypeSystemError> {
    let src =
      self.request_entity.as_mut().map(Box::as_mut).ok_or(TypeSystemError::SourceTypeUnknown)?;

    let caster = self.type_system.type_cast_wrapper_mut(Any::type_id(src), TypeId::of::<DST>())?;

    caster.call(src, receiver)
  }

  /// get the http version this request was made in by the client.
  pub fn get_version(&self) -> HttpVersion {
    self.request.get_version()
  }

  /// Returns the raw status line.
  pub fn get_raw_status_line(&self) -> &str {
    self.request.get_raw_status_line()
  }

  /// Returns the path the request will be routed to This should not contain any url encoding.
  pub fn get_path(&self) -> &str {
    self.request.get_path()
  }

  /// Sets the path the request will be routed to. This should not contain any url encoding.
  pub fn set_path(&mut self, path: impl ToString) {
    self.request.set_path(path)
  }

  /// Gets the query parameters.
  pub fn get_query(&self) -> &[(String, String)] {
    self.request.get_query()
  }

  /// Gets the mutable Vec that contains the query parameters.
  pub fn query_mut(&mut self) -> &mut Vec<(String, String)> {
    self.request.query_mut()
  }

  /// Set the query parameters
  pub fn set_query(&mut self, query: Vec<(String, String)>) {
    self.request.set_query(query)
  }

  /// Add a query parameter. Existing query parameters with the same key are not touched.
  pub fn add_query_param(&mut self, key: impl ToString, value: impl ToString) {
    self.request.add_query_param(key, value)
  }

  /// Removes all query parameters that match the given key. Returns the removed values.
  pub fn remove_query_params(&mut self, key: impl AsRef<str>) -> Vec<String> {
    self.request.remove_query_params(key)
  }

  /// Removes all instances of the query parameter with the given key if there are any and adds a new query parameter with the given key and value to the end of the query parameters.
  ///
  /// If the key already has the value then its position is retained. All other values for the key are still removed.
  ///
  /// Returns the removed values.
  pub fn set_query_param(&mut self, key: impl ToString, value: impl ToString) -> Vec<String> {
    self.request.set_query_param(key, value)
  }

  /// Gets the first query parameter with the given key.
  pub fn get_query_param(&self, key: impl AsRef<str>) -> Option<&str> {
    self.request.get_query_param(key)
  }

  /// Parses a query parameter into a given type.
  ///
  /// This function only looks at the first query parameter with the given name.
  ///
  /// # Returns
  /// Ok(None) if no such query parameter exists.
  /// Ok(Some) if the query parameter exists and can be parsed
  /// Err(...) if the query parameter exists but parsing fails.
  pub fn parse_query_param<T: Any + FromStr<Err = E>, E: Error + Send + Sync + 'static>(
    &self,
    name: impl AsRef<str>,
  ) -> TiiResult<Option<T>> {
    let name = name.as_ref();
    let Some(param) = self.get_query_param(name) else {
      return Ok(None);
    };

    param.parse::<T>().map(Some).map_err(|e| {
      TiiError::UserError(UserError::InvalidQueryParameter(
        name.to_string(),
        TypeId::of::<T>(),
        Box::new(e),
      ))
    })
  }

  /// Parses a query parameter into a given type.
  ///
  /// This function only looks at the first query parameter with the given name.
  ///
  /// If no such query parameter exists then this function calls the provided
  /// fallback constructor function.
  ///
  /// # Example
  /// ```rust
  /// use tii::{RequestContext, Response, TiiResult};
  ///
  /// fn endpoint(ctx: &RequestContext) -> TiiResult<Response> {
  ///   let timeout = ctx.parse_query_param_or::<u64, _>("timeout_ms", 10_000)?;
  ///   println!("timeout_ms is {timeout}");
  ///   todo!()
  /// }
  /// ```
  ///
  /// # Returns
  /// Ok - parsing succeeds or no such query parameter existed and the value was provided by the fallback constructor function.
  /// Err - query parameter exists but parsing failed.
  pub fn parse_query_param_or<T: Any + FromStr<Err = E>, E: Error + Send + Sync + 'static>(
    &self,
    name: impl AsRef<str>,
    default_value: T,
  ) -> TiiResult<T> {
    Ok(self.parse_query_param(name)?.unwrap_or(default_value))
  }

  /// Parses a query parameter into a given type.
  ///
  /// This function only looks at the first query parameter with the given name.
  ///
  /// If no such query parameter exists then this function calls the provided
  /// fallback constructor function.
  ///
  /// # Example
  /// ```rust
  /// use tii::{RequestContext, Response, TiiResult};
  ///
  /// fn endpoint(ctx: &RequestContext) -> TiiResult<Response> {
  ///   let timeout = ctx.parse_query_param_or_else::<u64, _>("timeout_ms", || 10_000)?;
  ///   println!("timeout_ms is {timeout}");
  ///   todo!()
  /// }
  /// ```
  ///
  /// # Returns
  /// Ok - parsing succeeds or no such query parameter existed and the value was provided by the fallback constructor function.
  /// Err - query parameter exists but parsing failed.
  pub fn parse_query_param_or_else<T: Any + FromStr<Err = E>, E: Error + Send + Sync + 'static>(
    &self,
    name: impl AsRef<str>,
    default_value: impl FnOnce() -> T,
  ) -> TiiResult<T> {
    Ok(self.parse_query_param(name)?.unwrap_or_else(default_value))
  }

  /// Gets all query params in order of appearance that contain the given key. Returns empty vec if the key doesn’t exist.
  pub fn get_query_params(&self, key: impl AsRef<str>) -> Vec<&str> {
    self.request.get_query_params(key)
  }

  /// gets the method of the request.
  pub fn get_method(&self) -> &HttpMethod {
    self.request.get_method()
  }

  /// Changes the method of the request
  pub fn set_method(&mut self, method: HttpMethod) {
    self.request.set_method(method)
  }

  /// Get the cookies from the request.
  pub fn get_cookies(&self) -> Vec<Cookie> {
    self.request.get_cookies()
  }

  /// Attempts to get a specific cookie from the request.
  pub fn get_cookie(&self, name: impl AsRef<str>) -> Option<Cookie> {
    self.request.get_cookie(name)
  }

  /// Manipulates the accept header values. This also overwrites the actual accept header!
  pub fn set_accept(&mut self, types: Vec<AcceptQualityMimeType>) {
    self.request.set_accept(types)
  }

  /// Returns the content type of the body if any.
  /// This is usually equivalent to parsing the raw get_header() value of Content-Type.
  /// The only case where this is different is if the request as received from the network had an invalid Content-Type value then this value is ApplicationOctetStream even tho the raw header value is different.
  /// This returns none if the Content-Type header was not present at all. (For example ordinary GET requests do not have this header)
  pub fn get_content_type(&self) -> Option<&MimeTypeWithCharset> {
    self.request.get_content_type()
  }

  /// sets the content type header to given MimeType. This will affect both the header and the return value of get_content_type.
  pub fn set_content_type(&mut self, content_type: MimeType) {
    self.request.set_content_type(content_type)
  }

  /// Removes the content type header. get_content_type will return None after this call.
  pub fn remove_content_type(&mut self) -> Option<MimeTypeWithCharset> {
    self.request.remove_content_type()
  }

  /// Returns the acceptable mime types.
  /// The returned accepted mime types are in the order the client sent them over the network.
  pub fn get_accept(&self) -> &[AcceptQualityMimeType] {
    self.request.get_accept()
  }

  /// Returns the acceptable charsets.
  /// The returned accepted charset types are in the order the client sent them over the network.
  pub fn get_accept_charset(&self) -> &[AcceptMimeCharset] {
    self.request.get_accept_charset()
  }

  /// Returns an iterator over all headers.
  pub fn iter_headers(&self) -> impl Iterator<Item = &HttpHeader> {
    self.request.iter_headers()
  }

  /// Returns the first header or None
  pub fn get_header(&self, name: impl AsRef<str>) -> Option<&str> {
    self.request.get_header(name)
  }

  /// Returns true if the client indicates that it accepts gzip.
  pub fn accepts_gzip(&self) -> bool {
    self.request.accepts_gzip()
  }

  /// Returns the all header values or empty Vec.
  pub fn get_headers(&self, name: impl AsRef<str>) -> Vec<&str> {
    self.request.get_headers(name)
  }

  /// Sets the header value. Some header values cannot be modified through this fn and attempting to change them will result in Err.
  pub fn remove_headers(&mut self, hdr: impl AsRef<str>) -> TiiResult<()> {
    self.request.remove_headers(hdr)
  }

  /// Sets the header value. Some header values cannot be modified through this fn and attempting to change them will result in Err.
  pub fn set_header(&mut self, hdr: impl AsRef<str>, value: impl ToString) -> TiiResult<()> {
    self.request.set_header(hdr, value)
  }

  /// Adds a new header value to the headers. This can be the first value with the given key or an additional value.
  pub fn add_header(&mut self, hdr: impl AsRef<str>, value: impl ToString) -> TiiResult<()> {
    self.request.add_header(hdr, value)
  }

  /// Ref to body.
  pub fn request_body(&self) -> Option<&RequestBody> {
    self.body.as_ref()
  }

  /// Get the routed path, yields "" before routing.
  pub fn routed_path(&self) -> &str {
    self.routed_path.as_deref().unwrap_or("")
  }

  /// get the path param keys.
  pub fn get_path_param_keys(&self) -> Box<dyn Iterator<Item = &str> + '_> {
    match self.path_params.as_ref() {
      Some(props) => Box::new(props.keys().map(|k| k.as_str())),
      None => Box::new(std::iter::empty()),
    }
  }

  /// get that path param key value pairs
  pub fn get_path_params(&self) -> Box<dyn Iterator<Item = (&str, &str)> + '_> {
    match self.path_params.as_ref() {
      Some(props) => Box::new(props.iter().map(|(k, v)| (k.as_str(), v.as_str()))),
      None => Box::new(std::iter::empty()),
    }
  }

  /// Gets a path param or None
  pub fn get_path_param(&self, asr: impl AsRef<str>) -> Option<&str> {
    if let Some(path) = self.path_params.as_ref() {
      return path.get(asr.as_ref()).map(|e| e.as_str());
    }

    None
  }

  ///
  /// This fn will parse a path param using its FromStr trait.
  ///
  /// # Errors
  /// - TiiError::UserError(UserError::InvalidPathParameter)
  ///   If the FromStr function fails. For example, you try to parse a number, and it's not a number.
  ///   This is reasonably common and your error handler should generally map this into a http 400 bad request response of some sorts.
  ///
  /// - TiiError::UserError(UserError::MissingPathParameter)
  ///   If the path parameter does not exist for the endpoint.
  ///   This is usually indicative of an error in the program, because an endpoint should not request path parameter by name that don't exist for its path.
  ///   Most likely scenario for this to happen, is if the path parameter was renamed in the path constant of the endpoint,
  ///   but not inside the actual endpoint handler.
  ///   The error handle should either abort the program or return http 500.
  ///
  /// # Example
  /// ```rust
  ///use std::num::ParseIntError;
  ///use tii::{MimeType, RequestContext, Response, TiiError, TiiResult, UserError};
  ///
  /// //Your endpoint at for example path '/some/path/{id}/whatever'
  /// pub fn endpoint(ctx: &RequestContext) -> TiiResult<Response> {
  ///  let id : u128 = ctx.parse_path_param("id")?;
  ///  Ok(Response::ok(format!("The id is {id}"), MimeType::TextPlain))
  /// }
  ///
  /// //Global error handler
  ///pub fn error_handler(ctx: &mut RequestContext, error: TiiError) -> TiiResult<Response> {
  ///  if let TiiError::UserError(UserError::InvalidPathParameter(name, _type, error)) = &error {
  ///     return Ok(Response::bad_request(format!("The path parameter {name} is invalid. error={error}"), MimeType::TextPlain));
  ///  }
  ///
  ///  if let TiiError::UserError(UserError::MissingPathParameter(name)) = &error {
  ///    eprintln!("The endpoint {} is buggy or mis-routed, its requesting path param {name}, but no such path param exist.", ctx.routed_path());
  ///    return Ok(Response::internal_server_error_no_body());
  ///  }
  ///
  ///  //Handle other errors here
  ///  todo!()
  ///}
  ///
  /// ```
  ///
  pub fn parse_path_param<T: Any + FromStr<Err = E>, E: Error + Send + Sync + 'static>(
    &self,
    name: impl AsRef<str>,
  ) -> TiiResult<T> {
    let name = name.as_ref();
    self
      .path_params
      .as_ref()
      .and_then(|params| params.get(name))
      .ok_or(TiiError::UserError(UserError::MissingPathParameter(name.to_string())))?
      .parse::<T>()
      .map_err(|e| {
        TiiError::UserError(UserError::InvalidPathParameter(
          name.to_string(),
          TypeId::of::<T>(),
          Box::new(e),
        ))
      })
  }

  /// Sets a path param.
  pub fn set_path_param(&mut self, key: impl ToString, value: impl ToString) -> Option<String> {
    if let Some(path) = self.path_params.as_mut() {
      return path.insert(key.to_string(), value.to_string());
    }

    self.path_params = Some(HashMap::new());
    unwrap_some(self.path_params.as_mut()).insert(key.to_string(), value.to_string());

    None
  }

  /// Sets the routed path, this is called after routing is performed.
  /// Calling this in a pre routing filter has no effect on routing.
  /// Calling this in a post routing filter will overwrite the value the endpoint sees.
  pub fn set_routed_path<T: ToString>(&mut self, rp: T) {
    self.routed_path.replace(rp.to_string());
  }

  /// Replaces the request body with a new one (or none).
  /// The old body if any is consumed/discarded.
  pub fn set_body_consume_old(&mut self, body: Option<RequestBody>) -> io::Result<()> {
    if let Some(old_body) = self.body.as_ref() {
      consume_body(old_body)?
    }
    self.body = body;
    Ok(())
  }

  /// Forces the Connection to be closed after the request is handled.
  /// This is sensible if errors are encountered.
  pub fn force_connection_close(&mut self) {
    self.force_connection_close = true;
  }

  /// Returns true if the connection will forcibly be closed after the request is handled.
  pub fn is_connection_close_forced(&self) -> bool {
    self.force_connection_close
  }

  /// Fully consumes the current request body.
  /// The body itself will remain valid, just yield EOF as soon as read.
  /// Calling this multiple times is a noop.
  pub fn consume_request_body(&self) -> io::Result<()> {
    if let Some(body) = self.body.as_ref() {
      consume_body(body)?
    }
    Ok(())
  }

  pub(crate) fn get_type_system(&self) -> &TypeSystem {
    &self.type_system
  }
}

/// utility ot consume the body.
fn consume_body(body: &RequestBody) -> io::Result<()> {
  let mut discarding_buffer = [0; 0x1_00_00]; //TODO heap alloc maybe? cfg-if!
  loop {
    let discarded = body.read(discarding_buffer.as_mut_slice()).or_else(|e| {
      if e.kind() == ErrorKind::UnexpectedEof {
        Ok(0)
      } else {
        Err(e)
      }
    })?; //Not so unexpected eof!

    if discarded == 0 {
      return Ok(());
    }
  }
}