spikard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,752 +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
- }
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
+ }