-
Notifications
You must be signed in to change notification settings - Fork 6
Home
miky_rola edited this page Feb 2, 2025
·
1 revision
- Overview
- Architecture
- Components
- Configuration
- API Reference
- Testing Guide
- Development Guide
- Security Considerations
- Performance Tuning
- Troubleshooting
The API Gateway is a high-performance proxy server built with Rust, designed to handle authentication, rate limiting, and caching for backend services. It serves as a single entry point for all client applications, providing a unified interface to access multiple backend services.
- Authentication via Bearer tokens
- Rate limiting per client IP
- Response caching for GET requests
- Request/Response logging
- CORS support
- Timeout handling
- Path-based routing
api-gateway/
├── src/
│ ├── services/ # Core business logic
│ │ ├── mod.rs # Service implementations
│ │ └── tests.rs # Service-specific tests
│ ├── handlers/ # Request handlers
│ │ ├── mod.rs # Handler implementations
│ │ └── tests.rs # Handler-specific tests
│ ├── middleware/ # HTTP middleware
│ │ ├── mod.rs # Middleware implementations
│ │ └── tests.rs # Middleware-specific tests
│ ├── lib.rs # Library definitions
│ ├── main.rs # Application entry point
│ ├── config.rs # Configuration constants
│ ├── error.rs # Error handling
│ └── models.rs # Data structures
└── tests/
└── integration_tests.rs # Integration tests
- Client sends request to API Gateway
- Request passes through authentication middleware
- Rate limiting check is performed
- For GET requests, cache is checked
- Request is proxied to backend service
- Response is cached (if GET request)
- Response is returned to client
Handles core business logic including:
- Rate limiting implementation
- Cache management
- Authentication verification
- Request proxying
pub async fn check_rate_limit(state: &Arc<RwLock<AppState>>, headers: &HeaderMap) -> bool
pub async fn get_cached_response(state: &Arc<RwLock<AppState>>, cache_key: &str) -> Option<Response<Body>>
pub fn is_authenticated(headers: &HeaderMap) -> boolManages HTTP request handling and error responses:
- Error handling
- Response formatting
- Status code mapping
Implements HTTP middleware functions:
- CORS headers
- Request/Response transformation
- Logging
Defines core data structures:
pub struct AppState {
pub cache: HashMap<String, CacheEntry>,
pub rate_limits: HashMap<String, RateLimit>,
}
pub struct CacheEntry {
pub response_parts: (StatusCode, HeaderMap, Bytes),
pub expires_at: SystemTime,
}All configuration is managed through constants in config.rs:
pub const BACKEND_BASE: &str = "http://localhost:8081";
pub const RATE_LIMIT_REQUESTS: u32 = 100;
pub const RATE_LIMIT_WINDOW_SECS: u64 = 60;
pub const REQUEST_TIMEOUT_SECS: u64 = 30;
pub const CACHE_DURATION_SECS: u64 = 300;
pub const STRIP_PATH_PREFIX: &str = "/api";Bearer token authentication is configured through VALID_AUTH_TOKENS:
lazy_static! {
pub static ref VALID_AUTH_TOKENS: HashMap<String, String> = {
let mut m = HashMap::new();
m.insert("example-token".to_string(), "example-user".to_string());
m
};
}GET /health
Response: 200 OK with body "OK"
All requests to /api/*
Method: Any HTTP method
Headers Required:
- Authorization: Bearer <token>
Rate Limit: 100 requests per 60 seconds
# Run all tests
cargo test
# Run specific test module
cargo test --test integration_tests
# Run with logging
RUST_LOG=debug cargo test-
Unit Tests
- Service tests (
src/services/tests.rs) - Handler tests (
src/handlers/tests.rs) - Middleware tests (
src/middleware/tests.rs)
- Service tests (
-
Integration Tests (
tests/integration_tests.rs)- Health check verification
- Authentication flow
- Rate limiting behavior
- Proxy functionality
- Rust 1.75 or higher
- Cargo package manager
# Build the project
cargo build
# Run in development mode
cargo run
# Run with logging
RUST_LOG=debug cargo run- Add new modules in appropriate directories
- Update
lib.rswith new module declarations - Add corresponding tests
- Update documentation
- Bearer token validation
- Token management in
VALID_AUTH_TOKENS - No sensitive data in logs
- Per-client IP tracking
- Configurable windows and limits
- Protection against DoS attacks
- Configurable CORS headers
- Origin validation
- Method restrictions
- In-memory cache for GET requests
- Configurable cache duration
- Automatic cache cleanup
- Reuse of HTTP client connections
- Connection timeout handling
- Request queuing
- Efficient rate limit tracking
- Window-based limiting
- Automatic window reset
-
Rate Limit Exceeded
- Check client IP
- Verify rate limit configuration
- Monitor request patterns
-
Authentication Failures
- Verify token format
- Check token validity
- Inspect request headers
-
Timeout Issues
- Check backend service health
- Verify timeout configuration
- Monitor network connectivity
# Enable debug logging
RUST_LOG=debug cargo run
# Monitor specific components
RUST_LOG=api_gateway=debug cargo run-
Health Check
curl http://localhost:3030/health
-
Rate Limit Status
# Monitor rate limit headers in response curl -v -H "Authorization: Bearer example-token" \ http://localhost:3030/api/test
-
Cache Status
# Verify cache headers curl -v -H "Authorization: Bearer example-token" \ http://localhost:3030/api/cached-endpoint