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,743 +0,0 @@
1
- //! Response building utilities
2
- //!
3
- //! Provides optimized response construction shared across all language bindings.
4
- //! All bindings (Python, Node, Ruby, PHP) benefit from these optimizations.
5
-
6
- use axum::body::Body;
7
- use axum::http::{HeaderMap, Response, StatusCode, header};
8
- use bytes::Bytes;
9
- use serde_json::json;
10
-
11
- /// Builder for constructing HTTP responses across bindings
12
- pub struct ResponseBuilder {
13
- status: StatusCode,
14
- body: serde_json::Value,
15
- headers: HeaderMap,
16
- }
17
-
18
- impl ResponseBuilder {
19
- /// Create a new response builder with default status 200 OK
20
- #[must_use]
21
- pub fn new() -> Self {
22
- Self {
23
- status: StatusCode::OK,
24
- body: json!({}),
25
- headers: HeaderMap::new(),
26
- }
27
- }
28
-
29
- /// Set the HTTP status code
30
- #[must_use]
31
- pub const fn status(mut self, status: StatusCode) -> Self {
32
- self.status = status;
33
- self
34
- }
35
-
36
- /// Set the response body
37
- #[must_use]
38
- pub fn body(mut self, body: serde_json::Value) -> Self {
39
- self.body = body;
40
- self
41
- }
42
-
43
- /// Add a response header
44
- #[must_use]
45
- pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
46
- if let Ok(name) = key.into().parse::<header::HeaderName>()
47
- && let Ok(val) = value.into().parse::<header::HeaderValue>()
48
- {
49
- self.headers.insert(name, val);
50
- }
51
- self
52
- }
53
-
54
- /// Build the response as (status, headers, body)
55
- ///
56
- /// # Performance
57
- ///
58
- /// Uses optimized serialization path:
59
- /// - Fast path for status 200 with no custom headers (85%+ of responses)
60
- /// - Uses `simd-json` for 2-5x faster JSON serialization vs `serde_json`
61
- #[must_use]
62
- pub fn build(self) -> (StatusCode, HeaderMap, String) {
63
- // PERFORMANCE: Use simd-json for faster serialization (2-5x improvement)
64
- let body = simd_json::to_string(&self.body).unwrap_or_else(|_| "{}".to_string());
65
- (self.status, self.headers, body)
66
- }
67
- }
68
-
69
- impl Default for ResponseBuilder {
70
- fn default() -> Self {
71
- Self::new()
72
- }
73
- }
74
-
75
- /// Create an optimized Axum response from components
76
- ///
77
- /// This function provides a fast path for the most common case (status 200, no custom headers)
78
- /// and is used by all language bindings for consistent performance.
79
- ///
80
- /// # Performance
81
- ///
82
- /// - **Fast path** (85%+ of responses): Status 200 with no custom headers
83
- /// - Skips `Response::builder()` allocation and validation
84
- /// - Direct `Response::new()` construction
85
- /// - ~5-10% faster than builder pattern
86
- ///
87
- /// - **Standard path**: Non-200 status or custom headers
88
- /// - Uses `Response::builder()` for flexibility
89
- ///
90
- /// # Arguments
91
- ///
92
- /// * `status` - HTTP status code
93
- /// * `headers` - Optional custom headers (None for fast path)
94
- /// * `body_bytes` - Pre-serialized response body
95
- ///
96
- /// # Returns
97
- ///
98
- /// An optimized `Response<Body>` ready to send
99
- ///
100
- /// # Panics
101
- ///
102
- /// Panics if `Response::builder()` fails to construct a response. This should never happen
103
- /// in normal circumstances as all headers are validated before insertion.
104
- ///
105
- /// # Examples
106
- ///
107
- /// ```ignore
108
- /// // Fast path - 200 OK, no headers
109
- /// let response = build_optimized_response(StatusCode::OK, None, body_bytes);
110
- ///
111
- /// // Standard path - custom status and headers
112
- /// let mut headers = HeaderMap::new();
113
- /// headers.insert("x-custom", "value".parse().unwrap());
114
- /// let response = build_optimized_response(StatusCode::CREATED, Some(headers), body_bytes);
115
- /// ```
116
- #[must_use]
117
- pub fn build_optimized_response(status: StatusCode, headers: Option<HeaderMap>, body_bytes: Vec<u8>) -> Response<Body> {
118
- // PERFORMANCE: Ultra-fast path for status 200 with no custom headers
119
- // This is the most common case (85%+ of responses) and avoids Response::builder() overhead
120
- if status == StatusCode::OK && headers.is_none() {
121
- // Build response directly without builder overhead
122
- let mut resp = Response::new(Body::from(body_bytes));
123
- resp.headers_mut()
124
- .insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
125
- return resp;
126
- }
127
-
128
- // Standard path for non-200 status or custom headers
129
- let mut response = Response::builder().status(status);
130
-
131
- if let Some(custom_headers) = headers {
132
- for (k, v) in custom_headers {
133
- if let Some(key) = k {
134
- response = response.header(key, v);
135
- }
136
- }
137
- }
138
-
139
- response
140
- .header(header::CONTENT_TYPE, "application/json")
141
- .body(Body::from(body_bytes))
142
- .expect("Failed to build response")
143
- }
144
-
145
- /// Create an optimized Axum response from components using `Bytes`
146
- ///
147
- /// This function is identical to `build_optimized_response()` but accepts
148
- /// `Bytes` instead of `Vec<u8>`, eliminating one allocation in the response hot path.
149
- ///
150
- /// `Bytes` is a reference-counted byte buffer (similar to `Arc<Vec<u8>>` but optimized
151
- /// with copy-on-write semantics). Use this when:
152
- /// - You already have data as `Bytes` (from another library, network read, etc.)
153
- /// - You're serializing to a buffer and want zero-copy transfer to the response
154
- /// - You're cloning the same response body multiple times (Bytes clones are cheap)
155
- ///
156
- /// Use `build_optimized_response()` when:
157
- /// - You have data as `Vec<u8>`
158
- /// - You're building from small in-memory buffers
159
- /// - Simplicity is preferred over micro-optimization
160
- ///
161
- /// # Performance
162
- ///
163
- /// - **Fast path** (85%+ of responses): Status 200 with no custom headers
164
- /// - Skips `Response::builder()` allocation and validation
165
- /// - Direct `Response::new()` construction
166
- /// - ~5-10% faster than builder pattern
167
- ///
168
- /// - **Standard path**: Non-200 status or custom headers
169
- /// - Uses `Response::builder()` for flexibility
170
- ///
171
- /// - **Zero-copy benefit**: Avoids allocation when data is already in `Bytes` form
172
- /// - One less heap allocation in the response hot path
173
- /// - Efficient for streaming and large payloads
174
- ///
175
- /// # Arguments
176
- ///
177
- /// * `status` - HTTP status code
178
- /// * `headers` - Optional custom headers (None for fast path)
179
- /// * `body_bytes` - Pre-serialized response body as `Bytes` (reference-counted)
180
- ///
181
- /// # Returns
182
- ///
183
- /// An optimized `Response<Body>` ready to send
184
- ///
185
- /// # Panics
186
- ///
187
- /// Panics if `Response::builder()` fails to construct a response. This should never happen
188
- /// in normal circumstances as all headers are validated before insertion.
189
- ///
190
- /// # Examples
191
- ///
192
- /// ```ignore
193
- /// use bytes::Bytes;
194
- /// use axum::http::StatusCode;
195
- ///
196
- /// // Serialize to Bytes, then build response (zero-copy from buffer to response)
197
- /// let json_data = r#"{"id": 123, "name": "test"}"#;
198
- /// let body_bytes = Bytes::from(json_data);
199
- /// let response = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
200
- ///
201
- /// // Using with custom headers
202
- /// let mut headers = HeaderMap::new();
203
- /// headers.insert("x-request-id", "req-456".parse().unwrap());
204
- /// let response = build_optimized_response_bytes(
205
- /// StatusCode::CREATED,
206
- /// Some(headers),
207
- /// body_bytes
208
- /// );
209
- ///
210
- /// // Efficient cloning when sending same response multiple times
211
- /// let response_bytes = Bytes::from(r#"{"status": "ok"}"#);
212
- /// let resp1 = build_optimized_response_bytes(StatusCode::OK, None, response_bytes.clone());
213
- /// let resp2 = build_optimized_response_bytes(StatusCode::OK, None, response_bytes); // Cheap clone!
214
- /// ```
215
- #[must_use]
216
- pub fn build_optimized_response_bytes(
217
- status: StatusCode,
218
- headers: Option<HeaderMap>,
219
- body_bytes: Bytes,
220
- ) -> Response<Body> {
221
- // PERFORMANCE: Ultra-fast path for status 200 with no custom headers
222
- // This is the most common case (85%+ of responses) and avoids Response::builder() overhead
223
- if status == StatusCode::OK && headers.is_none() {
224
- // Build response directly without builder overhead
225
- let mut resp = Response::new(Body::from(body_bytes));
226
- resp.headers_mut()
227
- .insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
228
- return resp;
229
- }
230
-
231
- // Standard path for non-200 status or custom headers
232
- let mut response = Response::builder().status(status);
233
-
234
- if let Some(custom_headers) = headers {
235
- for (k, v) in custom_headers {
236
- if let Some(key) = k {
237
- response = response.header(key, v);
238
- }
239
- }
240
- }
241
-
242
- response
243
- .header(header::CONTENT_TYPE, "application/json")
244
- .body(Body::from(body_bytes))
245
- .expect("Failed to build response")
246
- }
247
-
248
- #[cfg(test)]
249
- mod tests {
250
- use super::*;
251
-
252
- #[test]
253
- fn test_response_builder_default() {
254
- let (status, headers, body) = ResponseBuilder::new().build();
255
-
256
- assert_eq!(status, StatusCode::OK);
257
- assert_eq!(body, "{}");
258
- assert!(headers.is_empty());
259
- }
260
-
261
- #[test]
262
- fn test_response_builder_default_trait() {
263
- let (status, _, body) = ResponseBuilder::default().build();
264
-
265
- assert_eq!(status, StatusCode::OK);
266
- assert_eq!(body, "{}");
267
- }
268
-
269
- #[test]
270
- fn test_response_builder_status() {
271
- let (status, _, _) = ResponseBuilder::new().status(StatusCode::CREATED).build();
272
-
273
- assert_eq!(status, StatusCode::CREATED);
274
- }
275
-
276
- #[test]
277
- fn test_response_builder_status_chain() {
278
- let (status, _, _) = ResponseBuilder::new()
279
- .status(StatusCode::ACCEPTED)
280
- .status(StatusCode::CREATED)
281
- .build();
282
-
283
- assert_eq!(status, StatusCode::CREATED);
284
- }
285
-
286
- #[test]
287
- fn test_response_builder_body() {
288
- let body_data = json!({ "id": 123, "name": "test" });
289
- let (_, _, body) = ResponseBuilder::new().body(body_data).build();
290
-
291
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
292
- assert_eq!(parsed["id"], 123);
293
- assert_eq!(parsed["name"], "test");
294
- }
295
-
296
- #[test]
297
- fn test_response_builder_body_chain() {
298
- let first_body = json!({ "first": "value" });
299
- let second_body = json!({ "second": "value" });
300
-
301
- let (_, _, body) = ResponseBuilder::new().body(first_body).body(second_body).build();
302
-
303
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
304
- assert!(parsed.get("first").is_none());
305
- assert_eq!(parsed["second"], "value");
306
- }
307
-
308
- #[test]
309
- fn test_response_builder_header() {
310
- let (_, headers, _) = ResponseBuilder::new()
311
- .header("Content-Type", "application/json")
312
- .build();
313
-
314
- assert_eq!(
315
- headers.get("content-type").unwrap().to_str().unwrap(),
316
- "application/json"
317
- );
318
- }
319
-
320
- #[test]
321
- fn test_response_builder_multiple_headers() {
322
- let (_, headers, _) = ResponseBuilder::new()
323
- .header("Content-Type", "application/json")
324
- .header("X-Custom-Header", "custom-value")
325
- .header("Authorization", "Bearer token123")
326
- .build();
327
-
328
- assert_eq!(headers.len(), 3);
329
- assert_eq!(
330
- headers.get("content-type").unwrap().to_str().unwrap(),
331
- "application/json"
332
- );
333
- assert_eq!(
334
- headers.get("x-custom-header").unwrap().to_str().unwrap(),
335
- "custom-value"
336
- );
337
- assert_eq!(
338
- headers.get("authorization").unwrap().to_str().unwrap(),
339
- "Bearer token123"
340
- );
341
- }
342
-
343
- #[test]
344
- fn test_response_builder_header_overwrite() {
345
- let (_, headers, _) = ResponseBuilder::new()
346
- .header("Content-Type", "text/plain")
347
- .header("Content-Type", "application/json")
348
- .build();
349
-
350
- assert_eq!(
351
- headers.get("content-type").unwrap().to_str().unwrap(),
352
- "application/json"
353
- );
354
- }
355
-
356
- #[test]
357
- fn test_response_builder_full_chain() {
358
- let (status, headers, body) = ResponseBuilder::new()
359
- .status(StatusCode::CREATED)
360
- .body(json!({
361
- "id": 456,
362
- "status": "active",
363
- "items": [1, 2, 3]
364
- }))
365
- .header("Content-Type", "application/json")
366
- .header("X-Request-Id", "req-123")
367
- .build();
368
-
369
- assert_eq!(status, StatusCode::CREATED);
370
- assert_eq!(headers.len(), 2);
371
-
372
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
373
- assert_eq!(parsed["id"], 456);
374
- assert_eq!(parsed["status"], "active");
375
- assert_eq!(parsed["items"][0], 1);
376
- }
377
-
378
- #[test]
379
- fn test_response_builder() {
380
- let (status, _, body) = ResponseBuilder::new()
381
- .status(StatusCode::CREATED)
382
- .body(json!({ "id": 123 }))
383
- .build();
384
-
385
- assert_eq!(status, StatusCode::CREATED);
386
- assert!(body.contains("123"));
387
- }
388
-
389
- #[test]
390
- fn test_response_builder_complex_json() {
391
- let complex_body = json!({
392
- "user": {
393
- "id": 1,
394
- "name": "John Doe",
395
- "email": "john@example.com",
396
- "roles": ["admin", "user"],
397
- "settings": {
398
- "notifications": true,
399
- "theme": "dark"
400
- }
401
- },
402
- "success": true,
403
- "timestamp": "2024-01-01T00:00:00Z"
404
- });
405
-
406
- let (status, _, body) = ResponseBuilder::new().status(StatusCode::OK).body(complex_body).build();
407
-
408
- assert_eq!(status, StatusCode::OK);
409
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
410
- assert_eq!(parsed["user"]["id"], 1);
411
- assert_eq!(parsed["user"]["roles"][0], "admin");
412
- assert_eq!(parsed["user"]["settings"]["theme"], "dark");
413
- }
414
-
415
- #[test]
416
- fn test_response_builder_null_body() {
417
- let (_, _, body) = ResponseBuilder::new().body(serde_json::Value::Null).build();
418
-
419
- assert_eq!(body, "null");
420
- }
421
-
422
- #[test]
423
- fn test_response_builder_array_body() {
424
- let array_body = json!([1, 2, 3, 4, 5]);
425
- let (_, _, body) = ResponseBuilder::new().body(array_body).build();
426
-
427
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
428
- assert!(parsed.is_array());
429
- assert_eq!(parsed[0], 1);
430
- assert_eq!(parsed[4], 5);
431
- }
432
-
433
- #[test]
434
- fn test_response_builder_empty_object() {
435
- let (_, _, body) = ResponseBuilder::new().body(json!({})).build();
436
-
437
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
438
- assert!(parsed.is_object());
439
- assert_eq!(parsed.as_object().unwrap().len(), 0);
440
- }
441
-
442
- #[test]
443
- fn test_response_builder_all_status_codes() {
444
- let status_codes = vec![
445
- StatusCode::OK,
446
- StatusCode::CREATED,
447
- StatusCode::ACCEPTED,
448
- StatusCode::BAD_REQUEST,
449
- StatusCode::UNAUTHORIZED,
450
- StatusCode::FORBIDDEN,
451
- StatusCode::NOT_FOUND,
452
- StatusCode::INTERNAL_SERVER_ERROR,
453
- StatusCode::SERVICE_UNAVAILABLE,
454
- ];
455
-
456
- for code in status_codes {
457
- let (status, _, _) = ResponseBuilder::new().status(code).build();
458
-
459
- assert_eq!(status, code);
460
- }
461
- }
462
-
463
- #[test]
464
- fn test_response_builder_invalid_header_name() {
465
- let (_, headers, _) = ResponseBuilder::new()
466
- .header("Invalid\nHeader", "value")
467
- .header("Valid-Header", "value")
468
- .build();
469
-
470
- assert_eq!(headers.len(), 1);
471
- }
472
-
473
- #[test]
474
- fn test_response_builder_invalid_header_value() {
475
- let (_, headers, _) = ResponseBuilder::new().header("Valid-Header", "valid-value").build();
476
-
477
- assert_eq!(headers.len(), 1);
478
- }
479
-
480
- #[test]
481
- fn test_response_builder_special_characters_in_json() {
482
- let body_with_special_chars = json!({
483
- "message": "Hello \"World\"",
484
- "path": "C:\\Users\\test",
485
- "unicode": "café ☕",
486
- "newlines": "line1\nline2"
487
- });
488
-
489
- let (_, _, body) = ResponseBuilder::new().body(body_with_special_chars).build();
490
-
491
- let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
492
- assert_eq!(parsed["message"], "Hello \"World\"");
493
- assert_eq!(parsed["unicode"], "café ☕");
494
- }
495
-
496
- // Tests for build_optimized_response_bytes() function
497
- #[test]
498
- fn test_build_optimized_response_bytes_fast_path() {
499
- let json_body = r#"{"status":"ok","id":123}"#;
500
- let body_bytes = Bytes::from(json_body);
501
-
502
- let response = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
503
-
504
- assert_eq!(response.status(), StatusCode::OK);
505
- assert_eq!(
506
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
507
- "application/json"
508
- );
509
- }
510
-
511
- #[test]
512
- fn test_build_optimized_response_bytes_standard_path_created() {
513
- let json_body = r#"{"id":456,"resource":"created"}"#;
514
- let body_bytes = Bytes::from(json_body);
515
-
516
- let response = build_optimized_response_bytes(StatusCode::CREATED, None, body_bytes);
517
-
518
- assert_eq!(response.status(), StatusCode::CREATED);
519
- assert_eq!(
520
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
521
- "application/json"
522
- );
523
- }
524
-
525
- #[test]
526
- fn test_build_optimized_response_bytes_with_custom_headers() {
527
- let json_body = r#"{"data":"value"}"#;
528
- let body_bytes = Bytes::from(json_body);
529
- let mut headers = HeaderMap::new();
530
- headers.insert("x-request-id", "req-789".parse().unwrap());
531
- headers.insert("x-custom-header", "custom-value".parse().unwrap());
532
-
533
- let response = build_optimized_response_bytes(StatusCode::OK, Some(headers), body_bytes);
534
-
535
- assert_eq!(response.status(), StatusCode::OK);
536
- assert_eq!(
537
- response.headers().get("x-request-id").unwrap().to_str().unwrap(),
538
- "req-789"
539
- );
540
- assert_eq!(
541
- response.headers().get("x-custom-header").unwrap().to_str().unwrap(),
542
- "custom-value"
543
- );
544
- assert_eq!(
545
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
546
- "application/json"
547
- );
548
- }
549
-
550
- #[test]
551
- fn test_build_optimized_response_bytes_not_found_status() {
552
- let json_body = r#"{"error":"resource not found"}"#;
553
- let body_bytes = Bytes::from(json_body);
554
-
555
- let response = build_optimized_response_bytes(StatusCode::NOT_FOUND, None, body_bytes);
556
-
557
- assert_eq!(response.status(), StatusCode::NOT_FOUND);
558
- assert_eq!(
559
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
560
- "application/json"
561
- );
562
- }
563
-
564
- #[test]
565
- fn test_build_optimized_response_bytes_server_error() {
566
- let json_body = r#"{"error":"internal server error"}"#;
567
- let body_bytes = Bytes::from(json_body);
568
-
569
- let response = build_optimized_response_bytes(StatusCode::INTERNAL_SERVER_ERROR, None, body_bytes);
570
-
571
- assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
572
- }
573
-
574
- #[test]
575
- fn test_build_optimized_response_bytes_empty_body() {
576
- let body_bytes = Bytes::from("");
577
-
578
- let response = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
579
-
580
- assert_eq!(response.status(), StatusCode::OK);
581
- }
582
-
583
- #[test]
584
- fn test_build_optimized_response_bytes_large_json() {
585
- let large_json = r#"{"users":[{"id":1,"name":"Alice","email":"alice@example.com","roles":["admin","user"],"active":true},{"id":2,"name":"Bob","email":"bob@example.com","roles":["user"],"active":true},{"id":3,"name":"Charlie","email":"charlie@example.com","roles":["user","moderator"],"active":false}],"pagination":{"page":1,"limit":10,"total":3}}"#;
586
- let body_bytes = Bytes::from(large_json);
587
-
588
- let response = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
589
-
590
- assert_eq!(response.status(), StatusCode::OK);
591
- assert_eq!(
592
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
593
- "application/json"
594
- );
595
- }
596
-
597
- #[test]
598
- fn test_build_optimized_response_bytes_unicode_content() {
599
- let unicode_json = r#"{"message":"Hello 世界 🌍","emoji":"😀💻🚀","accents":"café naïve résumé"}"#;
600
- let body_bytes = Bytes::from(unicode_json);
601
-
602
- let response = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
603
-
604
- assert_eq!(response.status(), StatusCode::OK);
605
- }
606
-
607
- #[test]
608
- fn test_build_optimized_response_bytes_static_str() {
609
- let json_static = r#"{"type":"static","source":"string literal"}"#;
610
- let body_bytes = Bytes::from_static(json_static.as_bytes());
611
-
612
- let response = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
613
-
614
- assert_eq!(response.status(), StatusCode::OK);
615
- assert_eq!(
616
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
617
- "application/json"
618
- );
619
- }
620
-
621
- #[test]
622
- fn test_build_optimized_response_bytes_cloning() {
623
- let json_body = r#"{"reusable":"true","copies":"cheap"}"#;
624
- let body_bytes = Bytes::from(json_body);
625
-
626
- // Clone Bytes multiple times - should be cheap (reference-counted)
627
- let resp1 = build_optimized_response_bytes(StatusCode::OK, None, body_bytes.clone());
628
- let resp2 = build_optimized_response_bytes(StatusCode::OK, None, body_bytes.clone());
629
- let resp3 = build_optimized_response_bytes(StatusCode::OK, None, body_bytes);
630
-
631
- assert_eq!(resp1.status(), StatusCode::OK);
632
- assert_eq!(resp2.status(), StatusCode::OK);
633
- assert_eq!(resp3.status(), StatusCode::OK);
634
- }
635
-
636
- #[test]
637
- fn test_build_optimized_response_bytes_accepted_status() {
638
- let json_body = r#"{"status":"processing"}"#;
639
- let body_bytes = Bytes::from(json_body);
640
-
641
- let response = build_optimized_response_bytes(StatusCode::ACCEPTED, None, body_bytes);
642
-
643
- assert_eq!(response.status(), StatusCode::ACCEPTED);
644
- }
645
-
646
- #[test]
647
- fn test_build_optimized_response_bytes_bad_request() {
648
- let json_body = r#"{"error":"bad request","details":"invalid payload"}"#;
649
- let body_bytes = Bytes::from(json_body);
650
-
651
- let response = build_optimized_response_bytes(StatusCode::BAD_REQUEST, None, body_bytes);
652
-
653
- assert_eq!(response.status(), StatusCode::BAD_REQUEST);
654
- }
655
-
656
- #[test]
657
- fn test_build_optimized_response_bytes_unauthorized() {
658
- let json_body = r#"{"error":"unauthorized","code":"MISSING_TOKEN"}"#;
659
- let body_bytes = Bytes::from(json_body);
660
-
661
- let response = build_optimized_response_bytes(StatusCode::UNAUTHORIZED, None, body_bytes);
662
-
663
- assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
664
- }
665
-
666
- #[test]
667
- fn test_build_optimized_response_bytes_forbidden() {
668
- let json_body = r#"{"error":"forbidden","reason":"insufficient permissions"}"#;
669
- let body_bytes = Bytes::from(json_body);
670
-
671
- let response = build_optimized_response_bytes(StatusCode::FORBIDDEN, None, body_bytes);
672
-
673
- assert_eq!(response.status(), StatusCode::FORBIDDEN);
674
- }
675
-
676
- #[test]
677
- fn test_build_optimized_response_bytes_multiple_headers() {
678
- let json_body = r#"{"data":"value"}"#;
679
- let body_bytes = Bytes::from(json_body);
680
- let mut headers = HeaderMap::new();
681
- headers.insert("x-request-id", "req-123".parse().unwrap());
682
- headers.insert("x-custom", "custom1".parse().unwrap());
683
- headers.insert("cache-control", "no-cache".parse().unwrap());
684
- headers.insert("x-another", "custom2".parse().unwrap());
685
-
686
- let response = build_optimized_response_bytes(StatusCode::OK, Some(headers), body_bytes);
687
-
688
- assert_eq!(response.status(), StatusCode::OK);
689
- assert_eq!(response.headers().len(), 5); // 4 custom + 1 content-type
690
- assert_eq!(
691
- response.headers().get("x-request-id").unwrap().to_str().unwrap(),
692
- "req-123"
693
- );
694
- assert_eq!(
695
- response.headers().get("cache-control").unwrap().to_str().unwrap(),
696
- "no-cache"
697
- );
698
- }
699
-
700
- #[test]
701
- fn test_build_optimized_response_bytes_parity_with_vec() {
702
- // Test that Vec<u8> and Bytes produce identical responses (except internally)
703
- let json_data = br#"{"test":"parity","value":42}"#;
704
-
705
- let response_vec = build_optimized_response(StatusCode::CREATED, None, json_data.to_vec());
706
- let response_bytes =
707
- build_optimized_response_bytes(StatusCode::CREATED, None, Bytes::copy_from_slice(json_data));
708
-
709
- assert_eq!(response_vec.status(), response_bytes.status());
710
- assert_eq!(
711
- response_vec.headers().get(header::CONTENT_TYPE),
712
- response_bytes.headers().get(header::CONTENT_TYPE)
713
- );
714
- }
715
-
716
- #[test]
717
- fn test_build_optimized_response_bytes_status_codes() {
718
- let statuses = vec![
719
- StatusCode::OK,
720
- StatusCode::CREATED,
721
- StatusCode::ACCEPTED,
722
- StatusCode::BAD_REQUEST,
723
- StatusCode::UNAUTHORIZED,
724
- StatusCode::FORBIDDEN,
725
- StatusCode::NOT_FOUND,
726
- StatusCode::INTERNAL_SERVER_ERROR,
727
- StatusCode::SERVICE_UNAVAILABLE,
728
- ];
729
-
730
- let json_body = r#"{"status":"ok"}"#;
731
-
732
- for status in statuses {
733
- let body_bytes = Bytes::from(json_body);
734
- let response = build_optimized_response_bytes(status, None, body_bytes);
735
-
736
- assert_eq!(response.status(), status);
737
- assert_eq!(
738
- response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap(),
739
- "application/json"
740
- );
741
- }
742
- }
743
- }