spikard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,770 +1,789 @@
1
- //! Request parsing and data extraction utilities
2
-
3
- use crate::handler_trait::RequestData;
4
- use crate::query_parser::{parse_query_pairs_to_json, parse_query_string};
5
- use axum::body::Body;
6
- use http_body_util::BodyExt;
7
- use serde_json::Value;
8
- use std::collections::HashMap;
9
- use std::sync::Arc;
10
- use std::sync::OnceLock;
11
-
12
- #[derive(Debug, Clone, Copy)]
13
- pub struct WithoutBodyExtractionOptions {
14
- pub include_raw_query_params: bool,
15
- pub include_query_params_json: bool,
16
- pub include_headers: bool,
17
- pub include_cookies: bool,
18
- }
19
-
20
- fn extract_query_params_and_raw(
21
- uri: &axum::http::Uri,
22
- include_raw_query_params: bool,
23
- include_query_params_json: bool,
24
- ) -> (Value, HashMap<String, Vec<String>>) {
25
- let query_string = uri.query().unwrap_or("");
26
- if query_string.is_empty() {
27
- return (Value::Object(serde_json::Map::new()), HashMap::new());
28
- }
29
-
30
- match (include_raw_query_params, include_query_params_json) {
31
- (false, false) => (Value::Null, HashMap::new()),
32
- (false, true) => (
33
- crate::query_parser::parse_query_string_to_json(query_string.as_bytes(), true),
34
- HashMap::new(),
35
- ),
36
- (true, false) => {
37
- let raw =
38
- parse_query_string(query_string.as_bytes(), '&')
39
- .into_iter()
40
- .fold(HashMap::new(), |mut acc, (k, v)| {
41
- acc.entry(k).or_insert_with(Vec::new).push(v);
42
- acc
43
- });
44
- (Value::Null, raw)
45
- }
46
- (true, true) => {
47
- let pairs = parse_query_string(query_string.as_bytes(), '&');
48
- let json = parse_query_pairs_to_json(&pairs, true);
49
- let raw = pairs.into_iter().fold(HashMap::new(), |mut acc, (k, v)| {
50
- acc.entry(k).or_insert_with(Vec::new).push(v);
51
- acc
52
- });
53
- (json, raw)
54
- }
55
- }
56
- }
57
-
58
- /// Extract and parse query parameters from request URI
59
- pub fn extract_query_params(uri: &axum::http::Uri) -> Value {
60
- let query_string = uri.query().unwrap_or("");
61
- if query_string.is_empty() {
62
- Value::Object(serde_json::Map::new())
63
- } else {
64
- crate::query_parser::parse_query_string_to_json(query_string.as_bytes(), true)
65
- }
66
- }
67
-
68
- /// Extract raw query parameters as strings (no type conversion)
69
- /// Used for validation error messages to show the actual input values
70
- pub fn extract_raw_query_params(uri: &axum::http::Uri) -> HashMap<String, Vec<String>> {
71
- let query_string = uri.query().unwrap_or("");
72
- if query_string.is_empty() {
73
- HashMap::new()
74
- } else {
75
- parse_query_string(query_string.as_bytes(), '&')
76
- .into_iter()
77
- .fold(HashMap::new(), |mut acc, (k, v)| {
78
- acc.entry(k).or_insert_with(Vec::new).push(v);
79
- acc
80
- })
81
- }
82
- }
83
-
84
- /// Extract headers from request
85
- pub fn extract_headers(headers: &axum::http::HeaderMap) -> HashMap<String, String> {
86
- let mut map = HashMap::with_capacity(headers.len());
87
- for (name, value) in headers.iter() {
88
- if let Ok(val_str) = value.to_str() {
89
- // `HeaderName::as_str()` is already normalized to lowercase.
90
- map.insert(name.as_str().to_string(), val_str.to_string());
91
- }
92
- }
93
- map
94
- }
95
-
96
- /// Extract cookies from request headers
97
- pub fn extract_cookies(headers: &axum::http::HeaderMap) -> HashMap<String, String> {
98
- let mut cookies = HashMap::new();
99
-
100
- if let Some(cookie_str) = headers.get(axum::http::header::COOKIE).and_then(|h| h.to_str().ok()) {
101
- for cookie in cookie::Cookie::split_parse(cookie_str).flatten() {
102
- cookies.insert(cookie.name().to_string(), cookie.value().to_string());
103
- }
104
- }
105
-
106
- cookies
107
- }
108
-
109
- fn empty_string_map() -> Arc<HashMap<String, String>> {
110
- static EMPTY: OnceLock<Arc<HashMap<String, String>>> = OnceLock::new();
111
- Arc::clone(EMPTY.get_or_init(|| Arc::new(HashMap::new())))
112
- }
113
-
114
- fn empty_raw_query_map() -> Arc<HashMap<String, Vec<String>>> {
115
- static EMPTY: OnceLock<Arc<HashMap<String, Vec<String>>>> = OnceLock::new();
116
- Arc::clone(EMPTY.get_or_init(|| Arc::new(HashMap::new())))
117
- }
118
-
119
- /// Create RequestData from request parts (for requests without body)
120
- ///
121
- /// Wraps HashMaps in Arc to enable cheap cloning without duplicating data.
122
- pub fn create_request_data_without_body(
123
- uri: &axum::http::Uri,
124
- method: &axum::http::Method,
125
- headers: &axum::http::HeaderMap,
126
- path_params: HashMap<String, String>,
127
- options: WithoutBodyExtractionOptions,
128
- ) -> RequestData {
129
- let (query_params, raw_query_params) =
130
- extract_query_params_and_raw(uri, options.include_raw_query_params, options.include_query_params_json);
131
- RequestData {
132
- path_params: Arc::new(path_params),
133
- query_params,
134
- raw_query_params: if raw_query_params.is_empty() {
135
- empty_raw_query_map()
136
- } else {
137
- Arc::new(raw_query_params)
138
- },
139
- validated_params: None,
140
- headers: if options.include_headers {
141
- Arc::new(extract_headers(headers))
142
- } else {
143
- empty_string_map()
144
- },
145
- cookies: if options.include_cookies {
146
- Arc::new(extract_cookies(headers))
147
- } else {
148
- empty_string_map()
149
- },
150
- body: Value::Null,
151
- raw_body: None,
152
- method: method.as_str().to_string(),
153
- path: uri.path().to_string(),
154
- #[cfg(feature = "di")]
155
- dependencies: None,
156
- }
157
- }
158
-
159
- /// Create RequestData from request parts (for requests with body)
160
- ///
161
- /// Wraps HashMaps in Arc to enable cheap cloning without duplicating data.
162
- /// Performance optimization: stores raw body bytes without parsing JSON.
163
- /// JSON parsing is deferred until actually needed (e.g., for validation).
164
- pub async fn create_request_data_with_body(
165
- parts: &axum::http::request::Parts,
166
- path_params: HashMap<String, String>,
167
- body: Body,
168
- include_raw_query_params: bool,
169
- include_query_params_json: bool,
170
- include_headers: bool,
171
- include_cookies: bool,
172
- ) -> Result<RequestData, (axum::http::StatusCode, String)> {
173
- let body_bytes = if let Some(pre_read) = parts.extensions.get::<crate::middleware::PreReadBody>() {
174
- pre_read.0.clone()
175
- } else {
176
- body.collect()
177
- .await
178
- .map_err(|e| {
179
- (
180
- axum::http::StatusCode::BAD_REQUEST,
181
- format!("Failed to read body: {}", e),
182
- )
183
- })?
184
- .to_bytes()
185
- };
186
-
187
- let (query_params, raw_query_params) =
188
- extract_query_params_and_raw(&parts.uri, include_raw_query_params, include_query_params_json);
189
-
190
- Ok(RequestData {
191
- path_params: Arc::new(path_params),
192
- query_params,
193
- raw_query_params: if raw_query_params.is_empty() {
194
- empty_raw_query_map()
195
- } else {
196
- Arc::new(raw_query_params)
197
- },
198
- validated_params: None,
199
- headers: if include_headers {
200
- Arc::new(extract_headers(&parts.headers))
201
- } else {
202
- empty_string_map()
203
- },
204
- cookies: if include_cookies {
205
- Arc::new(extract_cookies(&parts.headers))
206
- } else {
207
- empty_string_map()
208
- },
209
- body: Value::Null,
210
- raw_body: if body_bytes.is_empty() { None } else { Some(body_bytes) },
211
- method: parts.method.as_str().to_string(),
212
- path: parts.uri.path().to_string(),
213
- #[cfg(feature = "di")]
214
- dependencies: None,
215
- })
216
- }
217
-
218
- #[cfg(test)]
219
- mod tests {
220
- use super::*;
221
- use axum::http::{HeaderMap, HeaderValue, Method, Uri};
222
- use futures_util::stream;
223
- use serde_json::json;
224
-
225
- const OPTIONS_ALL: WithoutBodyExtractionOptions = WithoutBodyExtractionOptions {
226
- include_raw_query_params: true,
227
- include_query_params_json: true,
228
- include_headers: true,
229
- include_cookies: true,
230
- };
231
-
232
- const OPTIONS_SKIP_HEADERS: WithoutBodyExtractionOptions = WithoutBodyExtractionOptions {
233
- include_raw_query_params: true,
234
- include_query_params_json: true,
235
- include_headers: false,
236
- include_cookies: true,
237
- };
238
-
239
- const OPTIONS_SKIP_COOKIES: WithoutBodyExtractionOptions = WithoutBodyExtractionOptions {
240
- include_raw_query_params: true,
241
- include_query_params_json: true,
242
- include_headers: true,
243
- include_cookies: false,
244
- };
245
-
246
- #[test]
247
- fn test_extract_query_params_empty() {
248
- let uri: Uri = "/path".parse().unwrap();
249
- let result = extract_query_params(&uri);
250
- assert_eq!(result, json!({}));
251
- }
252
-
253
- #[test]
254
- fn test_extract_query_params_single_param() {
255
- let uri: Uri = "/path?name=value".parse().unwrap();
256
- let result = extract_query_params(&uri);
257
- assert_eq!(result, json!({"name": "value"}));
258
- }
259
-
260
- #[test]
261
- fn test_extract_query_params_multiple_params() {
262
- let uri: Uri = "/path?foo=1&bar=2".parse().unwrap();
263
- let result = extract_query_params(&uri);
264
- assert_eq!(result, json!({"foo": 1, "bar": 2}));
265
- }
266
-
267
- #[test]
268
- fn test_extract_query_params_array_params() {
269
- let uri: Uri = "/path?tags=rust&tags=http".parse().unwrap();
270
- let result = extract_query_params(&uri);
271
- assert_eq!(result, json!({"tags": ["rust", "http"]}));
272
- }
273
-
274
- #[test]
275
- fn test_extract_query_params_mixed_array_and_single() {
276
- let uri: Uri = "/path?tags=rust&tags=web&id=123".parse().unwrap();
277
- let result = extract_query_params(&uri);
278
- assert_eq!(result, json!({"tags": ["rust", "web"], "id": 123}));
279
- }
280
-
281
- #[test]
282
- fn test_extract_query_params_url_encoded() {
283
- let uri: Uri = "/path?email=test%40example.com&name=john+doe".parse().unwrap();
284
- let result = extract_query_params(&uri);
285
- assert_eq!(result, json!({"email": "test@example.com", "name": "john doe"}));
286
- }
287
-
288
- #[test]
289
- fn test_extract_query_params_boolean_values() {
290
- let uri: Uri = "/path?active=true&enabled=false".parse().unwrap();
291
- let result = extract_query_params(&uri);
292
- assert_eq!(result, json!({"active": true, "enabled": false}));
293
- }
294
-
295
- #[test]
296
- fn test_extract_query_params_null_value() {
297
- let uri: Uri = "/path?value=null".parse().unwrap();
298
- let result = extract_query_params(&uri);
299
- assert_eq!(result, json!({"value": null}));
300
- }
301
-
302
- #[test]
303
- fn test_extract_query_params_empty_string_value() {
304
- let uri: Uri = "/path?key=".parse().unwrap();
305
- let result = extract_query_params(&uri);
306
- assert_eq!(result, json!({"key": ""}));
307
- }
308
-
309
- #[test]
310
- fn test_extract_raw_query_params_empty() {
311
- let uri: Uri = "/path".parse().unwrap();
312
- let result = extract_raw_query_params(&uri);
313
- assert!(result.is_empty());
314
- }
315
-
316
- #[test]
317
- fn test_extract_raw_query_params_single() {
318
- let uri: Uri = "/path?name=value".parse().unwrap();
319
- let result = extract_raw_query_params(&uri);
320
- assert_eq!(result.get("name"), Some(&vec!["value".to_string()]));
321
- }
322
-
323
- #[test]
324
- fn test_extract_raw_query_params_multiple_values() {
325
- let uri: Uri = "/path?tag=rust&tag=http".parse().unwrap();
326
- let result = extract_raw_query_params(&uri);
327
- assert_eq!(result.get("tag"), Some(&vec!["rust".to_string(), "http".to_string()]));
328
- }
329
-
330
- #[test]
331
- fn test_extract_raw_query_params_mixed() {
332
- let uri: Uri = "/path?id=123&tags=rust&tags=web&active=true".parse().unwrap();
333
- let result = extract_raw_query_params(&uri);
334
- assert_eq!(result.get("id"), Some(&vec!["123".to_string()]));
335
- assert_eq!(result.get("tags"), Some(&vec!["rust".to_string(), "web".to_string()]));
336
- assert_eq!(result.get("active"), Some(&vec!["true".to_string()]));
337
- }
338
-
339
- #[test]
340
- fn test_extract_raw_query_params_url_encoded() {
341
- let uri: Uri = "/path?email=test%40example.com".parse().unwrap();
342
- let result = extract_raw_query_params(&uri);
343
- assert_eq!(result.get("email"), Some(&vec!["test@example.com".to_string()]));
344
- }
345
-
346
- #[test]
347
- fn test_extract_headers_empty() {
348
- let headers = HeaderMap::new();
349
- let result = extract_headers(&headers);
350
- assert!(result.is_empty());
351
- }
352
-
353
- #[test]
354
- fn test_extract_headers_single() {
355
- let mut headers = HeaderMap::new();
356
- headers.insert("content-type", HeaderValue::from_static("application/json"));
357
- let result = extract_headers(&headers);
358
- assert_eq!(result.get("content-type"), Some(&"application/json".to_string()));
359
- }
360
-
361
- #[test]
362
- fn test_extract_headers_multiple() {
363
- let mut headers = HeaderMap::new();
364
- headers.insert("content-type", HeaderValue::from_static("application/json"));
365
- headers.insert("user-agent", HeaderValue::from_static("test-agent"));
366
- headers.insert("authorization", HeaderValue::from_static("Bearer token123"));
367
-
368
- let result = extract_headers(&headers);
369
- assert_eq!(result.len(), 3);
370
- assert_eq!(result.get("content-type"), Some(&"application/json".to_string()));
371
- assert_eq!(result.get("user-agent"), Some(&"test-agent".to_string()));
372
- assert_eq!(result.get("authorization"), Some(&"Bearer token123".to_string()));
373
- }
374
-
375
- #[test]
376
- fn test_extract_headers_case_insensitive() {
377
- let mut headers = HeaderMap::new();
378
- headers.insert("Content-Type", HeaderValue::from_static("text/html"));
379
- headers.insert("USER-Agent", HeaderValue::from_static("chrome"));
380
-
381
- let result = extract_headers(&headers);
382
- assert_eq!(result.get("content-type"), Some(&"text/html".to_string()));
383
- assert_eq!(result.get("user-agent"), Some(&"chrome".to_string()));
384
- }
385
-
386
- #[test]
387
- fn test_extract_headers_with_dashes() {
388
- let mut headers = HeaderMap::new();
389
- headers.insert("x-custom-header", HeaderValue::from_static("custom-value"));
390
- headers.insert("x-request-id", HeaderValue::from_static("req-12345"));
391
-
392
- let result = extract_headers(&headers);
393
- assert_eq!(result.get("x-custom-header"), Some(&"custom-value".to_string()));
394
- assert_eq!(result.get("x-request-id"), Some(&"req-12345".to_string()));
395
- }
396
-
397
- #[test]
398
- fn test_extract_cookies_no_cookie_header() {
399
- let headers = HeaderMap::new();
400
- let result = extract_cookies(&headers);
401
- assert!(result.is_empty());
402
- }
403
-
404
- #[test]
405
- fn test_extract_cookies_single() {
406
- let mut headers = HeaderMap::new();
407
- headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("session=abc123"));
408
-
409
- let result = extract_cookies(&headers);
410
- assert_eq!(result.get("session"), Some(&"abc123".to_string()));
411
- }
412
-
413
- #[test]
414
- fn test_extract_cookies_multiple() {
415
- let mut headers = HeaderMap::new();
416
- headers.insert(
417
- axum::http::header::COOKIE,
418
- HeaderValue::from_static("session=abc123; user_id=42; theme=dark"),
419
- );
420
-
421
- let result = extract_cookies(&headers);
422
- assert_eq!(result.len(), 3);
423
- assert_eq!(result.get("session"), Some(&"abc123".to_string()));
424
- assert_eq!(result.get("user_id"), Some(&"42".to_string()));
425
- assert_eq!(result.get("theme"), Some(&"dark".to_string()));
426
- }
427
-
428
- #[test]
429
- fn test_extract_cookies_with_spaces() {
430
- let mut headers = HeaderMap::new();
431
- headers.insert(
432
- axum::http::header::COOKIE,
433
- HeaderValue::from_static("session = abc123 ; theme = light"),
434
- );
435
-
436
- let result = extract_cookies(&headers);
437
- assert!(result.len() >= 1);
438
- }
439
-
440
- #[test]
441
- fn test_extract_cookies_empty_value() {
442
- let mut headers = HeaderMap::new();
443
- headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("empty="));
444
-
445
- let result = extract_cookies(&headers);
446
- assert_eq!(result.get("empty"), Some(&String::new()));
447
- }
448
-
449
- #[test]
450
- fn test_create_request_data_without_body_minimal() {
451
- let uri: Uri = "/test".parse().unwrap();
452
- let method = Method::GET;
453
- let headers = HeaderMap::new();
454
- let path_params = HashMap::new();
455
-
456
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
457
-
458
- assert_eq!(result.method, "GET");
459
- assert_eq!(result.path, "/test");
460
- assert!(result.path_params.is_empty());
461
- assert_eq!(result.query_params, json!({}));
462
- assert!(result.raw_query_params.is_empty());
463
- assert!(result.headers.is_empty());
464
- assert!(result.cookies.is_empty());
465
- assert_eq!(result.body, Value::Null);
466
- assert!(result.raw_body.is_none());
467
- }
468
-
469
- #[test]
470
- fn test_create_request_data_without_body_with_path_params() {
471
- let uri: Uri = "/users/42".parse().unwrap();
472
- let method = Method::GET;
473
- let headers = HeaderMap::new();
474
- let mut path_params = HashMap::new();
475
- path_params.insert("user_id".to_string(), "42".to_string());
476
-
477
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
478
-
479
- assert_eq!(result.path_params.get("user_id"), Some(&"42".to_string()));
480
- }
481
-
482
- #[test]
483
- fn test_create_request_data_without_body_with_query_params() {
484
- let uri: Uri = "/search?q=rust&limit=10".parse().unwrap();
485
- let method = Method::GET;
486
- let headers = HeaderMap::new();
487
- let path_params = HashMap::new();
488
-
489
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
490
-
491
- assert_eq!(result.query_params, json!({"q": "rust", "limit": 10}));
492
- assert_eq!(result.raw_query_params.get("q"), Some(&vec!["rust".to_string()]));
493
- assert_eq!(result.raw_query_params.get("limit"), Some(&vec!["10".to_string()]));
494
- }
495
-
496
- #[test]
497
- fn test_create_request_data_without_body_with_headers() {
498
- let uri: Uri = "/test".parse().unwrap();
499
- let method = Method::POST;
500
- let mut headers = HeaderMap::new();
501
- headers.insert("content-type", HeaderValue::from_static("application/json"));
502
- headers.insert("authorization", HeaderValue::from_static("Bearer token"));
503
- let path_params = HashMap::new();
504
-
505
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
506
-
507
- assert_eq!(
508
- result.headers.get("content-type"),
509
- Some(&"application/json".to_string())
510
- );
511
- assert_eq!(result.headers.get("authorization"), Some(&"Bearer token".to_string()));
512
- }
513
-
514
- #[test]
515
- fn test_create_request_data_without_body_with_cookies() {
516
- let uri: Uri = "/test".parse().unwrap();
517
- let method = Method::GET;
518
- let mut headers = HeaderMap::new();
519
- headers.insert(
520
- axum::http::header::COOKIE,
521
- HeaderValue::from_static("session=xyz; theme=dark"),
522
- );
523
- let path_params = HashMap::new();
524
-
525
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
526
-
527
- assert_eq!(result.cookies.get("session"), Some(&"xyz".to_string()));
528
- assert_eq!(result.cookies.get("theme"), Some(&"dark".to_string()));
529
- }
530
-
531
- #[test]
532
- fn test_create_request_data_without_body_skip_headers() {
533
- let uri: Uri = "/test".parse().unwrap();
534
- let method = Method::GET;
535
- let mut headers = HeaderMap::new();
536
- headers.insert("authorization", HeaderValue::from_static("Bearer token"));
537
- let path_params = HashMap::new();
538
-
539
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_SKIP_HEADERS);
540
-
541
- assert!(result.headers.is_empty());
542
- }
543
-
544
- #[test]
545
- fn test_create_request_data_without_body_skip_cookies() {
546
- let uri: Uri = "/test".parse().unwrap();
547
- let method = Method::GET;
548
- let mut headers = HeaderMap::new();
549
- headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("session=xyz"));
550
- let path_params = HashMap::new();
551
-
552
- let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_SKIP_COOKIES);
553
-
554
- assert!(result.cookies.is_empty());
555
- }
556
-
557
- #[test]
558
- fn test_create_request_data_without_body_different_methods() {
559
- let uri: Uri = "/resource".parse().unwrap();
560
- let headers = HeaderMap::new();
561
- let path_params = HashMap::new();
562
-
563
- for method in &[Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::PATCH] {
564
- let result = create_request_data_without_body(&uri, method, &headers, path_params.clone(), OPTIONS_ALL);
565
- assert_eq!(result.method, method.as_str());
566
- }
567
- }
568
-
569
- #[tokio::test]
570
- async fn test_create_request_data_with_body_empty() {
571
- let parts = axum::http::request::Request::builder()
572
- .method(Method::POST)
573
- .uri("/test")
574
- .body(Body::empty())
575
- .unwrap()
576
- .into_parts();
577
-
578
- let body = Body::empty();
579
- let path_params = HashMap::new();
580
-
581
- let result = create_request_data_with_body(&parts.0, path_params, body, true, true, true, true)
582
- .await
583
- .unwrap();
584
-
585
- assert_eq!(result.method, "POST");
586
- assert_eq!(result.path, "/test");
587
- assert_eq!(result.body, Value::Null);
588
- assert!(result.raw_body.is_none());
589
- }
590
-
591
- #[tokio::test]
592
- async fn test_create_request_data_with_body_json() {
593
- let request_body = Body::from(r#"{"key":"value"}"#);
594
- let request = axum::http::request::Request::builder()
595
- .method(Method::POST)
596
- .uri("/test")
597
- .body(Body::empty())
598
- .unwrap();
599
-
600
- let (parts, _) = request.into_parts();
601
- let path_params = HashMap::new();
602
-
603
- let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
604
- .await
605
- .unwrap();
606
-
607
- assert_eq!(result.method, "POST");
608
- assert_eq!(result.body, Value::Null);
609
- assert!(result.raw_body.is_some());
610
- assert_eq!(result.raw_body.as_ref().unwrap().as_ref(), br#"{"key":"value"}"#);
611
- }
612
-
613
- #[tokio::test]
614
- async fn test_create_request_data_with_body_with_query_params() {
615
- let request_body = Body::from("test");
616
- let request = axum::http::request::Request::builder()
617
- .method(Method::POST)
618
- .uri("/test?foo=bar&baz=qux")
619
- .body(Body::empty())
620
- .unwrap();
621
-
622
- let (parts, _) = request.into_parts();
623
- let path_params = HashMap::new();
624
-
625
- let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
626
- .await
627
- .unwrap();
628
-
629
- assert_eq!(result.query_params, json!({"foo": "bar", "baz": "qux"}));
630
- }
631
-
632
- #[tokio::test]
633
- async fn test_create_request_data_with_body_with_headers() {
634
- let request_body = Body::from("test");
635
- let request = axum::http::request::Request::builder()
636
- .method(Method::POST)
637
- .uri("/test")
638
- .header("content-type", "application/json")
639
- .header("x-request-id", "req123")
640
- .body(Body::empty())
641
- .unwrap();
642
-
643
- let (parts, _) = request.into_parts();
644
- let path_params = HashMap::new();
645
-
646
- let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
647
- .await
648
- .unwrap();
649
-
650
- assert_eq!(
651
- result.headers.get("content-type"),
652
- Some(&"application/json".to_string())
653
- );
654
- assert_eq!(result.headers.get("x-request-id"), Some(&"req123".to_string()));
655
- }
656
-
657
- #[tokio::test]
658
- async fn test_create_request_data_with_body_with_cookies() {
659
- let request_body = Body::from("test");
660
- let request = axum::http::request::Request::builder()
661
- .method(Method::POST)
662
- .uri("/test")
663
- .header("cookie", "session=xyz; user=123")
664
- .body(Body::empty())
665
- .unwrap();
666
-
667
- let (parts, _) = request.into_parts();
668
- let path_params = HashMap::new();
669
-
670
- let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
671
- .await
672
- .unwrap();
673
-
674
- assert_eq!(result.cookies.get("session"), Some(&"xyz".to_string()));
675
- assert_eq!(result.cookies.get("user"), Some(&"123".to_string()));
676
- }
677
-
678
- #[tokio::test]
679
- async fn test_create_request_data_with_body_large_payload() {
680
- let large_json = json!({
681
- "data": (0..100).map(|i| json!({"id": i, "value": format!("item-{}", i)})).collect::<Vec<_>>()
682
- });
683
- let json_str = serde_json::to_string(&large_json).unwrap();
684
- let request_body = Body::from(json_str.clone());
685
-
686
- let request = axum::http::request::Request::builder()
687
- .method(Method::POST)
688
- .uri("/test")
689
- .body(Body::empty())
690
- .unwrap();
691
-
692
- let (parts, _) = request.into_parts();
693
- let path_params = HashMap::new();
694
-
695
- let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
696
- .await
697
- .unwrap();
698
-
699
- assert!(result.raw_body.is_some());
700
- assert_eq!(result.raw_body.as_ref().unwrap().as_ref(), json_str.as_bytes());
701
- }
702
-
703
- #[tokio::test]
704
- async fn test_create_request_data_with_body_preserves_all_fields() {
705
- let request_body = Body::from("request data");
706
- let request = axum::http::request::Request::builder()
707
- .method(Method::PUT)
708
- .uri("/users/42?action=update")
709
- .header("authorization", "Bearer token")
710
- .header("cookie", "session=abc")
711
- .body(Body::empty())
712
- .unwrap();
713
-
714
- let (parts, _) = request.into_parts();
715
- let mut path_params = HashMap::new();
716
- path_params.insert("user_id".to_string(), "42".to_string());
717
-
718
- let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
719
- .await
720
- .unwrap();
721
-
722
- assert_eq!(result.method, "PUT");
723
- assert_eq!(result.path, "/users/42");
724
- assert_eq!(result.path_params.get("user_id"), Some(&"42".to_string()));
725
- assert_eq!(result.query_params, json!({"action": "update"}));
726
- assert!(result.headers.contains_key("authorization"));
727
- assert!(result.cookies.contains_key("session"));
728
- assert!(result.raw_body.is_some());
729
- }
730
-
731
- #[test]
732
- fn test_arc_wrapping_for_cheap_cloning() {
733
- let uri: Uri = "/test".parse().unwrap();
734
- let method = Method::GET;
735
- let mut headers = HeaderMap::new();
736
- headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("session=abc"));
737
- let mut path_params = HashMap::new();
738
- path_params.insert("id".to_string(), "1".to_string());
739
-
740
- let request_data = create_request_data_without_body(&uri, &method, &headers, path_params.clone(), OPTIONS_ALL);
741
-
742
- let cloned = request_data.clone();
743
-
744
- assert!(Arc::ptr_eq(&request_data.path_params, &cloned.path_params));
745
- assert!(Arc::ptr_eq(&request_data.headers, &cloned.headers));
746
- assert!(Arc::ptr_eq(&request_data.cookies, &cloned.cookies));
747
- assert!(Arc::ptr_eq(&request_data.raw_query_params, &cloned.raw_query_params));
748
- }
749
-
750
- #[tokio::test]
751
- async fn create_request_data_with_body_returns_bad_request_when_body_stream_errors() {
752
- let request = axum::http::Request::builder()
753
- .method(Method::POST)
754
- .uri("/path")
755
- .body(Body::empty())
756
- .unwrap();
757
- let (parts, _) = request.into_parts();
758
-
759
- let stream = stream::once(async move {
760
- Err::<bytes::Bytes, std::io::Error>(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
761
- });
762
- let body = Body::from_stream(stream);
763
-
764
- let err = create_request_data_with_body(&parts, HashMap::new(), body, true, true, true, true)
765
- .await
766
- .unwrap_err();
767
- assert_eq!(err.0, axum::http::StatusCode::BAD_REQUEST);
768
- assert!(err.1.contains("Failed to read body:"));
769
- }
770
- }
1
+ //! Request parsing and data extraction utilities
2
+
3
+ use crate::handler_trait::RequestData;
4
+ use crate::query_parser::{parse_query_pairs_to_json, parse_query_string};
5
+ use axum::body::Body;
6
+ use http_body_util::BodyExt;
7
+ use serde_json::Value;
8
+ use std::collections::HashMap;
9
+ use std::sync::Arc;
10
+ use std::sync::OnceLock;
11
+
12
+ #[derive(Debug, Clone, Copy)]
13
+ pub struct WithoutBodyExtractionOptions {
14
+ pub include_raw_query_params: bool,
15
+ pub include_query_params_json: bool,
16
+ pub include_headers: bool,
17
+ pub include_cookies: bool,
18
+ }
19
+
20
+ fn extract_query_params_and_raw(
21
+ uri: &axum::http::Uri,
22
+ include_raw_query_params: bool,
23
+ include_query_params_json: bool,
24
+ ) -> (Value, HashMap<String, Vec<String>>) {
25
+ let query_string = uri.query().unwrap_or("");
26
+ if query_string.is_empty() {
27
+ return (Value::Object(serde_json::Map::new()), HashMap::new());
28
+ }
29
+
30
+ match (include_raw_query_params, include_query_params_json) {
31
+ (false, false) => (Value::Null, HashMap::new()),
32
+ (false, true) => (
33
+ crate::query_parser::parse_query_string_to_json(query_string.as_bytes(), true),
34
+ HashMap::new(),
35
+ ),
36
+ (true, false) => {
37
+ let raw =
38
+ parse_query_string(query_string.as_bytes(), '&')
39
+ .into_iter()
40
+ .fold(HashMap::new(), |mut acc, (k, v)| {
41
+ acc.entry(k).or_insert_with(Vec::new).push(v);
42
+ acc
43
+ });
44
+ (Value::Null, raw)
45
+ }
46
+ (true, true) => {
47
+ let pairs = parse_query_string(query_string.as_bytes(), '&');
48
+ let json = parse_query_pairs_to_json(&pairs, true);
49
+ let raw = pairs.into_iter().fold(HashMap::new(), |mut acc, (k, v)| {
50
+ acc.entry(k).or_insert_with(Vec::new).push(v);
51
+ acc
52
+ });
53
+ (json, raw)
54
+ }
55
+ }
56
+ }
57
+
58
+ /// Extract and parse query parameters from request URI
59
+ pub fn extract_query_params(uri: &axum::http::Uri) -> Value {
60
+ let query_string = uri.query().unwrap_or("");
61
+ if query_string.is_empty() {
62
+ Value::Object(serde_json::Map::new())
63
+ } else {
64
+ crate::query_parser::parse_query_string_to_json(query_string.as_bytes(), true)
65
+ }
66
+ }
67
+
68
+ /// Extract raw query parameters as strings (no type conversion)
69
+ /// Used for validation error messages to show the actual input values
70
+ pub fn extract_raw_query_params(uri: &axum::http::Uri) -> HashMap<String, Vec<String>> {
71
+ let query_string = uri.query().unwrap_or("");
72
+ if query_string.is_empty() {
73
+ HashMap::new()
74
+ } else {
75
+ parse_query_string(query_string.as_bytes(), '&')
76
+ .into_iter()
77
+ .fold(HashMap::new(), |mut acc, (k, v)| {
78
+ acc.entry(k).or_insert_with(Vec::new).push(v);
79
+ acc
80
+ })
81
+ }
82
+ }
83
+
84
+ /// Extract headers from request
85
+ pub fn extract_headers(headers: &axum::http::HeaderMap) -> HashMap<String, String> {
86
+ let mut map = HashMap::with_capacity(headers.len());
87
+ for (name, value) in headers.iter() {
88
+ if let Ok(val_str) = value.to_str() {
89
+ // `HeaderName::as_str()` is already normalized to lowercase.
90
+ map.insert(name.as_str().to_string(), val_str.to_string());
91
+ }
92
+ }
93
+ map
94
+ }
95
+
96
+ fn extract_content_type_header(headers: &axum::http::HeaderMap) -> Arc<HashMap<String, String>> {
97
+ let Some(value) = headers
98
+ .get(axum::http::header::CONTENT_TYPE)
99
+ .and_then(|h| h.to_str().ok())
100
+ else {
101
+ return empty_string_map();
102
+ };
103
+
104
+ let mut map = HashMap::with_capacity(1);
105
+ map.insert("content-type".to_string(), value.to_string());
106
+ Arc::new(map)
107
+ }
108
+
109
+ /// Extract cookies from request headers
110
+ pub fn extract_cookies(headers: &axum::http::HeaderMap) -> HashMap<String, String> {
111
+ let mut cookies = HashMap::new();
112
+
113
+ if let Some(cookie_str) = headers.get(axum::http::header::COOKIE).and_then(|h| h.to_str().ok()) {
114
+ for cookie in cookie::Cookie::split_parse(cookie_str).flatten() {
115
+ cookies.insert(cookie.name().to_string(), cookie.value().to_string());
116
+ }
117
+ }
118
+
119
+ cookies
120
+ }
121
+
122
+ fn empty_string_map() -> Arc<HashMap<String, String>> {
123
+ static EMPTY: OnceLock<Arc<HashMap<String, String>>> = OnceLock::new();
124
+ Arc::clone(EMPTY.get_or_init(|| Arc::new(HashMap::new())))
125
+ }
126
+
127
+ fn empty_raw_query_map() -> Arc<HashMap<String, Vec<String>>> {
128
+ static EMPTY: OnceLock<Arc<HashMap<String, Vec<String>>>> = OnceLock::new();
129
+ Arc::clone(EMPTY.get_or_init(|| Arc::new(HashMap::new())))
130
+ }
131
+
132
+ /// Create RequestData from request parts (for requests without body)
133
+ ///
134
+ /// Wraps HashMaps in Arc to enable cheap cloning without duplicating data.
135
+ pub fn create_request_data_without_body(
136
+ uri: &axum::http::Uri,
137
+ method: &axum::http::Method,
138
+ headers: &axum::http::HeaderMap,
139
+ path_params: HashMap<String, String>,
140
+ options: WithoutBodyExtractionOptions,
141
+ ) -> RequestData {
142
+ let (query_params, raw_query_params) =
143
+ extract_query_params_and_raw(uri, options.include_raw_query_params, options.include_query_params_json);
144
+ RequestData {
145
+ path_params: Arc::new(path_params),
146
+ query_params,
147
+ raw_query_params: if raw_query_params.is_empty() {
148
+ empty_raw_query_map()
149
+ } else {
150
+ Arc::new(raw_query_params)
151
+ },
152
+ validated_params: None,
153
+ headers: if options.include_headers {
154
+ Arc::new(extract_headers(headers))
155
+ } else {
156
+ empty_string_map()
157
+ },
158
+ cookies: if options.include_cookies {
159
+ Arc::new(extract_cookies(headers))
160
+ } else {
161
+ empty_string_map()
162
+ },
163
+ body: Value::Null,
164
+ raw_body: None,
165
+ method: method.as_str().to_string(),
166
+ path: uri.path().to_string(),
167
+ #[cfg(feature = "di")]
168
+ dependencies: None,
169
+ }
170
+ }
171
+
172
+ /// Create RequestData from request parts (for requests with body)
173
+ ///
174
+ /// Wraps HashMaps in Arc to enable cheap cloning without duplicating data.
175
+ /// Performance optimization: stores raw body bytes without parsing JSON.
176
+ /// JSON parsing is deferred until actually needed (e.g., for validation).
177
+ pub async fn create_request_data_with_body(
178
+ parts: &axum::http::request::Parts,
179
+ path_params: HashMap<String, String>,
180
+ body: Body,
181
+ include_raw_query_params: bool,
182
+ include_query_params_json: bool,
183
+ include_headers: bool,
184
+ include_cookies: bool,
185
+ ) -> Result<RequestData, (axum::http::StatusCode, String)> {
186
+ let body_bytes = if let Some(pre_read) = parts.extensions.get::<crate::middleware::PreReadBody>() {
187
+ pre_read.0.clone()
188
+ } else {
189
+ body.collect()
190
+ .await
191
+ .map_err(|e| {
192
+ (
193
+ axum::http::StatusCode::BAD_REQUEST,
194
+ format!("Failed to read body: {}", e),
195
+ )
196
+ })?
197
+ .to_bytes()
198
+ };
199
+
200
+ let (query_params, raw_query_params) =
201
+ extract_query_params_and_raw(&parts.uri, include_raw_query_params, include_query_params_json);
202
+
203
+ let body_value = parts
204
+ .extensions
205
+ .get::<crate::middleware::PreParsedJson>()
206
+ .map(|parsed| parsed.0.clone())
207
+ .unwrap_or(Value::Null);
208
+
209
+ Ok(RequestData {
210
+ path_params: Arc::new(path_params),
211
+ query_params,
212
+ raw_query_params: if raw_query_params.is_empty() {
213
+ empty_raw_query_map()
214
+ } else {
215
+ Arc::new(raw_query_params)
216
+ },
217
+ validated_params: None,
218
+ headers: if include_headers {
219
+ Arc::new(extract_headers(&parts.headers))
220
+ } else {
221
+ extract_content_type_header(&parts.headers)
222
+ },
223
+ cookies: if include_cookies {
224
+ Arc::new(extract_cookies(&parts.headers))
225
+ } else {
226
+ empty_string_map()
227
+ },
228
+ body: body_value,
229
+ raw_body: if body_bytes.is_empty() { None } else { Some(body_bytes) },
230
+ method: parts.method.as_str().to_string(),
231
+ path: parts.uri.path().to_string(),
232
+ #[cfg(feature = "di")]
233
+ dependencies: None,
234
+ })
235
+ }
236
+
237
+ #[cfg(test)]
238
+ mod tests {
239
+ use super::*;
240
+ use axum::http::{HeaderMap, HeaderValue, Method, Uri};
241
+ use futures_util::stream;
242
+ use serde_json::json;
243
+
244
+ const OPTIONS_ALL: WithoutBodyExtractionOptions = WithoutBodyExtractionOptions {
245
+ include_raw_query_params: true,
246
+ include_query_params_json: true,
247
+ include_headers: true,
248
+ include_cookies: true,
249
+ };
250
+
251
+ const OPTIONS_SKIP_HEADERS: WithoutBodyExtractionOptions = WithoutBodyExtractionOptions {
252
+ include_raw_query_params: true,
253
+ include_query_params_json: true,
254
+ include_headers: false,
255
+ include_cookies: true,
256
+ };
257
+
258
+ const OPTIONS_SKIP_COOKIES: WithoutBodyExtractionOptions = WithoutBodyExtractionOptions {
259
+ include_raw_query_params: true,
260
+ include_query_params_json: true,
261
+ include_headers: true,
262
+ include_cookies: false,
263
+ };
264
+
265
+ #[test]
266
+ fn test_extract_query_params_empty() {
267
+ let uri: Uri = "/path".parse().unwrap();
268
+ let result = extract_query_params(&uri);
269
+ assert_eq!(result, json!({}));
270
+ }
271
+
272
+ #[test]
273
+ fn test_extract_query_params_single_param() {
274
+ let uri: Uri = "/path?name=value".parse().unwrap();
275
+ let result = extract_query_params(&uri);
276
+ assert_eq!(result, json!({"name": "value"}));
277
+ }
278
+
279
+ #[test]
280
+ fn test_extract_query_params_multiple_params() {
281
+ let uri: Uri = "/path?foo=1&bar=2".parse().unwrap();
282
+ let result = extract_query_params(&uri);
283
+ assert_eq!(result, json!({"foo": 1, "bar": 2}));
284
+ }
285
+
286
+ #[test]
287
+ fn test_extract_query_params_array_params() {
288
+ let uri: Uri = "/path?tags=rust&tags=http".parse().unwrap();
289
+ let result = extract_query_params(&uri);
290
+ assert_eq!(result, json!({"tags": ["rust", "http"]}));
291
+ }
292
+
293
+ #[test]
294
+ fn test_extract_query_params_mixed_array_and_single() {
295
+ let uri: Uri = "/path?tags=rust&tags=web&id=123".parse().unwrap();
296
+ let result = extract_query_params(&uri);
297
+ assert_eq!(result, json!({"tags": ["rust", "web"], "id": 123}));
298
+ }
299
+
300
+ #[test]
301
+ fn test_extract_query_params_url_encoded() {
302
+ let uri: Uri = "/path?email=test%40example.com&name=john+doe".parse().unwrap();
303
+ let result = extract_query_params(&uri);
304
+ assert_eq!(result, json!({"email": "test@example.com", "name": "john doe"}));
305
+ }
306
+
307
+ #[test]
308
+ fn test_extract_query_params_boolean_values() {
309
+ let uri: Uri = "/path?active=true&enabled=false".parse().unwrap();
310
+ let result = extract_query_params(&uri);
311
+ assert_eq!(result, json!({"active": true, "enabled": false}));
312
+ }
313
+
314
+ #[test]
315
+ fn test_extract_query_params_null_value() {
316
+ let uri: Uri = "/path?value=null".parse().unwrap();
317
+ let result = extract_query_params(&uri);
318
+ assert_eq!(result, json!({"value": null}));
319
+ }
320
+
321
+ #[test]
322
+ fn test_extract_query_params_empty_string_value() {
323
+ let uri: Uri = "/path?key=".parse().unwrap();
324
+ let result = extract_query_params(&uri);
325
+ assert_eq!(result, json!({"key": ""}));
326
+ }
327
+
328
+ #[test]
329
+ fn test_extract_raw_query_params_empty() {
330
+ let uri: Uri = "/path".parse().unwrap();
331
+ let result = extract_raw_query_params(&uri);
332
+ assert!(result.is_empty());
333
+ }
334
+
335
+ #[test]
336
+ fn test_extract_raw_query_params_single() {
337
+ let uri: Uri = "/path?name=value".parse().unwrap();
338
+ let result = extract_raw_query_params(&uri);
339
+ assert_eq!(result.get("name"), Some(&vec!["value".to_string()]));
340
+ }
341
+
342
+ #[test]
343
+ fn test_extract_raw_query_params_multiple_values() {
344
+ let uri: Uri = "/path?tag=rust&tag=http".parse().unwrap();
345
+ let result = extract_raw_query_params(&uri);
346
+ assert_eq!(result.get("tag"), Some(&vec!["rust".to_string(), "http".to_string()]));
347
+ }
348
+
349
+ #[test]
350
+ fn test_extract_raw_query_params_mixed() {
351
+ let uri: Uri = "/path?id=123&tags=rust&tags=web&active=true".parse().unwrap();
352
+ let result = extract_raw_query_params(&uri);
353
+ assert_eq!(result.get("id"), Some(&vec!["123".to_string()]));
354
+ assert_eq!(result.get("tags"), Some(&vec!["rust".to_string(), "web".to_string()]));
355
+ assert_eq!(result.get("active"), Some(&vec!["true".to_string()]));
356
+ }
357
+
358
+ #[test]
359
+ fn test_extract_raw_query_params_url_encoded() {
360
+ let uri: Uri = "/path?email=test%40example.com".parse().unwrap();
361
+ let result = extract_raw_query_params(&uri);
362
+ assert_eq!(result.get("email"), Some(&vec!["test@example.com".to_string()]));
363
+ }
364
+
365
+ #[test]
366
+ fn test_extract_headers_empty() {
367
+ let headers = HeaderMap::new();
368
+ let result = extract_headers(&headers);
369
+ assert!(result.is_empty());
370
+ }
371
+
372
+ #[test]
373
+ fn test_extract_headers_single() {
374
+ let mut headers = HeaderMap::new();
375
+ headers.insert("content-type", HeaderValue::from_static("application/json"));
376
+ let result = extract_headers(&headers);
377
+ assert_eq!(result.get("content-type"), Some(&"application/json".to_string()));
378
+ }
379
+
380
+ #[test]
381
+ fn test_extract_headers_multiple() {
382
+ let mut headers = HeaderMap::new();
383
+ headers.insert("content-type", HeaderValue::from_static("application/json"));
384
+ headers.insert("user-agent", HeaderValue::from_static("test-agent"));
385
+ headers.insert("authorization", HeaderValue::from_static("Bearer token123"));
386
+
387
+ let result = extract_headers(&headers);
388
+ assert_eq!(result.len(), 3);
389
+ assert_eq!(result.get("content-type"), Some(&"application/json".to_string()));
390
+ assert_eq!(result.get("user-agent"), Some(&"test-agent".to_string()));
391
+ assert_eq!(result.get("authorization"), Some(&"Bearer token123".to_string()));
392
+ }
393
+
394
+ #[test]
395
+ fn test_extract_headers_case_insensitive() {
396
+ let mut headers = HeaderMap::new();
397
+ headers.insert("Content-Type", HeaderValue::from_static("text/html"));
398
+ headers.insert("USER-Agent", HeaderValue::from_static("chrome"));
399
+
400
+ let result = extract_headers(&headers);
401
+ assert_eq!(result.get("content-type"), Some(&"text/html".to_string()));
402
+ assert_eq!(result.get("user-agent"), Some(&"chrome".to_string()));
403
+ }
404
+
405
+ #[test]
406
+ fn test_extract_headers_with_dashes() {
407
+ let mut headers = HeaderMap::new();
408
+ headers.insert("x-custom-header", HeaderValue::from_static("custom-value"));
409
+ headers.insert("x-request-id", HeaderValue::from_static("req-12345"));
410
+
411
+ let result = extract_headers(&headers);
412
+ assert_eq!(result.get("x-custom-header"), Some(&"custom-value".to_string()));
413
+ assert_eq!(result.get("x-request-id"), Some(&"req-12345".to_string()));
414
+ }
415
+
416
+ #[test]
417
+ fn test_extract_cookies_no_cookie_header() {
418
+ let headers = HeaderMap::new();
419
+ let result = extract_cookies(&headers);
420
+ assert!(result.is_empty());
421
+ }
422
+
423
+ #[test]
424
+ fn test_extract_cookies_single() {
425
+ let mut headers = HeaderMap::new();
426
+ headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("session=abc123"));
427
+
428
+ let result = extract_cookies(&headers);
429
+ assert_eq!(result.get("session"), Some(&"abc123".to_string()));
430
+ }
431
+
432
+ #[test]
433
+ fn test_extract_cookies_multiple() {
434
+ let mut headers = HeaderMap::new();
435
+ headers.insert(
436
+ axum::http::header::COOKIE,
437
+ HeaderValue::from_static("session=abc123; user_id=42; theme=dark"),
438
+ );
439
+
440
+ let result = extract_cookies(&headers);
441
+ assert_eq!(result.len(), 3);
442
+ assert_eq!(result.get("session"), Some(&"abc123".to_string()));
443
+ assert_eq!(result.get("user_id"), Some(&"42".to_string()));
444
+ assert_eq!(result.get("theme"), Some(&"dark".to_string()));
445
+ }
446
+
447
+ #[test]
448
+ fn test_extract_cookies_with_spaces() {
449
+ let mut headers = HeaderMap::new();
450
+ headers.insert(
451
+ axum::http::header::COOKIE,
452
+ HeaderValue::from_static("session = abc123 ; theme = light"),
453
+ );
454
+
455
+ let result = extract_cookies(&headers);
456
+ assert!(result.len() >= 1);
457
+ }
458
+
459
+ #[test]
460
+ fn test_extract_cookies_empty_value() {
461
+ let mut headers = HeaderMap::new();
462
+ headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("empty="));
463
+
464
+ let result = extract_cookies(&headers);
465
+ assert_eq!(result.get("empty"), Some(&String::new()));
466
+ }
467
+
468
+ #[test]
469
+ fn test_create_request_data_without_body_minimal() {
470
+ let uri: Uri = "/test".parse().unwrap();
471
+ let method = Method::GET;
472
+ let headers = HeaderMap::new();
473
+ let path_params = HashMap::new();
474
+
475
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
476
+
477
+ assert_eq!(result.method, "GET");
478
+ assert_eq!(result.path, "/test");
479
+ assert!(result.path_params.is_empty());
480
+ assert_eq!(result.query_params, json!({}));
481
+ assert!(result.raw_query_params.is_empty());
482
+ assert!(result.headers.is_empty());
483
+ assert!(result.cookies.is_empty());
484
+ assert_eq!(result.body, Value::Null);
485
+ assert!(result.raw_body.is_none());
486
+ }
487
+
488
+ #[test]
489
+ fn test_create_request_data_without_body_with_path_params() {
490
+ let uri: Uri = "/users/42".parse().unwrap();
491
+ let method = Method::GET;
492
+ let headers = HeaderMap::new();
493
+ let mut path_params = HashMap::new();
494
+ path_params.insert("user_id".to_string(), "42".to_string());
495
+
496
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
497
+
498
+ assert_eq!(result.path_params.get("user_id"), Some(&"42".to_string()));
499
+ }
500
+
501
+ #[test]
502
+ fn test_create_request_data_without_body_with_query_params() {
503
+ let uri: Uri = "/search?q=rust&limit=10".parse().unwrap();
504
+ let method = Method::GET;
505
+ let headers = HeaderMap::new();
506
+ let path_params = HashMap::new();
507
+
508
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
509
+
510
+ assert_eq!(result.query_params, json!({"q": "rust", "limit": 10}));
511
+ assert_eq!(result.raw_query_params.get("q"), Some(&vec!["rust".to_string()]));
512
+ assert_eq!(result.raw_query_params.get("limit"), Some(&vec!["10".to_string()]));
513
+ }
514
+
515
+ #[test]
516
+ fn test_create_request_data_without_body_with_headers() {
517
+ let uri: Uri = "/test".parse().unwrap();
518
+ let method = Method::POST;
519
+ let mut headers = HeaderMap::new();
520
+ headers.insert("content-type", HeaderValue::from_static("application/json"));
521
+ headers.insert("authorization", HeaderValue::from_static("Bearer token"));
522
+ let path_params = HashMap::new();
523
+
524
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
525
+
526
+ assert_eq!(
527
+ result.headers.get("content-type"),
528
+ Some(&"application/json".to_string())
529
+ );
530
+ assert_eq!(result.headers.get("authorization"), Some(&"Bearer token".to_string()));
531
+ }
532
+
533
+ #[test]
534
+ fn test_create_request_data_without_body_with_cookies() {
535
+ let uri: Uri = "/test".parse().unwrap();
536
+ let method = Method::GET;
537
+ let mut headers = HeaderMap::new();
538
+ headers.insert(
539
+ axum::http::header::COOKIE,
540
+ HeaderValue::from_static("session=xyz; theme=dark"),
541
+ );
542
+ let path_params = HashMap::new();
543
+
544
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_ALL);
545
+
546
+ assert_eq!(result.cookies.get("session"), Some(&"xyz".to_string()));
547
+ assert_eq!(result.cookies.get("theme"), Some(&"dark".to_string()));
548
+ }
549
+
550
+ #[test]
551
+ fn test_create_request_data_without_body_skip_headers() {
552
+ let uri: Uri = "/test".parse().unwrap();
553
+ let method = Method::GET;
554
+ let mut headers = HeaderMap::new();
555
+ headers.insert("authorization", HeaderValue::from_static("Bearer token"));
556
+ let path_params = HashMap::new();
557
+
558
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_SKIP_HEADERS);
559
+
560
+ assert!(result.headers.is_empty());
561
+ }
562
+
563
+ #[test]
564
+ fn test_create_request_data_without_body_skip_cookies() {
565
+ let uri: Uri = "/test".parse().unwrap();
566
+ let method = Method::GET;
567
+ let mut headers = HeaderMap::new();
568
+ headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("session=xyz"));
569
+ let path_params = HashMap::new();
570
+
571
+ let result = create_request_data_without_body(&uri, &method, &headers, path_params, OPTIONS_SKIP_COOKIES);
572
+
573
+ assert!(result.cookies.is_empty());
574
+ }
575
+
576
+ #[test]
577
+ fn test_create_request_data_without_body_different_methods() {
578
+ let uri: Uri = "/resource".parse().unwrap();
579
+ let headers = HeaderMap::new();
580
+ let path_params = HashMap::new();
581
+
582
+ for method in &[Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::PATCH] {
583
+ let result = create_request_data_without_body(&uri, method, &headers, path_params.clone(), OPTIONS_ALL);
584
+ assert_eq!(result.method, method.as_str());
585
+ }
586
+ }
587
+
588
+ #[tokio::test]
589
+ async fn test_create_request_data_with_body_empty() {
590
+ let parts = axum::http::request::Request::builder()
591
+ .method(Method::POST)
592
+ .uri("/test")
593
+ .body(Body::empty())
594
+ .unwrap()
595
+ .into_parts();
596
+
597
+ let body = Body::empty();
598
+ let path_params = HashMap::new();
599
+
600
+ let result = create_request_data_with_body(&parts.0, path_params, body, true, true, true, true)
601
+ .await
602
+ .unwrap();
603
+
604
+ assert_eq!(result.method, "POST");
605
+ assert_eq!(result.path, "/test");
606
+ assert_eq!(result.body, Value::Null);
607
+ assert!(result.raw_body.is_none());
608
+ }
609
+
610
+ #[tokio::test]
611
+ async fn test_create_request_data_with_body_json() {
612
+ let request_body = Body::from(r#"{"key":"value"}"#);
613
+ let request = axum::http::request::Request::builder()
614
+ .method(Method::POST)
615
+ .uri("/test")
616
+ .body(Body::empty())
617
+ .unwrap();
618
+
619
+ let (parts, _) = request.into_parts();
620
+ let path_params = HashMap::new();
621
+
622
+ let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
623
+ .await
624
+ .unwrap();
625
+
626
+ assert_eq!(result.method, "POST");
627
+ assert_eq!(result.body, Value::Null);
628
+ assert!(result.raw_body.is_some());
629
+ assert_eq!(result.raw_body.as_ref().unwrap().as_ref(), br#"{"key":"value"}"#);
630
+ }
631
+
632
+ #[tokio::test]
633
+ async fn test_create_request_data_with_body_with_query_params() {
634
+ let request_body = Body::from("test");
635
+ let request = axum::http::request::Request::builder()
636
+ .method(Method::POST)
637
+ .uri("/test?foo=bar&baz=qux")
638
+ .body(Body::empty())
639
+ .unwrap();
640
+
641
+ let (parts, _) = request.into_parts();
642
+ let path_params = HashMap::new();
643
+
644
+ let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
645
+ .await
646
+ .unwrap();
647
+
648
+ assert_eq!(result.query_params, json!({"foo": "bar", "baz": "qux"}));
649
+ }
650
+
651
+ #[tokio::test]
652
+ async fn test_create_request_data_with_body_with_headers() {
653
+ let request_body = Body::from("test");
654
+ let request = axum::http::request::Request::builder()
655
+ .method(Method::POST)
656
+ .uri("/test")
657
+ .header("content-type", "application/json")
658
+ .header("x-request-id", "req123")
659
+ .body(Body::empty())
660
+ .unwrap();
661
+
662
+ let (parts, _) = request.into_parts();
663
+ let path_params = HashMap::new();
664
+
665
+ let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
666
+ .await
667
+ .unwrap();
668
+
669
+ assert_eq!(
670
+ result.headers.get("content-type"),
671
+ Some(&"application/json".to_string())
672
+ );
673
+ assert_eq!(result.headers.get("x-request-id"), Some(&"req123".to_string()));
674
+ }
675
+
676
+ #[tokio::test]
677
+ async fn test_create_request_data_with_body_with_cookies() {
678
+ let request_body = Body::from("test");
679
+ let request = axum::http::request::Request::builder()
680
+ .method(Method::POST)
681
+ .uri("/test")
682
+ .header("cookie", "session=xyz; user=123")
683
+ .body(Body::empty())
684
+ .unwrap();
685
+
686
+ let (parts, _) = request.into_parts();
687
+ let path_params = HashMap::new();
688
+
689
+ let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
690
+ .await
691
+ .unwrap();
692
+
693
+ assert_eq!(result.cookies.get("session"), Some(&"xyz".to_string()));
694
+ assert_eq!(result.cookies.get("user"), Some(&"123".to_string()));
695
+ }
696
+
697
+ #[tokio::test]
698
+ async fn test_create_request_data_with_body_large_payload() {
699
+ let large_json = json!({
700
+ "data": (0..100).map(|i| json!({"id": i, "value": format!("item-{}", i)})).collect::<Vec<_>>()
701
+ });
702
+ let json_str = serde_json::to_string(&large_json).unwrap();
703
+ let request_body = Body::from(json_str.clone());
704
+
705
+ let request = axum::http::request::Request::builder()
706
+ .method(Method::POST)
707
+ .uri("/test")
708
+ .body(Body::empty())
709
+ .unwrap();
710
+
711
+ let (parts, _) = request.into_parts();
712
+ let path_params = HashMap::new();
713
+
714
+ let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
715
+ .await
716
+ .unwrap();
717
+
718
+ assert!(result.raw_body.is_some());
719
+ assert_eq!(result.raw_body.as_ref().unwrap().as_ref(), json_str.as_bytes());
720
+ }
721
+
722
+ #[tokio::test]
723
+ async fn test_create_request_data_with_body_preserves_all_fields() {
724
+ let request_body = Body::from("request data");
725
+ let request = axum::http::request::Request::builder()
726
+ .method(Method::PUT)
727
+ .uri("/users/42?action=update")
728
+ .header("authorization", "Bearer token")
729
+ .header("cookie", "session=abc")
730
+ .body(Body::empty())
731
+ .unwrap();
732
+
733
+ let (parts, _) = request.into_parts();
734
+ let mut path_params = HashMap::new();
735
+ path_params.insert("user_id".to_string(), "42".to_string());
736
+
737
+ let result = create_request_data_with_body(&parts, path_params, request_body, true, true, true, true)
738
+ .await
739
+ .unwrap();
740
+
741
+ assert_eq!(result.method, "PUT");
742
+ assert_eq!(result.path, "/users/42");
743
+ assert_eq!(result.path_params.get("user_id"), Some(&"42".to_string()));
744
+ assert_eq!(result.query_params, json!({"action": "update"}));
745
+ assert!(result.headers.contains_key("authorization"));
746
+ assert!(result.cookies.contains_key("session"));
747
+ assert!(result.raw_body.is_some());
748
+ }
749
+
750
+ #[test]
751
+ fn test_arc_wrapping_for_cheap_cloning() {
752
+ let uri: Uri = "/test".parse().unwrap();
753
+ let method = Method::GET;
754
+ let mut headers = HeaderMap::new();
755
+ headers.insert(axum::http::header::COOKIE, HeaderValue::from_static("session=abc"));
756
+ let mut path_params = HashMap::new();
757
+ path_params.insert("id".to_string(), "1".to_string());
758
+
759
+ let request_data = create_request_data_without_body(&uri, &method, &headers, path_params.clone(), OPTIONS_ALL);
760
+
761
+ let cloned = request_data.clone();
762
+
763
+ assert!(Arc::ptr_eq(&request_data.path_params, &cloned.path_params));
764
+ assert!(Arc::ptr_eq(&request_data.headers, &cloned.headers));
765
+ assert!(Arc::ptr_eq(&request_data.cookies, &cloned.cookies));
766
+ assert!(Arc::ptr_eq(&request_data.raw_query_params, &cloned.raw_query_params));
767
+ }
768
+
769
+ #[tokio::test]
770
+ async fn create_request_data_with_body_returns_bad_request_when_body_stream_errors() {
771
+ let request = axum::http::Request::builder()
772
+ .method(Method::POST)
773
+ .uri("/path")
774
+ .body(Body::empty())
775
+ .unwrap();
776
+ let (parts, _) = request.into_parts();
777
+
778
+ let stream = stream::once(async move {
779
+ Err::<bytes::Bytes, std::io::Error>(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
780
+ });
781
+ let body = Body::from_stream(stream);
782
+
783
+ let err = create_request_data_with_body(&parts, HashMap::new(), body, true, true, true, true)
784
+ .await
785
+ .unwrap_err();
786
+ assert_eq!(err.0, axum::http::StatusCode::BAD_REQUEST);
787
+ assert!(err.1.contains("Failed to read body:"));
788
+ }
789
+ }