spikard 0.3.5 → 0.5.0

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 (142) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -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 +405 -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 +256 -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-bindings-shared/Cargo.toml +63 -0
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  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 -63
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -726
  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 -538
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -545
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -411
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -283
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -39
  52. data/vendor/crates/spikard-core/src/http.rs +415 -153
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -422
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -722
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -310
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -189
  59. data/vendor/crates/spikard-core/src/router.rs +510 -249
  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 +688 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +64 -68
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -247
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -249
  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 -490
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -63
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -423
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -190
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +830 -228
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -284
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -529
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -149
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -428
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +540 -285
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -86
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -147
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +735 -287
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -190
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -308
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -195
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -369
  90. data/vendor/crates/spikard-http/src/response.rs +720 -399
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -87
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -98
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1502 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +770 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -447
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -14
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +283 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1375 -324
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -42
  113. data/vendor/crates/spikard-rb/build.rs +199 -8
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  116. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +285 -294
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -453
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  119. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +375 -409
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -625
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  122. data/vendor/crates/spikard-rb/src/lib.rs +1810 -2771
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -274
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  128. data/vendor/crates/spikard-rb/src/server.rs +308 -283
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +551 -404
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  132. data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +374 -233
  135. metadata +46 -13
  136. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  137. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  138. data/vendor/crates/spikard-http/src/router.rs +0 -1
  139. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  140. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  141. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  142. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
@@ -1,805 +1,1502 @@
1
- //! HTTP server implementation using Tokio and Axum
2
- //!
3
- //! This module provides the main server builder and routing infrastructure, with
4
- //! focused submodules for handler validation, request extraction, and lifecycle execution.
5
-
6
- pub mod handler;
7
- pub mod lifecycle_execution;
8
- pub mod request_extraction;
9
-
10
- use crate::handler_trait::Handler;
11
- use crate::{CorsConfig, Router, ServerConfig};
12
- use axum::Router as AxumRouter;
13
- use axum::body::Body;
14
- use axum::extract::{DefaultBodyLimit, Path};
15
- use axum::http::StatusCode;
16
- use axum::routing::{MethodRouter, get};
17
- use std::collections::HashMap;
18
- use std::net::SocketAddr;
19
- use std::sync::Arc;
20
- use std::time::Duration;
21
- use tokio::net::TcpListener;
22
- use tower_governor::governor::GovernorConfigBuilder;
23
- use tower_governor::key_extractor::GlobalKeyExtractor;
24
- use tower_http::compression::CompressionLayer;
25
- use tower_http::compression::predicate::{NotForContentType, Predicate, SizeAbove};
26
- use tower_http::request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer};
27
- use tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer;
28
- use tower_http::services::ServeDir;
29
- use tower_http::set_header::SetResponseHeaderLayer;
30
- use tower_http::timeout::TimeoutLayer;
31
- use tower_http::trace::TraceLayer;
32
- use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
33
- use uuid::Uuid;
34
-
35
- /// Type alias for route handler pairs
36
- type RouteHandlerPair = (crate::Route, Arc<dyn Handler>);
37
-
38
- /// Extract required dependencies from route metadata
39
- ///
40
- /// Placeholder implementation until routes can declare dependencies via metadata.
41
- #[cfg(feature = "di")]
42
- fn extract_handler_dependencies(route: &crate::Route) -> Vec<String> {
43
- route.handler_dependencies.clone()
44
- }
45
-
46
- /// Determines if a method typically has a request body
47
- fn method_expects_body(method: &str) -> bool {
48
- matches!(method, "POST" | "PUT" | "PATCH")
49
- }
50
-
51
- /// Creates a method router for the given HTTP method
52
- /// Handles both path parameters and non-path variants
53
- fn create_method_router(
54
- method: &str,
55
- has_path_params: bool,
56
- handler: Arc<dyn Handler>,
57
- hooks: Option<Arc<crate::LifecycleHooks>>,
58
- ) -> axum::routing::MethodRouter {
59
- let expects_body = method_expects_body(method);
60
-
61
- if expects_body {
62
- // POST, PUT, PATCH - need to handle body
63
- if has_path_params {
64
- let handler_clone = handler.clone();
65
- let hooks_clone = hooks.clone();
66
- match method {
67
- "POST" => axum::routing::post(
68
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
69
- let (parts, body) = req.into_parts();
70
- let request_data =
71
- request_extraction::create_request_data_with_body(&parts, path_params.0, body).await?;
72
- let req = axum::extract::Request::from_parts(parts, Body::empty());
73
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
74
- .await
75
- },
76
- ),
77
- "PUT" => axum::routing::put(
78
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
79
- let (parts, body) = req.into_parts();
80
- let request_data =
81
- request_extraction::create_request_data_with_body(&parts, path_params.0, body).await?;
82
- let req = axum::extract::Request::from_parts(parts, Body::empty());
83
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
84
- .await
85
- },
86
- ),
87
- "PATCH" => axum::routing::patch(
88
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
89
- let (parts, body) = req.into_parts();
90
- let request_data =
91
- request_extraction::create_request_data_with_body(&parts, path_params.0, body).await?;
92
- let req = axum::extract::Request::from_parts(parts, Body::empty());
93
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
94
- .await
95
- },
96
- ),
97
- _ => {
98
- eprintln!(
99
- "[spikard-router] unsupported HTTP method with path params: {} (defaulting to 405)",
100
- method
101
- );
102
- MethodRouter::new()
103
- }
104
- }
105
- } else {
106
- let handler_clone = handler.clone();
107
- let hooks_clone = hooks.clone();
108
- match method {
109
- "POST" => axum::routing::post(move |req: axum::extract::Request| async move {
110
- let (parts, body) = req.into_parts();
111
- let request_data =
112
- request_extraction::create_request_data_with_body(&parts, HashMap::new(), body).await?;
113
- let req = axum::extract::Request::from_parts(parts, Body::empty());
114
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
115
- .await
116
- }),
117
- "PUT" => axum::routing::put(move |req: axum::extract::Request| async move {
118
- let (parts, body) = req.into_parts();
119
- let request_data =
120
- request_extraction::create_request_data_with_body(&parts, HashMap::new(), body).await?;
121
- let req = axum::extract::Request::from_parts(parts, Body::empty());
122
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
123
- .await
124
- }),
125
- "PATCH" => axum::routing::patch(move |req: axum::extract::Request| async move {
126
- let (parts, body) = req.into_parts();
127
- let request_data =
128
- request_extraction::create_request_data_with_body(&parts, HashMap::new(), body).await?;
129
- let req = axum::extract::Request::from_parts(parts, Body::empty());
130
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
131
- .await
132
- }),
133
- _ => {
134
- eprintln!(
135
- "[spikard-router] unsupported HTTP method without path params: {} (defaulting to 405)",
136
- method
137
- );
138
- MethodRouter::new()
139
- }
140
- }
141
- }
142
- } else {
143
- // GET, DELETE, HEAD, TRACE - no body handling
144
- if has_path_params {
145
- let handler_clone = handler.clone();
146
- let hooks_clone = hooks.clone();
147
- match method {
148
- "GET" => axum::routing::get(
149
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
150
- let request_data = request_extraction::create_request_data_without_body(
151
- req.uri(),
152
- req.method(),
153
- req.headers(),
154
- path_params.0,
155
- );
156
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
157
- .await
158
- },
159
- ),
160
- "DELETE" => axum::routing::delete(
161
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
162
- let request_data = request_extraction::create_request_data_without_body(
163
- req.uri(),
164
- req.method(),
165
- req.headers(),
166
- path_params.0,
167
- );
168
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
169
- .await
170
- },
171
- ),
172
- "HEAD" => axum::routing::head(
173
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
174
- let request_data = request_extraction::create_request_data_without_body(
175
- req.uri(),
176
- req.method(),
177
- req.headers(),
178
- path_params.0,
179
- );
180
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
181
- .await
182
- },
183
- ),
184
- "TRACE" => axum::routing::trace(
185
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
186
- let request_data = request_extraction::create_request_data_without_body(
187
- req.uri(),
188
- req.method(),
189
- req.headers(),
190
- path_params.0,
191
- );
192
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
193
- .await
194
- },
195
- ),
196
- "OPTIONS" => axum::routing::options(
197
- move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
198
- let request_data = request_extraction::create_request_data_without_body(
199
- req.uri(),
200
- req.method(),
201
- req.headers(),
202
- path_params.0,
203
- );
204
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
205
- .await
206
- },
207
- ),
208
- _ => {
209
- eprintln!(
210
- "[spikard-router] unsupported HTTP method with path params: {} (defaulting to 405)",
211
- method
212
- );
213
- MethodRouter::new()
214
- }
215
- }
216
- } else {
217
- let handler_clone = handler.clone();
218
- let hooks_clone = hooks.clone();
219
- match method {
220
- "GET" => axum::routing::get(move |req: axum::extract::Request| async move {
221
- let request_data = request_extraction::create_request_data_without_body(
222
- req.uri(),
223
- req.method(),
224
- req.headers(),
225
- HashMap::new(),
226
- );
227
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
228
- .await
229
- }),
230
- "DELETE" => axum::routing::delete(move |req: axum::extract::Request| async move {
231
- let request_data = request_extraction::create_request_data_without_body(
232
- req.uri(),
233
- req.method(),
234
- req.headers(),
235
- HashMap::new(),
236
- );
237
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
238
- .await
239
- }),
240
- "HEAD" => axum::routing::head(move |req: axum::extract::Request| async move {
241
- let request_data = request_extraction::create_request_data_without_body(
242
- req.uri(),
243
- req.method(),
244
- req.headers(),
245
- HashMap::new(),
246
- );
247
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
248
- .await
249
- }),
250
- "TRACE" => axum::routing::trace(move |req: axum::extract::Request| async move {
251
- let request_data = request_extraction::create_request_data_without_body(
252
- req.uri(),
253
- req.method(),
254
- req.headers(),
255
- HashMap::new(),
256
- );
257
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
258
- .await
259
- }),
260
- "OPTIONS" => axum::routing::options(move |req: axum::extract::Request| async move {
261
- let request_data = request_extraction::create_request_data_without_body(
262
- req.uri(),
263
- req.method(),
264
- req.headers(),
265
- HashMap::new(),
266
- );
267
- lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
268
- .await
269
- }),
270
- _ => {
271
- eprintln!(
272
- "[spikard-router] unsupported HTTP method without path params: {} (defaulting to 405)",
273
- method
274
- );
275
- MethodRouter::new()
276
- }
277
- }
278
- }
279
- }
280
- }
281
-
282
- /// Request ID generator using UUIDs
283
- #[derive(Clone, Default)]
284
- struct MakeRequestUuid;
285
-
286
- impl MakeRequestId for MakeRequestUuid {
287
- fn make_request_id<B>(&mut self, _request: &axum::http::Request<B>) -> Option<RequestId> {
288
- let id = Uuid::new_v4().to_string().parse().ok()?;
289
- Some(RequestId::new(id))
290
- }
291
- }
292
-
293
- /// Graceful shutdown signal handler
294
- async fn shutdown_signal() {
295
- let ctrl_c = async {
296
- tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler");
297
- };
298
-
299
- #[cfg(unix)]
300
- let terminate = async {
301
- tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
302
- .expect("failed to install signal handler")
303
- .recv()
304
- .await;
305
- };
306
-
307
- #[cfg(not(unix))]
308
- let terminate = std::future::pending::<()>();
309
-
310
- tokio::select! {
311
- _ = ctrl_c => {
312
- tracing::info!("Received SIGINT (Ctrl+C), starting graceful shutdown");
313
- },
314
- _ = terminate => {
315
- tracing::info!("Received SIGTERM, starting graceful shutdown");
316
- },
317
- }
318
- }
319
-
320
- /// Build an Axum router from routes and foreign handlers
321
- #[cfg(not(feature = "di"))]
322
- pub fn build_router_with_handlers(
323
- routes: Vec<(crate::Route, Arc<dyn Handler>)>,
324
- hooks: Option<Arc<crate::LifecycleHooks>>,
325
- ) -> Result<AxumRouter, String> {
326
- build_router_with_handlers_inner(routes, hooks, None)
327
- }
328
-
329
- /// Build an Axum router from routes and foreign handlers with optional DI container
330
- #[cfg(feature = "di")]
331
- pub fn build_router_with_handlers(
332
- routes: Vec<(crate::Route, Arc<dyn Handler>)>,
333
- hooks: Option<Arc<crate::LifecycleHooks>>,
334
- di_container: Option<Arc<spikard_core::di::DependencyContainer>>,
335
- ) -> Result<AxumRouter, String> {
336
- build_router_with_handlers_inner(routes, hooks, di_container)
337
- }
338
-
339
- fn build_router_with_handlers_inner(
340
- routes: Vec<(crate::Route, Arc<dyn Handler>)>,
341
- hooks: Option<Arc<crate::LifecycleHooks>>,
342
- #[cfg(feature = "di")] di_container: Option<Arc<spikard_core::di::DependencyContainer>>,
343
- #[cfg(not(feature = "di"))] _di_container: Option<()>,
344
- ) -> Result<AxumRouter, String> {
345
- let mut app = AxumRouter::new();
346
-
347
- let mut registry = HashMap::new();
348
- for (route, _) in &routes {
349
- let axum_path = crate::type_hints::strip_type_hints(&route.path);
350
- let axum_path = if axum_path.starts_with('/') {
351
- axum_path
352
- } else {
353
- format!("/{}", axum_path)
354
- };
355
- registry.insert(
356
- (route.method.as_str().to_string(), axum_path),
357
- crate::middleware::RouteInfo {
358
- expects_json_body: route.expects_json_body,
359
- },
360
- );
361
- }
362
- let route_registry: crate::middleware::RouteRegistry = Arc::new(registry);
363
-
364
- let mut routes_by_path: HashMap<String, Vec<RouteHandlerPair>> = HashMap::new();
365
- for (route, handler) in routes {
366
- routes_by_path
367
- .entry(route.path.clone())
368
- .or_default()
369
- .push((route, handler));
370
- }
371
-
372
- let mut sorted_paths: Vec<String> = routes_by_path.keys().cloned().collect();
373
- sorted_paths.sort();
374
-
375
- for path in sorted_paths {
376
- let route_handlers = routes_by_path
377
- .remove(&path)
378
- .ok_or_else(|| format!("Missing handlers for path '{}'", path))?;
379
-
380
- let mut handlers_by_method: HashMap<crate::Method, (crate::Route, Arc<dyn Handler>)> = HashMap::new();
381
- for (route, handler) in route_handlers {
382
- #[cfg(feature = "di")]
383
- let handler = if let Some(ref container) = di_container {
384
- let mut required_deps = extract_handler_dependencies(&route);
385
- if required_deps.is_empty() {
386
- required_deps = container.keys();
387
- }
388
-
389
- if !required_deps.is_empty() {
390
- Arc::new(crate::di_handler::DependencyInjectingHandler::new(
391
- handler,
392
- Arc::clone(container),
393
- required_deps,
394
- )) as Arc<dyn Handler>
395
- } else {
396
- handler
397
- }
398
- } else {
399
- handler
400
- };
401
-
402
- let validating_handler = Arc::new(handler::ValidatingHandler::new(handler, &route));
403
- handlers_by_method.insert(route.method.clone(), (route, validating_handler));
404
- }
405
-
406
- let cors_config: Option<CorsConfig> = handlers_by_method
407
- .values()
408
- .find_map(|(route, _)| route.cors.as_ref())
409
- .cloned();
410
-
411
- let has_options_handler = handlers_by_method.keys().any(|m| m.as_str() == "OPTIONS");
412
-
413
- let mut combined_router: Option<MethodRouter> = None;
414
- let has_path_params = path.contains('{');
415
-
416
- for (_method, (route, handler)) in handlers_by_method {
417
- let method_router: MethodRouter = match route.method.as_str() {
418
- "OPTIONS" => {
419
- if let Some(ref cors_cfg) = route.cors {
420
- let cors_config = cors_cfg.clone();
421
- axum::routing::options(move |req: axum::extract::Request| async move {
422
- crate::cors::handle_preflight(req.headers(), &cors_config).map_err(|e| *e)
423
- })
424
- } else {
425
- create_method_router(route.method.as_str(), has_path_params, handler, hooks.clone())
426
- }
427
- }
428
- method => create_method_router(method, has_path_params, handler, hooks.clone()),
429
- };
430
-
431
- combined_router = Some(match combined_router {
432
- None => method_router,
433
- Some(existing) => existing.merge(method_router),
434
- });
435
-
436
- tracing::info!("Registered route: {} {}", route.method.as_str(), path);
437
- }
438
-
439
- if let Some(ref cors_cfg) = cors_config
440
- && !has_options_handler
441
- {
442
- let cors_config_clone: CorsConfig = cors_cfg.clone();
443
- let options_router = axum::routing::options(move |req: axum::extract::Request| async move {
444
- crate::cors::handle_preflight(req.headers(), &cors_config_clone).map_err(|e| *e)
445
- });
446
-
447
- combined_router = Some(match combined_router {
448
- None => options_router,
449
- Some(existing) => existing.merge(options_router),
450
- });
451
-
452
- tracing::info!("Auto-generated OPTIONS handler for CORS preflight: {}", path);
453
- }
454
-
455
- if let Some(router) = combined_router {
456
- let mut axum_path = crate::type_hints::strip_type_hints(&path);
457
- if !axum_path.starts_with('/') {
458
- axum_path = format!("/{}", axum_path);
459
- }
460
- app = app.route(&axum_path, router);
461
- }
462
- }
463
-
464
- app = app.layer(axum::middleware::from_fn(
465
- crate::middleware::validate_content_type_middleware,
466
- ));
467
- app = app.layer(TraceLayer::new_for_http());
468
-
469
- app = app.layer(axum::Extension(route_registry));
470
-
471
- Ok(app)
472
- }
473
-
474
- /// Build router with handlers and apply middleware based on config
475
- pub fn build_router_with_handlers_and_config(
476
- routes: Vec<RouteHandlerPair>,
477
- config: ServerConfig,
478
- route_metadata: Vec<crate::RouteMetadata>,
479
- ) -> Result<AxumRouter, String> {
480
- #[cfg(feature = "di")]
481
- if config.di_container.is_none() {
482
- eprintln!("[spikard-di] build_router: di_container is None");
483
- } else {
484
- eprintln!(
485
- "[spikard-di] build_router: di_container has keys: {:?}",
486
- config.di_container.as_ref().unwrap().keys()
487
- );
488
- }
489
- let hooks = config.lifecycle_hooks.clone();
490
-
491
- #[cfg(feature = "di")]
492
- let mut app = build_router_with_handlers(routes, hooks, config.di_container.clone())?;
493
- #[cfg(not(feature = "di"))]
494
- let mut app = build_router_with_handlers(routes, hooks)?;
495
-
496
- app = app.layer(SetSensitiveRequestHeadersLayer::new([
497
- axum::http::header::AUTHORIZATION,
498
- axum::http::header::COOKIE,
499
- ]));
500
-
501
- if let Some(ref compression) = config.compression {
502
- let mut compression_layer = CompressionLayer::new();
503
- if !compression.gzip {
504
- compression_layer = compression_layer.gzip(false);
505
- }
506
- if !compression.brotli {
507
- compression_layer = compression_layer.br(false);
508
- }
509
-
510
- let min_threshold = compression.min_size.min(u16::MAX as usize) as u16;
511
- let predicate = SizeAbove::new(min_threshold)
512
- .and(NotForContentType::GRPC)
513
- .and(NotForContentType::IMAGES)
514
- .and(NotForContentType::SSE);
515
- let compression_layer = compression_layer.compress_when(predicate);
516
-
517
- app = app.layer(compression_layer);
518
- }
519
-
520
- if let Some(ref rate_limit) = config.rate_limit {
521
- if rate_limit.ip_based {
522
- let governor_conf = Arc::new(
523
- GovernorConfigBuilder::default()
524
- .per_second(rate_limit.per_second)
525
- .burst_size(rate_limit.burst)
526
- .finish()
527
- .ok_or_else(|| "Failed to create rate limiter".to_string())?,
528
- );
529
- app = app.layer(tower_governor::GovernorLayer::new(governor_conf));
530
- } else {
531
- let governor_conf = Arc::new(
532
- GovernorConfigBuilder::default()
533
- .per_second(rate_limit.per_second)
534
- .burst_size(rate_limit.burst)
535
- .key_extractor(GlobalKeyExtractor)
536
- .finish()
537
- .ok_or_else(|| "Failed to create rate limiter".to_string())?,
538
- );
539
- app = app.layer(tower_governor::GovernorLayer::new(governor_conf));
540
- }
541
- }
542
-
543
- if let Some(ref jwt_config) = config.jwt_auth {
544
- let jwt_config_clone = jwt_config.clone();
545
- app = app.layer(axum::middleware::from_fn(move |headers, req, next| {
546
- crate::auth::jwt_auth_middleware(jwt_config_clone.clone(), headers, req, next)
547
- }));
548
- }
549
-
550
- if let Some(ref api_key_config) = config.api_key_auth {
551
- let api_key_config_clone = api_key_config.clone();
552
- app = app.layer(axum::middleware::from_fn(move |headers, req, next| {
553
- crate::auth::api_key_auth_middleware(api_key_config_clone.clone(), headers, req, next)
554
- }));
555
- }
556
-
557
- if let Some(timeout_secs) = config.request_timeout {
558
- app = app.layer(TimeoutLayer::with_status_code(
559
- StatusCode::REQUEST_TIMEOUT,
560
- Duration::from_secs(timeout_secs),
561
- ));
562
- }
563
-
564
- if config.enable_request_id {
565
- app = app
566
- .layer(PropagateRequestIdLayer::x_request_id())
567
- .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid));
568
- }
569
-
570
- if let Some(max_size) = config.max_body_size {
571
- app = app.layer(DefaultBodyLimit::max(max_size));
572
- } else {
573
- app = app.layer(DefaultBodyLimit::disable());
574
- }
575
-
576
- for static_config in &config.static_files {
577
- let mut serve_dir = ServeDir::new(&static_config.directory);
578
- if static_config.index_file {
579
- serve_dir = serve_dir.append_index_html_on_directories(true);
580
- }
581
-
582
- let mut static_router = AxumRouter::new().fallback_service(serve_dir);
583
- if let Some(ref cache_control) = static_config.cache_control {
584
- let header_value = axum::http::HeaderValue::from_str(cache_control)
585
- .map_err(|e| format!("Invalid cache-control header: {}", e))?;
586
- static_router = static_router.layer(SetResponseHeaderLayer::overriding(
587
- axum::http::header::CACHE_CONTROL,
588
- header_value,
589
- ));
590
- }
591
-
592
- app = app.nest_service(&static_config.route_prefix, static_router);
593
-
594
- tracing::info!(
595
- "Serving static files from '{}' at '{}'",
596
- static_config.directory,
597
- static_config.route_prefix
598
- );
599
- }
600
-
601
- if let Some(ref openapi_config) = config.openapi
602
- && openapi_config.enabled
603
- {
604
- use axum::response::{Html, Json};
605
-
606
- let schema_registry = crate::SchemaRegistry::new();
607
- let openapi_spec =
608
- crate::openapi::generate_openapi_spec(&route_metadata, openapi_config, &schema_registry, Some(&config))
609
- .map_err(|e| format!("Failed to generate OpenAPI spec: {}", e))?;
610
-
611
- let spec_json =
612
- serde_json::to_string(&openapi_spec).map_err(|e| format!("Failed to serialize OpenAPI spec: {}", e))?;
613
- let spec_value = serde_json::from_str::<serde_json::Value>(&spec_json)
614
- .map_err(|e| format!("Failed to parse OpenAPI spec: {}", e))?;
615
-
616
- let openapi_json_path = openapi_config.openapi_json_path.clone();
617
- app = app.route(&openapi_json_path, get(move || async move { Json(spec_value) }));
618
-
619
- let swagger_html = format!(
620
- r#"<!DOCTYPE html>
621
- <html>
622
- <head>
623
- <title>Swagger UI</title>
624
- <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css">
625
- </head>
626
- <body>
627
- <div id="swagger-ui"></div>
628
- <script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
629
- <script>
630
- SwaggerUIBundle({{
631
- url: '{}',
632
- dom_id: '#swagger-ui',
633
- }});
634
- </script>
635
- </body>
636
- </html>"#,
637
- openapi_json_path
638
- );
639
- let swagger_ui_path = openapi_config.swagger_ui_path.clone();
640
- app = app.route(&swagger_ui_path, get(move || async move { Html(swagger_html) }));
641
-
642
- let redoc_html = format!(
643
- r#"<!DOCTYPE html>
644
- <html>
645
- <head>
646
- <title>Redoc</title>
647
- </head>
648
- <body>
649
- <redoc spec-url='{}'></redoc>
650
- <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
651
- </body>
652
- </html>"#,
653
- openapi_json_path
654
- );
655
- let redoc_path = openapi_config.redoc_path.clone();
656
- app = app.route(&redoc_path, get(move || async move { Html(redoc_html) }));
657
-
658
- tracing::info!("OpenAPI documentation enabled at {}", openapi_json_path);
659
- }
660
-
661
- Ok(app)
662
- }
663
-
664
- /// HTTP Server
665
- pub struct Server {
666
- config: ServerConfig,
667
- router: Router,
668
- }
669
-
670
- impl Server {
671
- /// Create a new server with configuration
672
- pub fn new(config: ServerConfig, router: Router) -> Self {
673
- Self { config, router }
674
- }
675
-
676
- /// Create a new server with Python handlers
677
- ///
678
- /// Build router with trait-based handlers
679
- /// Routes are grouped by path before registration to support multiple HTTP methods
680
- /// for the same path (e.g., GET /data and POST /data). Axum requires that all methods
681
- /// for a path be merged into a single MethodRouter before calling `.route()`.
682
- pub fn with_handlers(
683
- config: ServerConfig,
684
- routes: Vec<(crate::Route, Arc<dyn Handler>)>,
685
- ) -> Result<AxumRouter, String> {
686
- let metadata: Vec<crate::RouteMetadata> = routes
687
- .iter()
688
- .map(|(route, _)| {
689
- #[cfg(feature = "di")]
690
- {
691
- crate::RouteMetadata {
692
- method: route.method.to_string(),
693
- path: route.path.clone(),
694
- handler_name: route.handler_name.clone(),
695
- request_schema: None,
696
- response_schema: None,
697
- parameter_schema: None,
698
- file_params: route.file_params.clone(),
699
- is_async: route.is_async,
700
- cors: route.cors.clone(),
701
- body_param_name: None,
702
- handler_dependencies: Some(route.handler_dependencies.clone()),
703
- }
704
- }
705
- #[cfg(not(feature = "di"))]
706
- {
707
- crate::RouteMetadata {
708
- method: route.method.to_string(),
709
- path: route.path.clone(),
710
- handler_name: route.handler_name.clone(),
711
- request_schema: None,
712
- response_schema: None,
713
- parameter_schema: None,
714
- file_params: route.file_params.clone(),
715
- is_async: route.is_async,
716
- cors: route.cors.clone(),
717
- body_param_name: None,
718
- }
719
- }
720
- })
721
- .collect();
722
- build_router_with_handlers_and_config(routes, config, metadata)
723
- }
724
-
725
- /// Create a new server with Python handlers and metadata for OpenAPI
726
- pub fn with_handlers_and_metadata(
727
- config: ServerConfig,
728
- routes: Vec<(crate::Route, Arc<dyn Handler>)>,
729
- metadata: Vec<crate::RouteMetadata>,
730
- ) -> Result<AxumRouter, String> {
731
- build_router_with_handlers_and_config(routes, config, metadata)
732
- }
733
-
734
- /// Run the server with the Axum router and config
735
- pub async fn run_with_config(app: AxumRouter, config: ServerConfig) -> Result<(), Box<dyn std::error::Error>> {
736
- let addr = format!("{}:{}", config.host, config.port);
737
- let socket_addr: SocketAddr = addr.parse()?;
738
- let listener = TcpListener::bind(socket_addr).await?;
739
-
740
- tracing::info!("Listening on http://{}", socket_addr);
741
-
742
- if config.graceful_shutdown {
743
- axum::serve(listener, app)
744
- .with_graceful_shutdown(shutdown_signal())
745
- .await?;
746
- } else {
747
- axum::serve(listener, app).await?;
748
- }
749
-
750
- Ok(())
751
- }
752
-
753
- /// Initialize logging
754
- pub fn init_logging() {
755
- tracing_subscriber::registry()
756
- .with(
757
- tracing_subscriber::EnvFilter::try_from_default_env()
758
- .unwrap_or_else(|_| "spikard=debug,tower_http=debug".into()),
759
- )
760
- .with(tracing_subscriber::fmt::layer())
761
- .init();
762
- }
763
-
764
- /// Start the server
765
- pub async fn serve(self) -> Result<(), Box<dyn std::error::Error>> {
766
- tracing::info!("Starting server with {} routes", self.router.route_count());
767
-
768
- let app = self.build_axum_router();
769
-
770
- let addr = format!("{}:{}", self.config.host, self.config.port);
771
- let socket_addr: SocketAddr = addr.parse()?;
772
- let listener = TcpListener::bind(socket_addr).await?;
773
-
774
- tracing::info!("Listening on http://{}", socket_addr);
775
-
776
- axum::serve(listener, app).await?;
777
-
778
- Ok(())
779
- }
780
-
781
- /// Build Axum router from our router
782
- fn build_axum_router(&self) -> AxumRouter {
783
- let mut app = AxumRouter::new();
784
-
785
- app = app.route("/health", get(|| async { "OK" }));
786
-
787
- // TODO: Add routes from self.router
788
-
789
- app = app.layer(TraceLayer::new_for_http());
790
-
791
- app
792
- }
793
- }
794
-
795
- #[cfg(test)]
796
- mod tests {
797
- use super::*;
798
-
799
- #[test]
800
- fn test_server_creation() {
801
- let config = ServerConfig::default();
802
- let router = Router::new();
803
- let _server = Server::new(config, router);
804
- }
805
- }
1
+ //! HTTP server implementation using Tokio and Axum
2
+ //!
3
+ //! This module provides the main server builder and routing infrastructure, with
4
+ //! focused submodules for handler validation, request extraction, and lifecycle execution.
5
+
6
+ pub mod handler;
7
+ pub mod lifecycle_execution;
8
+ pub mod request_extraction;
9
+
10
+ use crate::handler_trait::Handler;
11
+ use crate::{CorsConfig, Router, ServerConfig};
12
+ use axum::Router as AxumRouter;
13
+ use axum::body::Body;
14
+ use axum::extract::{DefaultBodyLimit, Path};
15
+ use axum::http::StatusCode;
16
+ use axum::routing::{MethodRouter, get, post};
17
+ use spikard_core::type_hints;
18
+ use std::collections::HashMap;
19
+ use std::net::SocketAddr;
20
+ use std::sync::Arc;
21
+ use std::time::Duration;
22
+ use tokio::net::TcpListener;
23
+ use tower_governor::governor::GovernorConfigBuilder;
24
+ use tower_governor::key_extractor::GlobalKeyExtractor;
25
+ use tower_http::compression::CompressionLayer;
26
+ use tower_http::compression::predicate::{NotForContentType, Predicate, SizeAbove};
27
+ use tower_http::request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer};
28
+ use tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer;
29
+ use tower_http::services::ServeDir;
30
+ use tower_http::set_header::SetResponseHeaderLayer;
31
+ use tower_http::timeout::TimeoutLayer;
32
+ use tower_http::trace::TraceLayer;
33
+ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
34
+ use uuid::Uuid;
35
+
36
+ /// Type alias for route handler pairs
37
+ type RouteHandlerPair = (crate::Route, Arc<dyn Handler>);
38
+
39
+ /// Extract required dependencies from route metadata
40
+ ///
41
+ /// Placeholder implementation until routes can declare dependencies via metadata.
42
+ #[cfg(feature = "di")]
43
+ fn extract_handler_dependencies(route: &crate::Route) -> Vec<String> {
44
+ route.handler_dependencies.clone()
45
+ }
46
+
47
+ /// Determines if a method typically has a request body
48
+ fn method_expects_body(method: &crate::Method) -> bool {
49
+ matches!(method, crate::Method::Post | crate::Method::Put | crate::Method::Patch)
50
+ }
51
+
52
+ /// Creates a method router for the given HTTP method.
53
+ /// Handles both path parameters and non-path variants.
54
+ fn create_method_router(
55
+ method: crate::Method,
56
+ has_path_params: bool,
57
+ handler: Arc<dyn Handler>,
58
+ hooks: Option<Arc<crate::LifecycleHooks>>,
59
+ include_raw_query_params: bool,
60
+ include_query_params_json: bool,
61
+ ) -> axum::routing::MethodRouter {
62
+ let expects_body = method_expects_body(&method);
63
+ let include_headers = handler.wants_headers();
64
+ let include_cookies = handler.wants_cookies();
65
+ let without_body_options = request_extraction::WithoutBodyExtractionOptions {
66
+ include_raw_query_params,
67
+ include_query_params_json,
68
+ include_headers,
69
+ include_cookies,
70
+ };
71
+
72
+ if expects_body {
73
+ if has_path_params {
74
+ let handler_clone = handler.clone();
75
+ let hooks_clone = hooks.clone();
76
+ match method {
77
+ crate::Method::Post => axum::routing::post(
78
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
79
+ let (parts, body) = req.into_parts();
80
+ let request_data = request_extraction::create_request_data_with_body(
81
+ &parts,
82
+ path_params.0,
83
+ body,
84
+ include_raw_query_params,
85
+ include_query_params_json,
86
+ include_headers,
87
+ include_cookies,
88
+ )
89
+ .await?;
90
+ let req = axum::extract::Request::from_parts(parts, Body::empty());
91
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
92
+ .await
93
+ },
94
+ ),
95
+ crate::Method::Put => axum::routing::put(
96
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
97
+ let (parts, body) = req.into_parts();
98
+ let request_data = request_extraction::create_request_data_with_body(
99
+ &parts,
100
+ path_params.0,
101
+ body,
102
+ include_raw_query_params,
103
+ include_query_params_json,
104
+ include_headers,
105
+ include_cookies,
106
+ )
107
+ .await?;
108
+ let req = axum::extract::Request::from_parts(parts, Body::empty());
109
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
110
+ .await
111
+ },
112
+ ),
113
+ crate::Method::Patch => axum::routing::patch(
114
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
115
+ let (parts, body) = req.into_parts();
116
+ let request_data = request_extraction::create_request_data_with_body(
117
+ &parts,
118
+ path_params.0,
119
+ body,
120
+ include_raw_query_params,
121
+ include_query_params_json,
122
+ include_headers,
123
+ include_cookies,
124
+ )
125
+ .await?;
126
+ let req = axum::extract::Request::from_parts(parts, Body::empty());
127
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
128
+ .await
129
+ },
130
+ ),
131
+ crate::Method::Get
132
+ | crate::Method::Delete
133
+ | crate::Method::Head
134
+ | crate::Method::Options
135
+ | crate::Method::Trace => MethodRouter::new(),
136
+ }
137
+ } else {
138
+ let handler_clone = handler.clone();
139
+ let hooks_clone = hooks.clone();
140
+ match method {
141
+ crate::Method::Post => axum::routing::post(move |req: axum::extract::Request| async move {
142
+ let (parts, body) = req.into_parts();
143
+ let request_data = request_extraction::create_request_data_with_body(
144
+ &parts,
145
+ HashMap::new(),
146
+ body,
147
+ include_raw_query_params,
148
+ include_query_params_json,
149
+ include_headers,
150
+ include_cookies,
151
+ )
152
+ .await?;
153
+ let req = axum::extract::Request::from_parts(parts, Body::empty());
154
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
155
+ .await
156
+ }),
157
+ crate::Method::Put => axum::routing::put(move |req: axum::extract::Request| async move {
158
+ let (parts, body) = req.into_parts();
159
+ let request_data = request_extraction::create_request_data_with_body(
160
+ &parts,
161
+ HashMap::new(),
162
+ body,
163
+ include_raw_query_params,
164
+ include_query_params_json,
165
+ include_headers,
166
+ include_cookies,
167
+ )
168
+ .await?;
169
+ let req = axum::extract::Request::from_parts(parts, Body::empty());
170
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
171
+ .await
172
+ }),
173
+ crate::Method::Patch => axum::routing::patch(move |req: axum::extract::Request| async move {
174
+ let (parts, body) = req.into_parts();
175
+ let request_data = request_extraction::create_request_data_with_body(
176
+ &parts,
177
+ HashMap::new(),
178
+ body,
179
+ include_raw_query_params,
180
+ include_query_params_json,
181
+ include_headers,
182
+ include_cookies,
183
+ )
184
+ .await?;
185
+ let req = axum::extract::Request::from_parts(parts, Body::empty());
186
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
187
+ .await
188
+ }),
189
+ crate::Method::Get
190
+ | crate::Method::Delete
191
+ | crate::Method::Head
192
+ | crate::Method::Options
193
+ | crate::Method::Trace => MethodRouter::new(),
194
+ }
195
+ }
196
+ } else if has_path_params {
197
+ let handler_clone = handler.clone();
198
+ let hooks_clone = hooks.clone();
199
+ match method {
200
+ crate::Method::Get => axum::routing::get(
201
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
202
+ let request_data = request_extraction::create_request_data_without_body(
203
+ req.uri(),
204
+ req.method(),
205
+ req.headers(),
206
+ path_params.0,
207
+ without_body_options,
208
+ );
209
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
210
+ .await
211
+ },
212
+ ),
213
+ crate::Method::Delete => axum::routing::delete(
214
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
215
+ let request_data = request_extraction::create_request_data_without_body(
216
+ req.uri(),
217
+ req.method(),
218
+ req.headers(),
219
+ path_params.0,
220
+ without_body_options,
221
+ );
222
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
223
+ .await
224
+ },
225
+ ),
226
+ crate::Method::Head => axum::routing::head(
227
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
228
+ let request_data = request_extraction::create_request_data_without_body(
229
+ req.uri(),
230
+ req.method(),
231
+ req.headers(),
232
+ path_params.0,
233
+ without_body_options,
234
+ );
235
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
236
+ .await
237
+ },
238
+ ),
239
+ crate::Method::Trace => axum::routing::trace(
240
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
241
+ let request_data = request_extraction::create_request_data_without_body(
242
+ req.uri(),
243
+ req.method(),
244
+ req.headers(),
245
+ path_params.0,
246
+ without_body_options,
247
+ );
248
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
249
+ .await
250
+ },
251
+ ),
252
+ crate::Method::Options => axum::routing::options(
253
+ move |path_params: Path<HashMap<String, String>>, req: axum::extract::Request| async move {
254
+ let request_data = request_extraction::create_request_data_without_body(
255
+ req.uri(),
256
+ req.method(),
257
+ req.headers(),
258
+ path_params.0,
259
+ without_body_options,
260
+ );
261
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone)
262
+ .await
263
+ },
264
+ ),
265
+ crate::Method::Post | crate::Method::Put | crate::Method::Patch => MethodRouter::new(),
266
+ }
267
+ } else {
268
+ let handler_clone = handler.clone();
269
+ let hooks_clone = hooks.clone();
270
+ match method {
271
+ crate::Method::Get => axum::routing::get(move |req: axum::extract::Request| async move {
272
+ let request_data = request_extraction::create_request_data_without_body(
273
+ req.uri(),
274
+ req.method(),
275
+ req.headers(),
276
+ HashMap::new(),
277
+ without_body_options,
278
+ );
279
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone).await
280
+ }),
281
+ crate::Method::Delete => axum::routing::delete(move |req: axum::extract::Request| async move {
282
+ let request_data = request_extraction::create_request_data_without_body(
283
+ req.uri(),
284
+ req.method(),
285
+ req.headers(),
286
+ HashMap::new(),
287
+ without_body_options,
288
+ );
289
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone).await
290
+ }),
291
+ crate::Method::Head => axum::routing::head(move |req: axum::extract::Request| async move {
292
+ let request_data = request_extraction::create_request_data_without_body(
293
+ req.uri(),
294
+ req.method(),
295
+ req.headers(),
296
+ HashMap::new(),
297
+ without_body_options,
298
+ );
299
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone).await
300
+ }),
301
+ crate::Method::Trace => axum::routing::trace(move |req: axum::extract::Request| async move {
302
+ let request_data = request_extraction::create_request_data_without_body(
303
+ req.uri(),
304
+ req.method(),
305
+ req.headers(),
306
+ HashMap::new(),
307
+ without_body_options,
308
+ );
309
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone).await
310
+ }),
311
+ crate::Method::Options => axum::routing::options(move |req: axum::extract::Request| async move {
312
+ let request_data = request_extraction::create_request_data_without_body(
313
+ req.uri(),
314
+ req.method(),
315
+ req.headers(),
316
+ HashMap::new(),
317
+ without_body_options,
318
+ );
319
+ lifecycle_execution::execute_with_lifecycle_hooks(req, request_data, handler_clone, hooks_clone).await
320
+ }),
321
+ crate::Method::Post | crate::Method::Put | crate::Method::Patch => MethodRouter::new(),
322
+ }
323
+ }
324
+ }
325
+
326
+ /// Request ID generator using UUIDs
327
+ #[derive(Clone, Default)]
328
+ struct MakeRequestUuid;
329
+
330
+ impl MakeRequestId for MakeRequestUuid {
331
+ fn make_request_id<B>(&mut self, _request: &axum::http::Request<B>) -> Option<RequestId> {
332
+ let id = Uuid::new_v4().to_string().parse().ok()?;
333
+ Some(RequestId::new(id))
334
+ }
335
+ }
336
+
337
+ /// Graceful shutdown signal handler
338
+ ///
339
+ /// Coverage: Tested via integration tests (Unix signal handling not easily unit testable)
340
+ #[cfg(not(tarpaulin_include))]
341
+ async fn shutdown_signal() {
342
+ let ctrl_c = async {
343
+ tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler");
344
+ };
345
+
346
+ #[cfg(unix)]
347
+ let terminate = async {
348
+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
349
+ .expect("failed to install signal handler")
350
+ .recv()
351
+ .await;
352
+ };
353
+
354
+ #[cfg(not(unix))]
355
+ let terminate = std::future::pending::<()>();
356
+
357
+ tokio::select! {
358
+ _ = ctrl_c => {
359
+ tracing::info!("Received SIGINT (Ctrl+C), starting graceful shutdown");
360
+ },
361
+ _ = terminate => {
362
+ tracing::info!("Received SIGTERM, starting graceful shutdown");
363
+ },
364
+ }
365
+ }
366
+
367
+ /// Build an Axum router from routes and foreign handlers
368
+ #[cfg(not(feature = "di"))]
369
+ pub fn build_router_with_handlers(
370
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
371
+ hooks: Option<Arc<crate::LifecycleHooks>>,
372
+ ) -> Result<AxumRouter, String> {
373
+ build_router_with_handlers_inner(routes, hooks, None, true)
374
+ }
375
+
376
+ /// Build an Axum router from routes and foreign handlers with optional DI container
377
+ #[cfg(feature = "di")]
378
+ pub fn build_router_with_handlers(
379
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
380
+ hooks: Option<Arc<crate::LifecycleHooks>>,
381
+ di_container: Option<Arc<spikard_core::di::DependencyContainer>>,
382
+ ) -> Result<AxumRouter, String> {
383
+ build_router_with_handlers_inner(routes, hooks, di_container, true)
384
+ }
385
+
386
+ fn build_router_with_handlers_inner(
387
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
388
+ hooks: Option<Arc<crate::LifecycleHooks>>,
389
+ #[cfg(feature = "di")] di_container: Option<Arc<spikard_core::di::DependencyContainer>>,
390
+ #[cfg(not(feature = "di"))] _di_container: Option<()>,
391
+ enable_http_trace: bool,
392
+ ) -> Result<AxumRouter, String> {
393
+ let mut app = AxumRouter::new();
394
+
395
+ let mut routes_by_path: HashMap<String, Vec<RouteHandlerPair>> = HashMap::new();
396
+ for (route, handler) in routes {
397
+ routes_by_path
398
+ .entry(route.path.clone())
399
+ .or_default()
400
+ .push((route, handler));
401
+ }
402
+
403
+ let mut sorted_paths: Vec<String> = routes_by_path.keys().cloned().collect();
404
+ sorted_paths.sort();
405
+
406
+ for path in sorted_paths {
407
+ let route_handlers = routes_by_path
408
+ .remove(&path)
409
+ .ok_or_else(|| format!("Missing handlers for path '{}'", path))?;
410
+
411
+ let mut handlers_by_method: HashMap<crate::Method, (crate::Route, Arc<dyn Handler>)> = HashMap::new();
412
+ for (route, handler) in route_handlers {
413
+ #[cfg(feature = "di")]
414
+ let handler = if let Some(ref container) = di_container {
415
+ let mut required_deps = extract_handler_dependencies(&route);
416
+ if required_deps.is_empty() {
417
+ required_deps = container.keys();
418
+ }
419
+
420
+ if !required_deps.is_empty() {
421
+ Arc::new(crate::di_handler::DependencyInjectingHandler::new(
422
+ handler,
423
+ Arc::clone(container),
424
+ required_deps,
425
+ )) as Arc<dyn Handler>
426
+ } else {
427
+ handler
428
+ }
429
+ } else {
430
+ handler
431
+ };
432
+
433
+ let validating_handler = Arc::new(handler::ValidatingHandler::new(handler, &route));
434
+ handlers_by_method.insert(route.method.clone(), (route, validating_handler));
435
+ }
436
+
437
+ let cors_config: Option<CorsConfig> = handlers_by_method
438
+ .values()
439
+ .find_map(|(route, _)| route.cors.as_ref())
440
+ .cloned();
441
+
442
+ let has_options_handler = handlers_by_method.keys().any(|m| m.as_str() == "OPTIONS");
443
+
444
+ let mut combined_router: Option<MethodRouter> = None;
445
+ let has_path_params = path.contains('{');
446
+
447
+ for (_method, (route, handler)) in handlers_by_method {
448
+ let method = route.method.clone();
449
+ let method_router: MethodRouter = match method {
450
+ crate::Method::Options => {
451
+ if let Some(ref cors_cfg) = route.cors {
452
+ let cors_config = cors_cfg.clone();
453
+ axum::routing::options(move |req: axum::extract::Request| async move {
454
+ crate::cors::handle_preflight(req.headers(), &cors_config).map_err(|e| *e)
455
+ })
456
+ } else {
457
+ let include_raw_query_params = route.parameter_validator.is_some();
458
+ let include_query_params_json = !handler.prefers_parameter_extraction();
459
+ create_method_router(
460
+ method,
461
+ has_path_params,
462
+ handler,
463
+ hooks.clone(),
464
+ include_raw_query_params,
465
+ include_query_params_json,
466
+ )
467
+ }
468
+ }
469
+ method => {
470
+ let include_raw_query_params = route.parameter_validator.is_some();
471
+ let include_query_params_json = !handler.prefers_parameter_extraction();
472
+ create_method_router(
473
+ method,
474
+ has_path_params,
475
+ handler,
476
+ hooks.clone(),
477
+ include_raw_query_params,
478
+ include_query_params_json,
479
+ )
480
+ }
481
+ };
482
+
483
+ let method_router = method_router.layer(axum::middleware::from_fn_with_state(
484
+ crate::middleware::RouteInfo {
485
+ expects_json_body: route.expects_json_body,
486
+ },
487
+ crate::middleware::validate_content_type_middleware,
488
+ ));
489
+
490
+ combined_router = Some(match combined_router {
491
+ None => method_router,
492
+ Some(existing) => existing.merge(method_router),
493
+ });
494
+
495
+ tracing::info!("Registered route: {} {}", route.method.as_str(), path);
496
+ }
497
+
498
+ if let Some(ref cors_cfg) = cors_config
499
+ && !has_options_handler
500
+ {
501
+ let cors_config_clone: CorsConfig = cors_cfg.clone();
502
+ let options_router = axum::routing::options(move |req: axum::extract::Request| async move {
503
+ crate::cors::handle_preflight(req.headers(), &cors_config_clone).map_err(|e| *e)
504
+ });
505
+
506
+ combined_router = Some(match combined_router {
507
+ None => options_router,
508
+ Some(existing) => existing.merge(options_router),
509
+ });
510
+
511
+ tracing::info!("Auto-generated OPTIONS handler for CORS preflight: {}", path);
512
+ }
513
+
514
+ if let Some(router) = combined_router {
515
+ let mut axum_path = type_hints::strip_type_hints(&path);
516
+ if !axum_path.starts_with('/') {
517
+ axum_path = format!("/{}", axum_path);
518
+ }
519
+ app = app.route(&axum_path, router);
520
+ }
521
+ }
522
+
523
+ if enable_http_trace {
524
+ app = app.layer(TraceLayer::new_for_http());
525
+ }
526
+
527
+ Ok(app)
528
+ }
529
+
530
+ /// Build router with handlers and apply middleware based on config
531
+ pub fn build_router_with_handlers_and_config(
532
+ routes: Vec<RouteHandlerPair>,
533
+ config: ServerConfig,
534
+ route_metadata: Vec<crate::RouteMetadata>,
535
+ ) -> Result<AxumRouter, String> {
536
+ #[cfg(feature = "di")]
537
+ if config.di_container.is_none() {
538
+ eprintln!("[spikard-di] build_router: di_container is None");
539
+ } else {
540
+ eprintln!(
541
+ "[spikard-di] build_router: di_container has keys: {:?}",
542
+ config.di_container.as_ref().unwrap().keys()
543
+ );
544
+ }
545
+ let hooks = config.lifecycle_hooks.clone();
546
+
547
+ let jsonrpc_registry = if let Some(ref jsonrpc_config) = config.jsonrpc {
548
+ if jsonrpc_config.enabled {
549
+ let registry = Arc::new(crate::jsonrpc::JsonRpcMethodRegistry::new());
550
+
551
+ for (route, handler) in &routes {
552
+ if let Some(ref jsonrpc_info) = route.jsonrpc_method {
553
+ let method_name = jsonrpc_info.method_name.clone();
554
+
555
+ let metadata = crate::jsonrpc::MethodMetadata::new(&method_name)
556
+ .with_params_schema(jsonrpc_info.params_schema.clone().unwrap_or(serde_json::json!({})))
557
+ .with_result_schema(jsonrpc_info.result_schema.clone().unwrap_or(serde_json::json!({})));
558
+
559
+ let metadata = if let Some(ref description) = jsonrpc_info.description {
560
+ metadata.with_description(description.clone())
561
+ } else {
562
+ metadata
563
+ };
564
+
565
+ let metadata = if jsonrpc_info.deprecated {
566
+ metadata.mark_deprecated()
567
+ } else {
568
+ metadata
569
+ };
570
+
571
+ let mut metadata = metadata;
572
+ for tag in &jsonrpc_info.tags {
573
+ metadata = metadata.with_tag(tag.clone());
574
+ }
575
+
576
+ if let Err(e) = registry.register(&method_name, Arc::clone(handler), metadata) {
577
+ tracing::warn!(
578
+ "Failed to register JSON-RPC method '{}' for route {}: {}",
579
+ method_name,
580
+ route.path,
581
+ e
582
+ );
583
+ } else {
584
+ tracing::debug!(
585
+ "Registered JSON-RPC method '{}' for route {} {} (handler: {})",
586
+ method_name,
587
+ route.method,
588
+ route.path,
589
+ route.handler_name
590
+ );
591
+ }
592
+ }
593
+ }
594
+
595
+ Some(registry)
596
+ } else {
597
+ None
598
+ }
599
+ } else {
600
+ None
601
+ };
602
+
603
+ #[cfg(feature = "di")]
604
+ let mut app =
605
+ build_router_with_handlers_inner(routes, hooks, config.di_container.clone(), config.enable_http_trace)?;
606
+ #[cfg(not(feature = "di"))]
607
+ let mut app = build_router_with_handlers_inner(routes, hooks, None, config.enable_http_trace)?;
608
+
609
+ app = app.layer(SetSensitiveRequestHeadersLayer::new([
610
+ axum::http::header::AUTHORIZATION,
611
+ axum::http::header::COOKIE,
612
+ ]));
613
+
614
+ if let Some(ref compression) = config.compression {
615
+ let mut compression_layer = CompressionLayer::new();
616
+ if !compression.gzip {
617
+ compression_layer = compression_layer.gzip(false);
618
+ }
619
+ if !compression.brotli {
620
+ compression_layer = compression_layer.br(false);
621
+ }
622
+
623
+ let min_threshold = compression.min_size.min(u16::MAX as usize) as u16;
624
+ let predicate = SizeAbove::new(min_threshold)
625
+ .and(NotForContentType::GRPC)
626
+ .and(NotForContentType::IMAGES)
627
+ .and(NotForContentType::SSE);
628
+ let compression_layer = compression_layer.compress_when(predicate);
629
+
630
+ app = app.layer(compression_layer);
631
+ }
632
+
633
+ if let Some(ref rate_limit) = config.rate_limit {
634
+ if rate_limit.ip_based {
635
+ let governor_conf = Arc::new(
636
+ GovernorConfigBuilder::default()
637
+ .per_second(rate_limit.per_second)
638
+ .burst_size(rate_limit.burst)
639
+ .finish()
640
+ .ok_or_else(|| "Failed to create rate limiter".to_string())?,
641
+ );
642
+ app = app.layer(tower_governor::GovernorLayer::new(governor_conf));
643
+ } else {
644
+ let governor_conf = Arc::new(
645
+ GovernorConfigBuilder::default()
646
+ .per_second(rate_limit.per_second)
647
+ .burst_size(rate_limit.burst)
648
+ .key_extractor(GlobalKeyExtractor)
649
+ .finish()
650
+ .ok_or_else(|| "Failed to create rate limiter".to_string())?,
651
+ );
652
+ app = app.layer(tower_governor::GovernorLayer::new(governor_conf));
653
+ }
654
+ }
655
+
656
+ if let Some(ref jwt_config) = config.jwt_auth {
657
+ let jwt_config_clone = jwt_config.clone();
658
+ app = app.layer(axum::middleware::from_fn(move |headers, req, next| {
659
+ crate::auth::jwt_auth_middleware(jwt_config_clone.clone(), headers, req, next)
660
+ }));
661
+ }
662
+
663
+ if let Some(ref api_key_config) = config.api_key_auth {
664
+ let api_key_config_clone = api_key_config.clone();
665
+ app = app.layer(axum::middleware::from_fn(move |headers, req, next| {
666
+ crate::auth::api_key_auth_middleware(api_key_config_clone.clone(), headers, req, next)
667
+ }));
668
+ }
669
+
670
+ if let Some(timeout_secs) = config.request_timeout {
671
+ app = app.layer(TimeoutLayer::with_status_code(
672
+ StatusCode::REQUEST_TIMEOUT,
673
+ Duration::from_secs(timeout_secs),
674
+ ));
675
+ }
676
+
677
+ if config.enable_request_id {
678
+ app = app
679
+ .layer(PropagateRequestIdLayer::x_request_id())
680
+ .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid));
681
+ }
682
+
683
+ if let Some(max_size) = config.max_body_size {
684
+ app = app.layer(DefaultBodyLimit::max(max_size));
685
+ } else {
686
+ app = app.layer(DefaultBodyLimit::disable());
687
+ }
688
+
689
+ for static_config in &config.static_files {
690
+ let mut serve_dir = ServeDir::new(&static_config.directory);
691
+ if static_config.index_file {
692
+ serve_dir = serve_dir.append_index_html_on_directories(true);
693
+ }
694
+
695
+ let mut static_router = AxumRouter::new().fallback_service(serve_dir);
696
+ if let Some(ref cache_control) = static_config.cache_control {
697
+ let header_value = axum::http::HeaderValue::from_str(cache_control)
698
+ .map_err(|e| format!("Invalid cache-control header: {}", e))?;
699
+ static_router = static_router.layer(SetResponseHeaderLayer::overriding(
700
+ axum::http::header::CACHE_CONTROL,
701
+ header_value,
702
+ ));
703
+ }
704
+
705
+ app = app.nest_service(&static_config.route_prefix, static_router);
706
+
707
+ tracing::info!(
708
+ "Serving static files from '{}' at '{}'",
709
+ static_config.directory,
710
+ static_config.route_prefix
711
+ );
712
+ }
713
+
714
+ if let Some(ref openapi_config) = config.openapi
715
+ && openapi_config.enabled
716
+ {
717
+ use axum::response::{Html, Json};
718
+
719
+ let schema_registry = crate::SchemaRegistry::new();
720
+ let openapi_spec =
721
+ crate::openapi::generate_openapi_spec(&route_metadata, openapi_config, &schema_registry, Some(&config))
722
+ .map_err(|e| format!("Failed to generate OpenAPI spec: {}", e))?;
723
+
724
+ let spec_json =
725
+ serde_json::to_string(&openapi_spec).map_err(|e| format!("Failed to serialize OpenAPI spec: {}", e))?;
726
+ let spec_value = serde_json::from_str::<serde_json::Value>(&spec_json)
727
+ .map_err(|e| format!("Failed to parse OpenAPI spec: {}", e))?;
728
+
729
+ let openapi_json_path = openapi_config.openapi_json_path.clone();
730
+ app = app.route(&openapi_json_path, get(move || async move { Json(spec_value) }));
731
+
732
+ let swagger_html = format!(
733
+ r#"<!DOCTYPE html>
734
+ <html>
735
+ <head>
736
+ <title>Swagger UI</title>
737
+ <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css">
738
+ </head>
739
+ <body>
740
+ <div id="swagger-ui"></div>
741
+ <script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
742
+ <script>
743
+ SwaggerUIBundle({{
744
+ url: '{}',
745
+ dom_id: '#swagger-ui',
746
+ }});
747
+ </script>
748
+ </body>
749
+ </html>"#,
750
+ openapi_json_path
751
+ );
752
+ let swagger_ui_path = openapi_config.swagger_ui_path.clone();
753
+ app = app.route(&swagger_ui_path, get(move || async move { Html(swagger_html) }));
754
+
755
+ let redoc_html = format!(
756
+ r#"<!DOCTYPE html>
757
+ <html>
758
+ <head>
759
+ <title>Redoc</title>
760
+ </head>
761
+ <body>
762
+ <redoc spec-url='{}'></redoc>
763
+ <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
764
+ </body>
765
+ </html>"#,
766
+ openapi_json_path
767
+ );
768
+ let redoc_path = openapi_config.redoc_path.clone();
769
+ app = app.route(&redoc_path, get(move || async move { Html(redoc_html) }));
770
+
771
+ tracing::info!("OpenAPI documentation enabled at {}", openapi_json_path);
772
+ }
773
+
774
+ if let Some(ref jsonrpc_config) = config.jsonrpc
775
+ && jsonrpc_config.enabled
776
+ && let Some(registry) = jsonrpc_registry
777
+ {
778
+ let jsonrpc_router = Arc::new(crate::jsonrpc::JsonRpcRouter::new(
779
+ registry,
780
+ jsonrpc_config.enable_batch,
781
+ jsonrpc_config.max_batch_size,
782
+ ));
783
+
784
+ let state = Arc::new(crate::jsonrpc::JsonRpcState { router: jsonrpc_router });
785
+
786
+ let endpoint_path = jsonrpc_config.endpoint_path.clone();
787
+ app = app.route(&endpoint_path, post(crate::jsonrpc::handle_jsonrpc).with_state(state));
788
+
789
+ // TODO: Add per-method routes if enabled
790
+ // TODO: Add WebSocket endpoint if enabled
791
+ // TODO: Add SSE endpoint if enabled
792
+ // TODO: Add OpenRPC spec endpoint if enabled
793
+
794
+ tracing::info!("JSON-RPC endpoint enabled at {}", endpoint_path);
795
+ }
796
+
797
+ Ok(app)
798
+ }
799
+
800
+ /// HTTP Server
801
+ pub struct Server {
802
+ config: ServerConfig,
803
+ router: Router,
804
+ }
805
+
806
+ impl Server {
807
+ /// Create a new server with configuration
808
+ pub fn new(config: ServerConfig, router: Router) -> Self {
809
+ Self { config, router }
810
+ }
811
+
812
+ /// Create a new server with Python handlers
813
+ ///
814
+ /// Build router with trait-based handlers
815
+ /// Routes are grouped by path before registration to support multiple HTTP methods
816
+ /// for the same path (e.g., GET /data and POST /data). Axum requires that all methods
817
+ /// for a path be merged into a single MethodRouter before calling `.route()`.
818
+ pub fn with_handlers(
819
+ config: ServerConfig,
820
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
821
+ ) -> Result<AxumRouter, String> {
822
+ let metadata: Vec<crate::RouteMetadata> = routes
823
+ .iter()
824
+ .map(|(route, _)| {
825
+ #[cfg(feature = "di")]
826
+ {
827
+ crate::RouteMetadata {
828
+ method: route.method.to_string(),
829
+ path: route.path.clone(),
830
+ handler_name: route.handler_name.clone(),
831
+ request_schema: None,
832
+ response_schema: None,
833
+ parameter_schema: None,
834
+ file_params: route.file_params.clone(),
835
+ is_async: route.is_async,
836
+ cors: route.cors.clone(),
837
+ body_param_name: None,
838
+ handler_dependencies: Some(route.handler_dependencies.clone()),
839
+ jsonrpc_method: route
840
+ .jsonrpc_method
841
+ .as_ref()
842
+ .map(|info| serde_json::to_value(info).unwrap_or(serde_json::json!(null))),
843
+ }
844
+ }
845
+ #[cfg(not(feature = "di"))]
846
+ {
847
+ crate::RouteMetadata {
848
+ method: route.method.to_string(),
849
+ path: route.path.clone(),
850
+ handler_name: route.handler_name.clone(),
851
+ request_schema: None,
852
+ response_schema: None,
853
+ parameter_schema: None,
854
+ file_params: route.file_params.clone(),
855
+ is_async: route.is_async,
856
+ cors: route.cors.clone(),
857
+ body_param_name: None,
858
+ jsonrpc_method: route
859
+ .jsonrpc_method
860
+ .as_ref()
861
+ .map(|info| serde_json::to_value(info).unwrap_or(serde_json::json!(null))),
862
+ }
863
+ }
864
+ })
865
+ .collect();
866
+ build_router_with_handlers_and_config(routes, config, metadata)
867
+ }
868
+
869
+ /// Create a new server with Python handlers and metadata for OpenAPI
870
+ pub fn with_handlers_and_metadata(
871
+ config: ServerConfig,
872
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
873
+ metadata: Vec<crate::RouteMetadata>,
874
+ ) -> Result<AxumRouter, String> {
875
+ build_router_with_handlers_and_config(routes, config, metadata)
876
+ }
877
+
878
+ /// Run the server with the Axum router and config
879
+ ///
880
+ /// Coverage: Production-only, tested via integration tests
881
+ #[cfg(not(tarpaulin_include))]
882
+ pub async fn run_with_config(app: AxumRouter, config: ServerConfig) -> Result<(), Box<dyn std::error::Error>> {
883
+ let addr = format!("{}:{}", config.host, config.port);
884
+ let socket_addr: SocketAddr = addr.parse()?;
885
+ let listener = TcpListener::bind(socket_addr).await?;
886
+
887
+ tracing::info!("Listening on http://{}", socket_addr);
888
+
889
+ if config.graceful_shutdown {
890
+ axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>())
891
+ .with_graceful_shutdown(shutdown_signal())
892
+ .await?;
893
+ } else {
894
+ axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
895
+ }
896
+
897
+ Ok(())
898
+ }
899
+
900
+ /// Initialize logging
901
+ pub fn init_logging() {
902
+ tracing_subscriber::registry()
903
+ .with(
904
+ tracing_subscriber::EnvFilter::try_from_default_env()
905
+ .unwrap_or_else(|_| "spikard=info,tower_http=info".into()),
906
+ )
907
+ .with(tracing_subscriber::fmt::layer())
908
+ .init();
909
+ }
910
+
911
+ /// Start the server
912
+ ///
913
+ /// Coverage: Production-only, tested via integration tests
914
+ #[cfg(not(tarpaulin_include))]
915
+ pub async fn serve(self) -> Result<(), Box<dyn std::error::Error>> {
916
+ tracing::info!("Starting server with {} routes", self.router.route_count());
917
+
918
+ let app = self.build_axum_router();
919
+
920
+ let addr = format!("{}:{}", self.config.host, self.config.port);
921
+ let socket_addr: SocketAddr = addr.parse()?;
922
+ let listener = TcpListener::bind(socket_addr).await?;
923
+
924
+ tracing::info!("Listening on http://{}", socket_addr);
925
+
926
+ axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
927
+
928
+ Ok(())
929
+ }
930
+
931
+ /// Build Axum router from our router
932
+ fn build_axum_router(&self) -> AxumRouter {
933
+ let mut app = AxumRouter::new();
934
+
935
+ app = app.route("/health", get(|| async { "OK" }));
936
+
937
+ // TODO: Add routes from self.router
938
+
939
+ if self.config.enable_http_trace {
940
+ app = app.layer(TraceLayer::new_for_http());
941
+ }
942
+
943
+ app
944
+ }
945
+ }
946
+
947
+ #[cfg(test)]
948
+ mod tests {
949
+ use super::*;
950
+ use std::pin::Pin;
951
+ use std::sync::Arc;
952
+
953
+ struct TestHandler;
954
+
955
+ impl Handler for TestHandler {
956
+ fn call(
957
+ &self,
958
+ _request: axum::http::Request<Body>,
959
+ _request_data: crate::handler_trait::RequestData,
960
+ ) -> Pin<Box<dyn std::future::Future<Output = crate::handler_trait::HandlerResult> + Send + '_>> {
961
+ Box::pin(async { Ok(axum::http::Response::builder().status(200).body(Body::empty()).unwrap()) })
962
+ }
963
+ }
964
+
965
+ fn build_test_route(path: &str, method: &str, handler_name: &str, expects_json_body: bool) -> crate::Route {
966
+ use std::str::FromStr;
967
+ crate::Route {
968
+ path: path.to_string(),
969
+ method: spikard_core::Method::from_str(method).expect("valid method"),
970
+ handler_name: handler_name.to_string(),
971
+ expects_json_body,
972
+ cors: None,
973
+ is_async: true,
974
+ file_params: None,
975
+ request_validator: None,
976
+ response_validator: None,
977
+ parameter_validator: None,
978
+ jsonrpc_method: None,
979
+ #[cfg(feature = "di")]
980
+ handler_dependencies: vec![],
981
+ }
982
+ }
983
+
984
+ fn build_test_route_with_cors(
985
+ path: &str,
986
+ method: &str,
987
+ handler_name: &str,
988
+ expects_json_body: bool,
989
+ cors: crate::CorsConfig,
990
+ ) -> crate::Route {
991
+ use std::str::FromStr;
992
+ crate::Route {
993
+ path: path.to_string(),
994
+ method: spikard_core::Method::from_str(method).expect("valid method"),
995
+ handler_name: handler_name.to_string(),
996
+ expects_json_body,
997
+ cors: Some(cors),
998
+ is_async: true,
999
+ file_params: None,
1000
+ request_validator: None,
1001
+ response_validator: None,
1002
+ parameter_validator: None,
1003
+ jsonrpc_method: None,
1004
+ #[cfg(feature = "di")]
1005
+ handler_dependencies: vec![],
1006
+ }
1007
+ }
1008
+
1009
+ #[test]
1010
+ fn test_method_expects_body_post() {
1011
+ assert!(method_expects_body(&crate::Method::Post));
1012
+ }
1013
+
1014
+ #[test]
1015
+ fn test_method_expects_body_put() {
1016
+ assert!(method_expects_body(&crate::Method::Put));
1017
+ }
1018
+
1019
+ #[test]
1020
+ fn test_method_expects_body_patch() {
1021
+ assert!(method_expects_body(&crate::Method::Patch));
1022
+ }
1023
+
1024
+ #[test]
1025
+ fn test_method_expects_body_get() {
1026
+ assert!(!method_expects_body(&crate::Method::Get));
1027
+ }
1028
+
1029
+ #[test]
1030
+ fn test_method_expects_body_delete() {
1031
+ assert!(!method_expects_body(&crate::Method::Delete));
1032
+ }
1033
+
1034
+ #[test]
1035
+ fn test_method_expects_body_head() {
1036
+ assert!(!method_expects_body(&crate::Method::Head));
1037
+ }
1038
+
1039
+ #[test]
1040
+ fn test_method_expects_body_options() {
1041
+ assert!(!method_expects_body(&crate::Method::Options));
1042
+ }
1043
+
1044
+ #[test]
1045
+ fn test_method_expects_body_trace() {
1046
+ assert!(!method_expects_body(&crate::Method::Trace));
1047
+ }
1048
+
1049
+ #[test]
1050
+ fn test_make_request_uuid_generates_valid_uuid() {
1051
+ let mut maker = MakeRequestUuid;
1052
+ let request = axum::http::Request::builder().body(Body::empty()).unwrap();
1053
+
1054
+ let id = maker.make_request_id(&request);
1055
+
1056
+ assert!(id.is_some());
1057
+ let id_val = id.unwrap();
1058
+ let id_str = id_val.header_value().to_str().expect("valid utf8");
1059
+ assert!(!id_str.is_empty());
1060
+ assert!(Uuid::parse_str(id_str).is_ok());
1061
+ }
1062
+
1063
+ #[test]
1064
+ fn test_make_request_uuid_unique_per_call() {
1065
+ let mut maker = MakeRequestUuid;
1066
+ let request = axum::http::Request::builder().body(Body::empty()).unwrap();
1067
+
1068
+ let id1 = maker.make_request_id(&request).unwrap();
1069
+ let id2 = maker.make_request_id(&request).unwrap();
1070
+
1071
+ let id1_str = id1.header_value().to_str().expect("valid utf8");
1072
+ let id2_str = id2.header_value().to_str().expect("valid utf8");
1073
+ assert_ne!(id1_str, id2_str);
1074
+ }
1075
+
1076
+ #[test]
1077
+ fn test_make_request_uuid_v4_format() {
1078
+ let mut maker = MakeRequestUuid;
1079
+ let request = axum::http::Request::builder().body(Body::empty()).unwrap();
1080
+
1081
+ let id = maker.make_request_id(&request).unwrap();
1082
+ let id_str = id.header_value().to_str().expect("valid utf8");
1083
+
1084
+ let uuid = Uuid::parse_str(id_str).expect("valid UUID");
1085
+ assert_eq!(uuid.get_version(), Some(uuid::Version::Random));
1086
+ }
1087
+
1088
+ #[test]
1089
+ fn test_make_request_uuid_multiple_independent_makers() {
1090
+ let request = axum::http::Request::builder().body(Body::empty()).unwrap();
1091
+
1092
+ let id1 = {
1093
+ let mut maker1 = MakeRequestUuid;
1094
+ maker1.make_request_id(&request).unwrap()
1095
+ };
1096
+ let id2 = {
1097
+ let mut maker2 = MakeRequestUuid;
1098
+ maker2.make_request_id(&request).unwrap()
1099
+ };
1100
+
1101
+ let id1_str = id1.header_value().to_str().expect("valid utf8");
1102
+ let id2_str = id2.header_value().to_str().expect("valid utf8");
1103
+ assert_ne!(id1_str, id2_str);
1104
+ }
1105
+
1106
+ #[test]
1107
+ fn test_make_request_uuid_clone_independence() {
1108
+ let mut maker1 = MakeRequestUuid;
1109
+ let mut maker2 = maker1.clone();
1110
+ let request = axum::http::Request::builder().body(Body::empty()).unwrap();
1111
+
1112
+ let id1 = maker1.make_request_id(&request).unwrap();
1113
+ let id2 = maker2.make_request_id(&request).unwrap();
1114
+
1115
+ let id1_str = id1.header_value().to_str().expect("valid utf8");
1116
+ let id2_str = id2.header_value().to_str().expect("valid utf8");
1117
+ assert_ne!(id1_str, id2_str);
1118
+ }
1119
+
1120
+ #[test]
1121
+ fn test_server_creation() {
1122
+ let config = ServerConfig::default();
1123
+ let router = Router::new();
1124
+ let _server = Server::new(config, router);
1125
+ }
1126
+
1127
+ #[test]
1128
+ fn test_server_creation_with_custom_host_port() {
1129
+ let mut config = ServerConfig::default();
1130
+ config.host = "0.0.0.0".to_string();
1131
+ config.port = 3000;
1132
+
1133
+ let router = Router::new();
1134
+ let server = Server::new(config.clone(), router);
1135
+
1136
+ assert_eq!(server.config.host, "0.0.0.0");
1137
+ assert_eq!(server.config.port, 3000);
1138
+ }
1139
+
1140
+ #[test]
1141
+ fn test_server_config_default_values() {
1142
+ let config = ServerConfig::default();
1143
+
1144
+ assert_eq!(config.host, "127.0.0.1");
1145
+ assert_eq!(config.port, 8000);
1146
+ assert_eq!(config.workers, 1);
1147
+ assert!(!config.enable_request_id);
1148
+ assert!(config.max_body_size.is_some());
1149
+ assert!(config.request_timeout.is_none());
1150
+ assert!(config.graceful_shutdown);
1151
+ }
1152
+
1153
+ #[test]
1154
+ fn test_server_config_builder_pattern() {
1155
+ let config = ServerConfig::builder().port(9000).host("0.0.0.0".to_string()).build();
1156
+
1157
+ assert_eq!(config.port, 9000);
1158
+ assert_eq!(config.host, "0.0.0.0");
1159
+ }
1160
+
1161
+ #[cfg(feature = "di")]
1162
+ fn build_router_for_tests(
1163
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
1164
+ hooks: Option<Arc<crate::LifecycleHooks>>,
1165
+ ) -> Result<AxumRouter, String> {
1166
+ build_router_with_handlers(routes, hooks, None)
1167
+ }
1168
+
1169
+ #[cfg(not(feature = "di"))]
1170
+ fn build_router_for_tests(
1171
+ routes: Vec<(crate::Route, Arc<dyn Handler>)>,
1172
+ hooks: Option<Arc<crate::LifecycleHooks>>,
1173
+ ) -> Result<AxumRouter, String> {
1174
+ build_router_with_handlers(routes, hooks)
1175
+ }
1176
+
1177
+ #[test]
1178
+ fn test_route_registry_empty_routes() {
1179
+ let routes: Vec<(crate::Route, Arc<dyn Handler>)> = vec![];
1180
+ let _result = build_router_for_tests(routes, None);
1181
+ }
1182
+
1183
+ #[test]
1184
+ fn test_route_registry_single_route() {
1185
+ let route = build_test_route("/test", "GET", "test_handler", false);
1186
+
1187
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1188
+ let routes = vec![(route, handler)];
1189
+
1190
+ let result = build_router_for_tests(routes, None);
1191
+ assert!(result.is_ok());
1192
+ }
1193
+
1194
+ #[test]
1195
+ fn test_route_path_normalization_without_leading_slash() {
1196
+ let route = build_test_route("api/users", "GET", "list_users", false);
1197
+
1198
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1199
+ let routes = vec![(route, handler)];
1200
+
1201
+ let result = build_router_for_tests(routes, None);
1202
+ assert!(result.is_ok());
1203
+ }
1204
+
1205
+ #[test]
1206
+ fn test_route_path_normalization_with_leading_slash() {
1207
+ let route = build_test_route("/api/users", "GET", "list_users", false);
1208
+
1209
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1210
+ let routes = vec![(route, handler)];
1211
+
1212
+ let result = build_router_for_tests(routes, None);
1213
+ assert!(result.is_ok());
1214
+ }
1215
+
1216
+ #[test]
1217
+ fn test_multiple_routes_same_path_different_methods() {
1218
+ let get_route = build_test_route("/users", "GET", "list_users", false);
1219
+ let post_route = build_test_route("/users", "POST", "create_user", true);
1220
+
1221
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1222
+ let routes = vec![(get_route, handler.clone()), (post_route, handler)];
1223
+
1224
+ let result = build_router_for_tests(routes, None);
1225
+ assert!(result.is_ok());
1226
+ }
1227
+
1228
+ #[test]
1229
+ fn test_multiple_different_routes() {
1230
+ let users_route = build_test_route("/users", "GET", "list_users", false);
1231
+ let posts_route = build_test_route("/posts", "GET", "list_posts", false);
1232
+
1233
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1234
+ let routes = vec![(users_route, handler.clone()), (posts_route, handler)];
1235
+
1236
+ let result = build_router_for_tests(routes, None);
1237
+ assert!(result.is_ok());
1238
+ }
1239
+
1240
+ #[test]
1241
+ fn test_route_with_single_path_parameter() {
1242
+ let route = build_test_route("/users/{id}", "GET", "get_user", false);
1243
+
1244
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1245
+ let routes = vec![(route, handler)];
1246
+
1247
+ let result = build_router_for_tests(routes, None);
1248
+ assert!(result.is_ok());
1249
+ }
1250
+
1251
+ #[test]
1252
+ fn test_route_with_multiple_path_parameters() {
1253
+ let route = build_test_route("/users/{user_id}/posts/{post_id}", "GET", "get_user_post", false);
1254
+
1255
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1256
+ let routes = vec![(route, handler)];
1257
+
1258
+ let result = build_router_for_tests(routes, None);
1259
+ assert!(result.is_ok());
1260
+ }
1261
+
1262
+ #[test]
1263
+ fn test_route_with_path_parameter_post_with_body() {
1264
+ let route = build_test_route("/users/{id}", "PUT", "update_user", true);
1265
+
1266
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1267
+ let routes = vec![(route, handler)];
1268
+
1269
+ let result = build_router_for_tests(routes, None);
1270
+ assert!(result.is_ok());
1271
+ }
1272
+
1273
+ #[test]
1274
+ fn test_route_with_path_parameter_delete() {
1275
+ let route = build_test_route("/users/{id}", "DELETE", "delete_user", false);
1276
+
1277
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1278
+ let routes = vec![(route, handler)];
1279
+
1280
+ let result = build_router_for_tests(routes, None);
1281
+ assert!(result.is_ok());
1282
+ }
1283
+
1284
+ #[test]
1285
+ fn test_route_post_method_with_body() {
1286
+ let route = build_test_route("/users", "POST", "create_user", true);
1287
+
1288
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1289
+ let routes = vec![(route, handler)];
1290
+
1291
+ let result = build_router_for_tests(routes, None);
1292
+ assert!(result.is_ok());
1293
+ }
1294
+
1295
+ #[test]
1296
+ fn test_route_put_method_with_body() {
1297
+ let route = build_test_route("/users/{id}", "PUT", "update_user", true);
1298
+
1299
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1300
+ let routes = vec![(route, handler)];
1301
+
1302
+ let result = build_router_for_tests(routes, None);
1303
+ assert!(result.is_ok());
1304
+ }
1305
+
1306
+ #[test]
1307
+ fn test_route_patch_method_with_body() {
1308
+ let route = build_test_route("/users/{id}", "PATCH", "patch_user", true);
1309
+
1310
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1311
+ let routes = vec![(route, handler)];
1312
+
1313
+ let result = build_router_for_tests(routes, None);
1314
+ assert!(result.is_ok());
1315
+ }
1316
+
1317
+ #[test]
1318
+ fn test_route_head_method() {
1319
+ let route = build_test_route("/users", "HEAD", "head_users", false);
1320
+
1321
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1322
+ let routes = vec![(route, handler)];
1323
+
1324
+ let result = build_router_for_tests(routes, None);
1325
+ assert!(result.is_ok());
1326
+ }
1327
+
1328
+ #[test]
1329
+ fn test_route_options_method() {
1330
+ let route = build_test_route("/users", "OPTIONS", "options_users", false);
1331
+
1332
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1333
+ let routes = vec![(route, handler)];
1334
+
1335
+ let result = build_router_for_tests(routes, None);
1336
+ assert!(result.is_ok());
1337
+ }
1338
+
1339
+ #[test]
1340
+ fn test_route_trace_method() {
1341
+ let route = build_test_route("/users", "TRACE", "trace_users", false);
1342
+
1343
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1344
+ let routes = vec![(route, handler)];
1345
+
1346
+ let result = build_router_for_tests(routes, None);
1347
+ assert!(result.is_ok());
1348
+ }
1349
+
1350
+ #[test]
1351
+ fn test_route_with_cors_config() {
1352
+ let cors_config = crate::CorsConfig {
1353
+ allowed_origins: vec!["https://example.com".to_string()],
1354
+ allowed_methods: vec!["GET".to_string(), "POST".to_string()],
1355
+ allowed_headers: vec!["Content-Type".to_string()],
1356
+ expose_headers: None,
1357
+ max_age: Some(3600),
1358
+ allow_credentials: Some(true),
1359
+ };
1360
+
1361
+ let route = build_test_route_with_cors("/users", "GET", "list_users", false, cors_config);
1362
+
1363
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1364
+ let routes = vec![(route, handler)];
1365
+
1366
+ let result = build_router_for_tests(routes, None);
1367
+ assert!(result.is_ok());
1368
+ }
1369
+
1370
+ #[test]
1371
+ fn test_multiple_routes_with_cors_same_path() {
1372
+ let cors_config = crate::CorsConfig {
1373
+ allowed_origins: vec!["https://example.com".to_string()],
1374
+ allowed_methods: vec!["GET".to_string(), "POST".to_string()],
1375
+ allowed_headers: vec!["Content-Type".to_string()],
1376
+ expose_headers: None,
1377
+ max_age: Some(3600),
1378
+ allow_credentials: Some(true),
1379
+ };
1380
+
1381
+ let get_route = build_test_route_with_cors("/users", "GET", "list_users", false, cors_config.clone());
1382
+ let post_route = build_test_route_with_cors("/users", "POST", "create_user", true, cors_config);
1383
+
1384
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1385
+ let routes = vec![(get_route, handler.clone()), (post_route, handler)];
1386
+
1387
+ let result = build_router_for_tests(routes, None);
1388
+ assert!(result.is_ok());
1389
+ }
1390
+
1391
+ #[test]
1392
+ fn test_routes_sorted_by_path() {
1393
+ let zebra_route = build_test_route("/zebra", "GET", "get_zebra", false);
1394
+ let alpha_route = build_test_route("/alpha", "GET", "get_alpha", false);
1395
+
1396
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1397
+ let routes = vec![(zebra_route, handler.clone()), (alpha_route, handler)];
1398
+
1399
+ let result = build_router_for_tests(routes, None);
1400
+ assert!(result.is_ok());
1401
+ }
1402
+
1403
+ #[test]
1404
+ fn test_routes_with_nested_paths() {
1405
+ let parent_route = build_test_route("/api", "GET", "get_api", false);
1406
+ let child_route = build_test_route("/api/users", "GET", "get_users", false);
1407
+
1408
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1409
+ let routes = vec![(parent_route, handler.clone()), (child_route, handler)];
1410
+
1411
+ let result = build_router_for_tests(routes, None);
1412
+ assert!(result.is_ok());
1413
+ }
1414
+
1415
+ #[test]
1416
+ fn test_routes_with_lifecycle_hooks() {
1417
+ let hooks = crate::LifecycleHooks::new();
1418
+ let hooks = Arc::new(hooks);
1419
+
1420
+ let route = build_test_route("/users", "GET", "list_users", false);
1421
+
1422
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1423
+ let routes = vec![(route, handler)];
1424
+
1425
+ let result = build_router_for_tests(routes, Some(hooks));
1426
+ assert!(result.is_ok());
1427
+ }
1428
+
1429
+ #[test]
1430
+ fn test_routes_without_lifecycle_hooks() {
1431
+ let route = build_test_route("/users", "GET", "list_users", false);
1432
+
1433
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1434
+ let routes = vec![(route, handler)];
1435
+
1436
+ let result = build_router_for_tests(routes, None);
1437
+ assert!(result.is_ok());
1438
+ }
1439
+
1440
+ #[test]
1441
+ fn test_route_with_trailing_slash() {
1442
+ let route = build_test_route("/users/", "GET", "list_users", false);
1443
+
1444
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1445
+ let routes = vec![(route, handler)];
1446
+
1447
+ let result = build_router_for_tests(routes, None);
1448
+ assert!(result.is_ok());
1449
+ }
1450
+
1451
+ #[test]
1452
+ fn test_route_with_root_path() {
1453
+ let route = build_test_route("/", "GET", "root_handler", false);
1454
+
1455
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1456
+ let routes = vec![(route, handler)];
1457
+
1458
+ let result = build_router_for_tests(routes, None);
1459
+ assert!(result.is_ok());
1460
+ }
1461
+
1462
+ #[test]
1463
+ fn test_large_number_of_routes() {
1464
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1465
+ let mut routes = vec![];
1466
+
1467
+ for i in 0..50 {
1468
+ let route = build_test_route(&format!("/route{}", i), "GET", &format!("handler_{}", i), false);
1469
+ routes.push((route, handler.clone()));
1470
+ }
1471
+
1472
+ let result = build_router_for_tests(routes, None);
1473
+ assert!(result.is_ok());
1474
+ }
1475
+
1476
+ #[test]
1477
+ fn test_route_with_query_params_in_path_definition() {
1478
+ let route = build_test_route("/search", "GET", "search", false);
1479
+
1480
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1481
+ let routes = vec![(route, handler)];
1482
+
1483
+ let result = build_router_for_tests(routes, None);
1484
+ assert!(result.is_ok());
1485
+ }
1486
+
1487
+ #[test]
1488
+ fn test_all_http_methods_on_same_path() {
1489
+ let handler: Arc<dyn Handler> = Arc::new(TestHandler);
1490
+ let methods = vec!["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
1491
+
1492
+ let mut routes = vec![];
1493
+ for method in methods {
1494
+ let expects_body = matches!(method, "POST" | "PUT" | "PATCH");
1495
+ let route = build_test_route("/resource", method, &format!("handler_{}", method), expects_body);
1496
+ routes.push((route, handler.clone()));
1497
+ }
1498
+
1499
+ let result = build_router_for_tests(routes, None);
1500
+ assert!(result.is_ok());
1501
+ }
1502
+ }