spikard 0.3.6 → 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 (113) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +21 -6
  3. data/ext/spikard_rb/Cargo.toml +2 -2
  4. data/lib/spikard/app.rb +33 -14
  5. data/lib/spikard/testing.rb +47 -12
  6. data/lib/spikard/version.rb +1 -1
  7. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  8. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  9. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  10. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  11. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  12. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  13. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  14. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  15. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  16. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  17. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  18. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  19. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  20. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  21. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  22. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  23. data/vendor/crates/spikard-core/Cargo.toml +4 -4
  24. data/vendor/crates/spikard-core/src/debug.rs +64 -0
  25. data/vendor/crates/spikard-core/src/di/container.rs +3 -27
  26. data/vendor/crates/spikard-core/src/di/factory.rs +1 -5
  27. data/vendor/crates/spikard-core/src/di/graph.rs +8 -47
  28. data/vendor/crates/spikard-core/src/di/mod.rs +1 -1
  29. data/vendor/crates/spikard-core/src/di/resolved.rs +1 -7
  30. data/vendor/crates/spikard-core/src/di/value.rs +2 -4
  31. data/vendor/crates/spikard-core/src/errors.rs +30 -0
  32. data/vendor/crates/spikard-core/src/http.rs +262 -0
  33. data/vendor/crates/spikard-core/src/lib.rs +1 -1
  34. data/vendor/crates/spikard-core/src/lifecycle.rs +764 -0
  35. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  36. data/vendor/crates/spikard-core/src/parameters.rs +1962 -159
  37. data/vendor/crates/spikard-core/src/problem.rs +34 -0
  38. data/vendor/crates/spikard-core/src/request_data.rs +966 -1
  39. data/vendor/crates/spikard-core/src/router.rs +263 -2
  40. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +688 -0
  41. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +26 -268
  42. data/vendor/crates/spikard-http/Cargo.toml +12 -16
  43. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  44. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  45. data/vendor/crates/spikard-http/src/auth.rs +65 -16
  46. data/vendor/crates/spikard-http/src/background.rs +1614 -3
  47. data/vendor/crates/spikard-http/src/cors.rs +515 -0
  48. data/vendor/crates/spikard-http/src/debug.rs +65 -0
  49. data/vendor/crates/spikard-http/src/di_handler.rs +1322 -77
  50. data/vendor/crates/spikard-http/src/handler_response.rs +711 -0
  51. data/vendor/crates/spikard-http/src/handler_trait.rs +607 -5
  52. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +6 -0
  53. data/vendor/crates/spikard-http/src/lib.rs +33 -28
  54. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +81 -0
  55. data/vendor/crates/spikard-http/src/lifecycle.rs +765 -0
  56. data/vendor/crates/spikard-http/src/middleware/mod.rs +372 -117
  57. data/vendor/crates/spikard-http/src/middleware/multipart.rs +836 -10
  58. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +409 -43
  59. data/vendor/crates/spikard-http/src/middleware/validation.rs +513 -65
  60. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +345 -0
  61. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1055 -0
  62. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +473 -3
  63. data/vendor/crates/spikard-http/src/query_parser.rs +455 -31
  64. data/vendor/crates/spikard-http/src/response.rs +321 -0
  65. data/vendor/crates/spikard-http/src/server/handler.rs +1572 -9
  66. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +136 -0
  67. data/vendor/crates/spikard-http/src/server/mod.rs +875 -178
  68. data/vendor/crates/spikard-http/src/server/request_extraction.rs +674 -23
  69. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  70. data/vendor/crates/spikard-http/src/sse.rs +983 -21
  71. data/vendor/crates/spikard-http/src/testing/form.rs +38 -0
  72. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -2
  73. data/vendor/crates/spikard-http/src/testing.rs +7 -7
  74. data/vendor/crates/spikard-http/src/websocket.rs +1055 -4
  75. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  76. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  77. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  78. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  79. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  80. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  81. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  82. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  83. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  84. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  85. data/vendor/crates/spikard-rb/Cargo.toml +10 -4
  86. data/vendor/crates/spikard-rb/build.rs +196 -5
  87. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  88. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +100 -109
  89. data/vendor/crates/spikard-rb/src/conversion.rs +121 -20
  90. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  91. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +12 -46
  92. data/vendor/crates/spikard-rb/src/handler.rs +100 -107
  93. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  94. data/vendor/crates/spikard-rb/src/lib.rs +467 -1428
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +1 -0
  96. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  97. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  98. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  99. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  100. data/vendor/crates/spikard-rb/src/server.rs +47 -22
  101. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +187 -40
  102. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  103. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  104. data/vendor/crates/spikard-rb/src/websocket.rs +178 -37
  105. metadata +46 -13
  106. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  107. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  108. data/vendor/crates/spikard-http/src/router.rs +0 -1
  109. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  110. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  111. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  112. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  113. /data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +0 -0
@@ -0,0 +1,752 @@
1
+ //! Configuration extraction trait and implementation for language bindings
2
+ //!
3
+ //! This module provides a trait-based abstraction for extracting ServerConfig and related
4
+ //! configuration structs from language-specific objects (Python dicts, JavaScript objects, etc.)
5
+ //! without duplicating extraction logic across bindings.
6
+ //!
7
+ //! The `ConfigSource` trait allows language bindings to implement a unified interface for
8
+ //! reading configuration, while `ConfigExtractor` provides the actual extraction logic that
9
+ //! works with any `ConfigSource` implementation.
10
+
11
+ use spikard_http::{
12
+ ApiKeyConfig, CompressionConfig, ContactInfo, JsonRpcConfig, JwtConfig, LicenseInfo, OpenApiConfig,
13
+ RateLimitConfig, SecuritySchemeInfo, ServerConfig, ServerInfo, StaticFilesConfig,
14
+ };
15
+ use std::collections::HashMap;
16
+
17
+ /// Trait for reading configuration from language-specific objects
18
+ ///
19
+ /// Bindings implement this trait to provide unified access to configuration values
20
+ /// regardless of the language-specific representation (PyDict, JavaScript Object, etc.).
21
+ pub trait ConfigSource {
22
+ /// Get a boolean value from the source
23
+ fn get_bool(&self, key: &str) -> Option<bool>;
24
+
25
+ /// Get a u64 value from the source
26
+ fn get_u64(&self, key: &str) -> Option<u64>;
27
+
28
+ /// Get a u16 value from the source
29
+ fn get_u16(&self, key: &str) -> Option<u16>;
30
+
31
+ /// Get a string value from the source
32
+ fn get_string(&self, key: &str) -> Option<String>;
33
+
34
+ /// Get a vector of strings from the source
35
+ fn get_vec_string(&self, key: &str) -> Option<Vec<String>>;
36
+
37
+ /// Get a nested ConfigSource for nested objects
38
+ fn get_nested(&self, key: &str) -> Option<Box<dyn ConfigSource + '_>>;
39
+
40
+ /// Check if a key exists in the source
41
+ fn has_key(&self, key: &str) -> bool;
42
+
43
+ /// Get array length (for collection iteration)
44
+ fn get_array_length(&self, _key: &str) -> Option<usize> {
45
+ None
46
+ }
47
+
48
+ /// Get element at index from array
49
+ fn get_array_element(&self, _key: &str, _index: usize) -> Option<Box<dyn ConfigSource + '_>> {
50
+ None
51
+ }
52
+
53
+ /// Get u32 value from the source (helper for common case)
54
+ fn get_u32(&self, key: &str) -> Option<u32> {
55
+ self.get_u64(key).and_then(|v| u32::try_from(v).ok())
56
+ }
57
+
58
+ /// Get usize value from the source (helper)
59
+ fn get_usize(&self, key: &str) -> Option<usize> {
60
+ self.get_u64(key).and_then(|v| usize::try_from(v).ok())
61
+ }
62
+ }
63
+
64
+ /// Configuration extractor that works with any ConfigSource
65
+ pub struct ConfigExtractor;
66
+
67
+ impl ConfigExtractor {
68
+ /// Extract a complete ServerConfig from a ConfigSource
69
+ pub fn extract_server_config(source: &dyn ConfigSource) -> Result<ServerConfig, String> {
70
+ let mut config = ServerConfig::default();
71
+
72
+ if let Some(host) = source.get_string("host").or_else(|| source.get_string("Host")) {
73
+ config.host = host;
74
+ }
75
+
76
+ if let Some(port) = source
77
+ .get_u16("port")
78
+ .or_else(|| source.get_u32("port").map(|p| p as u16))
79
+ {
80
+ config.port = port;
81
+ }
82
+
83
+ if let Some(workers) = source
84
+ .get_usize("workers")
85
+ .or_else(|| source.get_u32("workers").map(|w| w as usize))
86
+ {
87
+ config.workers = workers;
88
+ }
89
+
90
+ if let Some(enable_request_id) = source.get_bool("enable_request_id") {
91
+ config.enable_request_id = enable_request_id;
92
+ }
93
+
94
+ // `max_body_size = 0` is treated as unlimited.
95
+ if let Some(max_body_size) = source
96
+ .get_usize("max_body_size")
97
+ .or_else(|| source.get_u32("max_body_size").map(|v| v as usize))
98
+ {
99
+ config.max_body_size = if max_body_size == 0 { None } else { Some(max_body_size) };
100
+ }
101
+
102
+ if let Some(request_timeout) = source.get_u64("request_timeout") {
103
+ config.request_timeout = Some(request_timeout);
104
+ }
105
+
106
+ if let Some(graceful_shutdown) = source.get_bool("graceful_shutdown") {
107
+ config.graceful_shutdown = graceful_shutdown;
108
+ }
109
+
110
+ if let Some(shutdown_timeout) = source.get_u64("shutdown_timeout") {
111
+ config.shutdown_timeout = shutdown_timeout;
112
+ }
113
+
114
+ config.compression = source
115
+ .get_nested("compression")
116
+ .and_then(|cfg| Self::extract_compression_config(cfg.as_ref()).ok());
117
+
118
+ config.rate_limit = source
119
+ .get_nested("rate_limit")
120
+ .and_then(|cfg| Self::extract_rate_limit_config(cfg.as_ref()).ok());
121
+
122
+ config.jwt_auth = source
123
+ .get_nested("jwt_auth")
124
+ .and_then(|cfg| Self::extract_jwt_config(cfg.as_ref()).ok());
125
+
126
+ config.api_key_auth = source
127
+ .get_nested("api_key_auth")
128
+ .and_then(|cfg| Self::extract_api_key_config(cfg.as_ref()).ok());
129
+
130
+ config.static_files = Self::extract_static_files_config(source)?;
131
+
132
+ config.openapi = source
133
+ .get_nested("openapi")
134
+ .and_then(|cfg| Self::extract_openapi_config(cfg.as_ref()).ok());
135
+
136
+ config.jsonrpc = source
137
+ .get_nested("jsonrpc")
138
+ .and_then(|cfg| Self::extract_jsonrpc_config(cfg.as_ref()).ok());
139
+
140
+ if let Some(enable_http_trace) = source.get_bool("enable_http_trace") {
141
+ config.enable_http_trace = enable_http_trace;
142
+ }
143
+
144
+ Ok(config)
145
+ }
146
+
147
+ /// Extract CompressionConfig from a ConfigSource
148
+ pub fn extract_compression_config(source: &dyn ConfigSource) -> Result<CompressionConfig, String> {
149
+ let gzip = source.get_bool("gzip").unwrap_or(true);
150
+ let brotli = source.get_bool("brotli").unwrap_or(true);
151
+ let min_size = source
152
+ .get_usize("min_size")
153
+ .or_else(|| source.get_u32("min_size").map(|s| s as usize))
154
+ .unwrap_or(1024);
155
+ let quality = source.get_u32("quality").unwrap_or(6);
156
+
157
+ Ok(CompressionConfig {
158
+ gzip,
159
+ brotli,
160
+ min_size,
161
+ quality,
162
+ })
163
+ }
164
+
165
+ /// Extract RateLimitConfig from a ConfigSource
166
+ pub fn extract_rate_limit_config(source: &dyn ConfigSource) -> Result<RateLimitConfig, String> {
167
+ let per_second = source.get_u64("per_second").ok_or("Rate limit requires 'per_second'")?;
168
+
169
+ let burst = source.get_u32("burst").ok_or("Rate limit requires 'burst' as u32")?;
170
+
171
+ let ip_based = source.get_bool("ip_based").unwrap_or(true);
172
+
173
+ Ok(RateLimitConfig {
174
+ per_second,
175
+ burst,
176
+ ip_based,
177
+ })
178
+ }
179
+
180
+ /// Extract JwtConfig from a ConfigSource
181
+ pub fn extract_jwt_config(source: &dyn ConfigSource) -> Result<JwtConfig, String> {
182
+ let secret = source.get_string("secret").ok_or("JWT auth requires 'secret'")?;
183
+
184
+ let algorithm = source.get_string("algorithm").unwrap_or_else(|| "HS256".to_string());
185
+
186
+ let audience = source.get_vec_string("audience");
187
+
188
+ let issuer = source.get_string("issuer");
189
+
190
+ let leeway = source.get_u64("leeway").unwrap_or(0);
191
+
192
+ Ok(JwtConfig {
193
+ secret,
194
+ algorithm,
195
+ audience,
196
+ issuer,
197
+ leeway,
198
+ })
199
+ }
200
+
201
+ /// Extract ApiKeyConfig from a ConfigSource
202
+ pub fn extract_api_key_config(source: &dyn ConfigSource) -> Result<ApiKeyConfig, String> {
203
+ let keys = source
204
+ .get_vec_string("keys")
205
+ .ok_or("API Key auth requires 'keys' as Vec<String>)")?;
206
+
207
+ let header_name = source
208
+ .get_string("header_name")
209
+ .unwrap_or_else(|| "X-API-Key".to_string());
210
+
211
+ Ok(ApiKeyConfig { keys, header_name })
212
+ }
213
+
214
+ /// Extract static files configuration list from a ConfigSource
215
+ pub fn extract_static_files_config(source: &dyn ConfigSource) -> Result<Vec<StaticFilesConfig>, String> {
216
+ let length = source.get_array_length("static_files").unwrap_or(0);
217
+ if length == 0 {
218
+ return Ok(Vec::new());
219
+ }
220
+
221
+ let mut configs = Vec::new();
222
+ for i in 0..length {
223
+ let sf_source = source
224
+ .get_array_element("static_files", i)
225
+ .ok_or("Failed to get static files array element")?;
226
+
227
+ let directory = sf_source
228
+ .get_string("directory")
229
+ .ok_or("Static files requires 'directory'")?;
230
+
231
+ let route_prefix = sf_source
232
+ .get_string("route_prefix")
233
+ .ok_or("Static files requires 'route_prefix'")?;
234
+
235
+ let index_file = sf_source.get_bool("index_file").unwrap_or(true);
236
+
237
+ let cache_control = sf_source.get_string("cache_control");
238
+
239
+ configs.push(StaticFilesConfig {
240
+ directory,
241
+ route_prefix,
242
+ index_file,
243
+ cache_control,
244
+ });
245
+ }
246
+
247
+ Ok(configs)
248
+ }
249
+
250
+ /// Extract OpenApiConfig from a ConfigSource
251
+ pub fn extract_openapi_config(source: &dyn ConfigSource) -> Result<OpenApiConfig, String> {
252
+ let enabled = source.get_bool("enabled").unwrap_or(false);
253
+ let title = source.get_string("title").unwrap_or_else(|| "API".to_string());
254
+ let version = source.get_string("version").unwrap_or_else(|| "1.0.0".to_string());
255
+ let description = source.get_string("description");
256
+ let swagger_ui_path = source
257
+ .get_string("swagger_ui_path")
258
+ .unwrap_or_else(|| "/docs".to_string());
259
+ let redoc_path = source.get_string("redoc_path").unwrap_or_else(|| "/redoc".to_string());
260
+ let openapi_json_path = source
261
+ .get_string("openapi_json_path")
262
+ .unwrap_or_else(|| "/openapi.json".to_string());
263
+
264
+ let contact = source
265
+ .get_nested("contact")
266
+ .map(|cfg| {
267
+ let name = cfg.get_string("name");
268
+ let email = cfg.get_string("email");
269
+ let url = cfg.get_string("url");
270
+ ContactInfo { name, email, url }
271
+ })
272
+ .filter(|c| c.name.is_some() || c.email.is_some() || c.url.is_some());
273
+
274
+ let license = source.get_nested("license").and_then(|cfg| {
275
+ let name = cfg.get_string("name")?;
276
+ let url = cfg.get_string("url");
277
+ Some(LicenseInfo { name, url })
278
+ });
279
+
280
+ let servers = Self::extract_servers_config(source)?;
281
+
282
+ let security_schemes = Self::extract_security_schemes_config(source)?;
283
+
284
+ Ok(OpenApiConfig {
285
+ enabled,
286
+ title,
287
+ version,
288
+ description,
289
+ swagger_ui_path,
290
+ redoc_path,
291
+ openapi_json_path,
292
+ contact,
293
+ license,
294
+ servers,
295
+ security_schemes,
296
+ })
297
+ }
298
+
299
+ /// Extract servers list from OpenAPI config
300
+ fn extract_servers_config(source: &dyn ConfigSource) -> Result<Vec<ServerInfo>, String> {
301
+ let length = source.get_array_length("servers").unwrap_or(0);
302
+ if length == 0 {
303
+ return Ok(Vec::new());
304
+ }
305
+
306
+ let mut servers = Vec::new();
307
+ for i in 0..length {
308
+ let server_source = source
309
+ .get_array_element("servers", i)
310
+ .ok_or("Failed to get servers array element")?;
311
+
312
+ let url = server_source.get_string("url").ok_or("Server requires 'url'")?;
313
+
314
+ let description = server_source.get_string("description");
315
+
316
+ servers.push(ServerInfo { url, description });
317
+ }
318
+
319
+ Ok(servers)
320
+ }
321
+
322
+ /// Extract security schemes from OpenAPI config
323
+ fn extract_security_schemes_config(
324
+ _source: &dyn ConfigSource,
325
+ ) -> Result<HashMap<String, SecuritySchemeInfo>, String> {
326
+ // TODO: Implement when bindings support iterating HashMap-like structures
327
+ Ok(HashMap::new())
328
+ }
329
+
330
+ /// Extract JsonRpcConfig from a ConfigSource
331
+ pub fn extract_jsonrpc_config(source: &dyn ConfigSource) -> Result<JsonRpcConfig, String> {
332
+ let enabled = source.get_bool("enabled").unwrap_or(true);
333
+ let endpoint_path = source.get_string("endpoint_path").unwrap_or_else(|| "/rpc".to_string());
334
+ let enable_batch = source.get_bool("enable_batch").unwrap_or(true);
335
+ let max_batch_size = source
336
+ .get_usize("max_batch_size")
337
+ .or_else(|| source.get_u32("max_batch_size").map(|s| s as usize))
338
+ .unwrap_or(100);
339
+
340
+ Ok(JsonRpcConfig {
341
+ enabled,
342
+ endpoint_path,
343
+ enable_batch,
344
+ max_batch_size,
345
+ })
346
+ }
347
+ }
348
+
349
+ #[cfg(test)]
350
+ mod tests {
351
+ use super::*;
352
+ use serde_json::Value;
353
+
354
+ struct MockConfigSource {
355
+ data: HashMap<String, String>,
356
+ }
357
+
358
+ impl MockConfigSource {
359
+ fn new() -> Self {
360
+ Self { data: HashMap::new() }
361
+ }
362
+
363
+ fn with(mut self, key: &str, value: String) -> Self {
364
+ self.data.insert(key.to_string(), value);
365
+ self
366
+ }
367
+ }
368
+
369
+ impl ConfigSource for MockConfigSource {
370
+ fn get_bool(&self, key: &str) -> Option<bool> {
371
+ self.data.get(key).and_then(|v| match v.as_str() {
372
+ "true" => Some(true),
373
+ "false" => Some(false),
374
+ _ => v.parse().ok(),
375
+ })
376
+ }
377
+
378
+ fn get_u64(&self, key: &str) -> Option<u64> {
379
+ self.data.get(key).and_then(|v| v.parse().ok())
380
+ }
381
+
382
+ fn get_u16(&self, key: &str) -> Option<u16> {
383
+ self.data.get(key).and_then(|v| v.parse().ok())
384
+ }
385
+
386
+ fn get_string(&self, key: &str) -> Option<String> {
387
+ self.data.get(key).cloned()
388
+ }
389
+
390
+ fn get_vec_string(&self, key: &str) -> Option<Vec<String>> {
391
+ self.data
392
+ .get(key)
393
+ .map(|s| s.split(',').map(|t| t.trim().to_string()).collect())
394
+ }
395
+
396
+ fn get_nested(&self, _key: &str) -> Option<Box<dyn ConfigSource + '_>> {
397
+ None
398
+ }
399
+
400
+ fn has_key(&self, key: &str) -> bool {
401
+ self.data.contains_key(key)
402
+ }
403
+ }
404
+
405
+ #[test]
406
+ fn test_compression_config_extraction() {
407
+ let source = MockConfigSource::new()
408
+ .with("gzip", "true".to_string())
409
+ .with("brotli", "false".to_string())
410
+ .with("min_size", "2048".to_string())
411
+ .with("quality", "9".to_string());
412
+
413
+ let config = ConfigExtractor::extract_compression_config(&source).unwrap();
414
+ assert!(config.gzip);
415
+ assert!(!config.brotli);
416
+ assert_eq!(config.min_size, 2048);
417
+ assert_eq!(config.quality, 9);
418
+ }
419
+
420
+ #[test]
421
+ fn test_compression_config_defaults() {
422
+ let source = MockConfigSource::new();
423
+
424
+ let config = ConfigExtractor::extract_compression_config(&source).unwrap();
425
+ assert!(config.gzip);
426
+ assert!(config.brotli);
427
+ assert_eq!(config.min_size, 1024);
428
+ assert_eq!(config.quality, 6);
429
+ }
430
+
431
+ #[test]
432
+ fn test_jwt_config_extraction() {
433
+ let source = MockConfigSource::new()
434
+ .with("secret", "my-secret".to_string())
435
+ .with("algorithm", "HS512".to_string())
436
+ .with("leeway", "30".to_string());
437
+
438
+ let config = ConfigExtractor::extract_jwt_config(&source).unwrap();
439
+ assert_eq!(config.secret, "my-secret");
440
+ assert_eq!(config.algorithm, "HS512");
441
+ assert_eq!(config.leeway, 30);
442
+ }
443
+
444
+ #[test]
445
+ fn test_jwt_config_missing_secret() {
446
+ let source = MockConfigSource::new();
447
+ let result = ConfigExtractor::extract_jwt_config(&source);
448
+ assert!(result.is_err());
449
+ }
450
+
451
+ #[test]
452
+ fn test_api_key_config_extraction() {
453
+ let source = MockConfigSource::new()
454
+ .with("keys", "key1,key2,key3".to_string())
455
+ .with("header_name", "Authorization".to_string());
456
+
457
+ let config = ConfigExtractor::extract_api_key_config(&source).unwrap();
458
+ assert_eq!(config.keys, vec!["key1", "key2", "key3"]);
459
+ assert_eq!(config.header_name, "Authorization");
460
+ }
461
+
462
+ #[test]
463
+ fn test_api_key_config_defaults() {
464
+ let source = MockConfigSource::new().with("keys", "only-key".to_string());
465
+
466
+ let config = ConfigExtractor::extract_api_key_config(&source).unwrap();
467
+ assert_eq!(config.keys, vec!["only-key"]);
468
+ assert_eq!(config.header_name, "X-API-Key");
469
+ }
470
+
471
+ #[test]
472
+ fn test_rate_limit_config_extraction() {
473
+ let source = MockConfigSource::new()
474
+ .with("per_second", "100".to_string())
475
+ .with("burst", "50".to_string())
476
+ .with("ip_based", "false".to_string());
477
+
478
+ let config = ConfigExtractor::extract_rate_limit_config(&source).unwrap();
479
+ assert_eq!(config.per_second, 100);
480
+ assert_eq!(config.burst, 50);
481
+ assert!(!config.ip_based);
482
+ }
483
+
484
+ #[test]
485
+ fn test_rate_limit_config_missing_required() {
486
+ let source = MockConfigSource::new().with("per_second", "100".to_string());
487
+
488
+ let result = ConfigExtractor::extract_rate_limit_config(&source);
489
+ assert!(result.is_err());
490
+ }
491
+
492
+ #[test]
493
+ fn test_openapi_config_extraction() {
494
+ let source = MockConfigSource::new()
495
+ .with("enabled", "true".to_string())
496
+ .with("title", "Test API".to_string())
497
+ .with("version", "2.0.0".to_string())
498
+ .with("description", "A test API".to_string())
499
+ .with("swagger_ui_path", "/api-docs".to_string())
500
+ .with("redoc_path", "/api-redoc".to_string())
501
+ .with("openapi_json_path", "/api.json".to_string());
502
+
503
+ let config = ConfigExtractor::extract_openapi_config(&source).unwrap();
504
+ assert!(config.enabled);
505
+ assert_eq!(config.title, "Test API");
506
+ assert_eq!(config.version, "2.0.0");
507
+ assert_eq!(config.description, Some("A test API".to_string()));
508
+ assert_eq!(config.swagger_ui_path, "/api-docs");
509
+ assert_eq!(config.redoc_path, "/api-redoc");
510
+ assert_eq!(config.openapi_json_path, "/api.json");
511
+ }
512
+
513
+ #[test]
514
+ fn test_openapi_config_defaults() {
515
+ let source = MockConfigSource::new();
516
+
517
+ let config = ConfigExtractor::extract_openapi_config(&source).unwrap();
518
+ assert!(!config.enabled);
519
+ assert_eq!(config.title, "API");
520
+ assert_eq!(config.version, "1.0.0");
521
+ assert_eq!(config.description, None);
522
+ assert_eq!(config.swagger_ui_path, "/docs");
523
+ assert_eq!(config.redoc_path, "/redoc");
524
+ assert_eq!(config.openapi_json_path, "/openapi.json");
525
+ }
526
+
527
+ #[test]
528
+ fn test_static_files_config_empty() {
529
+ let source = MockConfigSource::new();
530
+
531
+ let configs = ConfigExtractor::extract_static_files_config(&source).unwrap();
532
+ assert_eq!(configs.len(), 0);
533
+ }
534
+
535
+ #[test]
536
+ fn test_server_config_extraction() {
537
+ let source = MockConfigSource::new()
538
+ .with("host", "0.0.0.0".to_string())
539
+ .with("port", "3000".to_string())
540
+ .with("workers", "4".to_string())
541
+ .with("enable_request_id", "false".to_string())
542
+ .with("max_body_size", "5242880".to_string())
543
+ .with("request_timeout", "60".to_string())
544
+ .with("graceful_shutdown", "false".to_string())
545
+ .with("shutdown_timeout", "10".to_string());
546
+
547
+ let config = ConfigExtractor::extract_server_config(&source).unwrap();
548
+ assert_eq!(config.host, "0.0.0.0");
549
+ assert_eq!(config.port, 3000);
550
+ assert_eq!(config.workers, 4);
551
+ assert!(!config.enable_request_id);
552
+ assert_eq!(config.max_body_size, Some(5242880));
553
+ assert_eq!(config.request_timeout, Some(60));
554
+ assert!(!config.graceful_shutdown);
555
+ assert_eq!(config.shutdown_timeout, 10);
556
+ }
557
+
558
+ #[test]
559
+ fn test_server_config_defaults() {
560
+ let source = MockConfigSource::new();
561
+
562
+ let config = ConfigExtractor::extract_server_config(&source).unwrap();
563
+ assert_eq!(config.host, "127.0.0.1");
564
+ assert_eq!(config.port, 8000);
565
+ assert_eq!(config.workers, 1);
566
+ assert!(!config.enable_request_id);
567
+ assert_eq!(config.max_body_size, Some(10 * 1024 * 1024));
568
+ assert_eq!(config.request_timeout, None);
569
+ assert!(config.graceful_shutdown);
570
+ assert_eq!(config.shutdown_timeout, 30);
571
+ }
572
+
573
+ #[test]
574
+ fn test_servers_config_empty() {
575
+ let source = MockConfigSource::new();
576
+
577
+ let servers = ConfigExtractor::extract_servers_config(&source).unwrap();
578
+ assert_eq!(servers.len(), 0);
579
+ }
580
+
581
+ #[test]
582
+ fn test_security_schemes_config_empty() {
583
+ let source = MockConfigSource::new();
584
+
585
+ let schemes = ConfigExtractor::extract_security_schemes_config(&source).unwrap();
586
+ assert_eq!(schemes.len(), 0);
587
+ }
588
+
589
+ struct JsonConfigSource<'a> {
590
+ value: &'a Value,
591
+ }
592
+
593
+ impl<'a> JsonConfigSource<'a> {
594
+ fn new(value: &'a Value) -> Self {
595
+ Self { value }
596
+ }
597
+ }
598
+
599
+ impl ConfigSource for JsonConfigSource<'_> {
600
+ fn get_bool(&self, key: &str) -> Option<bool> {
601
+ self.value.get(key)?.as_bool()
602
+ }
603
+
604
+ fn get_u64(&self, key: &str) -> Option<u64> {
605
+ self.value.get(key)?.as_u64()
606
+ }
607
+
608
+ fn get_u16(&self, key: &str) -> Option<u16> {
609
+ u16::try_from(self.get_u64(key)?).ok()
610
+ }
611
+
612
+ fn get_string(&self, key: &str) -> Option<String> {
613
+ self.value.get(key)?.as_str().map(str::to_string)
614
+ }
615
+
616
+ fn get_vec_string(&self, key: &str) -> Option<Vec<String>> {
617
+ self.value
618
+ .get(key)?
619
+ .as_array()
620
+ .map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
621
+ }
622
+
623
+ fn get_nested(&self, key: &str) -> Option<Box<dyn ConfigSource + '_>> {
624
+ let nested = self.value.get(key)?;
625
+ nested
626
+ .is_object()
627
+ .then(|| Box::new(JsonConfigSource::new(nested)) as Box<dyn ConfigSource>)
628
+ }
629
+
630
+ fn has_key(&self, key: &str) -> bool {
631
+ self.value.get(key).is_some()
632
+ }
633
+
634
+ fn get_array_length(&self, key: &str) -> Option<usize> {
635
+ self.value.get(key)?.as_array().map(Vec::len)
636
+ }
637
+
638
+ fn get_array_element(&self, key: &str, index: usize) -> Option<Box<dyn ConfigSource + '_>> {
639
+ let arr = self.value.get(key)?.as_array()?;
640
+ let elem = arr.get(index)?;
641
+ elem.is_object()
642
+ .then(|| Box::new(JsonConfigSource::new(elem)) as Box<dyn ConfigSource>)
643
+ }
644
+ }
645
+
646
+ #[test]
647
+ fn test_static_files_extraction_supports_arrays() {
648
+ let value = serde_json::json!({
649
+ "static_files": [
650
+ {
651
+ "directory": "public",
652
+ "route_prefix": "/assets",
653
+ "index_file": true,
654
+ "cache_control": "public, max-age=3600"
655
+ }
656
+ ]
657
+ });
658
+ let source = JsonConfigSource::new(&value);
659
+ let configs = ConfigExtractor::extract_static_files_config(&source).expect("extract");
660
+ assert_eq!(configs.len(), 1);
661
+ assert_eq!(configs[0].directory, "public");
662
+ assert_eq!(configs[0].route_prefix, "/assets");
663
+ assert!(configs[0].index_file);
664
+ assert_eq!(configs[0].cache_control.as_deref(), Some("public, max-age=3600"));
665
+ }
666
+
667
+ #[test]
668
+ fn test_static_files_extraction_missing_required_fields_errors() {
669
+ let value = serde_json::json!({
670
+ "static_files": [
671
+ {
672
+ "route_prefix": "/assets"
673
+ }
674
+ ]
675
+ });
676
+ let source = JsonConfigSource::new(&value);
677
+ let err = ConfigExtractor::extract_static_files_config(&source).expect_err("missing directory should error");
678
+ assert!(
679
+ err.contains("Static files requires 'directory'"),
680
+ "unexpected error: {err}"
681
+ );
682
+ }
683
+
684
+ #[test]
685
+ fn test_static_files_extraction_array_element_missing_errors() {
686
+ struct BrokenArraySource;
687
+
688
+ impl ConfigSource for BrokenArraySource {
689
+ fn get_bool(&self, _key: &str) -> Option<bool> {
690
+ None
691
+ }
692
+
693
+ fn get_u64(&self, _key: &str) -> Option<u64> {
694
+ None
695
+ }
696
+
697
+ fn get_u16(&self, _key: &str) -> Option<u16> {
698
+ None
699
+ }
700
+
701
+ fn get_string(&self, _key: &str) -> Option<String> {
702
+ None
703
+ }
704
+
705
+ fn get_vec_string(&self, _key: &str) -> Option<Vec<String>> {
706
+ None
707
+ }
708
+
709
+ fn get_nested(&self, _key: &str) -> Option<Box<dyn ConfigSource + '_>> {
710
+ None
711
+ }
712
+
713
+ fn has_key(&self, _key: &str) -> bool {
714
+ false
715
+ }
716
+
717
+ fn get_array_length(&self, key: &str) -> Option<usize> {
718
+ (key == "static_files").then_some(1)
719
+ }
720
+
721
+ fn get_array_element(&self, _key: &str, _index: usize) -> Option<Box<dyn ConfigSource + '_>> {
722
+ None
723
+ }
724
+ }
725
+
726
+ let err = ConfigExtractor::extract_static_files_config(&BrokenArraySource)
727
+ .expect_err("missing array element should error");
728
+ assert!(
729
+ err.contains("Failed to get static files array element"),
730
+ "unexpected error: {err}"
731
+ );
732
+ }
733
+
734
+ #[test]
735
+ fn test_server_config_prefers_host_key_variants() {
736
+ let value = serde_json::json!({
737
+ "Host": "0.0.0.0",
738
+ "port": 9000,
739
+ "workers": 2,
740
+ "enable_request_id": false,
741
+ "graceful_shutdown": true,
742
+ "shutdown_timeout": 1,
743
+ "static_files": []
744
+ });
745
+ let source = JsonConfigSource::new(&value);
746
+ let cfg = ConfigExtractor::extract_server_config(&source).expect("extract");
747
+ assert_eq!(cfg.host, "0.0.0.0");
748
+ assert_eq!(cfg.port, 9000);
749
+ assert_eq!(cfg.workers, 2);
750
+ assert!(!cfg.enable_request_id);
751
+ }
752
+ }