spikard 0.2.5 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/LICENSE +1 -1
- data/README.md +659 -626
- data/ext/spikard_rb/Cargo.toml +17 -17
- data/ext/spikard_rb/extconf.rb +10 -10
- data/ext/spikard_rb/src/lib.rs +6 -6
- data/lib/spikard/app.rb +386 -374
- data/lib/spikard/background.rb +27 -27
- data/lib/spikard/config.rb +396 -396
- data/lib/spikard/converters.rb +13 -85
- data/lib/spikard/handler_wrapper.rb +113 -116
- data/lib/spikard/provide.rb +214 -228
- data/lib/spikard/response.rb +173 -109
- data/lib/spikard/schema.rb +243 -243
- data/lib/spikard/sse.rb +111 -111
- data/lib/spikard/streaming_response.rb +44 -21
- data/lib/spikard/testing.rb +221 -221
- data/lib/spikard/upload_file.rb +131 -131
- data/lib/spikard/version.rb +5 -5
- data/lib/spikard/websocket.rb +59 -59
- data/lib/spikard.rb +43 -43
- data/sig/spikard.rbs +360 -349
- data/vendor/bundle/ruby/3.4.0/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +2 -0
- metadata +5 -85
- data/vendor/crates/spikard-core/Cargo.toml +0 -40
- data/vendor/crates/spikard-core/src/bindings/mod.rs +0 -3
- data/vendor/crates/spikard-core/src/bindings/response.rs +0 -133
- data/vendor/crates/spikard-core/src/debug.rs +0 -63
- data/vendor/crates/spikard-core/src/di/container.rs +0 -726
- data/vendor/crates/spikard-core/src/di/dependency.rs +0 -273
- data/vendor/crates/spikard-core/src/di/error.rs +0 -118
- data/vendor/crates/spikard-core/src/di/factory.rs +0 -538
- data/vendor/crates/spikard-core/src/di/graph.rs +0 -545
- data/vendor/crates/spikard-core/src/di/mod.rs +0 -192
- data/vendor/crates/spikard-core/src/di/resolved.rs +0 -411
- data/vendor/crates/spikard-core/src/di/value.rs +0 -283
- data/vendor/crates/spikard-core/src/http.rs +0 -153
- data/vendor/crates/spikard-core/src/lib.rs +0 -28
- data/vendor/crates/spikard-core/src/lifecycle.rs +0 -422
- data/vendor/crates/spikard-core/src/parameters.rs +0 -719
- data/vendor/crates/spikard-core/src/problem.rs +0 -310
- data/vendor/crates/spikard-core/src/request_data.rs +0 -189
- data/vendor/crates/spikard-core/src/router.rs +0 -249
- data/vendor/crates/spikard-core/src/schema_registry.rs +0 -183
- data/vendor/crates/spikard-core/src/type_hints.rs +0 -304
- data/vendor/crates/spikard-core/src/validation.rs +0 -699
- data/vendor/crates/spikard-http/Cargo.toml +0 -58
- data/vendor/crates/spikard-http/src/auth.rs +0 -247
- data/vendor/crates/spikard-http/src/background.rs +0 -249
- data/vendor/crates/spikard-http/src/bindings/mod.rs +0 -3
- data/vendor/crates/spikard-http/src/bindings/response.rs +0 -1
- data/vendor/crates/spikard-http/src/body_metadata.rs +0 -8
- data/vendor/crates/spikard-http/src/cors.rs +0 -490
- data/vendor/crates/spikard-http/src/debug.rs +0 -63
- data/vendor/crates/spikard-http/src/di_handler.rs +0 -423
- data/vendor/crates/spikard-http/src/handler_response.rs +0 -190
- data/vendor/crates/spikard-http/src/handler_trait.rs +0 -228
- data/vendor/crates/spikard-http/src/handler_trait_tests.rs +0 -284
- data/vendor/crates/spikard-http/src/lib.rs +0 -529
- data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +0 -149
- data/vendor/crates/spikard-http/src/lifecycle.rs +0 -428
- data/vendor/crates/spikard-http/src/middleware/mod.rs +0 -285
- data/vendor/crates/spikard-http/src/middleware/multipart.rs +0 -86
- data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +0 -147
- data/vendor/crates/spikard-http/src/middleware/validation.rs +0 -287
- data/vendor/crates/spikard-http/src/openapi/mod.rs +0 -309
- data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +0 -190
- data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +0 -308
- data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +0 -195
- data/vendor/crates/spikard-http/src/parameters.rs +0 -1
- data/vendor/crates/spikard-http/src/problem.rs +0 -1
- data/vendor/crates/spikard-http/src/query_parser.rs +0 -369
- data/vendor/crates/spikard-http/src/response.rs +0 -399
- data/vendor/crates/spikard-http/src/router.rs +0 -1
- data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
- data/vendor/crates/spikard-http/src/server/handler.rs +0 -80
- data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +0 -98
- data/vendor/crates/spikard-http/src/server/mod.rs +0 -805
- data/vendor/crates/spikard-http/src/server/request_extraction.rs +0 -119
- data/vendor/crates/spikard-http/src/sse.rs +0 -447
- data/vendor/crates/spikard-http/src/testing/form.rs +0 -14
- data/vendor/crates/spikard-http/src/testing/multipart.rs +0 -60
- data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -285
- data/vendor/crates/spikard-http/src/testing.rs +0 -377
- data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
- data/vendor/crates/spikard-http/src/validation.rs +0 -1
- data/vendor/crates/spikard-http/src/websocket.rs +0 -324
- data/vendor/crates/spikard-rb/Cargo.toml +0 -42
- data/vendor/crates/spikard-rb/build.rs +0 -8
- data/vendor/crates/spikard-rb/src/background.rs +0 -63
- data/vendor/crates/spikard-rb/src/config.rs +0 -294
- data/vendor/crates/spikard-rb/src/conversion.rs +0 -392
- data/vendor/crates/spikard-rb/src/di.rs +0 -409
- data/vendor/crates/spikard-rb/src/handler.rs +0 -534
- data/vendor/crates/spikard-rb/src/lib.rs +0 -2020
- data/vendor/crates/spikard-rb/src/lifecycle.rs +0 -267
- data/vendor/crates/spikard-rb/src/server.rs +0 -283
- data/vendor/crates/spikard-rb/src/sse.rs +0 -231
- data/vendor/crates/spikard-rb/src/test_client.rs +0 -404
- data/vendor/crates/spikard-rb/src/test_sse.rs +0 -143
- data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
- data/vendor/crates/spikard-rb/src/websocket.rs +0 -233
- /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/diff-lcs-1.6.2/mise.toml +0 -0
|
@@ -1,805 +0,0 @@
|
|
|
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
|
-
}
|