spikard 0.3.5 → 0.3.6

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 (102) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -659
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +386 -386
  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 +221 -221
  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 -360
  23. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -63
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -726
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -283
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -39
  36. data/vendor/crates/spikard-core/src/http.rs +153 -153
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -722
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -310
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -189
  42. data/vendor/crates/spikard-core/src/router.rs +249 -249
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -699
  46. data/vendor/crates/spikard-http/Cargo.toml +68 -68
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -247
  48. data/vendor/crates/spikard-http/src/background.rs +249 -249
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -490
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -63
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -529
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -1
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -1
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
  72. data/vendor/crates/spikard-http/src/response.rs +399 -399
  73. data/vendor/crates/spikard-http/src/router.rs +1 -1
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -447
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -1
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -324
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -42
  88. data/vendor/crates/spikard-rb/build.rs +8 -8
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -294
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -409
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -625
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -283
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
  102. metadata +1 -1
@@ -1,285 +1,285 @@
1
- //! HTTP middleware for request validation
2
- //!
3
- //! Provides middleware stack setup, JSON schema validation, multipart/form-data parsing,
4
- //! and URL-encoded form data handling.
5
-
6
- pub mod multipart;
7
- pub mod urlencoded;
8
- pub mod validation;
9
-
10
- use axum::{
11
- body::Body,
12
- extract::{FromRequest, Multipart, Request},
13
- http::StatusCode,
14
- middleware::Next,
15
- response::{IntoResponse, Response},
16
- };
17
- use serde_json::json;
18
- use std::collections::HashMap;
19
- use std::sync::Arc;
20
-
21
- /// Route information for middleware validation
22
- #[derive(Debug, Clone)]
23
- pub struct RouteInfo {
24
- /// Whether this route expects a JSON request body
25
- pub expects_json_body: bool,
26
- }
27
-
28
- /// Registry of route metadata indexed by (method, path)
29
- pub type RouteRegistry = Arc<HashMap<(String, String), RouteInfo>>;
30
-
31
- /// Middleware to validate Content-Type headers and related requirements
32
- ///
33
- /// This middleware performs comprehensive request body validation and transformation:
34
- ///
35
- /// - **Content-Type Validation:** Ensures the request's Content-Type header matches the
36
- /// expected format for the route (if configured).
37
- ///
38
- /// - **Multipart Form Data:** Automatically parses `multipart/form-data` requests and
39
- /// transforms them into JSON format for uniform downstream processing.
40
- ///
41
- /// - **URL-Encoded Forms:** Parses `application/x-www-form-urlencoded` requests and
42
- /// converts them to JSON.
43
- ///
44
- /// - **JSON Validation:** Validates JSON request bodies for well-formedness (when the
45
- /// Content-Type is `application/json`).
46
- ///
47
- /// - **Content-Length:** Validates that the Content-Length header is present and
48
- /// reasonable for POST, PUT, and PATCH requests.
49
- ///
50
- /// # Behavior
51
- ///
52
- /// For request methods POST, PUT, and PATCH:
53
- /// 1. Checks if the route expects a JSON body (via `RouteRegistry`)
54
- /// 2. Validates Content-Type headers based on route configuration
55
- /// 3. Parses the request body according to Content-Type:
56
- /// - `multipart/form-data` → JSON (form fields as object properties)
57
- /// - `application/x-www-form-urlencoded` → JSON (URL parameters as object)
58
- /// - `application/json` → Validates JSON syntax
59
- /// 4. Transforms the request to have `Content-Type: application/json`
60
- /// 5. Passes the transformed request to the next middleware
61
- ///
62
- /// For GET, DELETE, and other methods: passes through with minimal validation.
63
- ///
64
- /// # Errors
65
- ///
66
- /// Returns HTTP error responses for:
67
- /// - `400 Bad Request` - Failed to read request body, invalid JSON, malformed forms, invalid Content-Length
68
- /// - `500 Internal Server Error` - Failed to serialize transformed body
69
- ///
70
- /// # Examples
71
- ///
72
- /// ```rust
73
- /// use axum::{middleware::Next, extract::Request};
74
- /// use spikard_http::middleware::validate_content_type_middleware;
75
- ///
76
- /// // This is typically used as middleware in an Axum router:
77
- /// // router.layer(axum::middleware::from_fn(validate_content_type_middleware))
78
- /// ```
79
- pub async fn validate_content_type_middleware(request: Request, next: Next) -> Result<Response, Response> {
80
- use axum::body::to_bytes;
81
- use axum::http::Request as HttpRequest;
82
-
83
- let (parts, body) = request.into_parts();
84
- let headers = &parts.headers;
85
-
86
- let route_info = parts.extensions.get::<RouteRegistry>().and_then(|registry| {
87
- let method = parts.method.as_str();
88
- let path = parts.uri.path();
89
- registry.get(&(method.to_string(), path.to_string())).cloned()
90
- });
91
-
92
- let method = &parts.method;
93
- if method == axum::http::Method::POST || method == axum::http::Method::PUT || method == axum::http::Method::PATCH {
94
- if let Some(info) = &route_info
95
- && info.expects_json_body
96
- {
97
- validation::validate_json_content_type(headers)?;
98
- }
99
-
100
- validation::validate_content_type_headers(headers, 0)?;
101
-
102
- let (final_parts, final_body) = if let Some(content_type) = headers.get(axum::http::header::CONTENT_TYPE) {
103
- if let Ok(content_type_str) = content_type.to_str() {
104
- let parsed_mime = content_type_str.parse::<mime::Mime>().ok();
105
-
106
- let is_multipart = parsed_mime
107
- .as_ref()
108
- .map(|mime| mime.type_() == mime::MULTIPART && mime.subtype() == "form-data")
109
- .unwrap_or(false);
110
-
111
- let is_form_urlencoded = parsed_mime
112
- .as_ref()
113
- .map(|mime| mime.type_() == mime::APPLICATION && mime.subtype() == "x-www-form-urlencoded")
114
- .unwrap_or(false);
115
-
116
- if is_multipart {
117
- let mut response_headers = parts.headers.clone();
118
-
119
- let request = HttpRequest::from_parts(parts, body);
120
- let multipart = match Multipart::from_request(request, &()).await {
121
- Ok(mp) => mp,
122
- Err(e) => {
123
- let error_body = json!({
124
- "error": format!("Failed to parse multipart data: {}", e)
125
- });
126
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
127
- }
128
- };
129
-
130
- let json_body = match multipart::parse_multipart_to_json(multipart).await {
131
- Ok(json) => json,
132
- Err(e) => {
133
- let error_body = json!({
134
- "error": format!("Failed to process multipart data: {}", e)
135
- });
136
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
137
- }
138
- };
139
-
140
- let json_bytes = match serde_json::to_vec(&json_body) {
141
- Ok(bytes) => bytes,
142
- Err(e) => {
143
- let error_body = json!({
144
- "error": format!("Failed to serialize multipart data to JSON: {}", e)
145
- });
146
- return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
147
- }
148
- };
149
-
150
- response_headers.insert(
151
- axum::http::header::CONTENT_TYPE,
152
- axum::http::HeaderValue::from_static("application/json"),
153
- );
154
-
155
- let mut new_request = axum::http::Request::new(Body::from(json_bytes));
156
- *new_request.headers_mut() = response_headers;
157
-
158
- return Ok(next.run(new_request).await);
159
- } else if is_form_urlencoded {
160
- let body_bytes = match to_bytes(body, usize::MAX).await {
161
- Ok(bytes) => bytes,
162
- Err(_) => {
163
- let error_body = json!({
164
- "error": "Failed to read request body"
165
- });
166
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
167
- }
168
- };
169
-
170
- validation::validate_content_length(headers, body_bytes.len())?;
171
-
172
- let json_body = if body_bytes.is_empty() {
173
- serde_json::json!({})
174
- } else {
175
- match urlencoded::parse_urlencoded_to_json(&body_bytes) {
176
- Ok(json_body) => json_body,
177
- Err(e) => {
178
- let error_body = json!({
179
- "error": format!("Failed to parse URL-encoded form data: {}", e)
180
- });
181
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
182
- }
183
- }
184
- };
185
-
186
- let json_bytes = match serde_json::to_vec(&json_body) {
187
- Ok(bytes) => bytes,
188
- Err(e) => {
189
- let error_body = json!({
190
- "error": format!("Failed to serialize URL-encoded form data to JSON: {}", e)
191
- });
192
- return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
193
- }
194
- };
195
-
196
- let mut new_parts = parts;
197
- new_parts.headers.insert(
198
- axum::http::header::CONTENT_TYPE,
199
- axum::http::HeaderValue::from_static("application/json"),
200
- );
201
-
202
- (new_parts, Body::from(json_bytes))
203
- } else {
204
- let body_bytes = match to_bytes(body, usize::MAX).await {
205
- Ok(bytes) => bytes,
206
- Err(_) => {
207
- let error_body = json!({
208
- "error": "Failed to read request body"
209
- });
210
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
211
- }
212
- };
213
-
214
- validation::validate_content_length(headers, body_bytes.len())?;
215
-
216
- let is_json = parsed_mime
217
- .as_ref()
218
- .map(validation::is_json_content_type)
219
- .unwrap_or(false);
220
-
221
- if is_json
222
- && !body_bytes.is_empty()
223
- && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
224
- {
225
- let error_body = json!({
226
- "detail": "Invalid request format"
227
- });
228
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
229
- }
230
-
231
- (parts, Body::from(body_bytes))
232
- }
233
- } else {
234
- let body_bytes = match to_bytes(body, usize::MAX).await {
235
- Ok(bytes) => bytes,
236
- Err(_) => {
237
- let error_body = json!({
238
- "error": "Failed to read request body"
239
- });
240
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
241
- }
242
- };
243
-
244
- validation::validate_content_length(headers, body_bytes.len())?;
245
-
246
- (parts, Body::from(body_bytes))
247
- }
248
- } else {
249
- let body_bytes = match to_bytes(body, usize::MAX).await {
250
- Ok(bytes) => bytes,
251
- Err(_) => {
252
- let error_body = json!({
253
- "error": "Failed to read request body"
254
- });
255
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
256
- }
257
- };
258
-
259
- validation::validate_content_length(headers, body_bytes.len())?;
260
-
261
- (parts, Body::from(body_bytes))
262
- };
263
-
264
- let request = HttpRequest::from_parts(final_parts, final_body);
265
- Ok(next.run(request).await)
266
- } else {
267
- validation::validate_content_type_headers(headers, 0)?;
268
-
269
- let request = HttpRequest::from_parts(parts, body);
270
- Ok(next.run(request).await)
271
- }
272
- }
273
-
274
- #[cfg(test)]
275
- mod tests {
276
- use super::*;
277
-
278
- #[test]
279
- fn test_route_info_creation() {
280
- let info = RouteInfo {
281
- expects_json_body: true,
282
- };
283
- assert!(info.expects_json_body);
284
- }
285
- }
1
+ //! HTTP middleware for request validation
2
+ //!
3
+ //! Provides middleware stack setup, JSON schema validation, multipart/form-data parsing,
4
+ //! and URL-encoded form data handling.
5
+
6
+ pub mod multipart;
7
+ pub mod urlencoded;
8
+ pub mod validation;
9
+
10
+ use axum::{
11
+ body::Body,
12
+ extract::{FromRequest, Multipart, Request},
13
+ http::StatusCode,
14
+ middleware::Next,
15
+ response::{IntoResponse, Response},
16
+ };
17
+ use serde_json::json;
18
+ use std::collections::HashMap;
19
+ use std::sync::Arc;
20
+
21
+ /// Route information for middleware validation
22
+ #[derive(Debug, Clone)]
23
+ pub struct RouteInfo {
24
+ /// Whether this route expects a JSON request body
25
+ pub expects_json_body: bool,
26
+ }
27
+
28
+ /// Registry of route metadata indexed by (method, path)
29
+ pub type RouteRegistry = Arc<HashMap<(String, String), RouteInfo>>;
30
+
31
+ /// Middleware to validate Content-Type headers and related requirements
32
+ ///
33
+ /// This middleware performs comprehensive request body validation and transformation:
34
+ ///
35
+ /// - **Content-Type Validation:** Ensures the request's Content-Type header matches the
36
+ /// expected format for the route (if configured).
37
+ ///
38
+ /// - **Multipart Form Data:** Automatically parses `multipart/form-data` requests and
39
+ /// transforms them into JSON format for uniform downstream processing.
40
+ ///
41
+ /// - **URL-Encoded Forms:** Parses `application/x-www-form-urlencoded` requests and
42
+ /// converts them to JSON.
43
+ ///
44
+ /// - **JSON Validation:** Validates JSON request bodies for well-formedness (when the
45
+ /// Content-Type is `application/json`).
46
+ ///
47
+ /// - **Content-Length:** Validates that the Content-Length header is present and
48
+ /// reasonable for POST, PUT, and PATCH requests.
49
+ ///
50
+ /// # Behavior
51
+ ///
52
+ /// For request methods POST, PUT, and PATCH:
53
+ /// 1. Checks if the route expects a JSON body (via `RouteRegistry`)
54
+ /// 2. Validates Content-Type headers based on route configuration
55
+ /// 3. Parses the request body according to Content-Type:
56
+ /// - `multipart/form-data` → JSON (form fields as object properties)
57
+ /// - `application/x-www-form-urlencoded` → JSON (URL parameters as object)
58
+ /// - `application/json` → Validates JSON syntax
59
+ /// 4. Transforms the request to have `Content-Type: application/json`
60
+ /// 5. Passes the transformed request to the next middleware
61
+ ///
62
+ /// For GET, DELETE, and other methods: passes through with minimal validation.
63
+ ///
64
+ /// # Errors
65
+ ///
66
+ /// Returns HTTP error responses for:
67
+ /// - `400 Bad Request` - Failed to read request body, invalid JSON, malformed forms, invalid Content-Length
68
+ /// - `500 Internal Server Error` - Failed to serialize transformed body
69
+ ///
70
+ /// # Examples
71
+ ///
72
+ /// ```rust
73
+ /// use axum::{middleware::Next, extract::Request};
74
+ /// use spikard_http::middleware::validate_content_type_middleware;
75
+ ///
76
+ /// // This is typically used as middleware in an Axum router:
77
+ /// // router.layer(axum::middleware::from_fn(validate_content_type_middleware))
78
+ /// ```
79
+ pub async fn validate_content_type_middleware(request: Request, next: Next) -> Result<Response, Response> {
80
+ use axum::body::to_bytes;
81
+ use axum::http::Request as HttpRequest;
82
+
83
+ let (parts, body) = request.into_parts();
84
+ let headers = &parts.headers;
85
+
86
+ let route_info = parts.extensions.get::<RouteRegistry>().and_then(|registry| {
87
+ let method = parts.method.as_str();
88
+ let path = parts.uri.path();
89
+ registry.get(&(method.to_string(), path.to_string())).cloned()
90
+ });
91
+
92
+ let method = &parts.method;
93
+ if method == axum::http::Method::POST || method == axum::http::Method::PUT || method == axum::http::Method::PATCH {
94
+ if let Some(info) = &route_info
95
+ && info.expects_json_body
96
+ {
97
+ validation::validate_json_content_type(headers)?;
98
+ }
99
+
100
+ validation::validate_content_type_headers(headers, 0)?;
101
+
102
+ let (final_parts, final_body) = if let Some(content_type) = headers.get(axum::http::header::CONTENT_TYPE) {
103
+ if let Ok(content_type_str) = content_type.to_str() {
104
+ let parsed_mime = content_type_str.parse::<mime::Mime>().ok();
105
+
106
+ let is_multipart = parsed_mime
107
+ .as_ref()
108
+ .map(|mime| mime.type_() == mime::MULTIPART && mime.subtype() == "form-data")
109
+ .unwrap_or(false);
110
+
111
+ let is_form_urlencoded = parsed_mime
112
+ .as_ref()
113
+ .map(|mime| mime.type_() == mime::APPLICATION && mime.subtype() == "x-www-form-urlencoded")
114
+ .unwrap_or(false);
115
+
116
+ if is_multipart {
117
+ let mut response_headers = parts.headers.clone();
118
+
119
+ let request = HttpRequest::from_parts(parts, body);
120
+ let multipart = match Multipart::from_request(request, &()).await {
121
+ Ok(mp) => mp,
122
+ Err(e) => {
123
+ let error_body = json!({
124
+ "error": format!("Failed to parse multipart data: {}", e)
125
+ });
126
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
127
+ }
128
+ };
129
+
130
+ let json_body = match multipart::parse_multipart_to_json(multipart).await {
131
+ Ok(json) => json,
132
+ Err(e) => {
133
+ let error_body = json!({
134
+ "error": format!("Failed to process multipart data: {}", e)
135
+ });
136
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
137
+ }
138
+ };
139
+
140
+ let json_bytes = match serde_json::to_vec(&json_body) {
141
+ Ok(bytes) => bytes,
142
+ Err(e) => {
143
+ let error_body = json!({
144
+ "error": format!("Failed to serialize multipart data to JSON: {}", e)
145
+ });
146
+ return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
147
+ }
148
+ };
149
+
150
+ response_headers.insert(
151
+ axum::http::header::CONTENT_TYPE,
152
+ axum::http::HeaderValue::from_static("application/json"),
153
+ );
154
+
155
+ let mut new_request = axum::http::Request::new(Body::from(json_bytes));
156
+ *new_request.headers_mut() = response_headers;
157
+
158
+ return Ok(next.run(new_request).await);
159
+ } else if is_form_urlencoded {
160
+ let body_bytes = match to_bytes(body, usize::MAX).await {
161
+ Ok(bytes) => bytes,
162
+ Err(_) => {
163
+ let error_body = json!({
164
+ "error": "Failed to read request body"
165
+ });
166
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
167
+ }
168
+ };
169
+
170
+ validation::validate_content_length(headers, body_bytes.len())?;
171
+
172
+ let json_body = if body_bytes.is_empty() {
173
+ serde_json::json!({})
174
+ } else {
175
+ match urlencoded::parse_urlencoded_to_json(&body_bytes) {
176
+ Ok(json_body) => json_body,
177
+ Err(e) => {
178
+ let error_body = json!({
179
+ "error": format!("Failed to parse URL-encoded form data: {}", e)
180
+ });
181
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
182
+ }
183
+ }
184
+ };
185
+
186
+ let json_bytes = match serde_json::to_vec(&json_body) {
187
+ Ok(bytes) => bytes,
188
+ Err(e) => {
189
+ let error_body = json!({
190
+ "error": format!("Failed to serialize URL-encoded form data to JSON: {}", e)
191
+ });
192
+ return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
193
+ }
194
+ };
195
+
196
+ let mut new_parts = parts;
197
+ new_parts.headers.insert(
198
+ axum::http::header::CONTENT_TYPE,
199
+ axum::http::HeaderValue::from_static("application/json"),
200
+ );
201
+
202
+ (new_parts, Body::from(json_bytes))
203
+ } else {
204
+ let body_bytes = match to_bytes(body, usize::MAX).await {
205
+ Ok(bytes) => bytes,
206
+ Err(_) => {
207
+ let error_body = json!({
208
+ "error": "Failed to read request body"
209
+ });
210
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
211
+ }
212
+ };
213
+
214
+ validation::validate_content_length(headers, body_bytes.len())?;
215
+
216
+ let is_json = parsed_mime
217
+ .as_ref()
218
+ .map(validation::is_json_content_type)
219
+ .unwrap_or(false);
220
+
221
+ if is_json
222
+ && !body_bytes.is_empty()
223
+ && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
224
+ {
225
+ let error_body = json!({
226
+ "detail": "Invalid request format"
227
+ });
228
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
229
+ }
230
+
231
+ (parts, Body::from(body_bytes))
232
+ }
233
+ } else {
234
+ let body_bytes = match to_bytes(body, usize::MAX).await {
235
+ Ok(bytes) => bytes,
236
+ Err(_) => {
237
+ let error_body = json!({
238
+ "error": "Failed to read request body"
239
+ });
240
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
241
+ }
242
+ };
243
+
244
+ validation::validate_content_length(headers, body_bytes.len())?;
245
+
246
+ (parts, Body::from(body_bytes))
247
+ }
248
+ } else {
249
+ let body_bytes = match to_bytes(body, usize::MAX).await {
250
+ Ok(bytes) => bytes,
251
+ Err(_) => {
252
+ let error_body = json!({
253
+ "error": "Failed to read request body"
254
+ });
255
+ return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
256
+ }
257
+ };
258
+
259
+ validation::validate_content_length(headers, body_bytes.len())?;
260
+
261
+ (parts, Body::from(body_bytes))
262
+ };
263
+
264
+ let request = HttpRequest::from_parts(final_parts, final_body);
265
+ Ok(next.run(request).await)
266
+ } else {
267
+ validation::validate_content_type_headers(headers, 0)?;
268
+
269
+ let request = HttpRequest::from_parts(parts, body);
270
+ Ok(next.run(request).await)
271
+ }
272
+ }
273
+
274
+ #[cfg(test)]
275
+ mod tests {
276
+ use super::*;
277
+
278
+ #[test]
279
+ fn test_route_info_creation() {
280
+ let info = RouteInfo {
281
+ expects_json_body: true,
282
+ };
283
+ assert!(info.expects_json_body);
284
+ }
285
+ }