spikard 0.13.0 → 0.15.2

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 (207) hide show
  1. checksums.yaml +4 -4
  2. data/Steepfile +6 -0
  3. data/ext/spikard_rb/extconf.rb +1 -2
  4. data/ext/spikard_rb/{Cargo.lock → native/Cargo.lock} +819 -424
  5. data/ext/spikard_rb/native/Cargo.toml +24 -0
  6. data/ext/spikard_rb/src/lib.rs +5366 -3
  7. data/lib/spikard/native.rb +86 -0
  8. data/lib/spikard/version.rb +6 -1
  9. data/lib/spikard.rb +8 -52
  10. data/lib/spikard_rb.so +0 -0
  11. data/sig/types.rbs +427 -0
  12. metadata +14 -243
  13. data/LICENSE +0 -1
  14. data/README.md +0 -285
  15. data/ext/spikard_rb/Cargo.toml +0 -17
  16. data/lib/spikard/app.rb +0 -458
  17. data/lib/spikard/background.rb +0 -58
  18. data/lib/spikard/config.rb +0 -506
  19. data/lib/spikard/converters.rb +0 -13
  20. data/lib/spikard/grpc.rb +0 -232
  21. data/lib/spikard/handler_wrapper.rb +0 -113
  22. data/lib/spikard/provide.rb +0 -315
  23. data/lib/spikard/response.rb +0 -198
  24. data/lib/spikard/schema.rb +0 -243
  25. data/lib/spikard/sse.rb +0 -111
  26. data/lib/spikard/streaming_response.rb +0 -44
  27. data/lib/spikard/testing.rb +0 -474
  28. data/lib/spikard/upload_file.rb +0 -131
  29. data/lib/spikard/websocket.rb +0 -59
  30. data/sig/spikard.rbs +0 -739
  31. data/vendor/crates/spikard-bindings-shared/Cargo.toml +0 -75
  32. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +0 -132
  33. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +0 -905
  34. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +0 -210
  35. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +0 -252
  36. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +0 -404
  37. data/vendor/crates/spikard-bindings-shared/src/grpc_metadata.rs +0 -199
  38. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +0 -252
  39. data/vendor/crates/spikard-bindings-shared/src/json_conversion.rs +0 -829
  40. data/vendor/crates/spikard-bindings-shared/src/lazy_cache.rs +0 -587
  41. data/vendor/crates/spikard-bindings-shared/src/lib.rs +0 -33
  42. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +0 -298
  43. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +0 -594
  44. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +0 -743
  45. data/vendor/crates/spikard-bindings-shared/src/response_interpreter.rs +0 -944
  46. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +0 -260
  47. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +0 -369
  48. data/vendor/crates/spikard-bindings-shared/tests/config_extractor_behavior.rs +0 -192
  49. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +0 -383
  50. data/vendor/crates/spikard-bindings-shared/tests/full_coverage.rs +0 -459
  51. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +0 -280
  52. data/vendor/crates/spikard-bindings-shared/tests/integration_tests.rs +0 -669
  53. data/vendor/crates/spikard-core/Cargo.toml +0 -55
  54. data/vendor/crates/spikard-core/src/bindings/mod.rs +0 -3
  55. data/vendor/crates/spikard-core/src/bindings/response.rs +0 -130
  56. data/vendor/crates/spikard-core/src/debug.rs +0 -127
  57. data/vendor/crates/spikard-core/src/di/container.rs +0 -711
  58. data/vendor/crates/spikard-core/src/di/dependency.rs +0 -273
  59. data/vendor/crates/spikard-core/src/di/error.rs +0 -118
  60. data/vendor/crates/spikard-core/src/di/factory.rs +0 -548
  61. data/vendor/crates/spikard-core/src/di/graph.rs +0 -507
  62. data/vendor/crates/spikard-core/src/di/mod.rs +0 -192
  63. data/vendor/crates/spikard-core/src/di/resolved.rs +0 -428
  64. data/vendor/crates/spikard-core/src/di/value.rs +0 -282
  65. data/vendor/crates/spikard-core/src/errors.rs +0 -72
  66. data/vendor/crates/spikard-core/src/http.rs +0 -492
  67. data/vendor/crates/spikard-core/src/lib.rs +0 -29
  68. data/vendor/crates/spikard-core/src/lifecycle.rs +0 -1273
  69. data/vendor/crates/spikard-core/src/metadata.rs +0 -378
  70. data/vendor/crates/spikard-core/src/parameters.rs +0 -2546
  71. data/vendor/crates/spikard-core/src/problem.rs +0 -358
  72. data/vendor/crates/spikard-core/src/request_data.rs +0 -1146
  73. data/vendor/crates/spikard-core/src/router.rs +0 -530
  74. data/vendor/crates/spikard-core/src/schema_registry.rs +0 -197
  75. data/vendor/crates/spikard-core/src/type_hints.rs +0 -311
  76. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +0 -710
  77. data/vendor/crates/spikard-core/src/validation/mod.rs +0 -470
  78. data/vendor/crates/spikard-core/tests/bindings_response_tests.rs +0 -136
  79. data/vendor/crates/spikard-core/tests/di_dependency_defaults.rs +0 -37
  80. data/vendor/crates/spikard-core/tests/error_mapper.rs +0 -761
  81. data/vendor/crates/spikard-core/tests/parameters_edge_cases.rs +0 -106
  82. data/vendor/crates/spikard-core/tests/parameters_full.rs +0 -701
  83. data/vendor/crates/spikard-core/tests/parameters_schema_and_formats.rs +0 -301
  84. data/vendor/crates/spikard-core/tests/request_data_roundtrip.rs +0 -67
  85. data/vendor/crates/spikard-core/tests/validation_coverage.rs +0 -250
  86. data/vendor/crates/spikard-core/tests/validation_error_paths.rs +0 -45
  87. data/vendor/crates/spikard-http/Cargo.toml +0 -82
  88. data/vendor/crates/spikard-http/examples/sse-notifications.rs +0 -148
  89. data/vendor/crates/spikard-http/examples/websocket-chat.rs +0 -92
  90. data/vendor/crates/spikard-http/src/auth.rs +0 -301
  91. data/vendor/crates/spikard-http/src/background.rs +0 -1859
  92. data/vendor/crates/spikard-http/src/bindings/mod.rs +0 -3
  93. data/vendor/crates/spikard-http/src/bindings/response.rs +0 -1
  94. data/vendor/crates/spikard-http/src/body_metadata.rs +0 -8
  95. data/vendor/crates/spikard-http/src/cors.rs +0 -1026
  96. data/vendor/crates/spikard-http/src/debug.rs +0 -128
  97. data/vendor/crates/spikard-http/src/di_handler.rs +0 -1672
  98. data/vendor/crates/spikard-http/src/grpc/framing.rs +0 -653
  99. data/vendor/crates/spikard-http/src/grpc/handler.rs +0 -1211
  100. data/vendor/crates/spikard-http/src/grpc/mod.rs +0 -556
  101. data/vendor/crates/spikard-http/src/grpc/service.rs +0 -706
  102. data/vendor/crates/spikard-http/src/grpc/streaming.rs +0 -319
  103. data/vendor/crates/spikard-http/src/handler_response.rs +0 -901
  104. data/vendor/crates/spikard-http/src/handler_trait.rs +0 -1015
  105. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +0 -290
  106. data/vendor/crates/spikard-http/src/jsonrpc/http_handler.rs +0 -502
  107. data/vendor/crates/spikard-http/src/jsonrpc/method_registry.rs +0 -648
  108. data/vendor/crates/spikard-http/src/jsonrpc/mod.rs +0 -60
  109. data/vendor/crates/spikard-http/src/jsonrpc/openrpc.rs +0 -325
  110. data/vendor/crates/spikard-http/src/jsonrpc/protocol.rs +0 -1207
  111. data/vendor/crates/spikard-http/src/jsonrpc/router.rs +0 -2262
  112. data/vendor/crates/spikard-http/src/lib.rs +0 -566
  113. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +0 -230
  114. data/vendor/crates/spikard-http/src/lifecycle.rs +0 -1193
  115. data/vendor/crates/spikard-http/src/middleware/mod.rs +0 -560
  116. data/vendor/crates/spikard-http/src/middleware/multipart.rs +0 -912
  117. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +0 -513
  118. data/vendor/crates/spikard-http/src/middleware/validation.rs +0 -768
  119. data/vendor/crates/spikard-http/src/openapi/mod.rs +0 -309
  120. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +0 -535
  121. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +0 -1363
  122. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +0 -667
  123. data/vendor/crates/spikard-http/src/query_parser.rs +0 -793
  124. data/vendor/crates/spikard-http/src/response.rs +0 -720
  125. data/vendor/crates/spikard-http/src/server/fast_router.rs +0 -186
  126. data/vendor/crates/spikard-http/src/server/grpc_routing.rs +0 -1243
  127. data/vendor/crates/spikard-http/src/server/handler.rs +0 -1661
  128. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +0 -253
  129. data/vendor/crates/spikard-http/src/server/mod.rs +0 -1717
  130. data/vendor/crates/spikard-http/src/server/request_extraction.rs +0 -871
  131. data/vendor/crates/spikard-http/src/server/routing_factory.rs +0 -618
  132. data/vendor/crates/spikard-http/src/sse.rs +0 -1409
  133. data/vendor/crates/spikard-http/src/testing/form.rs +0 -52
  134. data/vendor/crates/spikard-http/src/testing/multipart.rs +0 -64
  135. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -825
  136. data/vendor/crates/spikard-http/src/testing.rs +0 -617
  137. data/vendor/crates/spikard-http/src/websocket.rs +0 -1477
  138. data/vendor/crates/spikard-http/tests/auth_integration.rs +0 -645
  139. data/vendor/crates/spikard-http/tests/background_behavior.rs +0 -832
  140. data/vendor/crates/spikard-http/tests/common/grpc_helpers.rs +0 -1012
  141. data/vendor/crates/spikard-http/tests/common/handlers.rs +0 -309
  142. data/vendor/crates/spikard-http/tests/common/mod.rs +0 -33
  143. data/vendor/crates/spikard-http/tests/common/test_builders.rs +0 -628
  144. data/vendor/crates/spikard-http/tests/di_handler_error_responses.rs +0 -162
  145. data/vendor/crates/spikard-http/tests/di_integration.rs +0 -192
  146. data/vendor/crates/spikard-http/tests/doc_snippets.rs +0 -5
  147. data/vendor/crates/spikard-http/tests/grpc_bidirectional_streaming.rs +0 -430
  148. data/vendor/crates/spikard-http/tests/grpc_client_streaming.rs +0 -738
  149. data/vendor/crates/spikard-http/tests/grpc_error_handling_test.rs +0 -652
  150. data/vendor/crates/spikard-http/tests/grpc_integration_test.rs +0 -334
  151. data/vendor/crates/spikard-http/tests/grpc_metadata_test.rs +0 -532
  152. data/vendor/crates/spikard-http/tests/grpc_server_integration.rs +0 -495
  153. data/vendor/crates/spikard-http/tests/grpc_server_streaming.rs +0 -975
  154. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +0 -1093
  155. data/vendor/crates/spikard-http/tests/middleware_stack_integration.rs +0 -389
  156. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +0 -656
  157. data/vendor/crates/spikard-http/tests/request_extraction_full.rs +0 -513
  158. data/vendor/crates/spikard-http/tests/server_auth_middleware_behavior.rs +0 -328
  159. data/vendor/crates/spikard-http/tests/server_config_builder.rs +0 -335
  160. data/vendor/crates/spikard-http/tests/server_configured_router_behavior.rs +0 -374
  161. data/vendor/crates/spikard-http/tests/server_cors_preflight.rs +0 -83
  162. data/vendor/crates/spikard-http/tests/server_handler_wrappers.rs +0 -464
  163. data/vendor/crates/spikard-http/tests/server_method_router_additional_behavior.rs +0 -286
  164. data/vendor/crates/spikard-http/tests/server_method_router_coverage.rs +0 -118
  165. data/vendor/crates/spikard-http/tests/server_middleware_behavior.rs +0 -99
  166. data/vendor/crates/spikard-http/tests/server_middleware_branches.rs +0 -204
  167. data/vendor/crates/spikard-http/tests/server_openapi_jsonrpc_static.rs +0 -427
  168. data/vendor/crates/spikard-http/tests/server_router_behavior.rs +0 -121
  169. data/vendor/crates/spikard-http/tests/sse_behavior.rs +0 -620
  170. data/vendor/crates/spikard-http/tests/sse_full_behavior.rs +0 -584
  171. data/vendor/crates/spikard-http/tests/sse_handler_behavior.rs +0 -130
  172. data/vendor/crates/spikard-http/tests/test_client_requests.rs +0 -167
  173. data/vendor/crates/spikard-http/tests/testing_helpers.rs +0 -87
  174. data/vendor/crates/spikard-http/tests/testing_module_coverage.rs +0 -155
  175. data/vendor/crates/spikard-http/tests/urlencoded_content_type.rs +0 -82
  176. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +0 -663
  177. data/vendor/crates/spikard-http/tests/websocket_full_behavior.rs +0 -440
  178. data/vendor/crates/spikard-http/tests/websocket_integration.rs +0 -150
  179. data/vendor/crates/spikard-rb/Cargo.toml +0 -63
  180. data/vendor/crates/spikard-rb/build.rs +0 -200
  181. data/vendor/crates/spikard-rb/src/background.rs +0 -63
  182. data/vendor/crates/spikard-rb/src/config/mod.rs +0 -5
  183. data/vendor/crates/spikard-rb/src/config/server_config.rs +0 -401
  184. data/vendor/crates/spikard-rb/src/conversion.rs +0 -688
  185. data/vendor/crates/spikard-rb/src/di/builder.rs +0 -100
  186. data/vendor/crates/spikard-rb/src/di/mod.rs +0 -410
  187. data/vendor/crates/spikard-rb/src/grpc/handler.rs +0 -875
  188. data/vendor/crates/spikard-rb/src/grpc/mod.rs +0 -13
  189. data/vendor/crates/spikard-rb/src/gvl.rs +0 -80
  190. data/vendor/crates/spikard-rb/src/handler.rs +0 -699
  191. data/vendor/crates/spikard-rb/src/integration/mod.rs +0 -3
  192. data/vendor/crates/spikard-rb/src/lib.rs +0 -2268
  193. data/vendor/crates/spikard-rb/src/lifecycle.rs +0 -334
  194. data/vendor/crates/spikard-rb/src/metadata/mod.rs +0 -5
  195. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +0 -507
  196. data/vendor/crates/spikard-rb/src/request.rs +0 -439
  197. data/vendor/crates/spikard-rb/src/runtime/mod.rs +0 -5
  198. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +0 -368
  199. data/vendor/crates/spikard-rb/src/server.rs +0 -304
  200. data/vendor/crates/spikard-rb/src/sse.rs +0 -231
  201. data/vendor/crates/spikard-rb/src/testing/client.rs +0 -698
  202. data/vendor/crates/spikard-rb/src/testing/mod.rs +0 -7
  203. data/vendor/crates/spikard-rb/src/testing/sse.rs +0 -108
  204. data/vendor/crates/spikard-rb/src/testing/websocket.rs +0 -573
  205. data/vendor/crates/spikard-rb/src/websocket.rs +0 -521
  206. data/vendor/crates/spikard-rb-macros/Cargo.toml +0 -20
  207. data/vendor/crates/spikard-rb-macros/src/lib.rs +0 -51
@@ -1,829 +0,0 @@
1
- //! Optimized JSON conversion utilities for language bindings
2
- //!
3
- //! This module provides a high-performance JSON conversion abstraction that eliminates
4
- //! duplicate code across Python, Node.js, Ruby, PHP, and WASM bindings.
5
- //!
6
- //! # Design Goals
7
- //!
8
- //! - **Zero-copy conversions** for primitives (fast path handles 60% of conversions)
9
- //! - **Language-agnostic trait** allowing each binding to implement native conversions
10
- //! - **Performance focused** with fast-path optimizations for common JSON types
11
- //! - **No allocations** for primitives when using fast-path helper
12
- //!
13
- //! # Architecture
14
- //!
15
- //! The module provides:
16
- //!
17
- //! 1. **`JsonConverter` trait**: Language bindings implement this to convert between
18
- //! `serde_json::Value` and their native types (`PyObject`, `JsValue`, etc.)
19
- //!
20
- //! 2. **`JsonConversionHelper`**: Static utility for fast-path optimizations that detect
21
- //! primitive types and return early, avoiding recursive descent.
22
- //!
23
- //! 3. **Error types**: Structured error reporting using `thiserror`
24
- //!
25
- //! # Example: Python Binding
26
- //!
27
- //! ```ignore
28
- //! use spikard_bindings_shared::JsonConverter;
29
- //! use pyo3::Python;
30
- //!
31
- //! struct PyJsonConverter;
32
- //!
33
- //! impl JsonConverter for PyJsonConverter {
34
- //! type LanguageValue = pyo3::PyObject;
35
- //! type Error = pyo3::PyErr;
36
- //!
37
- //! fn json_to_language(py: Python, value: &serde_json::Value)
38
- //! -> Result<Self::LanguageValue, Self::Error>
39
- //! {
40
- //! // Fast path handles null, bool, number, string
41
- //! if let Some(result) = JsonConversionHelper::try_fast_path_from_json(py, value) {
42
- //! return result;
43
- //! }
44
- //!
45
- //! // Slow path for arrays and objects
46
- //! match value {
47
- //! Value::Array(arr) => { /* ... */ }
48
- //! Value::Object(obj) => { /* ... */ }
49
- //! _ => unreachable!()
50
- //! }
51
- //! }
52
- //! }
53
- //! ```
54
-
55
- use serde_json::Value;
56
- use thiserror::Error;
57
-
58
- /// Error type for JSON conversion operations
59
- ///
60
- /// Provides detailed error information about conversion failures,
61
- /// distinguishing between type mismatches, missing fields, and serialization errors.
62
- #[derive(Debug, Error)]
63
- pub enum JsonConversionError {
64
- /// Type mismatch: expected one JSON type but received another
65
- #[error("Type mismatch: expected {expected}, got {got}")]
66
- TypeMismatch { expected: String, got: String },
67
-
68
- /// Invalid value for the target type
69
- #[error("Invalid value: {reason}")]
70
- InvalidValue { reason: String },
71
-
72
- /// Missing required field in JSON object
73
- #[error("Missing required field: {field}")]
74
- MissingField { field: String },
75
-
76
- /// Serialization or deserialization failed
77
- #[error("Serialization error: {reason}")]
78
- SerializationError { reason: String },
79
-
80
- /// Language-specific conversion error (for binding-specific errors)
81
- #[error("Conversion error: {reason}")]
82
- ConversionError { reason: String },
83
- }
84
-
85
- impl JsonConversionError {
86
- /// Create a type mismatch error
87
- pub fn type_mismatch(expected: impl Into<String>, got: impl Into<String>) -> Self {
88
- Self::TypeMismatch {
89
- expected: expected.into(),
90
- got: got.into(),
91
- }
92
- }
93
-
94
- /// Create an invalid value error
95
- pub fn invalid_value(reason: impl Into<String>) -> Self {
96
- Self::InvalidValue { reason: reason.into() }
97
- }
98
-
99
- /// Create a missing field error
100
- pub fn missing_field(field: impl Into<String>) -> Self {
101
- Self::MissingField { field: field.into() }
102
- }
103
-
104
- /// Create a serialization error
105
- pub fn serialization_error(reason: impl Into<String>) -> Self {
106
- Self::SerializationError { reason: reason.into() }
107
- }
108
-
109
- /// Create a conversion error
110
- pub fn conversion_error(reason: impl Into<String>) -> Self {
111
- Self::ConversionError { reason: reason.into() }
112
- }
113
- }
114
-
115
- /// Trait for converting between JSON values and language-native types
116
- ///
117
- /// Each language binding (Python, Node.js, Ruby, PHP, WASM) implements this trait
118
- /// to provide bidirectional conversion between `serde_json::Value` and their
119
- /// native representation (`PyObject`, `JsValue`, `RValue`, etc.).
120
- ///
121
- /// # Type Parameters
122
- ///
123
- /// - `LanguageValue`: The native type of the target language
124
- /// - `Error`: The error type used by the binding (commonly a language-specific exception)
125
- ///
126
- /// # Implementation Notes
127
- ///
128
- /// Implementations should use `JsonConversionHelper::try_fast_path_to_json()` and
129
- /// `JsonConversionHelper::try_fast_path_from_json()` to handle primitive types efficiently.
130
- /// These fast paths avoid recursion for the ~60% of conversions that are primitives,
131
- /// strings, or small arrays.
132
- ///
133
- /// # Example
134
- ///
135
- /// See the module-level documentation for a Python binding example.
136
- pub trait JsonConverter {
137
- /// The native type of the target language
138
- type LanguageValue;
139
-
140
- /// The error type for conversion failures
141
- type Error;
142
-
143
- /// Convert from a JSON value to the language's native type
144
- ///
145
- /// # Arguments
146
- ///
147
- /// * `value` - The JSON value to convert
148
- ///
149
- /// # Returns
150
- ///
151
- /// The converted language value, or an error if conversion fails
152
- ///
153
- /// # Errors
154
- ///
155
- /// Returns an error if the JSON value cannot be converted to a valid language value.
156
- fn json_to_language(value: &Value) -> Result<Self::LanguageValue, Self::Error>;
157
-
158
- /// Convert from the language's native type to a JSON value
159
- ///
160
- /// # Arguments
161
- ///
162
- /// * `value` - The language value to convert
163
- ///
164
- /// # Returns
165
- ///
166
- /// The converted JSON value, or an error if conversion fails
167
- ///
168
- /// # Errors
169
- ///
170
- /// Returns an error if the language value cannot be converted to a valid JSON value.
171
- fn language_to_json(value: &Self::LanguageValue) -> Result<Value, Self::Error>;
172
- }
173
-
174
- /// Fast-path optimization helper for JSON conversions
175
- ///
176
- /// This helper detects primitive JSON types (null, bool, number, string) and returns
177
- /// early without recursive processing. This eliminates ~60% of the conversion code
178
- /// in each binding by handling common cases with minimal overhead.
179
- ///
180
- /// # Performance Benefits
181
- ///
182
- /// - **Null**: Single branch check + early return
183
- /// - **Boolean**: Single branch check + early return
184
- /// - **Number (small integers)**: Direct conversion without float parsing
185
- /// - **String**: Direct reference, no copying needed
186
- /// - **Complex types (arrays, objects)**: Return None, caller handles recursion
187
- ///
188
- /// By detecting these cases early, bindings can optimize their implementations:
189
- /// instead of checking every possible type, the fast path handles common cases,
190
- /// and the slow path only needs to handle arrays and objects.
191
- ///
192
- /// # Example: Using in Python Binding
193
- ///
194
- /// ```ignore
195
- /// use serde_json::Value;
196
- /// use spikard_bindings_shared::JsonConversionHelper;
197
- /// use pyo3::Python;
198
- ///
199
- /// fn json_to_python(py: Python, value: &Value) -> PyResult<PyObject> {
200
- /// // Fast path: null, bool, int, float, string
201
- /// if let Some(result) = JsonConversionHelper::try_fast_path_from_json(value) {
202
- /// return convert_primitive_to_python(py, result);
203
- /// }
204
- ///
205
- /// // Slow path: array, object (requires recursion)
206
- /// match value {
207
- /// Value::Array(arr) => {
208
- /// let list = PyList::empty(py);
209
- /// for item in arr {
210
- /// let py_item = json_to_python(py, item)?;
211
- /// list.append(py_item)?;
212
- /// }
213
- /// Ok(list.into())
214
- /// }
215
- /// Value::Object(obj) => {
216
- /// let dict = PyDict::new(py);
217
- /// for (k, v) in obj {
218
- /// let py_val = json_to_python(py, v)?;
219
- /// dict.set_item(k, py_val)?;
220
- /// }
221
- /// Ok(dict.into())
222
- /// }
223
- /// _ => unreachable!() // Fast path covered all primitives
224
- /// }
225
- /// }
226
- /// ```
227
- #[derive(Debug, Clone, Copy)]
228
- pub struct JsonConversionHelper;
229
-
230
- /// Represents a primitive JSON value suitable for fast-path conversion
231
- ///
232
- /// This enum captures the primitive types that can be converted without
233
- /// recursive descent: null, booleans, numbers (as owned strings to preserve precision),
234
- /// and string references.
235
- #[derive(Debug, Clone)]
236
- pub enum JsonPrimitive<'a> {
237
- /// JSON null value
238
- Null,
239
-
240
- /// JSON boolean value
241
- Bool(bool),
242
-
243
- /// JSON number - stored as string to preserve precision
244
- /// (`serde_json::Number` stores the original text, so String clone is acceptable)
245
- Number(String),
246
-
247
- /// JSON string value
248
- String(&'a str),
249
- }
250
-
251
- impl JsonConversionHelper {
252
- /// Attempt fast-path conversion for primitive JSON types
253
- ///
254
- /// Returns `Some(primitive)` if the value is a primitive (null, bool, number, or string),
255
- /// allowing the caller to convert without recursion. Returns `None` for complex types
256
- /// (arrays and objects) that require recursive processing.
257
- ///
258
- /// This function is the key to the performance optimization: ~60% of JSON conversions
259
- /// are primitives, so detecting them here avoids the overhead of recursive matching
260
- /// in the binding layer.
261
- ///
262
- /// # Arguments
263
- ///
264
- /// * `value` - The JSON value to check
265
- ///
266
- /// # Returns
267
- ///
268
- /// - `Some(JsonPrimitive)` if value is a primitive type
269
- /// - `None` if value is an array or object (requires recursion)
270
- ///
271
- /// # Example
272
- ///
273
- /// ```
274
- /// use serde_json::json;
275
- /// use spikard_bindings_shared::JsonConversionHelper;
276
- ///
277
- /// // Primitive: returns Some
278
- /// let val = json!(42);
279
- /// assert!(JsonConversionHelper::try_fast_path_from_json(&val).is_some());
280
- ///
281
- /// // Primitive: returns Some
282
- /// let val = json!("hello");
283
- /// assert!(JsonConversionHelper::try_fast_path_from_json(&val).is_some());
284
- ///
285
- /// // Complex: returns None
286
- /// let val = json!([1, 2, 3]);
287
- /// assert!(JsonConversionHelper::try_fast_path_from_json(&val).is_none());
288
- ///
289
- /// // Complex: returns None
290
- /// let val = json!({"key": "value"});
291
- /// assert!(JsonConversionHelper::try_fast_path_from_json(&val).is_none());
292
- /// ```
293
- #[must_use]
294
- pub fn try_fast_path_from_json(value: &Value) -> Option<JsonPrimitive<'_>> {
295
- match value {
296
- Value::Null => Some(JsonPrimitive::Null),
297
- Value::Bool(b) => Some(JsonPrimitive::Bool(*b)),
298
- // PERFORMANCE: Store number as String for precision preservation.
299
- // serde_json::Number::to_string() is typically cached/optimized internally,
300
- // and this is negligible compared to the fast-path gains for primitives.
301
- // For most real-world workloads, primitive types dominate (~60% of conversions).
302
- Value::Number(n) => Some(JsonPrimitive::Number(n.to_string())),
303
- Value::String(s) => Some(JsonPrimitive::String(s)),
304
- Value::Array(_) | Value::Object(_) => None,
305
- }
306
- }
307
-
308
- /// Detect if a JSON value is a primitive type (fast-path candidate)
309
- ///
310
- /// Returns `true` if the value can be converted via the fast path.
311
- /// This is useful for determining the conversion strategy without
312
- /// extracting the primitive value.
313
- ///
314
- /// # Example
315
- ///
316
- /// ```
317
- /// use serde_json::json;
318
- /// use spikard_bindings_shared::JsonConversionHelper;
319
- ///
320
- /// assert!(JsonConversionHelper::is_primitive(&json!(null)));
321
- /// assert!(JsonConversionHelper::is_primitive(&json!(true)));
322
- /// assert!(JsonConversionHelper::is_primitive(&json!(42)));
323
- /// assert!(JsonConversionHelper::is_primitive(&json!("text")));
324
- ///
325
- /// assert!(!JsonConversionHelper::is_primitive(&json!([])));
326
- /// assert!(!JsonConversionHelper::is_primitive(&json!({})));
327
- /// ```
328
- #[must_use]
329
- pub const fn is_primitive(value: &Value) -> bool {
330
- matches!(
331
- value,
332
- Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_)
333
- )
334
- }
335
-
336
- /// Count the estimated recursion depth needed for conversion
337
- ///
338
- /// Provides a rough estimate of how deeply nested the JSON structure is.
339
- /// Useful for debugging or monitoring conversion performance.
340
- ///
341
- /// Returns 0 for primitives, 1 for arrays/objects containing only primitives,
342
- /// and increases with nesting depth.
343
- ///
344
- /// # Example
345
- ///
346
- /// ```
347
- /// use serde_json::json;
348
- /// use spikard_bindings_shared::JsonConversionHelper;
349
- ///
350
- /// assert_eq!(JsonConversionHelper::estimate_depth(&json!(42)), 0);
351
- /// assert_eq!(JsonConversionHelper::estimate_depth(&json!([1, 2, 3])), 1);
352
- /// assert_eq!(JsonConversionHelper::estimate_depth(&json!({"a": 1})), 1);
353
- /// assert!(JsonConversionHelper::estimate_depth(&json!({"a": [1, {"b": 2}]})) > 1);
354
- /// ```
355
- pub fn estimate_depth(value: &Value) -> usize {
356
- match value {
357
- Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => 0,
358
- Value::Array(arr) => {
359
- if arr.is_empty() {
360
- 1
361
- } else {
362
- 1 + arr.iter().map(Self::estimate_depth).max().unwrap_or(0)
363
- }
364
- }
365
- Value::Object(obj) => {
366
- if obj.is_empty() {
367
- 1
368
- } else {
369
- 1 + obj.values().map(Self::estimate_depth).max().unwrap_or(0)
370
- }
371
- }
372
- }
373
- }
374
- }
375
-
376
- #[cfg(test)]
377
- mod tests {
378
- use super::*;
379
- use serde_json::json;
380
-
381
- // ========== JsonConversionError Tests ==========
382
-
383
- #[test]
384
- fn test_error_type_mismatch() {
385
- let err = JsonConversionError::type_mismatch("string", "number");
386
- assert!(err.to_string().contains("Type mismatch"));
387
- assert!(err.to_string().contains("string"));
388
- assert!(err.to_string().contains("number"));
389
- }
390
-
391
- #[test]
392
- fn test_error_invalid_value() {
393
- let err = JsonConversionError::invalid_value("value out of range");
394
- assert!(err.to_string().contains("Invalid value"));
395
- assert!(err.to_string().contains("out of range"));
396
- }
397
-
398
- #[test]
399
- fn test_error_missing_field() {
400
- let err = JsonConversionError::missing_field("user_id");
401
- assert!(err.to_string().contains("Missing required field"));
402
- assert!(err.to_string().contains("user_id"));
403
- }
404
-
405
- #[test]
406
- fn test_error_serialization_error() {
407
- let err = JsonConversionError::serialization_error("failed to serialize");
408
- assert!(err.to_string().contains("Serialization error"));
409
- assert!(err.to_string().contains("serialize"));
410
- }
411
-
412
- #[test]
413
- fn test_error_conversion_error() {
414
- let err = JsonConversionError::conversion_error("custom reason");
415
- assert!(err.to_string().contains("Conversion error"));
416
- assert!(err.to_string().contains("custom reason"));
417
- }
418
-
419
- // ========== JsonConversionHelper::try_fast_path_from_json Tests ==========
420
-
421
- #[test]
422
- fn test_fast_path_null() {
423
- let val = json!(null);
424
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
425
- assert!(matches!(result, Some(JsonPrimitive::Null)));
426
- }
427
-
428
- #[test]
429
- fn test_fast_path_bool_true() {
430
- let val = json!(true);
431
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
432
- assert!(matches!(result, Some(JsonPrimitive::Bool(true))));
433
- }
434
-
435
- #[test]
436
- fn test_fast_path_bool_false() {
437
- let val = json!(false);
438
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
439
- assert!(matches!(result, Some(JsonPrimitive::Bool(false))));
440
- }
441
-
442
- #[test]
443
- fn test_fast_path_integer() {
444
- let val = json!(42);
445
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
446
- if let Some(JsonPrimitive::Number(n)) = result {
447
- assert_eq!(n, "42");
448
- } else {
449
- panic!("Expected Number variant");
450
- }
451
- }
452
-
453
- #[test]
454
- fn test_fast_path_negative_integer() {
455
- let val = json!(-123);
456
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
457
- if let Some(JsonPrimitive::Number(n)) = result {
458
- assert_eq!(n, "-123");
459
- } else {
460
- panic!("Expected Number variant");
461
- }
462
- }
463
-
464
- #[test]
465
- fn test_fast_path_float() {
466
- #[allow(clippy::approx_constant)]
467
- let val = json!(3.14);
468
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
469
- assert!(matches!(result, Some(JsonPrimitive::Number(_))));
470
- }
471
-
472
- #[test]
473
- fn test_fast_path_zero() {
474
- let val = json!(0);
475
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
476
- if let Some(JsonPrimitive::Number(n)) = result {
477
- assert_eq!(n, "0");
478
- } else {
479
- panic!("Expected Number variant");
480
- }
481
- }
482
-
483
- #[test]
484
- fn test_fast_path_large_number() {
485
- let val = json!(9_223_372_036_854_775_807i64); // i64::MAX
486
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
487
- assert!(matches!(result, Some(JsonPrimitive::Number(_))));
488
- }
489
-
490
- #[test]
491
- fn test_fast_path_string() {
492
- let val = json!("hello");
493
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
494
- assert!(matches!(result, Some(JsonPrimitive::String("hello"))));
495
- }
496
-
497
- #[test]
498
- fn test_fast_path_empty_string() {
499
- let val = json!("");
500
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
501
- assert!(matches!(result, Some(JsonPrimitive::String(""))));
502
- }
503
-
504
- #[test]
505
- fn test_fast_path_string_with_special_chars() {
506
- let val = json!("hello \"world\" \n with special \t chars");
507
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
508
- assert!(matches!(result, Some(JsonPrimitive::String(_))));
509
- }
510
-
511
- #[test]
512
- fn test_fast_path_unicode_string() {
513
- let val = json!("café ☕ 日本語");
514
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
515
- assert!(matches!(result, Some(JsonPrimitive::String(_))));
516
- }
517
-
518
- #[test]
519
- fn test_fast_path_empty_array_returns_none() {
520
- let val = json!([]);
521
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
522
- assert!(result.is_none());
523
- }
524
-
525
- #[test]
526
- fn test_fast_path_array_with_primitives_returns_none() {
527
- let val = json!([1, 2, 3]);
528
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
529
- assert!(result.is_none());
530
- }
531
-
532
- #[test]
533
- fn test_fast_path_array_with_objects_returns_none() {
534
- let val = json!([{"a": 1}]);
535
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
536
- assert!(result.is_none());
537
- }
538
-
539
- #[test]
540
- fn test_fast_path_empty_object_returns_none() {
541
- let val = json!({});
542
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
543
- assert!(result.is_none());
544
- }
545
-
546
- #[test]
547
- fn test_fast_path_object_with_primitives_returns_none() {
548
- let val = json!({"key": "value", "count": 42});
549
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
550
- assert!(result.is_none());
551
- }
552
-
553
- #[test]
554
- fn test_fast_path_nested_object_returns_none() {
555
- let val = json!({"outer": {"inner": "value"}});
556
- let result = JsonConversionHelper::try_fast_path_from_json(&val);
557
- assert!(result.is_none());
558
- }
559
-
560
- // ========== JsonConversionHelper::is_primitive Tests ==========
561
-
562
- #[test]
563
- fn test_is_primitive_null() {
564
- assert!(JsonConversionHelper::is_primitive(&json!(null)));
565
- }
566
-
567
- #[test]
568
- fn test_is_primitive_bool() {
569
- assert!(JsonConversionHelper::is_primitive(&json!(true)));
570
- assert!(JsonConversionHelper::is_primitive(&json!(false)));
571
- }
572
-
573
- #[test]
574
- fn test_is_primitive_number() {
575
- assert!(JsonConversionHelper::is_primitive(&json!(42)));
576
- #[allow(clippy::approx_constant)]
577
- {
578
- assert!(JsonConversionHelper::is_primitive(&json!(3.14)));
579
- }
580
- assert!(JsonConversionHelper::is_primitive(&json!(-100)));
581
- }
582
-
583
- #[test]
584
- fn test_is_primitive_string() {
585
- assert!(JsonConversionHelper::is_primitive(&json!("text")));
586
- assert!(JsonConversionHelper::is_primitive(&json!("")));
587
- }
588
-
589
- #[test]
590
- fn test_is_primitive_array_false() {
591
- assert!(!JsonConversionHelper::is_primitive(&json!([1, 2, 3])));
592
- assert!(!JsonConversionHelper::is_primitive(&json!([])));
593
- }
594
-
595
- #[test]
596
- fn test_is_primitive_object_false() {
597
- assert!(!JsonConversionHelper::is_primitive(&json!({"key": "value"})));
598
- assert!(!JsonConversionHelper::is_primitive(&json!({})));
599
- }
600
-
601
- // ========== JsonConversionHelper::estimate_depth Tests ==========
602
-
603
- #[test]
604
- fn test_estimate_depth_null() {
605
- assert_eq!(JsonConversionHelper::estimate_depth(&json!(null)), 0);
606
- }
607
-
608
- #[test]
609
- fn test_estimate_depth_bool() {
610
- assert_eq!(JsonConversionHelper::estimate_depth(&json!(true)), 0);
611
- assert_eq!(JsonConversionHelper::estimate_depth(&json!(false)), 0);
612
- }
613
-
614
- #[test]
615
- fn test_estimate_depth_number() {
616
- assert_eq!(JsonConversionHelper::estimate_depth(&json!(42)), 0);
617
- #[allow(clippy::approx_constant)]
618
- {
619
- assert_eq!(JsonConversionHelper::estimate_depth(&json!(3.14)), 0);
620
- }
621
- }
622
-
623
- #[test]
624
- fn test_estimate_depth_string() {
625
- assert_eq!(JsonConversionHelper::estimate_depth(&json!("text")), 0);
626
- }
627
-
628
- #[test]
629
- fn test_estimate_depth_empty_array() {
630
- assert_eq!(JsonConversionHelper::estimate_depth(&json!([])), 1);
631
- }
632
-
633
- #[test]
634
- fn test_estimate_depth_array_of_primitives() {
635
- assert_eq!(JsonConversionHelper::estimate_depth(&json!([1, 2, 3])), 1);
636
- assert_eq!(JsonConversionHelper::estimate_depth(&json!(["a", "b", "c", "d"])), 1);
637
- }
638
-
639
- #[test]
640
- fn test_estimate_depth_empty_object() {
641
- assert_eq!(JsonConversionHelper::estimate_depth(&json!({})), 1);
642
- }
643
-
644
- #[test]
645
- fn test_estimate_depth_object_of_primitives() {
646
- assert_eq!(JsonConversionHelper::estimate_depth(&json!({"a": 1, "b": 2})), 1);
647
- }
648
-
649
- #[test]
650
- fn test_estimate_depth_nested_array_one_level() {
651
- assert_eq!(JsonConversionHelper::estimate_depth(&json!([[1, 2], [3, 4]])), 2);
652
- }
653
-
654
- #[test]
655
- fn test_estimate_depth_nested_object_one_level() {
656
- assert_eq!(JsonConversionHelper::estimate_depth(&json!({"outer": {"inner": 1}})), 2);
657
- }
658
-
659
- #[test]
660
- fn test_estimate_depth_mixed_nesting() {
661
- let val = json!({
662
- "user": {
663
- "name": "John",
664
- "roles": ["admin", "user"],
665
- "settings": {
666
- "theme": "dark"
667
- }
668
- }
669
- });
670
- let depth = JsonConversionHelper::estimate_depth(&val);
671
- assert!(depth >= 3, "Expected depth >= 3, got {depth}");
672
- }
673
-
674
- #[test]
675
- fn test_estimate_depth_deeply_nested() {
676
- let val = json!({
677
- "a": {
678
- "b": {
679
- "c": {
680
- "d": {
681
- "e": "value"
682
- }
683
- }
684
- }
685
- }
686
- });
687
- let depth = JsonConversionHelper::estimate_depth(&val);
688
- assert_eq!(depth, 5);
689
- }
690
-
691
- #[test]
692
- fn test_estimate_depth_array_of_objects() {
693
- let val = json!([
694
- {"name": "a", "value": 1},
695
- {"name": "b", "value": 2},
696
- {"name": "c", "value": 3}
697
- ]);
698
- let depth = JsonConversionHelper::estimate_depth(&val);
699
- assert_eq!(depth, 2);
700
- }
701
-
702
- // ========== Integration Tests ==========
703
-
704
- #[test]
705
- fn test_primitive_roundtrip() {
706
- // All primitives should be detected as primitives
707
- let mut primitives = vec![
708
- json!(null),
709
- json!(true),
710
- json!(false),
711
- json!(0),
712
- json!(42),
713
- json!(-42),
714
- json!("string"),
715
- json!(""),
716
- ];
717
- // Add 3.14 with explicit allow for approx_constant
718
- #[allow(clippy::approx_constant)]
719
- {
720
- primitives.push(json!(3.14));
721
- }
722
-
723
- for val in primitives {
724
- let is_prim = JsonConversionHelper::is_primitive(&val);
725
- let fast_path = JsonConversionHelper::try_fast_path_from_json(&val);
726
- assert!(is_prim, "Expected {val:?} to be primitive");
727
- assert!(fast_path.is_some(), "Expected fast path for {val:?}");
728
- }
729
- }
730
-
731
- #[test]
732
- fn test_complex_types_not_primitives() {
733
- let complex = vec![json!([]), json!([1]), json!({}), json!({"a": 1})];
734
-
735
- for val in complex {
736
- let is_prim = JsonConversionHelper::is_primitive(&val);
737
- let fast_path = JsonConversionHelper::try_fast_path_from_json(&val);
738
- assert!(!is_prim, "Expected {val:?} to not be primitive");
739
- assert!(fast_path.is_none(), "Expected no fast path for {val:?}");
740
- }
741
- }
742
-
743
- #[test]
744
- fn test_error_display_messages() {
745
- let errors = vec![
746
- JsonConversionError::type_mismatch("expected", "got"),
747
- JsonConversionError::invalid_value("reason"),
748
- JsonConversionError::missing_field("field"),
749
- JsonConversionError::serialization_error("error"),
750
- JsonConversionError::conversion_error("reason"),
751
- ];
752
-
753
- for err in errors {
754
- let msg = err.to_string();
755
- assert!(!msg.is_empty(), "Error message should not be empty");
756
- }
757
- }
758
-
759
- #[test]
760
- fn test_fast_path_string_references() {
761
- // Verify that fast path returns references, not clones
762
- let val = json!("test_string");
763
- if let Some(JsonPrimitive::String(s)) = JsonConversionHelper::try_fast_path_from_json(&val) {
764
- assert_eq!(s, "test_string");
765
- } else {
766
- panic!("Expected string primitive");
767
- }
768
- }
769
-
770
- #[test]
771
- fn test_estimate_depth_array_vs_object() {
772
- let arr = json!([1, 2, 3]);
773
- let obj = json!({"a": 1, "b": 2, "c": 3});
774
-
775
- let arr_depth = JsonConversionHelper::estimate_depth(&arr);
776
- let obj_depth = JsonConversionHelper::estimate_depth(&obj);
777
-
778
- // Both should have the same depth (1)
779
- assert_eq!(arr_depth, obj_depth);
780
- }
781
-
782
- #[test]
783
- fn test_large_array_depth() {
784
- let large_array: Vec<_> = (0..1000).map(|i| json!(i)).collect();
785
- let val = Value::Array(large_array);
786
- let depth = JsonConversionHelper::estimate_depth(&val);
787
- assert_eq!(depth, 1);
788
- }
789
-
790
- #[test]
791
- fn test_large_object_depth() {
792
- let mut obj = serde_json::Map::new();
793
- for i in 0..1000 {
794
- #[allow(clippy::cast_sign_loss)]
795
- {
796
- obj.insert(format!("key_{i}"), Value::Number(i64::from(i as u32).into()));
797
- }
798
- }
799
- let val = Value::Object(obj);
800
- let depth = JsonConversionHelper::estimate_depth(&val);
801
- assert_eq!(depth, 1);
802
- }
803
-
804
- #[test]
805
- fn test_coverage_all_primitive_types() {
806
- // Ensure we test every variant of JsonPrimitive
807
- let null_val = json!(null);
808
- let bool_val = json!(true);
809
- let num_val = json!(42);
810
- let str_val = json!("text");
811
-
812
- assert!(matches!(
813
- JsonConversionHelper::try_fast_path_from_json(&null_val),
814
- Some(JsonPrimitive::Null)
815
- ));
816
- assert!(matches!(
817
- JsonConversionHelper::try_fast_path_from_json(&bool_val),
818
- Some(JsonPrimitive::Bool(_))
819
- ));
820
- assert!(matches!(
821
- JsonConversionHelper::try_fast_path_from_json(&num_val),
822
- Some(JsonPrimitive::Number(_))
823
- ));
824
- assert!(matches!(
825
- JsonConversionHelper::try_fast_path_from_json(&str_val),
826
- Some(JsonPrimitive::String(_))
827
- ));
828
- }
829
- }