1use std::collections::HashMap;
13use std::sync::OnceLock;
14
15use bytes::Bytes;
16use http::{HeaderMap, Method, Uri, Version};
17use rainier_support::{Error, Extensions, Result};
18use serde::de::DeserializeOwned;
19use serde_json::Value;
20
21use crate::cookie::parse_cookie_header;
22use crate::input;
23use crate::upload::{self, Multipart, UploadedFile};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct ClientIp(pub std::net::IpAddr);
31
32#[derive(Debug)]
34enum ParsedBody {
35 Json(Value),
37 Form(Value),
39 Multipart(Box<Multipart>),
41 Opaque,
46}
47
48#[derive(Debug)]
50pub struct Request {
51 method: Method,
52 uri: Uri,
53 version: Version,
54 headers: HeaderMap,
55 body: Bytes,
56 extensions: Extensions,
57 route_params: HashMap<String, String>,
58 input_override: Option<Value>,
64
65 query: OnceLock<Value>,
66 parsed_body: OnceLock<ParsedBody>,
67 cookies: OnceLock<HashMap<String, String>>,
68}
69
70impl Request {
71 pub fn new(method: Method, uri: Uri, headers: HeaderMap, body: Bytes) -> Self {
74 Self {
75 method,
76 uri,
77 version: Version::HTTP_11,
78 headers,
79 body,
80 extensions: Extensions::new(),
81 route_params: HashMap::new(),
82 input_override: None,
83 query: OnceLock::new(),
84 parsed_body: OnceLock::new(),
85 cookies: OnceLock::new(),
86 }
87 }
88
89 pub fn builder() -> RequestBuilder {
91 RequestBuilder::new()
92 }
93
94 pub fn from_http(request: http::Request<Bytes>) -> Self {
96 let (parts, body) = request.into_parts();
97 let mut request = Self::new(parts.method, parts.uri, parts.headers, body);
98 request.version = parts.version;
99 request
100 }
101
102 pub fn method(&self) -> &Method {
106 &self.method
107 }
108
109 pub fn uri(&self) -> &Uri {
111 &self.uri
112 }
113
114 pub fn path(&self) -> &str {
116 self.uri.path()
117 }
118
119 pub fn query_string(&self) -> &str {
121 self.uri.query().unwrap_or("")
122 }
123
124 pub fn version(&self) -> Version {
126 self.version
127 }
128
129 pub fn headers(&self) -> &HeaderMap {
131 &self.headers
132 }
133
134 pub fn headers_mut(&mut self) -> &mut HeaderMap {
136 &mut self.headers
137 }
138
139 pub fn header(&self, name: &str) -> Option<&str> {
141 self.headers.get(name)?.to_str().ok()
142 }
143
144 pub fn set_method(&mut self, method: Method) {
153 self.method = method;
154 }
155
156 pub fn is_method(&self, method: &Method) -> bool {
158 self.method == method
159 }
160
161 pub fn body(&self) -> &Bytes {
163 &self.body
164 }
165
166 pub fn body_string(&self) -> String {
168 String::from_utf8_lossy(&self.body).into_owned()
169 }
170
171 pub fn content_type(&self) -> Option<String> {
173 let raw = self.header("content-type")?;
174 let base = raw.split(';').next().unwrap_or(raw);
175 Some(base.trim().to_ascii_lowercase())
176 }
177
178 pub fn is_json(&self) -> bool {
181 self.content_type().is_some_and(|ct| ct == "application/json" || ct.ends_with("+json"))
182 }
183
184 pub fn expects_json(&self) -> bool {
190 if self.is_json() {
191 return true;
192 }
193 if self.header("x-requested-with").is_some_and(|v| v.eq_ignore_ascii_case("XMLHttpRequest"))
194 {
195 return true;
196 }
197 match self.header("accept") {
198 Some(accept) => accept.split(',').any(|part| {
201 let part = part.split(';').next().unwrap_or(part).trim();
202 part == "application/json" || part.ends_with("+json")
203 }),
204 None => false,
205 }
206 }
207
208 pub fn query(&self) -> &Value {
212 self.query.get_or_init(|| input::parse_urlencoded(self.query_string().as_bytes()))
213 }
214
215 fn parsed_body(&self) -> &ParsedBody {
216 self.parsed_body.get_or_init(|| {
217 if self.body.is_empty() {
218 return ParsedBody::Opaque;
219 }
220 match self.content_type().as_deref() {
221 Some(ct) if ct == "application/json" || ct.ends_with("+json") => {
222 match serde_json::from_slice(&self.body) {
223 Ok(value) => ParsedBody::Json(value),
224 Err(_) => ParsedBody::Opaque,
225 }
226 }
227 Some("application/x-www-form-urlencoded") => {
228 ParsedBody::Form(input::parse_urlencoded(&self.body))
229 }
230 Some("multipart/form-data") => {
231 let boundary = self.header("content-type").and_then(upload::boundary_of);
232 match boundary.and_then(|b| upload::parse(&self.body, &b).ok()) {
233 Some(parsed) => ParsedBody::Multipart(Box::new(parsed)),
234 None => ParsedBody::Opaque,
235 }
236 }
237 _ => ParsedBody::Opaque,
238 }
239 })
240 }
241
242 pub fn body_input(&self) -> &Value {
244 static EMPTY: OnceLock<Value> = OnceLock::new();
245 if let Some(overridden) = &self.input_override {
246 return overridden;
247 }
248 match self.parsed_body() {
249 ParsedBody::Json(value) => value,
250 ParsedBody::Form(value) => value,
251 ParsedBody::Multipart(parsed) => &parsed.fields,
252 ParsedBody::Opaque => EMPTY.get_or_init(|| Value::Object(serde_json::Map::new())),
253 }
254 }
255
256 pub fn all(&self) -> Value {
263 match &self.input_override {
264 Some(overridden) => overridden.clone(),
265 None => input::merge(self.query().clone(), self.body_input().clone()),
266 }
267 }
268
269 pub fn input(&self, key: &str) -> Option<String> {
271 if let Some(overridden) = &self.input_override {
272 return input::lookup(overridden, key).and_then(input::scalar_to_string);
273 }
274 input::lookup(self.body_input(), key)
275 .or_else(|| input::lookup(self.query(), key))
276 .and_then(input::scalar_to_string)
277 }
278
279 pub fn transform_input(&mut self, transform: impl FnOnce(Value) -> Value) {
285 self.input_override = Some(transform(self.all()));
286 }
287
288 pub fn set_input(&mut self, value: Value) {
290 self.input_override = Some(value);
291 }
292
293 pub fn merge_input(&mut self, extra: Value) {
296 self.transform_input(|current| input::merge(current, extra));
297 }
298
299 pub fn input_or(&self, key: &str, default: impl Into<String>) -> String {
301 self.input(key).unwrap_or_else(|| default.into())
302 }
303
304 pub fn input_value(&self, key: &str) -> Option<&Value> {
306 if let Some(overridden) = &self.input_override {
307 return input::lookup(overridden, key);
308 }
309 input::lookup(self.body_input(), key).or_else(|| input::lookup(self.query(), key))
310 }
311
312 pub fn has(&self, key: &str) -> bool {
314 self.input_value(key).is_some()
315 }
316
317 pub fn input_was_rewritten(&self) -> bool {
319 self.input_override.is_some()
320 }
321
322 pub fn filled(&self, key: &str) -> bool {
324 match self.input_value(key) {
325 Some(Value::String(s)) => !s.trim().is_empty(),
326 Some(Value::Null) | None => false,
327 Some(Value::Array(items)) => !items.is_empty(),
328 Some(Value::Object(map)) => !map.is_empty(),
329 Some(_) => true,
330 }
331 }
332
333 pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
338 if self.body.is_empty() {
339 return Err(Error::bad_request("a JSON body is required but the request had none"));
340 }
341 if !self.is_json() {
342 return Err(Error::bad_request(format!(
343 "expected a JSON body but the Content-Type was `{}`",
344 self.content_type().unwrap_or_else(|| "(none)".into())
345 )));
346 }
347 serde_json::from_slice(&self.body)
348 .map_err(|e| Error::bad_request(format!("malformed JSON body: {e}")))
349 }
350
351 pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
357 serde_json::from_value(self.all())
358 .map_err(|e| Error::bad_request(format!("could not read the request input: {e}")))
359 }
360
361 pub fn query_as<T: DeserializeOwned>(&self) -> Result<T> {
363 serde_json::from_value(self.query().clone())
364 .map_err(|e| Error::bad_request(format!("could not read the query string: {e}")))
365 }
366
367 pub fn files(&self, field: &str) -> &[UploadedFile] {
371 match self.parsed_body() {
372 ParsedBody::Multipart(parsed) => {
373 parsed.files.get(field).map(Vec::as_slice).unwrap_or(&[])
374 }
375 _ => &[],
376 }
377 }
378
379 pub fn file(&self, field: &str) -> Option<&UploadedFile> {
381 self.files(field).first()
382 }
383
384 pub fn has_file(&self, field: &str) -> bool {
386 self.file(field).is_some_and(|f| !f.is_empty())
387 }
388
389 pub fn cookies(&self) -> &HashMap<String, String> {
393 self.cookies.get_or_init(|| match self.header("cookie") {
394 Some(header) => parse_cookie_header(header),
395 None => HashMap::new(),
396 })
397 }
398
399 pub fn cookie(&self, name: &str) -> Option<&str> {
401 self.cookies().get(name).map(String::as_str)
402 }
403
404 pub fn bearer_token(&self) -> Option<&str> {
406 let header = self.header("authorization")?;
407 let (scheme, token) = header.split_once(' ')?;
408 scheme.eq_ignore_ascii_case("bearer").then(|| token.trim())
409 }
410
411 pub fn route_param(&self, name: &str) -> Option<&str> {
415 self.route_params.get(name).map(String::as_str)
416 }
417
418 pub fn route_params(&self) -> &HashMap<String, String> {
420 &self.route_params
421 }
422
423 pub fn set_route_params(&mut self, params: HashMap<String, String>) {
425 self.route_params = params;
426 }
427
428 pub fn extensions(&self) -> &Extensions {
433 &self.extensions
434 }
435
436 pub fn extensions_mut(&mut self) -> &mut Extensions {
438 &mut self.extensions
439 }
440
441 pub fn with_extension<T: Send + Sync + 'static>(mut self, value: T) -> Self {
443 self.extensions.insert(value);
444 self
445 }
446
447 pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
449 self.extensions.get::<T>()
450 }
451
452 pub fn ip(&self) -> Option<std::net::IpAddr> {
454 self.extensions.get::<ClientIp>().map(|ip| ip.0)
455 }
456}
457
458#[derive(Debug)]
473pub struct RequestBuilder {
474 method: Method,
475 uri: String,
476 headers: HeaderMap,
477 body: Bytes,
478 route_params: HashMap<String, String>,
479}
480
481impl Default for RequestBuilder {
482 fn default() -> Self {
483 Self::new()
484 }
485}
486
487impl RequestBuilder {
488 pub fn new() -> Self {
490 Self {
491 method: Method::GET,
492 uri: "/".to_string(),
493 headers: HeaderMap::new(),
494 body: Bytes::new(),
495 route_params: HashMap::new(),
496 }
497 }
498
499 pub fn method(mut self, method: Method) -> Self {
501 self.method = method;
502 self
503 }
504
505 pub fn uri(mut self, uri: impl Into<String>) -> Self {
507 self.uri = uri.into();
508 self
509 }
510
511 pub fn header(mut self, name: &str, value: &str) -> Self {
513 if let (Ok(name), Ok(value)) =
514 (http::header::HeaderName::try_from(name), http::header::HeaderValue::from_str(value))
515 {
516 self.headers.insert(name, value);
517 }
518 self
519 }
520
521 pub fn body(mut self, body: impl Into<Bytes>) -> Self {
523 self.body = body.into();
524 self
525 }
526
527 pub fn json(self, value: &impl serde::Serialize) -> Self {
529 let encoded = serde_json::to_vec(value).unwrap_or_default();
530 self.header("content-type", "application/json").body(encoded)
531 }
532
533 pub fn form(self, pairs: &[(&str, &str)]) -> Self {
535 let encoded: String =
536 form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
537 self.header("content-type", "application/x-www-form-urlencoded").body(encoded)
538 }
539
540 pub fn route_param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
542 self.route_params.insert(name.into(), value.into());
543 self
544 }
545
546 pub fn build(self) -> Request {
548 let uri: Uri = self.uri.parse().unwrap_or_else(|_| Uri::from_static("/"));
549 let mut request = Request::new(self.method, uri, self.headers, self.body);
550 request.route_params = self.route_params;
551 request
552 }
553}
554
555#[cfg(test)]
556mod input_rewriting_tests {
557 use super::*;
558 use serde_json::json;
559
560 #[test]
561 fn transform_input_replaces_what_later_reads_see() {
562 let mut request = Request::builder().uri("/x?name=+ada+&age=36").build();
563 assert_eq!(request.input("name").as_deref(), Some(" ada "));
564
565 request.transform_input(|value| {
566 let mut object = value.as_object().cloned().unwrap_or_default();
567 if let Some(Value::String(name)) = object.get_mut("name") {
568 *name = name.trim().to_string();
569 }
570 Value::Object(object)
571 });
572
573 assert!(request.input_was_rewritten());
574 assert_eq!(request.input("name").as_deref(), Some("ada"));
575 assert_eq!(request.all(), json!({ "name": "ada", "age": "36" }));
576 }
577
578 #[test]
579 fn a_rewrite_is_not_undone_by_the_original_query_string() {
580 let mut request = Request::builder().uri("/x?secret=leak").build();
583 request.set_input(json!({}));
584 assert_eq!(request.input("secret"), None);
585 assert!(!request.has("secret"));
586 }
587
588 #[test]
589 fn merge_input_layers_over_the_current_values() {
590 let mut request = Request::builder().uri("/x?a=1").build();
591 request.merge_input(json!({ "b": "2" }));
592 assert_eq!(request.all(), json!({ "a": "1", "b": "2" }));
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use serde_json::json;
600
601 #[test]
602 fn exposes_the_message_basics() {
603 let request = Request::builder().method(Method::POST).uri("/posts?page=2").build();
604 assert_eq!(request.method(), Method::POST);
605 assert_eq!(request.path(), "/posts");
606 assert_eq!(request.query_string(), "page=2");
607 assert!(request.is_method(&Method::POST));
608 }
609
610 #[test]
611 fn reads_query_string_input() {
612 let request = Request::builder().uri("/search?q=rust&tags[]=a&tags[]=b").build();
613 assert_eq!(request.input("q").as_deref(), Some("rust"));
614 assert_eq!(request.input_value("tags"), Some(&json!(["a", "b"])));
615 }
616
617 #[test]
618 fn reads_json_body_input() {
619 let request = Request::builder()
620 .method(Method::POST)
621 .json(&json!({ "title": "Hi", "meta": { "tag": "rust" } }))
622 .build();
623
624 assert_eq!(request.input("title").as_deref(), Some("Hi"));
625 assert_eq!(request.input("meta.tag").as_deref(), Some("rust"));
626 assert!(request.is_json());
627 }
628
629 #[test]
630 fn reads_form_body_input() {
631 let request = Request::builder()
632 .method(Method::POST)
633 .form(&[("title", "Hi"), ("body", "there")])
634 .build();
635 assert_eq!(request.input("title").as_deref(), Some("Hi"));
636 assert_eq!(request.input("body").as_deref(), Some("there"));
637 }
638
639 #[test]
640 fn the_body_wins_over_the_query_string() {
641 let request = Request::builder()
642 .method(Method::POST)
643 .uri("/x?name=query")
644 .json(&json!({ "name": "body" }))
645 .build();
646 assert_eq!(request.input("name").as_deref(), Some("body"));
647 assert_eq!(request.all(), json!({ "name": "body" }));
648 }
649
650 #[test]
651 fn all_merges_query_and_body() {
652 let request = Request::builder()
653 .method(Method::POST)
654 .uri("/x?page=2")
655 .json(&json!({ "name": "ada" }))
656 .build();
657 assert_eq!(request.all(), json!({ "page": "2", "name": "ada" }));
658 }
659
660 #[test]
661 fn route_params_stay_out_of_input() {
662 let request = Request::builder().uri("/posts/7").route_param("post", "7").build();
663 assert_eq!(request.route_param("post"), Some("7"));
664 assert!(!request.has("post"), "route params must not shadow or appear as input");
665 }
666
667 #[test]
668 fn has_and_filled_differ_on_blank_values() {
669 let request = Request::builder().uri("/x?a=&b=v&c[]=").build();
670 assert!(request.has("a"));
671 assert!(!request.filled("a"));
672 assert!(request.filled("b"));
673 assert!(!request.has("missing"));
674 }
675
676 #[test]
677 fn json_reports_why_it_failed() {
678 let empty = Request::builder().build();
679 assert!(empty.json::<Value>().unwrap_err().message().contains("had none"));
680
681 let wrong_type = Request::builder().body("hello").build();
682 assert!(wrong_type.json::<Value>().unwrap_err().message().contains("Content-Type"));
683
684 let malformed =
685 Request::builder().header("content-type", "application/json").body("{oops").build();
686 let err = malformed.json::<Value>().unwrap_err();
687 assert_eq!(err.status(), 400);
688 assert!(err.message().contains("malformed JSON"));
689 }
690
691 #[test]
692 fn a_malformed_body_does_not_break_unrelated_accessors() {
693 let request = Request::builder()
694 .header("content-type", "application/json")
695 .uri("/x?page=2")
696 .body("{oops")
697 .build();
698 assert_eq!(request.input("page").as_deref(), Some("2"));
700 assert_eq!(request.body_input(), &json!({}));
701 }
702
703 #[test]
704 fn detects_json_content_types_including_suffixes() {
705 let plain =
706 Request::builder().header("content-type", "application/json; charset=utf-8").build();
707 assert!(plain.is_json());
708 assert_eq!(plain.content_type().as_deref(), Some("application/json"));
709
710 let suffixed = Request::builder().header("content-type", "application/ld+json").build();
711 assert!(suffixed.is_json());
712
713 let html = Request::builder().header("content-type", "text/html").build();
714 assert!(!html.is_json());
715 }
716
717 #[test]
718 fn expects_json_reads_the_accept_header() {
719 let asked = Request::builder().header("accept", "application/json").build();
720 assert!(asked.expects_json());
721
722 let xhr = Request::builder().header("x-requested-with", "XMLHttpRequest").build();
723 assert!(xhr.expects_json());
724
725 let browser = Request::builder()
726 .header("accept", "text/html,application/xhtml+xml,*/*;q=0.8")
727 .build();
728 assert!(!browser.expects_json(), "`*/*` must not count as wanting JSON");
729
730 assert!(!Request::builder().build().expects_json());
731 }
732
733 #[test]
734 fn reads_cookies() {
735 let request = Request::builder().header("cookie", "session=abc; theme=dark").build();
736 assert_eq!(request.cookie("session"), Some("abc"));
737 assert_eq!(request.cookie("nope"), None);
738 assert_eq!(request.cookies().len(), 2);
739 }
740
741 #[test]
742 fn reads_a_bearer_token() {
743 let request = Request::builder().header("authorization", "Bearer tok_123").build();
744 assert_eq!(request.bearer_token(), Some("tok_123"));
745
746 let lower = Request::builder().header("authorization", "bearer tok_123").build();
748 assert_eq!(lower.bearer_token(), Some("tok_123"));
749
750 let basic = Request::builder().header("authorization", "Basic abc").build();
751 assert_eq!(basic.bearer_token(), None);
752 assert_eq!(Request::builder().build().bearer_token(), None);
753 }
754
755 #[test]
756 fn extensions_carry_typed_attributes() {
757 #[derive(Debug, PartialEq)]
758 struct CurrentUser(u64);
759
760 let request = Request::builder().build().with_extension(CurrentUser(7));
761 assert_eq!(request.extension::<CurrentUser>(), Some(&CurrentUser(7)));
762 assert_eq!(request.extension::<ClientIp>(), None);
763 }
764
765 #[test]
766 fn deserialises_the_json_body_into_a_struct() {
767 #[derive(serde::Deserialize, PartialEq, Debug)]
768 struct NewPost {
769 title: String,
770 draft: bool,
771 }
772
773 let request = Request::builder()
774 .method(Method::POST)
775 .json(&json!({ "title": "Hi", "draft": true }))
776 .build();
777 assert_eq!(request.json::<NewPost>().unwrap(), NewPost { title: "Hi".into(), draft: true });
778 }
779
780 #[test]
781 fn parses_uploads_from_a_multipart_body() {
782 let boundary = "X";
783 let body = format!(
784 "--{boundary}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHi\r\n\
785 --{boundary}\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\nDATA\r\n\
786 --{boundary}--\r\n"
787 );
788 let request = Request::builder()
789 .method(Method::POST)
790 .header("content-type", &format!("multipart/form-data; boundary={boundary}"))
791 .body(body)
792 .build();
793
794 assert_eq!(request.input("title").as_deref(), Some("Hi"));
795 assert!(request.has_file("doc"));
796 assert_eq!(request.file("doc").unwrap().bytes().as_ref(), b"DATA");
797 assert!(!request.has_file("missing"));
798 assert!(request.files("missing").is_empty());
799 }
800
801 #[test]
802 fn parsing_is_cached_across_calls() {
803 let request = Request::builder().uri("/x?a=1").build();
804 let first = request.query() as *const Value;
805 let second = request.query() as *const Value;
806 assert_eq!(first, second, "the query string must be parsed once");
807 }
808
809 #[test]
810 fn adopts_an_http_request() {
811 let inner = http::Request::builder()
812 .method(Method::PUT)
813 .uri("/things/1")
814 .header("x-test", "yes")
815 .body(Bytes::from("payload"))
816 .unwrap();
817
818 let request = Request::from_http(inner);
819 assert_eq!(request.method(), Method::PUT);
820 assert_eq!(request.path(), "/things/1");
821 assert_eq!(request.header("x-test"), Some("yes"));
822 assert_eq!(request.body_string(), "payload");
823 }
824}