spikard 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -659
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +386 -386
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +221 -221
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -360
  23. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -63
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -726
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -283
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -39
  36. data/vendor/crates/spikard-core/src/http.rs +153 -153
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -722
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -310
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -189
  42. data/vendor/crates/spikard-core/src/router.rs +249 -249
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -699
  46. data/vendor/crates/spikard-http/Cargo.toml +68 -58
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -247
  48. data/vendor/crates/spikard-http/src/background.rs +249 -249
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -490
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -63
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -529
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -1
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -1
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
  72. data/vendor/crates/spikard-http/src/response.rs +399 -399
  73. data/vendor/crates/spikard-http/src/router.rs +1 -1
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -447
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -1
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -324
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -42
  88. data/vendor/crates/spikard-rb/build.rs +8 -8
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -294
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -409
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -625
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -283
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
  102. metadata +1 -79
  103. data/vendor/spikard-core/Cargo.toml +0 -40
  104. data/vendor/spikard-core/src/bindings/mod.rs +0 -3
  105. data/vendor/spikard-core/src/bindings/response.rs +0 -133
  106. data/vendor/spikard-core/src/debug.rs +0 -63
  107. data/vendor/spikard-core/src/di/container.rs +0 -726
  108. data/vendor/spikard-core/src/di/dependency.rs +0 -273
  109. data/vendor/spikard-core/src/di/error.rs +0 -118
  110. data/vendor/spikard-core/src/di/factory.rs +0 -538
  111. data/vendor/spikard-core/src/di/graph.rs +0 -545
  112. data/vendor/spikard-core/src/di/mod.rs +0 -192
  113. data/vendor/spikard-core/src/di/resolved.rs +0 -411
  114. data/vendor/spikard-core/src/di/value.rs +0 -283
  115. data/vendor/spikard-core/src/http.rs +0 -153
  116. data/vendor/spikard-core/src/lib.rs +0 -28
  117. data/vendor/spikard-core/src/lifecycle.rs +0 -422
  118. data/vendor/spikard-core/src/parameters.rs +0 -719
  119. data/vendor/spikard-core/src/problem.rs +0 -310
  120. data/vendor/spikard-core/src/request_data.rs +0 -189
  121. data/vendor/spikard-core/src/router.rs +0 -249
  122. data/vendor/spikard-core/src/schema_registry.rs +0 -183
  123. data/vendor/spikard-core/src/type_hints.rs +0 -304
  124. data/vendor/spikard-core/src/validation.rs +0 -699
  125. data/vendor/spikard-http/Cargo.toml +0 -58
  126. data/vendor/spikard-http/src/auth.rs +0 -247
  127. data/vendor/spikard-http/src/background.rs +0 -249
  128. data/vendor/spikard-http/src/bindings/mod.rs +0 -3
  129. data/vendor/spikard-http/src/bindings/response.rs +0 -1
  130. data/vendor/spikard-http/src/body_metadata.rs +0 -8
  131. data/vendor/spikard-http/src/cors.rs +0 -490
  132. data/vendor/spikard-http/src/debug.rs +0 -63
  133. data/vendor/spikard-http/src/di_handler.rs +0 -423
  134. data/vendor/spikard-http/src/handler_response.rs +0 -190
  135. data/vendor/spikard-http/src/handler_trait.rs +0 -228
  136. data/vendor/spikard-http/src/handler_trait_tests.rs +0 -284
  137. data/vendor/spikard-http/src/lib.rs +0 -529
  138. data/vendor/spikard-http/src/lifecycle/adapter.rs +0 -149
  139. data/vendor/spikard-http/src/lifecycle.rs +0 -428
  140. data/vendor/spikard-http/src/middleware/mod.rs +0 -285
  141. data/vendor/spikard-http/src/middleware/multipart.rs +0 -86
  142. data/vendor/spikard-http/src/middleware/urlencoded.rs +0 -147
  143. data/vendor/spikard-http/src/middleware/validation.rs +0 -287
  144. data/vendor/spikard-http/src/openapi/mod.rs +0 -309
  145. data/vendor/spikard-http/src/openapi/parameter_extraction.rs +0 -190
  146. data/vendor/spikard-http/src/openapi/schema_conversion.rs +0 -308
  147. data/vendor/spikard-http/src/openapi/spec_generation.rs +0 -195
  148. data/vendor/spikard-http/src/parameters.rs +0 -1
  149. data/vendor/spikard-http/src/problem.rs +0 -1
  150. data/vendor/spikard-http/src/query_parser.rs +0 -369
  151. data/vendor/spikard-http/src/response.rs +0 -399
  152. data/vendor/spikard-http/src/router.rs +0 -1
  153. data/vendor/spikard-http/src/schema_registry.rs +0 -1
  154. data/vendor/spikard-http/src/server/handler.rs +0 -80
  155. data/vendor/spikard-http/src/server/lifecycle_execution.rs +0 -98
  156. data/vendor/spikard-http/src/server/mod.rs +0 -805
  157. data/vendor/spikard-http/src/server/request_extraction.rs +0 -119
  158. data/vendor/spikard-http/src/sse.rs +0 -447
  159. data/vendor/spikard-http/src/testing/form.rs +0 -14
  160. data/vendor/spikard-http/src/testing/multipart.rs +0 -60
  161. data/vendor/spikard-http/src/testing/test_client.rs +0 -285
  162. data/vendor/spikard-http/src/testing.rs +0 -377
  163. data/vendor/spikard-http/src/type_hints.rs +0 -1
  164. data/vendor/spikard-http/src/validation.rs +0 -1
  165. data/vendor/spikard-http/src/websocket.rs +0 -324
  166. data/vendor/spikard-rb/Cargo.toml +0 -42
  167. data/vendor/spikard-rb/build.rs +0 -8
  168. data/vendor/spikard-rb/src/background.rs +0 -63
  169. data/vendor/spikard-rb/src/config.rs +0 -294
  170. data/vendor/spikard-rb/src/conversion.rs +0 -392
  171. data/vendor/spikard-rb/src/di.rs +0 -409
  172. data/vendor/spikard-rb/src/handler.rs +0 -534
  173. data/vendor/spikard-rb/src/lib.rs +0 -2020
  174. data/vendor/spikard-rb/src/lifecycle.rs +0 -267
  175. data/vendor/spikard-rb/src/server.rs +0 -283
  176. data/vendor/spikard-rb/src/sse.rs +0 -231
  177. data/vendor/spikard-rb/src/test_client.rs +0 -404
  178. data/vendor/spikard-rb/src/test_sse.rs +0 -143
  179. data/vendor/spikard-rb/src/test_websocket.rs +0 -221
  180. data/vendor/spikard-rb/src/websocket.rs +0 -233
@@ -1,294 +0,0 @@
1
- //! ServerConfig extraction from Ruby configuration objects.
2
- //!
3
- //! This module handles conversion of Ruby ServerConfig objects
4
- //! into Rust ServerConfig structs for Spikard HTTP server setup.
5
-
6
- #![allow(dead_code)]
7
-
8
- use magnus::prelude::*;
9
- use magnus::{Error, RArray, RHash, Ruby, TryConvert, Value};
10
- use spikard_http::{
11
- ApiKeyConfig, CompressionConfig, ContactInfo, JwtConfig, LicenseInfo, OpenApiConfig, RateLimitConfig, ServerConfig,
12
- ServerInfo, StaticFilesConfig,
13
- };
14
- use std::collections::HashMap;
15
-
16
- use crate::conversion::{get_optional_string_from_hash, get_required_string_from_hash};
17
-
18
- /// Extract a ServerConfig from a Ruby configuration object.
19
- ///
20
- /// Handles all ServerConfig properties including middleware configs,
21
- /// authentication, static files, and OpenAPI documentation settings.
22
- pub fn extract_server_config(ruby: &Ruby, config_value: Value) -> Result<ServerConfig, Error> {
23
- let host: String = config_value.funcall("host", ())?;
24
-
25
- let port: u32 = config_value.funcall("port", ())?;
26
-
27
- let workers: usize = config_value.funcall("workers", ())?;
28
-
29
- let enable_request_id: bool = config_value.funcall("enable_request_id", ())?;
30
-
31
- let max_body_size_value: Value = config_value.funcall("max_body_size", ())?;
32
- let max_body_size = if max_body_size_value.is_nil() {
33
- None
34
- } else {
35
- Some(u64::try_convert(max_body_size_value)? as usize)
36
- };
37
-
38
- let request_timeout_value: Value = config_value.funcall("request_timeout", ())?;
39
- let request_timeout = if request_timeout_value.is_nil() {
40
- None
41
- } else {
42
- Some(u64::try_convert(request_timeout_value)?)
43
- };
44
-
45
- let graceful_shutdown: bool = config_value.funcall("graceful_shutdown", ())?;
46
-
47
- let shutdown_timeout: u64 = config_value.funcall("shutdown_timeout", ())?;
48
-
49
- // Compression config
50
- let compression_value: Value = config_value.funcall("compression", ())?;
51
- let compression = if compression_value.is_nil() {
52
- None
53
- } else {
54
- let gzip: bool = compression_value.funcall("gzip", ())?;
55
- let brotli: bool = compression_value.funcall("brotli", ())?;
56
- let min_size: usize = compression_value.funcall("min_size", ())?;
57
- let quality: u32 = compression_value.funcall("quality", ())?;
58
- Some(CompressionConfig {
59
- gzip,
60
- brotli,
61
- min_size,
62
- quality,
63
- })
64
- };
65
-
66
- // Rate limit config
67
- let rate_limit_value: Value = config_value.funcall("rate_limit", ())?;
68
- let rate_limit = if rate_limit_value.is_nil() {
69
- None
70
- } else {
71
- let per_second: u64 = rate_limit_value.funcall("per_second", ())?;
72
- let burst: u32 = rate_limit_value.funcall("burst", ())?;
73
- let ip_based: bool = rate_limit_value.funcall("ip_based", ())?;
74
- Some(RateLimitConfig {
75
- per_second,
76
- burst,
77
- ip_based,
78
- })
79
- };
80
-
81
- // JWT auth config
82
- let jwt_auth_value: Value = config_value.funcall("jwt_auth", ())?;
83
- let jwt_auth = if jwt_auth_value.is_nil() {
84
- None
85
- } else {
86
- let secret: String = jwt_auth_value.funcall("secret", ())?;
87
- let algorithm: String = jwt_auth_value.funcall("algorithm", ())?;
88
- let audience_value: Value = jwt_auth_value.funcall("audience", ())?;
89
- let audience = if audience_value.is_nil() {
90
- None
91
- } else {
92
- Some(Vec::<String>::try_convert(audience_value)?)
93
- };
94
- let issuer_value: Value = jwt_auth_value.funcall("issuer", ())?;
95
- let issuer = if issuer_value.is_nil() {
96
- None
97
- } else {
98
- Some(String::try_convert(issuer_value)?)
99
- };
100
- let leeway: u64 = jwt_auth_value.funcall("leeway", ())?;
101
- Some(JwtConfig {
102
- secret,
103
- algorithm,
104
- audience,
105
- issuer,
106
- leeway,
107
- })
108
- };
109
-
110
- // API key auth config
111
- let api_key_auth_value: Value = config_value.funcall("api_key_auth", ())?;
112
- let api_key_auth = if api_key_auth_value.is_nil() {
113
- None
114
- } else {
115
- let keys: Vec<String> = api_key_auth_value.funcall("keys", ())?;
116
- let header_name: String = api_key_auth_value.funcall("header_name", ())?;
117
- Some(ApiKeyConfig { keys, header_name })
118
- };
119
-
120
- // Static files config
121
- let static_files_value: Value = config_value.funcall("static_files", ())?;
122
- let static_files_array = RArray::from_value(static_files_value)
123
- .ok_or_else(|| Error::new(ruby.exception_type_error(), "static_files must be an Array"))?;
124
-
125
- let mut static_files = Vec::new();
126
- for i in 0..static_files_array.len() {
127
- let sf_value = static_files_array.entry::<Value>(i as isize)?;
128
- let directory: String = sf_value.funcall("directory", ())?;
129
- let route_prefix: String = sf_value.funcall("route_prefix", ())?;
130
- let index_file: bool = sf_value.funcall("index_file", ())?;
131
- let cache_control_value: Value = sf_value.funcall("cache_control", ())?;
132
- let cache_control = if cache_control_value.is_nil() {
133
- None
134
- } else {
135
- Some(String::try_convert(cache_control_value)?)
136
- };
137
- static_files.push(StaticFilesConfig {
138
- directory,
139
- route_prefix,
140
- index_file,
141
- cache_control,
142
- });
143
- }
144
-
145
- // OpenAPI config
146
- let openapi_value: Value = config_value.funcall("openapi", ())?;
147
- let openapi = if openapi_value.is_nil() {
148
- None
149
- } else {
150
- let enabled: bool = openapi_value.funcall("enabled", ())?;
151
- let title: String = openapi_value.funcall("title", ())?;
152
- let version: String = openapi_value.funcall("version", ())?;
153
- let description_value: Value = openapi_value.funcall("description", ())?;
154
- let description = if description_value.is_nil() {
155
- None
156
- } else {
157
- Some(String::try_convert(description_value)?)
158
- };
159
- let swagger_ui_path: String = openapi_value.funcall("swagger_ui_path", ())?;
160
- let redoc_path: String = openapi_value.funcall("redoc_path", ())?;
161
- let openapi_json_path: String = openapi_value.funcall("openapi_json_path", ())?;
162
-
163
- let contact = extract_contact_info(ruby, &openapi_value)?;
164
- let license = extract_license_info(ruby, &openapi_value)?;
165
- let servers = extract_servers(ruby, &openapi_value)?;
166
-
167
- let security_schemes = HashMap::new();
168
-
169
- Some(OpenApiConfig {
170
- enabled,
171
- title,
172
- version,
173
- description,
174
- swagger_ui_path,
175
- redoc_path,
176
- openapi_json_path,
177
- contact,
178
- license,
179
- servers,
180
- security_schemes,
181
- })
182
- };
183
-
184
- Ok(ServerConfig {
185
- host,
186
- port: port as u16,
187
- workers,
188
- enable_request_id,
189
- max_body_size,
190
- request_timeout,
191
- compression,
192
- rate_limit,
193
- jwt_auth,
194
- api_key_auth,
195
- static_files,
196
- graceful_shutdown,
197
- shutdown_timeout,
198
- background_tasks: spikard_http::BackgroundTaskConfig::default(),
199
- openapi,
200
- lifecycle_hooks: None,
201
- #[cfg(feature = "di")]
202
- di_container: None,
203
- })
204
- }
205
-
206
- /// Extract contact information from OpenAPI config.
207
- fn extract_contact_info(_ruby: &Ruby, openapi_value: &Value) -> Result<Option<ContactInfo>, Error> {
208
- let contact_value: Value = openapi_value.funcall("contact", ())?;
209
- if contact_value.is_nil() {
210
- return Ok(None);
211
- }
212
-
213
- if let Some(contact_hash) = RHash::from_value(contact_value) {
214
- let name = get_optional_string_from_hash(contact_hash, "name")?;
215
- let email = get_optional_string_from_hash(contact_hash, "email")?;
216
- let url = get_optional_string_from_hash(contact_hash, "url")?;
217
- return Ok(Some(ContactInfo { name, email, url }));
218
- }
219
-
220
- let name_value: Value = contact_value.funcall("name", ())?;
221
- let email_value: Value = contact_value.funcall("email", ())?;
222
- let url_value: Value = contact_value.funcall("url", ())?;
223
- Ok(Some(ContactInfo {
224
- name: if name_value.is_nil() {
225
- None
226
- } else {
227
- Some(String::try_convert(name_value)?)
228
- },
229
- email: if email_value.is_nil() {
230
- None
231
- } else {
232
- Some(String::try_convert(email_value)?)
233
- },
234
- url: if url_value.is_nil() {
235
- None
236
- } else {
237
- Some(String::try_convert(url_value)?)
238
- },
239
- }))
240
- }
241
-
242
- /// Extract license information from OpenAPI config.
243
- fn extract_license_info(ruby: &Ruby, openapi_value: &Value) -> Result<Option<LicenseInfo>, Error> {
244
- let license_value: Value = openapi_value.funcall("license", ())?;
245
- if license_value.is_nil() {
246
- return Ok(None);
247
- }
248
-
249
- if let Some(license_hash) = RHash::from_value(license_value) {
250
- let name = get_required_string_from_hash(license_hash, "name", ruby)?;
251
- let url = get_optional_string_from_hash(license_hash, "url")?;
252
- return Ok(Some(LicenseInfo { name, url }));
253
- }
254
-
255
- let name: String = license_value.funcall("name", ())?;
256
- let url_value: Value = license_value.funcall("url", ())?;
257
- let url = if url_value.is_nil() {
258
- None
259
- } else {
260
- Some(String::try_convert(url_value)?)
261
- };
262
- Ok(Some(LicenseInfo { name, url }))
263
- }
264
-
265
- /// Extract server information from OpenAPI config.
266
- fn extract_servers(ruby: &Ruby, openapi_value: &Value) -> Result<Vec<ServerInfo>, Error> {
267
- let servers_value: Value = openapi_value.funcall("servers", ())?;
268
- let servers_array = RArray::from_value(servers_value)
269
- .ok_or_else(|| Error::new(ruby.exception_type_error(), "servers must be an Array"))?;
270
-
271
- let mut servers = Vec::new();
272
- for i in 0..servers_array.len() {
273
- let server_value = servers_array.entry::<Value>(i as isize)?;
274
-
275
- let (url, description) = if let Some(server_hash) = RHash::from_value(server_value) {
276
- let url = get_required_string_from_hash(server_hash, "url", ruby)?;
277
- let description = get_optional_string_from_hash(server_hash, "description")?;
278
- (url, description)
279
- } else {
280
- let url: String = server_value.funcall("url", ())?;
281
- let description_value: Value = server_value.funcall("description", ())?;
282
- let description = if description_value.is_nil() {
283
- None
284
- } else {
285
- Some(String::try_convert(description_value)?)
286
- };
287
- (url, description)
288
- };
289
-
290
- servers.push(ServerInfo { url, description });
291
- }
292
-
293
- Ok(servers)
294
- }
@@ -1,392 +0,0 @@
1
- //! Ruby ↔ Rust type conversion utilities.
2
- //!
3
- //! This module provides functions for converting between Ruby and Rust types,
4
- //! including JSON conversion, string conversion, and request/response building.
5
-
6
- #![allow(dead_code)]
7
-
8
- use bytes::Bytes;
9
- use magnus::prelude::*;
10
- use magnus::{Error, RArray, RHash, RString, Ruby, TryConvert, Value};
11
- use serde_json::Value as JsonValue;
12
- use spikard_http::problem::ProblemDetails;
13
- use spikard_http::testing::MultipartFilePart;
14
- use std::collections::HashMap;
15
-
16
- use crate::test_client::{RequestBody, RequestConfig, TestResponseData};
17
-
18
- /// Convert a Ruby value to JSON.
19
- ///
20
- /// Uses Ruby's JSON.generate method to serialize the Ruby object
21
- /// and then parses the result.
22
- pub fn ruby_value_to_json(ruby: &Ruby, json_module: Value, value: Value) -> Result<JsonValue, Error> {
23
- if value.is_nil() {
24
- return Ok(JsonValue::Null);
25
- }
26
-
27
- let json_string: String = json_module.funcall("generate", (value,))?;
28
- serde_json::from_str(&json_string).map_err(|err| {
29
- Error::new(
30
- ruby.exception_runtime_error(),
31
- format!("Failed to convert Ruby value to JSON: {err}"),
32
- )
33
- })
34
- }
35
-
36
- /// Convert JSON to a Ruby value.
37
- ///
38
- /// Recursively converts JSON types to native Ruby types:
39
- /// - null → nil
40
- /// - bool → true/false
41
- /// - number → integer or float
42
- /// - string → string
43
- /// - array → array
44
- /// - object → hash
45
- pub fn json_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
46
- match value {
47
- JsonValue::Null => Ok(ruby.qnil().as_value()),
48
- JsonValue::Bool(b) => Ok(if *b {
49
- ruby.qtrue().as_value()
50
- } else {
51
- ruby.qfalse().as_value()
52
- }),
53
- JsonValue::Number(num) => {
54
- if let Some(i) = num.as_i64() {
55
- Ok(ruby.integer_from_i64(i).as_value())
56
- } else if let Some(f) = num.as_f64() {
57
- Ok(ruby.float_from_f64(f).as_value())
58
- } else {
59
- Ok(ruby.qnil().as_value())
60
- }
61
- }
62
- JsonValue::String(str_val) => Ok(ruby.str_new(str_val).as_value()),
63
- JsonValue::Array(items) => {
64
- let array = ruby.ary_new();
65
- for item in items {
66
- array.push(json_to_ruby(ruby, item)?)?;
67
- }
68
- Ok(array.as_value())
69
- }
70
- JsonValue::Object(map) => {
71
- let hash = ruby.hash_new();
72
- for (key, item) in map {
73
- hash.aset(ruby.str_new(key), json_to_ruby(ruby, item)?)?;
74
- }
75
- Ok(hash.as_value())
76
- }
77
- }
78
- }
79
-
80
- /// Convert a HashMap to a Ruby Hash.
81
- pub fn map_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, String>) -> Result<Value, Error> {
82
- let hash = ruby.hash_new();
83
- for (key, value) in map {
84
- hash.aset(ruby.str_new(key), ruby.str_new(value))?;
85
- }
86
- Ok(hash.as_value())
87
- }
88
-
89
- /// Convert a HashMap of Vecs to a Ruby Hash with array values.
90
- pub fn multimap_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, Vec<String>>) -> Result<Value, Error> {
91
- let hash = ruby.hash_new();
92
- for (key, values) in map {
93
- let array = ruby.ary_new();
94
- for value in values {
95
- array.push(ruby.str_new(value))?;
96
- }
97
- hash.aset(ruby.str_new(key), array)?;
98
- }
99
- Ok(hash.as_value())
100
- }
101
-
102
- /// Convert a Ruby value to Bytes.
103
- ///
104
- /// Accepts either String or Array of bytes.
105
- pub fn ruby_value_to_bytes(value: Value) -> Result<Bytes, std::io::Error> {
106
- if let Ok(str_value) = RString::try_convert(value) {
107
- // SAFETY: Magnus guarantees RString::as_slice() returns valid UTF-8 (or binary)
108
- // bytes for the lifetime of the RString. The slice is only used within this
109
- // function scope to copy into a Bytes buffer, and does not outlive the RString
110
- // reference. The copy_from_slice operation is safe for the borrowed data.
111
- let slice = unsafe { str_value.as_slice() };
112
- return Ok(Bytes::copy_from_slice(slice));
113
- }
114
-
115
- if let Ok(vec_bytes) = Vec::<u8>::try_convert(value) {
116
- return Ok(Bytes::from(vec_bytes));
117
- }
118
-
119
- Err(std::io::Error::other(
120
- "Streaming chunks must be Strings or Arrays of bytes",
121
- ))
122
- }
123
-
124
- /// Convert a response to a Ruby Hash.
125
- pub fn response_to_ruby(ruby: &Ruby, response: TestResponseData) -> Result<Value, Error> {
126
- let hash = ruby.hash_new();
127
-
128
- hash.aset(
129
- ruby.intern("status_code"),
130
- ruby.integer_from_i64(response.status as i64),
131
- )?;
132
-
133
- let headers_hash = ruby.hash_new();
134
- for (key, value) in response.headers {
135
- headers_hash.aset(ruby.str_new(&key), ruby.str_new(&value))?;
136
- }
137
- hash.aset(ruby.intern("headers"), headers_hash)?;
138
-
139
- if let Some(body) = response.body_text {
140
- let body_value = ruby.str_new(&body);
141
- hash.aset(ruby.intern("body"), body_value)?;
142
- hash.aset(ruby.intern("body_text"), body_value)?;
143
- } else {
144
- hash.aset(ruby.intern("body"), ruby.qnil())?;
145
- hash.aset(ruby.intern("body_text"), ruby.qnil())?;
146
- }
147
-
148
- Ok(hash.as_value())
149
- }
150
-
151
- /// Convert a ProblemDetails to a JSON string.
152
- pub fn problem_to_json(problem: &ProblemDetails) -> String {
153
- problem
154
- .to_json_pretty()
155
- .unwrap_or_else(|err| format!("Failed to serialise problem details: {err}"))
156
- }
157
-
158
- /// Fetch a handler from a Ruby Hash by name.
159
- ///
160
- /// Tries both symbol and string keys.
161
- pub fn fetch_handler(ruby: &Ruby, handlers: &RHash, name: &str) -> Result<Value, Error> {
162
- let symbol_key = ruby.intern(name);
163
- if let Some(value) = handlers.get(symbol_key) {
164
- return Ok(value);
165
- }
166
-
167
- let string_key = ruby.str_new(name);
168
- if let Some(value) = handlers.get(string_key) {
169
- return Ok(value);
170
- }
171
-
172
- Err(Error::new(
173
- ruby.exception_name_error(),
174
- format!("Handler '{name}' not provided"),
175
- ))
176
- }
177
-
178
- /// Get an optional keyword argument from a Ruby Hash.
179
- pub fn get_kw(ruby: &Ruby, hash: RHash, name: &str) -> Option<Value> {
180
- let sym = ruby.intern(name);
181
- hash.get(sym).or_else(|| hash.get(name))
182
- }
183
-
184
- /// Parse request configuration from a Ruby options Hash.
185
- ///
186
- /// Supports: query, headers, cookies, json, data, raw_body, files
187
- pub fn parse_request_config(ruby: &Ruby, options: Value) -> Result<RequestConfig, Error> {
188
- if options.is_nil() {
189
- return Ok(RequestConfig {
190
- query: None,
191
- headers: HashMap::new(),
192
- cookies: HashMap::new(),
193
- body: None,
194
- });
195
- }
196
-
197
- let hash = RHash::from_value(options)
198
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "request options must be a Hash"))?;
199
-
200
- let json_module = ruby
201
- .class_object()
202
- .const_get("JSON")
203
- .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
204
-
205
- let query = if let Some(value) = get_kw(ruby, hash, "query") {
206
- if value.is_nil() {
207
- None
208
- } else {
209
- Some(ruby_value_to_json(ruby, json_module, value)?)
210
- }
211
- } else {
212
- None
213
- };
214
-
215
- let headers = if let Some(value) = get_kw(ruby, hash, "headers") {
216
- if value.is_nil() {
217
- HashMap::new()
218
- } else {
219
- let hash = RHash::try_convert(value)?;
220
- hash.to_hash_map::<String, String>()?
221
- }
222
- } else {
223
- HashMap::new()
224
- };
225
-
226
- let cookies = if let Some(value) = get_kw(ruby, hash, "cookies") {
227
- if value.is_nil() {
228
- HashMap::new()
229
- } else {
230
- let hash = RHash::try_convert(value)?;
231
- hash.to_hash_map::<String, String>()?
232
- }
233
- } else {
234
- HashMap::new()
235
- };
236
-
237
- let files_opt = get_kw(ruby, hash, "files");
238
- let has_files = files_opt.is_some() && !files_opt.unwrap().is_nil();
239
-
240
- let body = if has_files {
241
- let files_value = files_opt.unwrap();
242
- let files = extract_files(ruby, files_value)?;
243
-
244
- let mut form_data = Vec::new();
245
- if let Some(data_value) = get_kw(ruby, hash, "data")
246
- && !data_value.is_nil()
247
- {
248
- let data_hash = RHash::try_convert(data_value)?;
249
-
250
- let keys_array: RArray = data_hash.funcall("keys", ())?;
251
-
252
- for i in 0..keys_array.len() {
253
- let key_val = keys_array.entry::<Value>(i as isize)?;
254
- let field_name = String::try_convert(key_val)?;
255
- let value = data_hash
256
- .get(key_val)
257
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
258
-
259
- if let Some(array) = RArray::from_value(value) {
260
- for j in 0..array.len() {
261
- let item = array.entry::<Value>(j as isize)?;
262
- let item_str = String::try_convert(item)?;
263
- form_data.push((field_name.clone(), item_str));
264
- }
265
- } else {
266
- let value_str = String::try_convert(value)?;
267
- form_data.push((field_name, value_str));
268
- }
269
- }
270
- }
271
-
272
- Some(RequestBody::Multipart { form_data, files })
273
- } else if let Some(value) = get_kw(ruby, hash, "json") {
274
- if value.is_nil() {
275
- None
276
- } else {
277
- Some(RequestBody::Json(ruby_value_to_json(ruby, json_module, value)?))
278
- }
279
- } else if let Some(value) = get_kw(ruby, hash, "data") {
280
- if value.is_nil() {
281
- None
282
- } else {
283
- Some(RequestBody::Form(ruby_value_to_json(ruby, json_module, value)?))
284
- }
285
- } else if let Some(value) = get_kw(ruby, hash, "raw_body") {
286
- if value.is_nil() {
287
- None
288
- } else {
289
- Some(RequestBody::Raw(String::try_convert(value)?))
290
- }
291
- } else {
292
- None
293
- };
294
-
295
- Ok(RequestConfig {
296
- query,
297
- headers,
298
- cookies,
299
- body,
300
- })
301
- }
302
-
303
- /// Extract files from a Ruby Hash.
304
- ///
305
- /// Files can be provided as [filename, content] or [filename, content, content_type]
306
- pub fn extract_files(ruby: &Ruby, files_value: Value) -> Result<Vec<MultipartFilePart>, Error> {
307
- let files_hash = RHash::try_convert(files_value)?;
308
-
309
- let keys_array: RArray = files_hash.funcall("keys", ())?;
310
- let mut result = Vec::new();
311
-
312
- for i in 0..keys_array.len() {
313
- let key_val = keys_array.entry::<Value>(i as isize)?;
314
- let field_name = String::try_convert(key_val)?;
315
- let value = files_hash
316
- .get(key_val)
317
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
318
-
319
- if let Some(outer_array) = RArray::from_value(value) {
320
- if outer_array.is_empty() {
321
- continue;
322
- }
323
-
324
- let first_elem = outer_array.entry::<Value>(0)?;
325
-
326
- if RArray::from_value(first_elem).is_some() {
327
- for j in 0..outer_array.len() {
328
- let file_array = outer_array.entry::<Value>(j as isize)?;
329
- let file_data = extract_single_file(ruby, &field_name, file_array)?;
330
- result.push(file_data);
331
- }
332
- } else {
333
- let file_data = extract_single_file(ruby, &field_name, value)?;
334
- result.push(file_data);
335
- }
336
- }
337
- }
338
-
339
- Ok(result)
340
- }
341
-
342
- /// Extract a single file from a Ruby array [filename, content, content_type (optional)].
343
- pub fn extract_single_file(ruby: &Ruby, field_name: &str, array_value: Value) -> Result<MultipartFilePart, Error> {
344
- let array = RArray::from_value(array_value)
345
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "file must be an Array [filename, content]"))?;
346
-
347
- if array.len() < 2 {
348
- return Err(Error::new(
349
- ruby.exception_arg_error(),
350
- "file Array must have at least 2 elements: [filename, content]",
351
- ));
352
- }
353
-
354
- let filename: String = String::try_convert(array.shift()?)?;
355
- let content_str: String = String::try_convert(array.shift()?)?;
356
- let content = content_str.into_bytes();
357
-
358
- let content_type: Option<String> = if !array.is_empty() {
359
- String::try_convert(array.shift()?).ok()
360
- } else {
361
- None
362
- };
363
-
364
- Ok(MultipartFilePart {
365
- field_name: field_name.to_string(),
366
- filename,
367
- content,
368
- content_type,
369
- })
370
- }
371
-
372
- /// Extract an optional string from a Ruby Hash.
373
- pub fn get_optional_string_from_hash(hash: RHash, key: &str) -> Result<Option<String>, Error> {
374
- match hash.get(String::from(key)) {
375
- Some(v) if !v.is_nil() => Ok(Some(String::try_convert(v)?)),
376
- _ => Ok(None),
377
- }
378
- }
379
-
380
- /// Extract a required string from a Ruby Hash.
381
- pub fn get_required_string_from_hash(hash: RHash, key: &str, ruby: &Ruby) -> Result<String, Error> {
382
- let value = hash
383
- .get(String::from(key))
384
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), format!("missing required key '{}'", key)))?;
385
- if value.is_nil() {
386
- return Err(Error::new(
387
- ruby.exception_arg_error(),
388
- format!("key '{}' cannot be nil", key),
389
- ));
390
- }
391
- String::try_convert(value)
392
- }