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
//! # MoonClient 🌙
//!
//! An enterprise-grade, resilient, and middleware-driven HTTP client framework engineered
//! for high-concurrency API integrations, robust web scrapers, and mission-critical microservices.
//!
//! ---
//!
//! ## 🚀 Quick Start
//!
//! Here is a complete, copy-paste-ready example demonstrating how to initialize [`MoonClient`],
//! configure automatic rate limiting, construct endpoint URLs using [`build_url!`], and deserialize
//! typed JSON payloads:
//!
//! ```rust,no_run
//! use moonclient::response::Json;
//! use moonclient::{build_url, ClientHook, MoonClient, Result};
//! use serde::Deserialize;
//! use std::time::Duration;
//!
//! #[derive(Debug, Deserialize)]
//! struct UserProfile {
//! id: u64,
//! username: String,
//! is_active: bool,
//! }
//!
//! // 1. Define a minimal lifecycle hook (or use an empty unit hook)
//! struct DefaultHook;
//!
//! #[async_trait::async_trait]
//! impl ClientHook for DefaultHook {
//! type Error = std::convert::Infallible;
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//! // 2. Build the client with timeouts, rate limits, and hooks
//! let client = MoonClient::builder(DefaultHook)
//! .with_base_url("https://api.example.com/v1")
//! .with_app_name("MyProductionApp/1.0")
//! .with_timeout(Duration::from_secs(10))
//! .requests_per_second(5) // Autonomous 5 RPS Token Bucket
//! .build();
//!
//! // 3. Construct the endpoint safely with zero heap allocations
//! let user_id = 42;
//! let endpoint = build_url!(client, "users", user_id, "profile")?;
//!
//! // 4. Dispatch request and extract typed JSON in one expression
//! let request = client.get(endpoint);
//! let Json(profile): Json<UserProfile> = client.execute(request).await?;
//!
//! println!("Successfully loaded user: {} (ID: {})", profile.username, profile.id);
//! Ok(())
//! }
//! ```
//!
//! ---
//!
//! ## 🏛️ Architectural Pillars
//!
//! - **Middleware & Exponential Retries:** Built-in fault tolerance powered by
//! [`reqwest-retry`](https://docs.rs/reqwest-retry) and [`reqwest-tracing`](https://docs.rs/reqwest-tracing).
//! Features a hybrid retry middleware that transparently passes through non-cloneable streaming
//! multipart file uploads without panics.
//! - **Autonomous Traffic Shaping (Rate Limiting):** Multi-window Token Bucket rate limiting
//! powered by [`governor`](https://docs.rs/governor). Supports granular millisecond-level time windows
//! ([`std::time::Duration`]), pre-configured RPS/RPM quotas, and optional distributed coordination
//! via [`redis`](https://docs.rs/redis) connection pools.
//! - **Pluggable Lifecycle Hooks:** Interceptor architecture via the [`ClientHook`] trait,
//! enabling asynchronous pre-request header injection (e.g., Bearer tokens, dynamic HMAC signatures)
//! and reactive `401 Unauthorized` token renewal with automatic request replaying.
//! - **Memory Bomb Protection:** Bounded response buffer decoders safeguarding host processes
//! against memory exhaustion attacks (unbounded streams or multi-gigabyte error payloads).
//! - **Extractor Pattern:** Unified, strongly typed `.execute()` pipeline automatically deserializing
//! responses into `Json<T>`, `Xml<T>`, streaming `Response`, or empty `()` (void) unit types.
//! - **Zero-Allocation Routing:** High-performance [`build_url!`] macro converting arbitrary primitives
//! and domain enums into safe URL paths via copy-on-write strings ([`std::borrow::Cow<'_, str>`]).
//! - **Project Fluent i18n:** Native multi-language diagnostic engine powered by
//! [`fluent`](https://docs.rs/fluent), supporting thread-safe [`tokio`](https://docs.rs/tokio)
//! Task-Local contexts and extensible external bundle registries.
//!
//! ---
//!
//! ## 🏗️ Pipeline Execution Flow
//!
//! Every outbound HTTP request dispatched through [`MoonClient::execute`] traverses an opinionated,
//! defensive pipeline designed to guarantee safety under extreme load:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ MoonClient::execute(req) │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 1. Rate Limiting Gate (Token Bucket via governor or distributed Redis) │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 2. Pre-Request Lifecycle Hook (ClientHook::pre_request - Auth / HMAC) │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 3. Resilient Middleware Pipeline (reqwest-retry + reqwest-tracing) │
//! │ • Transparent retry with exponential backoff on transient 5xx / drops │
//! │ • Safe bypass for streaming multipart uploads (Zero-Panic Guarantee) │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 4. Outbound Wire Transmission (reqwest + rustls) │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 5. Post-Request Interceptor & Reactive Auth Recovery │
//! │ • Intercepts 401 Unauthorized -> ClientHook::handle_unauthorized() │
//! │ • Seamless background token refresh & automatic request replay │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 6. OOM-Safe Bounded Buffer Decoders (Max response capacity guards) │
//! └──────────────────────────────────────┬──────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │ 7. Extractor Pattern (FromResponse) -> Json<T>, Xml<T>, Response, () │
//! └─────────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ---
//!
//! ## 🧩 Feature Flags
//!
//! | Feature | Description | Dependencies | Default |
//! | :--- | :--- | :--- | :---: |
//! | `xml` | Enables strongly typed XML response deserialization via [`quick-xml`](https://docs.rs/quick-xml). | `quick-xml` | **Disabled** |
//! | `redis-limit` | Enables distributed multi-pod rate limiting synchronized via [`redis`](https://docs.rs/redis) connection pools. | `redis` | **Disabled** |
// Public re-exports of core engine types
pub use ;
pub use ;
pub use ClientHook;
pub use ;
pub use ;
pub use FromResponse;
// Direct re-exports of underlying network primitives for downstream consumers
pub use reqwest;
pub use reqwest_middleware;
pub use reqwest_tracing;
pub use RedisLimiter;
// =============================================================================
// 🧭 ZERO-ALLOCATION ROUTING PRIMITIVES
// =============================================================================
/// Trait for automatically coercing arbitrary types into safe URL path segments.
///
/// This trait powers the [`build_url!`] macro. It uses the copy-on-write abstraction
/// [`std::borrow::Cow<'_, str>`] to guarantee **zero redundant heap allocations**
/// for borrowed string literals and slices (`&str`), while seamlessly allocating owned strings
/// only when necessary (e.g. formatting numeric identifiers like `u32` or `i64`).
///
/// # Implementing for Custom Domain Types
///
/// You can implement this trait for your own domain types (such as custom IDs, entity models,
/// or API routing enums) to pass them directly into [`build_url!`]:
///
/// ```rust
/// use moonclient::{build_url, IntoSegment};
/// use std::borrow::Cow;
///
/// /// Domain routing enumeration
/// enum ApiRoute {
/// Users,
/// Posts,
/// Comments,
/// }
///
/// impl IntoSegment for ApiRoute {
/// fn to_segment(&self) -> Cow<'_, str> {
/// match self {
/// Self::Users => Cow::Borrowed("users"),
/// Self::Posts => Cow::Borrowed("posts"),
/// Self::Comments => Cow::Borrowed("comments"),
/// }
/// }
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # struct MockClient { base_url: url::Url }
/// # impl MockClient { fn base_url(&self) -> &url::Url { &self.base_url } }
/// # let client = MockClient { base_url: url::Url::parse("https://api.test.com")? };
/// let route = ApiRoute::Users;
/// let user_id = 940032;
///
/// // Notice how both `route` and `user_id` are passed without manual `.to_string()` calls:
/// let endpoint = build_url!(client, route, user_id)?;
/// assert_eq!(endpoint.as_str(), "https://api.test.com/users/940032");
/// # Ok(())
/// # }
/// ```
/// Global macro for safe, declarative, and zero-allocation construction of endpoint URLs.
///
/// Polymorphically converts any combination of string slices, numeric IDs, primitives,
/// and custom domain enums implementing [`IntoSegment`] into proper hierarchical URL path segments.
///
/// # Advantages over `format!("{}/foo/{}", base, id)`
///
/// 1. **Zero Path Concatenation Bugs:** Automatically handles leading and trailing slashes (`/`),
/// preventing duplicate slashes (`//`) or accidental host overrides.
/// 2. **Zero-Allocation Routing:** String slices are borrowed directly into the URL path buffer
/// via [`std::borrow::Cow::Borrowed`].
/// 3. **Non-Panicking Validation:** Completely avoids runtime panics. If the client base URL cannot
/// act as a base, it returns an explicit, localized [`crate::error::Result<url::Url>`].
///
/// # Arguments
///
/// * `$client` - An instance or reference to any client structure exposing a `.base_url() -> &url::Url` method (such as [`MoonClient`]).
/// * `$($segment)*` - One or more comma-separated path segments implementing [`IntoSegment`].
///
/// # Errors
///
/// Returns [`crate::error::MoonError::Config`] if the underlying base URL has a non-hierarchical scheme
/// (e.g. `data:`, `mailto:`) that cannot support path segments.
///
/// # Practical Examples
///
/// ### Combining Strings, Integers, and Sub-routes
/// ```rust
/// use moonclient::build_url;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # struct MockClient { base_url: url::Url }
/// # impl MockClient { fn base_url(&self) -> &url::Url { &self.base_url } }
/// # let client = MockClient { base_url: url::Url::parse("https://api.site.com/api/v2")? };
/// let target_user = 1007;
/// let action = "deactivate";
///
/// // Result: "https://api.site.com/api/v2/users/1007/deactivate"
/// let url = build_url!(client, "users", target_user, action)?;
/// assert_eq!(url.as_str(), "https://api.site.com/api/v2/users/1007/deactivate");
/// # Ok(())
/// # }
/// ```
///
/// ### Safe Query Parameter Chaining
/// The returned [`url::Url`] can be immediately mutated or chained with query parameters:
/// ```rust
/// use moonclient::build_url;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # struct MockClient { base_url: url::Url }
/// # impl MockClient { fn base_url(&self) -> &url::Url { &self.base_url } }
/// # let client = MockClient { base_url: url::Url::parse("https://api.site.com")? };
/// let mut url = build_url!(client, "search")?;
/// url.query_pairs_mut().append_pair("q", "rustlang");
///
/// assert_eq!(url.as_str(), "https://api.site.com/search?q=rustlang");
/// # Ok(())
/// # }
/// ```