MoonClient π
English | Π ΡΡΡΠΊΠΈΠΉ
An enterprise-grade, resilient HTTP client engine engineered for mission-critical API integrations, distributed scrapers, and high-concurrency microservices.
π Table of Contents
- Overview
- Key Features
- Installation
- Quick Start
- Core Concepts
- Feature Flags
- Architecture & Re-exports
- License
π Overview
moonclient is designed from the ground up to eliminate the recurring boilerplate associated with building robust production API client libraries in Rust. It wraps reqwest and reqwest-middleware into a clean, thread-safe, decoupled engine that isolates transport mechanics, retry policies, rate limits, and memory safety from application-level business logic.
β‘ Key Features
- π‘οΈ Autonomous Rate Limiting: Built-in Token Bucket traffic shaping powered by
governor: granular configuration of multiple arbitrary time windows (Duration), quick RPS/RPM presets, and optional distributed Redis coordination. - π Hybrid Resilient Middleware: Transparent exponential backoff retries via
reqwest-retry, engineered to automatically pass through non-cloneable streaming multipart file uploads without panics. - πͺ Pluggable Lifecycle Hooks: Interceptor trait ([
ClientHook]) supporting pre-request header injection (e.g., Bearer tokens, HMAC signatures) and reactive401 Unauthorizedtoken renewal with request replaying. - π OOM Protection: Bounded response buffer decoders safeguarding against unbounded streaming memory exhaustion attacks (e.g., unexpected multi-gigabyte server error pages).
- π¦ Extractor Pattern: Unified, strongly typed
.execute()method returningJson<T>,Xml<T>,Response, or()(void). - π Native Project Fluent i18n: Built-in localized diagnostics and network error reporting with thread-safe Task-Local locale resolution.
- π Zero-Allocation Routing: The [
build_url!] macro converts primitives, strings, and custom enums into safe URL paths viaCow<'_, str>.
π¦ Installation
Add moonclient to your Cargo.toml:
[]
= "0.1"
= { = "1.53", = ["full"] }
= { = "1.0", = ["derive"] }
π Quick Start
Here is a minimal standalone example demonstrating initialization, rate limiting, and typed JSON response extraction:
use Json;
use ;
use Deserialize;
// Minimal no-op lifecycle hook
;
async
π§ Core Concepts
1. Lifecycle Hooks (ClientHook)
MoonClient decouples authentication and domain quirks through the [ClientHook] trait:
use async_trait;
use ClientHook;
use RequestBuilder;
use Response;
2. Token Bucket Rate Limiting
Rate limiting is applied transparently prior to network transmission:
let client = builder
.add_limit // Custom window: 5 requests per 200ms
.requests_per_second // Quick preset: 5 RPS
.requests_per_minute // Quick preset: 90 RPM
.build;
For distributed multi-instance clusters, enable the redis-limit feature to coordinate limits via Redis.
3. Memory-Safe Bounded Responses (OOM Protection)
Standard HTTP libraries read the entire response body into memory. If an upstream proxy or faulty API returns an unbounded stream or a 500 MB HTML crash dump, your process can trigger an Out-Of-Memory (OOM) panic.
moonclient buffers responses with strict, configurable capacity limits:
DEFAULT_ERROR_BODY_LIMIT(64 KiB): For HTTP 4xx/5xx error responses.DEFAULT_BODY_LIMIT(16 MiB): For successful payloads.set_max_response_size(bytes): Runtime dynamic adjustment via an atomic counter.
4. Zero-Allocation URL Macro (build_url!)
The build_url! macro accepts any type implementing [IntoSegment]:
let user_id = 42;
let route = "profile";
// Produces: https://api.site.com/users/42/profile
let url = build_url!?;
5. Dedicated Split File Logging (MoonLogger)
MoonLogger provides non-blocking, multi-threaded logging with Mutex-poisoning recovery and split file sinks:
init
.with_level
.with_split_files
.setup?;
- Logs matching target
moonclient*are routed tocore.log. - External consumer domain logs are routed to
api.log.
6. Project Fluent Localization (i18n)
All internal engine error diagnostics and logging strings are localized via Mozilla's Project Fluent:
- Automatic resolution hierarchy: Tokio Task-Local β‘οΈ Global Override β‘οΈ Host OS locale β‘οΈ Default (
en). - External crates can inject their own translation bundles via
moonclient::i18n::register_resource().
π© Feature Flags
| Feature | Description | Default |
|---|---|---|
xml |
Enables XML response payload extraction via quick-xml. |
Disabled |
redis-limit |
Enables distributed token bucket rate limiting via Redis connection pools. | Disabled |
ποΈ Architecture & Re-exports
To prevent dependency version drift across your workspace, moonclient directly re-exports its fundamental HTTP networking stack:
pub use reqwest;
pub use reqwest_middleware;
pub use reqwest_tracing;
π License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.