spikard 0.3.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +21 -6
  3. data/ext/spikard_rb/Cargo.toml +2 -2
  4. data/lib/spikard/app.rb +33 -14
  5. data/lib/spikard/testing.rb +47 -12
  6. data/lib/spikard/version.rb +1 -1
  7. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  8. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  9. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  10. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  11. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  12. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  13. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  14. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  15. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  16. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  17. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  18. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  19. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  20. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  21. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  22. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  23. data/vendor/crates/spikard-core/Cargo.toml +4 -4
  24. data/vendor/crates/spikard-core/src/debug.rs +64 -0
  25. data/vendor/crates/spikard-core/src/di/container.rs +3 -27
  26. data/vendor/crates/spikard-core/src/di/factory.rs +1 -5
  27. data/vendor/crates/spikard-core/src/di/graph.rs +8 -47
  28. data/vendor/crates/spikard-core/src/di/mod.rs +1 -1
  29. data/vendor/crates/spikard-core/src/di/resolved.rs +1 -7
  30. data/vendor/crates/spikard-core/src/di/value.rs +2 -4
  31. data/vendor/crates/spikard-core/src/errors.rs +30 -0
  32. data/vendor/crates/spikard-core/src/http.rs +262 -0
  33. data/vendor/crates/spikard-core/src/lib.rs +1 -1
  34. data/vendor/crates/spikard-core/src/lifecycle.rs +764 -0
  35. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  36. data/vendor/crates/spikard-core/src/parameters.rs +1962 -159
  37. data/vendor/crates/spikard-core/src/problem.rs +34 -0
  38. data/vendor/crates/spikard-core/src/request_data.rs +966 -1
  39. data/vendor/crates/spikard-core/src/router.rs +263 -2
  40. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +688 -0
  41. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +26 -268
  42. data/vendor/crates/spikard-http/Cargo.toml +12 -16
  43. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  44. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  45. data/vendor/crates/spikard-http/src/auth.rs +65 -16
  46. data/vendor/crates/spikard-http/src/background.rs +1614 -3
  47. data/vendor/crates/spikard-http/src/cors.rs +515 -0
  48. data/vendor/crates/spikard-http/src/debug.rs +65 -0
  49. data/vendor/crates/spikard-http/src/di_handler.rs +1322 -77
  50. data/vendor/crates/spikard-http/src/handler_response.rs +711 -0
  51. data/vendor/crates/spikard-http/src/handler_trait.rs +607 -5
  52. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +6 -0
  53. data/vendor/crates/spikard-http/src/lib.rs +33 -28
  54. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +81 -0
  55. data/vendor/crates/spikard-http/src/lifecycle.rs +765 -0
  56. data/vendor/crates/spikard-http/src/middleware/mod.rs +372 -117
  57. data/vendor/crates/spikard-http/src/middleware/multipart.rs +836 -10
  58. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +409 -43
  59. data/vendor/crates/spikard-http/src/middleware/validation.rs +513 -65
  60. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +345 -0
  61. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1055 -0
  62. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +473 -3
  63. data/vendor/crates/spikard-http/src/query_parser.rs +455 -31
  64. data/vendor/crates/spikard-http/src/response.rs +321 -0
  65. data/vendor/crates/spikard-http/src/server/handler.rs +1572 -9
  66. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +136 -0
  67. data/vendor/crates/spikard-http/src/server/mod.rs +875 -178
  68. data/vendor/crates/spikard-http/src/server/request_extraction.rs +674 -23
  69. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  70. data/vendor/crates/spikard-http/src/sse.rs +983 -21
  71. data/vendor/crates/spikard-http/src/testing/form.rs +38 -0
  72. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -2
  73. data/vendor/crates/spikard-http/src/testing.rs +7 -7
  74. data/vendor/crates/spikard-http/src/websocket.rs +1055 -4
  75. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  76. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  77. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  78. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  79. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  80. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  81. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  82. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  83. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  84. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  85. data/vendor/crates/spikard-rb/Cargo.toml +10 -4
  86. data/vendor/crates/spikard-rb/build.rs +196 -5
  87. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  88. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +100 -109
  89. data/vendor/crates/spikard-rb/src/conversion.rs +121 -20
  90. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  91. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +12 -46
  92. data/vendor/crates/spikard-rb/src/handler.rs +100 -107
  93. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  94. data/vendor/crates/spikard-rb/src/lib.rs +467 -1428
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +1 -0
  96. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  97. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  98. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  99. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  100. data/vendor/crates/spikard-rb/src/server.rs +47 -22
  101. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +187 -40
  102. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  103. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  104. data/vendor/crates/spikard-rb/src/websocket.rs +178 -37
  105. metadata +46 -13
  106. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  107. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  108. data/vendor/crates/spikard-http/src/router.rs +0 -1
  109. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  110. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  111. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  112. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  113. /data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +0 -0
@@ -0,0 +1,401 @@
1
+ //! Shared error response formatting
2
+ //!
3
+ //! This module consolidates error response building across all language bindings,
4
+ //! eliminating duplicate `structured_error()` functions in Node, Ruby, and PHP bindings.
5
+
6
+ use axum::http::StatusCode;
7
+ use serde_json::Value;
8
+ use spikard_core::errors::StructuredError;
9
+ use spikard_core::problem::ProblemDetails;
10
+ use spikard_core::validation::ValidationError;
11
+
12
+ /// Builder for creating standardized error responses across all bindings
13
+ pub struct ErrorResponseBuilder;
14
+
15
+ impl ErrorResponseBuilder {
16
+ /// Create a structured error response with status code and error details
17
+ ///
18
+ /// Returns a tuple of (StatusCode, JSON body as String)
19
+ ///
20
+ /// # Arguments
21
+ /// * `status` - HTTP status code
22
+ /// * `code` - Machine-readable error code
23
+ /// * `message` - Human-readable error message
24
+ ///
25
+ /// # Example
26
+ /// ```
27
+ /// use axum::http::StatusCode;
28
+ /// use spikard_bindings_shared::ErrorResponseBuilder;
29
+ ///
30
+ /// let (status, body) = ErrorResponseBuilder::structured_error(
31
+ /// StatusCode::BAD_REQUEST,
32
+ /// "invalid_input",
33
+ /// "Missing required field",
34
+ /// );
35
+ /// ```
36
+ pub fn structured_error(status: StatusCode, code: &str, message: impl Into<String>) -> (StatusCode, String) {
37
+ let payload = StructuredError::simple(code.to_string(), message.into());
38
+ let body = serde_json::to_string(&payload)
39
+ .unwrap_or_else(|_| r#"{"error":"serialization_failed","code":"internal_error","details":{}}"#.to_string());
40
+ (status, body)
41
+ }
42
+
43
+ /// Create an error response with additional details
44
+ ///
45
+ /// Returns a tuple of (StatusCode, JSON body as String)
46
+ ///
47
+ /// # Arguments
48
+ /// * `status` - HTTP status code
49
+ /// * `code` - Machine-readable error code
50
+ /// * `message` - Human-readable error message
51
+ /// * `details` - Structured details about the error
52
+ ///
53
+ /// # Example
54
+ /// ```
55
+ /// use axum::http::StatusCode;
56
+ /// use serde_json::json;
57
+ /// use spikard_bindings_shared::ErrorResponseBuilder;
58
+ ///
59
+ /// let details = json!({
60
+ /// "field": "email",
61
+ /// "reason": "invalid_format"
62
+ /// });
63
+ /// let (status, body) = ErrorResponseBuilder::with_details(
64
+ /// StatusCode::BAD_REQUEST,
65
+ /// "validation_error",
66
+ /// "Invalid email format",
67
+ /// details,
68
+ /// );
69
+ /// ```
70
+ pub fn with_details(
71
+ status: StatusCode,
72
+ code: &str,
73
+ message: impl Into<String>,
74
+ details: Value,
75
+ ) -> (StatusCode, String) {
76
+ let payload = StructuredError::new(code.to_string(), message.into(), details);
77
+ let body = serde_json::to_string(&payload)
78
+ .unwrap_or_else(|_| r#"{"error":"serialization_failed","code":"internal_error","details":{}}"#.to_string());
79
+ (status, body)
80
+ }
81
+
82
+ /// Create an error response from a StructuredError
83
+ ///
84
+ /// Returns a tuple of (StatusCode, JSON body as String)
85
+ ///
86
+ /// # Arguments
87
+ /// * `error` - The structured error
88
+ ///
89
+ /// # Note
90
+ /// Uses INTERNAL_SERVER_ERROR as the default status code. Override with
91
+ /// `structured_error()` or `with_details()` for specific status codes.
92
+ pub fn from_structured_error(error: StructuredError) -> (StatusCode, String) {
93
+ let status = StatusCode::INTERNAL_SERVER_ERROR;
94
+ let body = serde_json::to_string(&error)
95
+ .unwrap_or_else(|_| r#"{"error":"serialization_failed","code":"internal_error","details":{}}"#.to_string());
96
+ (status, body)
97
+ }
98
+
99
+ /// Create a validation error response
100
+ ///
101
+ /// Converts ValidationError to RFC 9457 Problem Details format.
102
+ /// Returns (StatusCode::UNPROCESSABLE_ENTITY, JSON body)
103
+ ///
104
+ /// # Arguments
105
+ /// * `validation_error` - The validation error containing one or more details
106
+ ///
107
+ /// # Example
108
+ /// ```
109
+ /// use spikard_core::validation::{ValidationError, ValidationErrorDetail};
110
+ /// use serde_json::Value;
111
+ /// use spikard_bindings_shared::ErrorResponseBuilder;
112
+ ///
113
+ /// let validation_error = ValidationError {
114
+ /// errors: vec![
115
+ /// ValidationErrorDetail {
116
+ /// error_type: "missing".to_string(),
117
+ /// loc: vec!["body".to_string(), "username".to_string()],
118
+ /// msg: "Field required".to_string(),
119
+ /// input: Value::String("".to_string()),
120
+ /// ctx: None,
121
+ /// },
122
+ /// ],
123
+ /// };
124
+ ///
125
+ /// let (status, body) = ErrorResponseBuilder::validation_error(&validation_error);
126
+ /// ```
127
+ pub fn validation_error(validation_error: &ValidationError) -> (StatusCode, String) {
128
+ let problem = ProblemDetails::from_validation_error(validation_error);
129
+ let status = problem.status_code();
130
+ let body = serde_json::to_string(&problem).unwrap_or_else(|_| {
131
+ r#"{"title":"Validation Failed","type":"https://spikard.dev/errors/validation-error","status":422}"#
132
+ .to_string()
133
+ });
134
+ (status, body)
135
+ }
136
+
137
+ /// Create an RFC 9457 Problem Details response
138
+ ///
139
+ /// Returns a tuple of (StatusCode, JSON body as String)
140
+ ///
141
+ /// # Arguments
142
+ /// * `problem` - The Problem Details object
143
+ ///
144
+ /// # Example
145
+ /// ```
146
+ /// use axum::http::StatusCode;
147
+ /// use spikard_core::problem::ProblemDetails;
148
+ /// use spikard_bindings_shared::ErrorResponseBuilder;
149
+ ///
150
+ /// let problem = ProblemDetails::not_found("User with id 123 not found");
151
+ /// let (status, body) = ErrorResponseBuilder::problem_details_response(&problem);
152
+ /// ```
153
+ pub fn problem_details_response(problem: &ProblemDetails) -> (StatusCode, String) {
154
+ let status = problem.status_code();
155
+ let body = serde_json::to_string(problem).unwrap_or_else(|_| {
156
+ r#"{"title":"Internal Server Error","type":"https://spikard.dev/errors/internal-server-error","status":500}"#
157
+ .to_string()
158
+ });
159
+ (status, body)
160
+ }
161
+
162
+ /// Create a generic bad request error
163
+ ///
164
+ /// Returns (StatusCode::BAD_REQUEST, JSON body)
165
+ pub fn bad_request(message: impl Into<String>) -> (StatusCode, String) {
166
+ Self::structured_error(StatusCode::BAD_REQUEST, "bad_request", message)
167
+ }
168
+
169
+ /// Create a generic internal server error
170
+ ///
171
+ /// Returns (StatusCode::INTERNAL_SERVER_ERROR, JSON body)
172
+ pub fn internal_error(message: impl Into<String>) -> (StatusCode, String) {
173
+ Self::structured_error(StatusCode::INTERNAL_SERVER_ERROR, "internal_error", message)
174
+ }
175
+
176
+ /// Create an unauthorized error
177
+ ///
178
+ /// Returns (StatusCode::UNAUTHORIZED, JSON body)
179
+ pub fn unauthorized(message: impl Into<String>) -> (StatusCode, String) {
180
+ Self::structured_error(StatusCode::UNAUTHORIZED, "unauthorized", message)
181
+ }
182
+
183
+ /// Create a forbidden error
184
+ ///
185
+ /// Returns (StatusCode::FORBIDDEN, JSON body)
186
+ pub fn forbidden(message: impl Into<String>) -> (StatusCode, String) {
187
+ Self::structured_error(StatusCode::FORBIDDEN, "forbidden", message)
188
+ }
189
+
190
+ /// Create a not found error
191
+ ///
192
+ /// Returns (StatusCode::NOT_FOUND, JSON body)
193
+ pub fn not_found(message: impl Into<String>) -> (StatusCode, String) {
194
+ Self::structured_error(StatusCode::NOT_FOUND, "not_found", message)
195
+ }
196
+
197
+ /// Create a method not allowed error
198
+ ///
199
+ /// Returns (StatusCode::METHOD_NOT_ALLOWED, JSON body)
200
+ pub fn method_not_allowed(message: impl Into<String>) -> (StatusCode, String) {
201
+ Self::structured_error(StatusCode::METHOD_NOT_ALLOWED, "method_not_allowed", message)
202
+ }
203
+
204
+ /// Create an unprocessable entity error (validation failed)
205
+ ///
206
+ /// Returns (StatusCode::UNPROCESSABLE_ENTITY, JSON body)
207
+ pub fn unprocessable_entity(message: impl Into<String>) -> (StatusCode, String) {
208
+ Self::structured_error(StatusCode::UNPROCESSABLE_ENTITY, "unprocessable_entity", message)
209
+ }
210
+
211
+ /// Create a conflict error
212
+ ///
213
+ /// Returns (StatusCode::CONFLICT, JSON body)
214
+ pub fn conflict(message: impl Into<String>) -> (StatusCode, String) {
215
+ Self::structured_error(StatusCode::CONFLICT, "conflict", message)
216
+ }
217
+
218
+ /// Create a service unavailable error
219
+ ///
220
+ /// Returns (StatusCode::SERVICE_UNAVAILABLE, JSON body)
221
+ pub fn service_unavailable(message: impl Into<String>) -> (StatusCode, String) {
222
+ Self::structured_error(StatusCode::SERVICE_UNAVAILABLE, "service_unavailable", message)
223
+ }
224
+
225
+ /// Create a request timeout error
226
+ ///
227
+ /// Returns (StatusCode::REQUEST_TIMEOUT, JSON body)
228
+ pub fn request_timeout(message: impl Into<String>) -> (StatusCode, String) {
229
+ Self::structured_error(StatusCode::REQUEST_TIMEOUT, "request_timeout", message)
230
+ }
231
+ }
232
+
233
+ #[cfg(test)]
234
+ mod tests {
235
+ use super::*;
236
+ use serde_json::json;
237
+ use spikard_core::validation::ValidationErrorDetail;
238
+
239
+ #[test]
240
+ fn test_structured_error() {
241
+ let (status, body) =
242
+ ErrorResponseBuilder::structured_error(StatusCode::BAD_REQUEST, "invalid_input", "Missing required field");
243
+ assert_eq!(status, StatusCode::BAD_REQUEST);
244
+ let parsed: Value = serde_json::from_str(&body).unwrap();
245
+ assert_eq!(parsed["error"], "Missing required field");
246
+ assert_eq!(parsed["code"], "invalid_input");
247
+ assert!(parsed["details"].is_object());
248
+ }
249
+
250
+ #[test]
251
+ fn test_with_details() {
252
+ let details = json!({
253
+ "field": "email",
254
+ "reason": "invalid_format"
255
+ });
256
+ let (status, body) = ErrorResponseBuilder::with_details(
257
+ StatusCode::BAD_REQUEST,
258
+ "validation_error",
259
+ "Invalid email format",
260
+ details.clone(),
261
+ );
262
+ assert_eq!(status, StatusCode::BAD_REQUEST);
263
+ let parsed: Value = serde_json::from_str(&body).unwrap();
264
+ assert_eq!(parsed["code"], "validation_error");
265
+ assert_eq!(parsed["error"], "Invalid email format");
266
+ assert_eq!(parsed["details"]["field"], "email");
267
+ assert_eq!(parsed["details"]["reason"], "invalid_format");
268
+ }
269
+
270
+ #[test]
271
+ fn test_from_structured_error() {
272
+ let error = StructuredError::simple("test_error", "Something went wrong");
273
+ let (status, body) = ErrorResponseBuilder::from_structured_error(error);
274
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
275
+ let parsed: Value = serde_json::from_str(&body).unwrap();
276
+ assert_eq!(parsed["code"], "test_error");
277
+ assert_eq!(parsed["error"], "Something went wrong");
278
+ }
279
+
280
+ #[test]
281
+ fn test_validation_error() {
282
+ let validation_error = ValidationError {
283
+ errors: vec![ValidationErrorDetail {
284
+ error_type: "missing".to_string(),
285
+ loc: vec!["body".to_string(), "username".to_string()],
286
+ msg: "Field required".to_string(),
287
+ input: Value::String("".to_string()),
288
+ ctx: None,
289
+ }],
290
+ };
291
+
292
+ let (status, body) = ErrorResponseBuilder::validation_error(&validation_error);
293
+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
294
+ let parsed: Value = serde_json::from_str(&body).unwrap();
295
+ assert_eq!(parsed["title"], "Request Validation Failed");
296
+ assert_eq!(parsed["status"], 422);
297
+ assert!(parsed["errors"].is_array());
298
+ }
299
+
300
+ #[test]
301
+ fn test_problem_details_response() {
302
+ let problem = ProblemDetails::not_found("User with id 123 not found");
303
+ let (status, body) = ErrorResponseBuilder::problem_details_response(&problem);
304
+ assert_eq!(status, StatusCode::NOT_FOUND);
305
+ let parsed: Value = serde_json::from_str(&body).unwrap();
306
+ assert_eq!(parsed["type"], "https://spikard.dev/errors/not-found");
307
+ assert_eq!(parsed["title"], "Resource Not Found");
308
+ assert_eq!(parsed["status"], 404);
309
+ }
310
+
311
+ #[test]
312
+ fn test_bad_request() {
313
+ let (status, body) = ErrorResponseBuilder::bad_request("Invalid data");
314
+ assert_eq!(status, StatusCode::BAD_REQUEST);
315
+ let parsed: Value = serde_json::from_str(&body).unwrap();
316
+ assert_eq!(parsed["code"], "bad_request");
317
+ assert_eq!(parsed["error"], "Invalid data");
318
+ }
319
+
320
+ #[test]
321
+ fn test_internal_error() {
322
+ let (status, body) = ErrorResponseBuilder::internal_error("Something went wrong");
323
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
324
+ let parsed: Value = serde_json::from_str(&body).unwrap();
325
+ assert_eq!(parsed["code"], "internal_error");
326
+ assert_eq!(parsed["error"], "Something went wrong");
327
+ }
328
+
329
+ #[test]
330
+ fn test_unauthorized() {
331
+ let (status, body) = ErrorResponseBuilder::unauthorized("Authentication required");
332
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
333
+ let parsed: Value = serde_json::from_str(&body).unwrap();
334
+ assert_eq!(parsed["code"], "unauthorized");
335
+ }
336
+
337
+ #[test]
338
+ fn test_forbidden() {
339
+ let (status, body) = ErrorResponseBuilder::forbidden("Access denied");
340
+ assert_eq!(status, StatusCode::FORBIDDEN);
341
+ let parsed: Value = serde_json::from_str(&body).unwrap();
342
+ assert_eq!(parsed["code"], "forbidden");
343
+ }
344
+
345
+ #[test]
346
+ fn test_not_found() {
347
+ let (status, body) = ErrorResponseBuilder::not_found("Resource not found");
348
+ assert_eq!(status, StatusCode::NOT_FOUND);
349
+ let parsed: Value = serde_json::from_str(&body).unwrap();
350
+ assert_eq!(parsed["code"], "not_found");
351
+ }
352
+
353
+ #[test]
354
+ fn test_method_not_allowed() {
355
+ let (status, body) = ErrorResponseBuilder::method_not_allowed("Method POST not allowed");
356
+ assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
357
+ let parsed: Value = serde_json::from_str(&body).unwrap();
358
+ assert_eq!(parsed["code"], "method_not_allowed");
359
+ }
360
+
361
+ #[test]
362
+ fn test_unprocessable_entity() {
363
+ let (status, body) = ErrorResponseBuilder::unprocessable_entity("Validation failed");
364
+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
365
+ let parsed: Value = serde_json::from_str(&body).unwrap();
366
+ assert_eq!(parsed["code"], "unprocessable_entity");
367
+ }
368
+
369
+ #[test]
370
+ fn test_conflict() {
371
+ let (status, body) = ErrorResponseBuilder::conflict("Resource already exists");
372
+ assert_eq!(status, StatusCode::CONFLICT);
373
+ let parsed: Value = serde_json::from_str(&body).unwrap();
374
+ assert_eq!(parsed["code"], "conflict");
375
+ }
376
+
377
+ #[test]
378
+ fn test_service_unavailable() {
379
+ let (status, body) = ErrorResponseBuilder::service_unavailable("Service temporarily unavailable");
380
+ assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
381
+ let parsed: Value = serde_json::from_str(&body).unwrap();
382
+ assert_eq!(parsed["code"], "service_unavailable");
383
+ }
384
+
385
+ #[test]
386
+ fn test_request_timeout() {
387
+ let (status, body) = ErrorResponseBuilder::request_timeout("Request timed out");
388
+ assert_eq!(status, StatusCode::REQUEST_TIMEOUT);
389
+ let parsed: Value = serde_json::from_str(&body).unwrap();
390
+ assert_eq!(parsed["code"], "request_timeout");
391
+ }
392
+
393
+ #[test]
394
+ fn test_serialization_fallback() {
395
+ let details = serde_json::Map::new();
396
+ let (_status, body) =
397
+ ErrorResponseBuilder::with_details(StatusCode::BAD_REQUEST, "test", "Test error", Value::Object(details));
398
+
399
+ assert!(serde_json::from_str::<Value>(&body).is_ok());
400
+ }
401
+ }
@@ -0,0 +1,238 @@
1
+ //! Base handler traits and execution infrastructure
2
+ //!
3
+ //! This module provides language-agnostic handler execution patterns that
4
+ //! eliminate duplicate code across Node, Ruby, PHP, and WASM bindings.
5
+
6
+ use std::future::Future;
7
+ use std::pin::Pin;
8
+ use std::sync::Arc;
9
+
10
+ use axum::body::Body;
11
+ use axum::http::{Request, Response};
12
+ use spikard_core::validation::{SchemaValidator, ValidationError};
13
+ use spikard_http::Handler;
14
+ use spikard_http::handler_trait::{HandlerResult, RequestData};
15
+
16
+ use crate::error_response::ErrorResponseBuilder;
17
+
18
+ /// Error type for handler operations
19
+ #[derive(Debug, thiserror::Error)]
20
+ pub enum HandlerError {
21
+ #[error("Validation error: {0}")]
22
+ Validation(String),
23
+
24
+ #[error("Handler execution error: {0}")]
25
+ Execution(String),
26
+
27
+ #[error("Response conversion error: {0}")]
28
+ ResponseConversion(String),
29
+
30
+ #[error("Internal error: {0}")]
31
+ Internal(String),
32
+ }
33
+
34
+ impl From<ValidationError> for HandlerError {
35
+ fn from(err: ValidationError) -> Self {
36
+ HandlerError::Validation(format!("{:?}", err))
37
+ }
38
+ }
39
+
40
+ /// Language-specific handler implementation
41
+ ///
42
+ /// This trait defines the three key operations that every language binding must implement:
43
+ /// 1. Prepare request data for the language runtime
44
+ /// 2. Invoke the handler in the language runtime
45
+ /// 3. Interpret the response from the language runtime
46
+ ///
47
+ /// The `HandlerExecutor` handles all common logic (validation, error formatting)
48
+ /// while delegating language-specific operations to implementations of this trait.
49
+ pub trait LanguageHandler: Send + Sync {
50
+ /// Input type passed to the language handler
51
+ type Input: Send;
52
+
53
+ /// Output type returned from the language handler
54
+ type Output: Send;
55
+
56
+ /// Prepare request data for passing to the language handler
57
+ fn prepare_request(&self, request_data: &RequestData) -> Result<Self::Input, HandlerError>;
58
+
59
+ /// Invoke the language-specific handler with the prepared input
60
+ fn invoke_handler(
61
+ &self,
62
+ input: Self::Input,
63
+ ) -> Pin<Box<dyn Future<Output = Result<Self::Output, HandlerError>> + Send + '_>>;
64
+
65
+ /// Interpret the handler's output and convert it to an HTTP response
66
+ fn interpret_response(&self, output: Self::Output) -> Result<Response<Body>, HandlerError>;
67
+ }
68
+
69
+ /// Universal handler executor that works with any language binding
70
+ ///
71
+ /// This struct consolidates the common handler execution flow:
72
+ /// - Request body validation
73
+ /// - Handler invocation
74
+ /// - Error handling and formatting
75
+ ///
76
+ /// Language bindings provide thin wrappers that implement `LanguageHandler`.
77
+ pub struct HandlerExecutor<L: LanguageHandler> {
78
+ language_handler: Arc<L>,
79
+ request_validator: Option<Arc<SchemaValidator>>,
80
+ }
81
+
82
+ impl<L: LanguageHandler> HandlerExecutor<L> {
83
+ /// Create a new handler executor
84
+ pub fn new(language_handler: Arc<L>, request_validator: Option<Arc<SchemaValidator>>) -> Self {
85
+ Self {
86
+ language_handler,
87
+ request_validator,
88
+ }
89
+ }
90
+
91
+ /// Create a handler executor with only a language handler
92
+ pub fn with_handler(language_handler: Arc<L>) -> Self {
93
+ Self {
94
+ language_handler,
95
+ request_validator: None,
96
+ }
97
+ }
98
+
99
+ /// Add request validation to this executor
100
+ pub fn with_request_validator(mut self, validator: Arc<SchemaValidator>) -> Self {
101
+ self.request_validator = Some(validator);
102
+ self
103
+ }
104
+ }
105
+
106
+ impl<L: LanguageHandler + 'static> Handler for HandlerExecutor<L> {
107
+ fn call(
108
+ &self,
109
+ _request: Request<Body>,
110
+ request_data: RequestData,
111
+ ) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>> {
112
+ Box::pin(async move {
113
+ if let Some(validator) = &self.request_validator
114
+ && let Err(validation_err) = validator.validate(&request_data.body)
115
+ {
116
+ return Err(ErrorResponseBuilder::validation_error(&validation_err));
117
+ }
118
+
119
+ let input = self
120
+ .language_handler
121
+ .prepare_request(&request_data)
122
+ .map_err(|e| ErrorResponseBuilder::internal_error(format!("Failed to prepare request: {}", e)))?;
123
+
124
+ let output = self
125
+ .language_handler
126
+ .invoke_handler(input)
127
+ .await
128
+ .map_err(|e| ErrorResponseBuilder::internal_error(format!("Handler execution failed: {}", e)))?;
129
+
130
+ let response = self
131
+ .language_handler
132
+ .interpret_response(output)
133
+ .map_err(|e| ErrorResponseBuilder::internal_error(format!("Failed to interpret response: {}", e)))?;
134
+
135
+ Ok(response)
136
+ })
137
+ }
138
+ }
139
+
140
+ #[cfg(test)]
141
+ mod tests {
142
+ use super::*;
143
+ use serde_json::json;
144
+
145
+ struct MockLanguageHandler;
146
+
147
+ impl LanguageHandler for MockLanguageHandler {
148
+ type Input = String;
149
+ type Output = String;
150
+
151
+ fn prepare_request(&self, _data: &RequestData) -> Result<Self::Input, HandlerError> {
152
+ Ok("test_input".to_string())
153
+ }
154
+
155
+ fn invoke_handler(
156
+ &self,
157
+ _input: Self::Input,
158
+ ) -> Pin<Box<dyn Future<Output = Result<Self::Output, HandlerError>> + Send + '_>> {
159
+ Box::pin(async { Ok("test_output".to_string()) })
160
+ }
161
+
162
+ fn interpret_response(&self, output: Self::Output) -> Result<Response<Body>, HandlerError> {
163
+ Ok(Response::builder().status(200).body(Body::from(output)).unwrap())
164
+ }
165
+ }
166
+
167
+ #[tokio::test]
168
+ async fn test_handler_executor_basic() {
169
+ let mock_handler = Arc::new(MockLanguageHandler);
170
+ let executor = HandlerExecutor::new(mock_handler, None);
171
+
172
+ let request = Request::builder().body(Body::empty()).unwrap();
173
+ let request_data = RequestData {
174
+ path_params: Arc::new(std::collections::HashMap::new()),
175
+ query_params: json!({}),
176
+ validated_params: None,
177
+ raw_query_params: Arc::new(std::collections::HashMap::new()),
178
+ body: json!({}),
179
+ raw_body: None,
180
+ headers: Arc::new(std::collections::HashMap::new()),
181
+ cookies: Arc::new(std::collections::HashMap::new()),
182
+ method: "GET".to_string(),
183
+ path: "/test".to_string(),
184
+ dependencies: None,
185
+ };
186
+
187
+ let result = executor.call(request, request_data).await;
188
+ assert!(result.is_ok());
189
+ }
190
+
191
+ #[tokio::test]
192
+ async fn test_handler_executor_with_handler_only() {
193
+ let mock_handler = Arc::new(MockLanguageHandler);
194
+ let executor = HandlerExecutor::with_handler(mock_handler);
195
+
196
+ let request = Request::builder().body(Body::empty()).unwrap();
197
+ let request_data = RequestData {
198
+ path_params: Arc::new(std::collections::HashMap::new()),
199
+ query_params: json!({}),
200
+ validated_params: None,
201
+ raw_query_params: Arc::new(std::collections::HashMap::new()),
202
+ body: json!({}),
203
+ raw_body: None,
204
+ headers: Arc::new(std::collections::HashMap::new()),
205
+ cookies: Arc::new(std::collections::HashMap::new()),
206
+ method: "GET".to_string(),
207
+ path: "/test".to_string(),
208
+ dependencies: None,
209
+ };
210
+
211
+ let result = executor.call(request, request_data).await;
212
+ assert!(result.is_ok());
213
+ }
214
+
215
+ #[test]
216
+ fn test_handler_error_validation() {
217
+ let err = HandlerError::Validation("test error".to_string());
218
+ assert_eq!(err.to_string(), "Validation error: test error");
219
+ }
220
+
221
+ #[test]
222
+ fn test_handler_error_execution() {
223
+ let err = HandlerError::Execution("test error".to_string());
224
+ assert_eq!(err.to_string(), "Handler execution error: test error");
225
+ }
226
+
227
+ #[test]
228
+ fn test_handler_error_response_conversion() {
229
+ let err = HandlerError::ResponseConversion("test error".to_string());
230
+ assert_eq!(err.to_string(), "Response conversion error: test error");
231
+ }
232
+
233
+ #[test]
234
+ fn test_handler_error_internal() {
235
+ let err = HandlerError::Internal("test error".to_string());
236
+ assert_eq!(err.to_string(), "Internal error: test error");
237
+ }
238
+ }
@@ -0,0 +1,24 @@
1
+ //! Shared utilities for language bindings
2
+ //!
3
+ //! This crate provides common functionality used across all language bindings
4
+ //! (Python, Node.js, Ruby, PHP, WASM) to eliminate code duplication and ensure
5
+ //! consistent behavior.
6
+
7
+ pub mod config_extractor;
8
+ pub mod conversion_traits;
9
+ pub mod di_traits;
10
+ pub mod error_response;
11
+ pub mod handler_base;
12
+ pub mod lifecycle_base;
13
+ pub mod lifecycle_executor;
14
+ pub mod response_builder;
15
+ pub mod test_client_base;
16
+ pub mod validation_helpers;
17
+
18
+ pub use config_extractor::{ConfigExtractor, ConfigSource};
19
+ pub use di_traits::{FactoryDependencyAdapter, ValueDependencyAdapter};
20
+ pub use error_response::ErrorResponseBuilder;
21
+ pub use handler_base::{HandlerError, HandlerExecutor, LanguageHandler};
22
+ pub use lifecycle_executor::{
23
+ HookResultData, LanguageLifecycleHook, LifecycleExecutor, RequestModifications, extract_body,
24
+ };