spikard 0.4.0-x86_64-linux

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 (138) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +1 -0
  3. data/README.md +659 -0
  4. data/ext/spikard_rb/Cargo.toml +17 -0
  5. data/ext/spikard_rb/extconf.rb +10 -0
  6. data/ext/spikard_rb/src/lib.rs +6 -0
  7. data/lib/spikard/app.rb +405 -0
  8. data/lib/spikard/background.rb +27 -0
  9. data/lib/spikard/config.rb +396 -0
  10. data/lib/spikard/converters.rb +13 -0
  11. data/lib/spikard/handler_wrapper.rb +113 -0
  12. data/lib/spikard/provide.rb +214 -0
  13. data/lib/spikard/response.rb +173 -0
  14. data/lib/spikard/schema.rb +243 -0
  15. data/lib/spikard/sse.rb +111 -0
  16. data/lib/spikard/streaming_response.rb +44 -0
  17. data/lib/spikard/testing.rb +221 -0
  18. data/lib/spikard/upload_file.rb +131 -0
  19. data/lib/spikard/version.rb +5 -0
  20. data/lib/spikard/websocket.rb +59 -0
  21. data/lib/spikard.rb +43 -0
  22. data/sig/spikard.rbs +366 -0
  23. data/vendor/bundle/ruby/3.4.0/gems/diff-lcs-1.6.2/mise.toml +5 -0
  24. data/vendor/bundle/ruby/3.4.0/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +2 -0
  25. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  26. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +139 -0
  27. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +561 -0
  28. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  29. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  30. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +403 -0
  31. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +274 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lib.rs +25 -0
  33. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +298 -0
  34. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +637 -0
  35. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +309 -0
  36. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  37. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +355 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +502 -0
  39. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +389 -0
  40. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +413 -0
  41. data/vendor/crates/spikard-core/Cargo.toml +40 -0
  42. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -0
  43. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -0
  44. data/vendor/crates/spikard-core/src/debug.rs +63 -0
  45. data/vendor/crates/spikard-core/src/di/container.rs +726 -0
  46. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -0
  47. data/vendor/crates/spikard-core/src/di/error.rs +118 -0
  48. data/vendor/crates/spikard-core/src/di/factory.rs +538 -0
  49. data/vendor/crates/spikard-core/src/di/graph.rs +545 -0
  50. data/vendor/crates/spikard-core/src/di/mod.rs +192 -0
  51. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -0
  52. data/vendor/crates/spikard-core/src/di/value.rs +283 -0
  53. data/vendor/crates/spikard-core/src/errors.rs +39 -0
  54. data/vendor/crates/spikard-core/src/http.rs +153 -0
  55. data/vendor/crates/spikard-core/src/lib.rs +29 -0
  56. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -0
  57. data/vendor/crates/spikard-core/src/metadata.rs +397 -0
  58. data/vendor/crates/spikard-core/src/parameters.rs +723 -0
  59. data/vendor/crates/spikard-core/src/problem.rs +310 -0
  60. data/vendor/crates/spikard-core/src/request_data.rs +189 -0
  61. data/vendor/crates/spikard-core/src/router.rs +249 -0
  62. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -0
  63. data/vendor/crates/spikard-core/src/type_hints.rs +304 -0
  64. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +689 -0
  65. data/vendor/crates/spikard-core/src/validation/mod.rs +459 -0
  66. data/vendor/crates/spikard-http/Cargo.toml +58 -0
  67. data/vendor/crates/spikard-http/examples/sse-notifications.rs +147 -0
  68. data/vendor/crates/spikard-http/examples/websocket-chat.rs +91 -0
  69. data/vendor/crates/spikard-http/src/auth.rs +247 -0
  70. data/vendor/crates/spikard-http/src/background.rs +1562 -0
  71. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -0
  72. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -0
  73. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -0
  74. data/vendor/crates/spikard-http/src/cors.rs +490 -0
  75. data/vendor/crates/spikard-http/src/debug.rs +63 -0
  76. data/vendor/crates/spikard-http/src/di_handler.rs +1878 -0
  77. data/vendor/crates/spikard-http/src/handler_response.rs +532 -0
  78. data/vendor/crates/spikard-http/src/handler_trait.rs +861 -0
  79. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -0
  80. data/vendor/crates/spikard-http/src/lib.rs +524 -0
  81. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -0
  82. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -0
  83. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -0
  84. data/vendor/crates/spikard-http/src/middleware/multipart.rs +930 -0
  85. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +541 -0
  86. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -0
  87. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -0
  88. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -0
  89. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +867 -0
  90. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +678 -0
  91. data/vendor/crates/spikard-http/src/query_parser.rs +369 -0
  92. data/vendor/crates/spikard-http/src/response.rs +399 -0
  93. data/vendor/crates/spikard-http/src/server/handler.rs +1557 -0
  94. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -0
  95. data/vendor/crates/spikard-http/src/server/mod.rs +806 -0
  96. data/vendor/crates/spikard-http/src/server/request_extraction.rs +630 -0
  97. data/vendor/crates/spikard-http/src/server/routing_factory.rs +497 -0
  98. data/vendor/crates/spikard-http/src/sse.rs +961 -0
  99. data/vendor/crates/spikard-http/src/testing/form.rs +14 -0
  100. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -0
  101. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -0
  102. data/vendor/crates/spikard-http/src/testing.rs +377 -0
  103. data/vendor/crates/spikard-http/src/websocket.rs +831 -0
  104. data/vendor/crates/spikard-http/tests/background_behavior.rs +918 -0
  105. data/vendor/crates/spikard-http/tests/common/handlers.rs +308 -0
  106. data/vendor/crates/spikard-http/tests/common/mod.rs +21 -0
  107. data/vendor/crates/spikard-http/tests/di_integration.rs +202 -0
  108. data/vendor/crates/spikard-http/tests/doc_snippets.rs +4 -0
  109. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1135 -0
  110. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +688 -0
  111. data/vendor/crates/spikard-http/tests/server_config_builder.rs +324 -0
  112. data/vendor/crates/spikard-http/tests/sse_behavior.rs +728 -0
  113. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +724 -0
  114. data/vendor/crates/spikard-rb/Cargo.toml +43 -0
  115. data/vendor/crates/spikard-rb/build.rs +199 -0
  116. data/vendor/crates/spikard-rb/src/background.rs +63 -0
  117. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  118. data/vendor/crates/spikard-rb/src/config/server_config.rs +283 -0
  119. data/vendor/crates/spikard-rb/src/conversion.rs +459 -0
  120. data/vendor/crates/spikard-rb/src/di/builder.rs +105 -0
  121. data/vendor/crates/spikard-rb/src/di/mod.rs +413 -0
  122. data/vendor/crates/spikard-rb/src/handler.rs +612 -0
  123. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  124. data/vendor/crates/spikard-rb/src/lib.rs +1857 -0
  125. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -0
  126. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +427 -0
  128. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  129. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +326 -0
  130. data/vendor/crates/spikard-rb/src/server.rs +283 -0
  131. data/vendor/crates/spikard-rb/src/sse.rs +231 -0
  132. data/vendor/crates/spikard-rb/src/testing/client.rs +404 -0
  133. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  134. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -0
  135. data/vendor/crates/spikard-rb/src/testing/websocket.rs +221 -0
  136. data/vendor/crates/spikard-rb/src/websocket.rs +233 -0
  137. data/vendor/crates/spikard-rb/tests/magnus_ffi_tests.rs +14 -0
  138. metadata +213 -0
@@ -0,0 +1,403 @@
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
+ // Create an error with deeply nested details to test fallback
396
+ let details = serde_json::Map::new();
397
+ let (_status, body) =
398
+ ErrorResponseBuilder::with_details(StatusCode::BAD_REQUEST, "test", "Test error", Value::Object(details));
399
+
400
+ // Verify we get valid JSON even if serialization fails
401
+ assert!(serde_json::from_str::<Value>(&body).is_ok());
402
+ }
403
+ }
@@ -0,0 +1,274 @@
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::parameters::ParameterValidator;
13
+ use spikard_core::validation::{SchemaValidator, ValidationError};
14
+ use spikard_http::Handler;
15
+ use spikard_http::handler_trait::{HandlerResult, RequestData};
16
+
17
+ use crate::error_response::ErrorResponseBuilder;
18
+
19
+ /// Error type for handler operations
20
+ #[derive(Debug, thiserror::Error)]
21
+ pub enum HandlerError {
22
+ #[error("Validation error: {0}")]
23
+ Validation(String),
24
+
25
+ #[error("Handler execution error: {0}")]
26
+ Execution(String),
27
+
28
+ #[error("Response conversion error: {0}")]
29
+ ResponseConversion(String),
30
+
31
+ #[error("Internal error: {0}")]
32
+ Internal(String),
33
+ }
34
+
35
+ impl From<ValidationError> for HandlerError {
36
+ fn from(err: ValidationError) -> Self {
37
+ HandlerError::Validation(format!("{:?}", err))
38
+ }
39
+ }
40
+
41
+ /// Language-specific handler implementation
42
+ ///
43
+ /// This trait defines the three key operations that every language binding must implement:
44
+ /// 1. Prepare request data for the language runtime
45
+ /// 2. Invoke the handler in the language runtime
46
+ /// 3. Interpret the response from the language runtime
47
+ ///
48
+ /// The `HandlerExecutor` handles all common logic (validation, error formatting)
49
+ /// while delegating language-specific operations to implementations of this trait.
50
+ pub trait LanguageHandler: Send + Sync {
51
+ /// Input type passed to the language handler
52
+ type Input: Send;
53
+
54
+ /// Output type returned from the language handler
55
+ type Output: Send;
56
+
57
+ /// Prepare request data for passing to the language handler
58
+ fn prepare_request(&self, request_data: &RequestData) -> Result<Self::Input, HandlerError>;
59
+
60
+ /// Invoke the language-specific handler with the prepared input
61
+ fn invoke_handler(
62
+ &self,
63
+ input: Self::Input,
64
+ ) -> Pin<Box<dyn Future<Output = Result<Self::Output, HandlerError>> + Send + '_>>;
65
+
66
+ /// Interpret the handler's output and convert it to an HTTP response
67
+ fn interpret_response(&self, output: Self::Output) -> Result<Response<Body>, HandlerError>;
68
+ }
69
+
70
+ /// Universal handler executor that works with any language binding
71
+ ///
72
+ /// This struct consolidates the common handler execution flow:
73
+ /// - Parameter validation
74
+ /// - Request body validation
75
+ /// - Handler invocation
76
+ /// - Error handling and formatting
77
+ ///
78
+ /// Language bindings provide thin wrappers that implement `LanguageHandler`.
79
+ pub struct HandlerExecutor<L: LanguageHandler> {
80
+ language_handler: Arc<L>,
81
+ request_validator: Option<Arc<SchemaValidator>>,
82
+ parameter_validator: Option<Arc<ParameterValidator>>,
83
+ }
84
+
85
+ impl<L: LanguageHandler> HandlerExecutor<L> {
86
+ /// Create a new handler executor
87
+ pub fn new(
88
+ language_handler: Arc<L>,
89
+ request_validator: Option<Arc<SchemaValidator>>,
90
+ parameter_validator: Option<Arc<ParameterValidator>>,
91
+ ) -> Self {
92
+ Self {
93
+ language_handler,
94
+ request_validator,
95
+ parameter_validator,
96
+ }
97
+ }
98
+
99
+ /// Create a handler executor with only a language handler
100
+ pub fn with_handler(language_handler: Arc<L>) -> Self {
101
+ Self {
102
+ language_handler,
103
+ request_validator: None,
104
+ parameter_validator: None,
105
+ }
106
+ }
107
+
108
+ /// Add request validation to this executor
109
+ pub fn with_request_validator(mut self, validator: Arc<SchemaValidator>) -> Self {
110
+ self.request_validator = Some(validator);
111
+ self
112
+ }
113
+
114
+ /// Add parameter validation to this executor
115
+ pub fn with_parameter_validator(mut self, validator: Arc<ParameterValidator>) -> Self {
116
+ self.parameter_validator = Some(validator);
117
+ self
118
+ }
119
+ }
120
+
121
+ impl<L: LanguageHandler + 'static> Handler for HandlerExecutor<L> {
122
+ fn call(
123
+ &self,
124
+ _request: Request<Body>,
125
+ mut request_data: RequestData,
126
+ ) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>> {
127
+ Box::pin(async move {
128
+ // Validate parameters if validator is present
129
+ if let Some(validator) = &self.parameter_validator {
130
+ match validator.validate_and_extract(
131
+ &request_data.query_params,
132
+ &request_data.raw_query_params,
133
+ &request_data.path_params,
134
+ &request_data.headers,
135
+ &request_data.cookies,
136
+ ) {
137
+ Ok(validated_params) => {
138
+ // Merge validated params back into request_data
139
+ request_data.query_params = validated_params;
140
+ }
141
+ Err(validation_err) => {
142
+ return Err(ErrorResponseBuilder::validation_error(&validation_err));
143
+ }
144
+ }
145
+ }
146
+
147
+ // Validate request body if validator is present
148
+ if let Some(validator) = &self.request_validator
149
+ && let Err(validation_err) = validator.validate(&request_data.body)
150
+ {
151
+ return Err(ErrorResponseBuilder::validation_error(&validation_err));
152
+ }
153
+
154
+ // Prepare language-specific input
155
+ let input = self
156
+ .language_handler
157
+ .prepare_request(&request_data)
158
+ .map_err(|e| ErrorResponseBuilder::internal_error(format!("Failed to prepare request: {}", e)))?;
159
+
160
+ // Invoke the language handler
161
+ let output = self
162
+ .language_handler
163
+ .invoke_handler(input)
164
+ .await
165
+ .map_err(|e| ErrorResponseBuilder::internal_error(format!("Handler execution failed: {}", e)))?;
166
+
167
+ // Interpret the response
168
+ let response = self
169
+ .language_handler
170
+ .interpret_response(output)
171
+ .map_err(|e| ErrorResponseBuilder::internal_error(format!("Failed to interpret response: {}", e)))?;
172
+
173
+ Ok(response)
174
+ })
175
+ }
176
+ }
177
+
178
+ #[cfg(test)]
179
+ mod tests {
180
+ use super::*;
181
+ use serde_json::json;
182
+
183
+ struct MockLanguageHandler;
184
+
185
+ impl LanguageHandler for MockLanguageHandler {
186
+ type Input = String;
187
+ type Output = String;
188
+
189
+ fn prepare_request(&self, _data: &RequestData) -> Result<Self::Input, HandlerError> {
190
+ Ok("test_input".to_string())
191
+ }
192
+
193
+ fn invoke_handler(
194
+ &self,
195
+ _input: Self::Input,
196
+ ) -> Pin<Box<dyn Future<Output = Result<Self::Output, HandlerError>> + Send + '_>> {
197
+ Box::pin(async { Ok("test_output".to_string()) })
198
+ }
199
+
200
+ fn interpret_response(&self, output: Self::Output) -> Result<Response<Body>, HandlerError> {
201
+ Ok(Response::builder().status(200).body(Body::from(output)).unwrap())
202
+ }
203
+ }
204
+
205
+ #[tokio::test]
206
+ async fn test_handler_executor_basic() {
207
+ let mock_handler = Arc::new(MockLanguageHandler);
208
+ let executor = HandlerExecutor::new(mock_handler, None, None);
209
+
210
+ let request = Request::builder().body(Body::empty()).unwrap();
211
+ let request_data = RequestData {
212
+ path_params: Arc::new(std::collections::HashMap::new()),
213
+ query_params: json!({}),
214
+ raw_query_params: Arc::new(std::collections::HashMap::new()),
215
+ body: json!({}),
216
+ raw_body: None,
217
+ headers: Arc::new(std::collections::HashMap::new()),
218
+ cookies: Arc::new(std::collections::HashMap::new()),
219
+ method: "GET".to_string(),
220
+ path: "/test".to_string(),
221
+ dependencies: None,
222
+ };
223
+
224
+ let result = executor.call(request, request_data).await;
225
+ assert!(result.is_ok());
226
+ }
227
+
228
+ #[tokio::test]
229
+ async fn test_handler_executor_with_handler_only() {
230
+ let mock_handler = Arc::new(MockLanguageHandler);
231
+ let executor = HandlerExecutor::with_handler(mock_handler);
232
+
233
+ let request = Request::builder().body(Body::empty()).unwrap();
234
+ let request_data = RequestData {
235
+ path_params: Arc::new(std::collections::HashMap::new()),
236
+ query_params: json!({}),
237
+ raw_query_params: Arc::new(std::collections::HashMap::new()),
238
+ body: json!({}),
239
+ raw_body: None,
240
+ headers: Arc::new(std::collections::HashMap::new()),
241
+ cookies: Arc::new(std::collections::HashMap::new()),
242
+ method: "GET".to_string(),
243
+ path: "/test".to_string(),
244
+ dependencies: None,
245
+ };
246
+
247
+ let result = executor.call(request, request_data).await;
248
+ assert!(result.is_ok());
249
+ }
250
+
251
+ #[test]
252
+ fn test_handler_error_validation() {
253
+ let err = HandlerError::Validation("test error".to_string());
254
+ assert_eq!(err.to_string(), "Validation error: test error");
255
+ }
256
+
257
+ #[test]
258
+ fn test_handler_error_execution() {
259
+ let err = HandlerError::Execution("test error".to_string());
260
+ assert_eq!(err.to_string(), "Handler execution error: test error");
261
+ }
262
+
263
+ #[test]
264
+ fn test_handler_error_response_conversion() {
265
+ let err = HandlerError::ResponseConversion("test error".to_string());
266
+ assert_eq!(err.to_string(), "Response conversion error: test error");
267
+ }
268
+
269
+ #[test]
270
+ fn test_handler_error_internal() {
271
+ let err = HandlerError::Internal("test error".to_string());
272
+ assert_eq!(err.to_string(), "Internal error: test error");
273
+ }
274
+ }