A feature-rich, production-grade Rust SDK with async operations, advanced error handling, middleware system, caching, rate limiting, and comprehensive testing.
- Async HTTP Client - Built on
tokioandreqwestwith full async support - Advanced Error Handling - Comprehensive error types with context information
- Middleware System - Pluggable middleware for request/response processing
- Request Validation - Email, URL, UUID, length, and custom validators
- Rate Limiting - Token bucket and sliding window rate limiters
- Caching Layer - In-memory cache with TTL and LRU eviction
- Database Integration - Query builder, repository pattern, soft deletes
- Configuration Management - Environment variables and file-based configuration
- Authentication - API key, HMAC signatures, OAuth support
- Retry Logic - Exponential backoff with jitter
- Logging - Structured logging with tracing
- HMAC-SHA256 signature generation and verification
- Input sanitization (HTML, SQL, path traversal)
- Request validation
- Rate limiting per user/endpoint
- Error context tracking with request IDs
- Metrics - Rate limiter metrics and acceptance rates
- Query Builder - Fluent SQL query construction
- Soft Deletes - Entity soft delete support
- Pagination - Pagination support for list responses
- Request Context - Request metadata and correlation IDs
- Middleware Chain - Sequential middleware processing
Add to your Cargo.toml:
[dependencies]
rust-sdk = { path = "./rust-sdk" }
tokio = { version = "1.35", features = ["full"] }use rust_sdk::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create client
let client = Client::new("https://api.example.com")?;
// Make requests
let data: serde_json::Value = client.get("/endpoint").await?;
Ok(())
}use rust_sdk::config::Config;
let config = Config::new("https://api.example.com")
.with_api_key("your-api-key")
.with_header("X-Custom-Header", "value")
.with_debug(true);
let client = Client::with_config(config)?;// Load from .env file
let client = Client::from_env()?;Requires environment variables:
SDK_BASE_URL- API base URL (required)SDK_API_KEY- API key (optional)SDK_DEBUG- Debug mode (optional)
let cache = Cache::new(1000, 3600); // 1000 entries, 1 hour TTL
// Store
cache.set("key", &value)?;
// Retrieve
let result: Option<T> = cache.get("key")?;
// Clear
cache.clear();use rust_sdk::validation::*;
// Built-in validators
let email_validator = EmailValidator;
email_validator.validate("test@example.com")?;
let url_validator = UrlValidator;
url_validator.validate("https://example.com")?;
// Length validator
let len_validator = LengthValidator::new(3, 20);
len_validator.validate("username")?;
// Sanitization
let sanitized = Sanitizer::sanitize_html("<script>alert(1)</script>");use rust_sdk::rate_limit::*;
use std::time::Duration;
// Token bucket
let bucket = TokenBucket::new(100, 10); // 100 capacity, 10 refill/sec
bucket.try_acquire(5)?;
// Per-user rate limiter
let limiter = PerUserRateLimiter::new(1000, 100);
limiter.try_acquire("user123", 5)?;
// Sliding window
let limiter = SlidingWindowRateLimiter::new(100, Duration::from_secs(60));
limiter.allow_request("client1")?;use rust_sdk::database::*;
// Query builder
let query = QueryBuilder::new()
.select(vec!["id", "name", "email"])
.from("users")
.where_clause("is_active = true")
.order_by("created_at", "DESC")
.limit(50)
.build()?;
// Repository pattern
let db = InMemoryDatabase::new();
let user_repo = UserRepository::new(Arc::new(db));
// Soft deletes
let mut entity = BaseEntity::new();
entity.soft_delete();use rust_sdk::error::*;
match some_operation() {
Ok(result) => println!("Success: {:?}", result),
Err(SdkError::ValidationError(msg)) => {
eprintln!("Validation failed: {}", msg);
}
Err(SdkError::RateLimitExceeded(msg)) => {
eprintln!("Rate limit: {}", msg);
}
Err(e) => eprintln!("Error: {}", e),
}
// Check if error is retryable
if error.is_retryable() {
// Retry operation
}rust-sdk/
├── src/
│ ├── lib.rs # Main library entry point
│ ├── client.rs # Main SDK client
│ ├── config.rs # Configuration management
│ ├── error.rs # Error types and handling
│ ├── models.rs # Data models
│ ├── middleware.rs # Middleware system
│ ├── cache.rs # Caching layer
│ ├── validation.rs # Input validation
│ ├── rate_limit.rs # Rate limiting
│ ├── database.rs # Database integration
│ └── utils.rs # Utility functions
├── tests/
│ └── integration_tests.rs # Comprehensive tests
├── examples/
│ └── main.rs # Usage examples
└── Cargo.toml # Dependencies
Client- Main entry point- HTTP methods: GET, POST, PUT, DELETE
- Health checks
- Cache integration
- Rate limiting
Config- Main configuration structHttpConfig- HTTP client settingsRetryConfig- Retry policyCacheConfig- Cache settingsRateLimitConfig- Rate limit settings
SdkError- Comprehensive error typesErrorContext- Error context information- Error categorization (retryable, auth, etc.)
Middlewaretrait - Async middleware interfaceMiddlewareChain- Sequential middleware processing- Built-in middlewares: Logging, Auth, RateLimit, Validation, Caching
Cache- In-memory cache with TTLLruCache- LRU cache implementation- Automatic expiration
- Thread-safe operations
ValidatortraitEmailValidator,UrlValidator,UuidValidatorLengthValidator,AlphanumericValidatorRegexValidator- Custom regex patternsSanitizer- XSS, SQL injection, path traversal prevention
TokenBucket- Token bucket algorithmSlidingWindowRateLimiter- Sliding window rate limitingPerUserRateLimiter- Per-user rate limiting
DatabaseConnectiontraitInMemoryDatabase- Test databaseUserRepository- Example repositoryQueryBuilder- Fluent query constructionBaseEntity- Base entity with soft deletes
exponential_backoff()- Backoff calculationRetryHelper- Retry logicSignatureGenerator- HMAC-SHA256TimeUtils- Time utilitiesRateLimiterMetrics- Metrics tracking
cargo testcargo test test_cache_set_getcargo test --test integration_testscargo test -- --nocapturecargo run --example mainThe SDK includes comprehensive tests covering:
- ✅ Configuration management
- ✅ Client creation and configuration
- ✅ Email validation
- ✅ Caching (set, get, TTL, eviction)
- ✅ Rate limiting (token bucket, sliding window)
- ✅ Database operations (query builder, soft deletes)
- ✅ Error handling and retry logic
- ✅ Signature generation and verification
- ✅ Input sanitization
- ✅ Models serialization/deserialization
- Default TTL: 1 hour
- Maximum entries: 1000
- LRU eviction policy
- Token bucket: 100 requests/sec default
- Sliding window: 60-second window default
- Per-user limiting supported
- Initial backoff: 100ms
- Maximum backoff: 30 seconds
- Multiplier: 2.0
- Jitter: Enabled
- Input Validation - Always validate user input
- Sanitization - Sanitize HTML, SQL, and paths
- HTTPS - Always use HTTPS in production
- API Keys - Store securely in environment variables
- Rate Limiting - Implement per-user and per-endpoint
- Error Messages - Don't expose sensitive data in errors
- Logging - Don't log sensitive information
Contributions are welcome! Please:
- Add tests for new features
- Update documentation
- Follow Rust conventions
- Run
cargo fmtandcargo clippy
MIT License - See LICENSE file for details
See examples/main.rs for comprehensive usage examples.
new(base_url)- Create clientwith_config(config)- Create from configfrom_env()- Create from environmentget::<T>(path)- GET requestpost::<T, R>(path, body)- POST requestput::<T, R>(path, body)- PUT requestdelete::<R>(path)- DELETE requesthealth_check()- Health checkvalidate_email(email)- Email validationclear_cache()- Clear cache
Config::new(url)- Create default configConfig::from_env()- Load from environmentConfig::from_file(path)- Load from file.with_api_key(key)- Set API key.with_header(key, value)- Add custom header.with_debug(bool)- Enable debug mode
- Increase
http.timeout_secsin config - Check network connectivity
- Implement backoff logic
- Use
RetryHelper::retry_with_backoff()
- Ensure
cache.enabledis true in config - Check cache TTL settings
- Use appropriate validators
- Check input format
For issues and questions, please open an issue in the repository.