1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//! Strongly typed response extractors and memory-safe bounded stream decoders.
//!
//! Standard HTTP clients frequently suffer from Out-Of-Memory (OOM) panics when upstream
//! proxies, web application firewalls (e.g. Cloudflare), or faulty backend APIs return
//! multi-gigabyte crash dumps or unbounded streaming error bodies.
//!
//! This module implements the **Extractor Pattern**, unifying deserialization across formats
//! through the [`FromResponse`] trait, while enforcing strict capacity boundaries via
//! chunk-by-chunk streaming decoders.
//!
//! ### Supported Extractors
//!
//! | Extractor | Target Representation | Allocation & Decoding Strategy |
//! | :--- | :--- | :--- |
//! | [`Json<T>`] | Deserialized JSON payload | Buffers up to [`DEFAULT_BODY_LIMIT`] (16 MiB), decodes via [`serde_json`](https://docs.rs/serde_json). |
//! | [`Xml<T>`] | Deserialized XML payload | Buffers up to [`DEFAULT_BODY_LIMIT`] (16 MiB), decodes via [`quick-xml`](https://docs.rs/quick-xml). Requires `"xml"` feature. |
//! | [`Response`] | Raw wire response stream | Zero buffering. Provides direct streaming byte access (e.g. file downloads). |
//! | `()` | Void / Unit type | Zero body allocation on success. Validates HTTP 2xx/3xx status codes. |
//!
//! ### Quick Example
//!
//! ```rust,no_run
//! use moonclient::response::Json;
//! use moonclient::{ClientHook, MoonClient, Result};
//! use serde::Deserialize;
//!
//! #[derive(Debug, Deserialize)]
//! struct ServerStatus {
//! healthy: bool,
//! version: String,
//! }
//!
//! # async fn doc_example<H: ClientHook>(client: &MoonClient<H>) -> Result<()> {
//! let request = client.get("https://api.site.com/health");
//!
//! // The extractor pattern automatically decodes the body based on type inference
//! let Json(status): Json<ServerStatus> = client.execute(request).await?;
//! println!("System health: {}, version: {}", status.healthy, status.version);
//! # Ok(())
//! # }
//! ```
use crateMoonError;
use async_trait;
use Response;
/// Default buffer capacity limit for reading error response payloads (64 KiB).
///
/// Prevents memory exhaustion attacks when upstream proxies return massive HTML error pages.
pub const DEFAULT_ERROR_BODY_LIMIT: usize = 64 * 1024;
/// Default buffer capacity limit for reading successful API response payloads (16 MiB).
///
/// Comfortably accommodates high-volume JSON and XML result sets while preventing unbounded allocations.
pub const DEFAULT_BODY_LIMIT: usize = 16 * 1024 * 1024;
/// Safely streams and buffers asynchronous response chunks up to an enforced byte ceiling.
///
/// # Implementation Details
///
/// 1. Iterates over incoming network chunks asynchronously via [`reqwest::Response::chunk`].
/// 2. Verifies that cumulative buffered bytes do not exceed `max_size`.
/// 3. If the next chunk breaches `max_size`, truncates the buffer precisely at the limit and halts streaming immediately.
/// 4. Converts the accumulated byte vector into a UTF-8 string via lossy conversion ([`String::from_utf8_lossy`]).
///
/// # Arguments
///
/// * `response` ([`Response`](https://docs.rs/reqwest/latest/reqwest/struct.Response.html)) — Raw streaming HTTP response object from `reqwest`.
/// * `max_size` (`usize`) — Maximum permitted buffer capacity in bytes.
///
/// # Returns
///
/// Returns `Ok(String)` containing the decoded text representation up to `max_size` bytes.
///
/// # Errors
///
/// Emits [`MoonError::Network`] if an I/O or connection error occurs while receiving chunks.
///
/// # Example
///
/// ```rust,no_run
/// use moonclient::response::{read_response_text_bounded, DEFAULT_ERROR_BODY_LIMIT};
/// use reqwest::Response;
///
/// # async fn doc_example(response: Response) -> moonclient::Result<()> {
/// // Read up to 64 KiB of error body text safely
/// let error_text = read_response_text_bounded(response, DEFAULT_ERROR_BODY_LIMIT).await?;
/// println!("Safely captured error payload: {}", error_text);
/// # Ok(())
/// # }
/// ```
pub async
/// Abstract contract for parsing and extracting typed values from raw HTTP responses.
///
/// Powers the unified [`MoonClient::execute`](crate::client::MoonClient::execute) pipeline,
/// replacing disparate format-specific execution methods with idiomatic generic type inference.
/// Extractor implementation for empty HTTP responses (unit type replacement for `execute_void`).
///
/// Validates that the HTTP status falls within the successful range (2xx/3xx)
/// without allocating heap memory to decode or deserialize the response body.
///
/// # Implementation Details
///
/// * **HTTP 2xx/3xx:** Immediately returns `Ok(())` with zero body reads.
/// * **HTTP 4xx/5xx:** Reads up to [`DEFAULT_ERROR_BODY_LIMIT`] (64 KiB) to build an informative [`MoonError::ApiError`].
///
/// # Example
///
/// ```rust,no_run
/// use moonclient::{ClientHook, MoonClient, Result};
///
/// # async fn doc_example<H: ClientHook>(client: &MoonClient<H>) -> Result<()> {
/// let delete_request = client.delete("https://api.site.com/items/123");
///
/// // Extracting unit `()` confirms successful HTTP 204 No Content or 200 OK
/// client.execute::<()>(delete_request).await?;
/// println!("Resource deleted successfully!");
/// # Ok(())
/// # }
/// ```
/// Extractor implementation yielding the raw [`reqwest::Response`](https://docs.rs/reqwest/latest/reqwest/struct.Response.html) object.
///
/// Grants consumer API clients low-level access to the response stream
/// (e.g., for byte-level binary file downloads with CLI progress bars),
/// while guaranteeing execution through all configured pre-request and post-response hooks.
///
/// # Errors
///
/// Returns [`MoonError::ApiError`] if the server returned an unsuccessful HTTP status code.
///
/// # Example
///
/// ```rust,no_run
/// use moonclient::{ClientHook, MoonClient, Result};
/// use reqwest::Response;
///
/// # async fn doc_example<H: ClientHook>(client: &MoonClient<H>) -> Result<()> {
/// let download_request = client.get("https://site.com/large_archive.zip");
///
/// // Extract raw response stream for custom chunk-by-chunk processing
/// let raw_stream: Response = client.execute(download_request).await?;
/// println!("Streaming content length: {:?}", raw_stream.content_length());
/// # Ok(())
/// # }
/// ```
/// Extractor for automatically decoding JSON payloads from response bodies.
///
/// Wraps the deserialized data model of type `T`.
///
/// # Example
///
/// ```rust,no_run
/// use moonclient::response::Json;
/// use moonclient::{ClientHook, MoonClient, Result};
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize)]
/// struct User {
/// id: u64,
/// name: String,
/// }
///
/// # async fn doc_example<H: ClientHook>(client: &MoonClient<H>) -> Result<()> {
/// let request = client.get("https://api.site.com/users/1");
///
/// // Tuple pattern matching unwraps the inner `User` directly
/// let Json(user): Json<User> = client.execute(request).await?;
/// println!("Loaded user: {}", user.name);
/// # Ok(())
/// # }
/// ```
;
/// Extractor for automatically decoding XML payloads from response bodies.
///
/// Available only when the `"xml"` feature flag is enabled in `Cargo.toml`.
///
/// # Example
///
/// ```rust,no_run
/// # #[cfg(feature = "xml")]
/// # {
/// use moonclient::response::Xml;
/// use moonclient::{ClientHook, MoonClient, Result};
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize)]
/// struct RssFeed {
/// title: String,
/// }
///
/// # async fn doc_example<H: ClientHook>(client: &MoonClient<H>) -> Result<()> {
/// let request = client.get("https://site.com/feed.xml");
/// let Xml(feed): Xml<RssFeed> = client.execute(request).await?;
/// println!("Feed title: {}", feed.title);
/// # Ok(())
/// # }
/// # }
/// ```
;