Skip to content
miky_rola edited this page Feb 2, 2025 · 1 revision

API Gateway Documentation

Table of Contents

  1. Overview
  2. Architecture
  3. Components
  4. Configuration
  5. API Reference
  6. Testing Guide
  7. Development Guide
  8. Security Considerations
  9. Performance Tuning
  10. Troubleshooting

Overview

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.

Key Features

  • Authentication via Bearer tokens
  • Rate limiting per client IP
  • Response caching for GET requests
  • Request/Response logging
  • CORS support
  • Timeout handling
  • Path-based routing

Architecture

Project Structure

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

Data Flow

  1. Client sends request to API Gateway
  2. Request passes through authentication middleware
  3. Rate limiting check is performed
  4. For GET requests, cache is checked
  5. Request is proxied to backend service
  6. Response is cached (if GET request)
  7. Response is returned to client

Components

Services (src/services/mod.rs)

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) -> bool

Handlers (src/handlers/mod.rs)

Manages HTTP request handling and error responses:

  • Error handling
  • Response formatting
  • Status code mapping

Middleware (src/middleware/mod.rs)

Implements HTTP middleware functions:

  • CORS headers
  • Request/Response transformation
  • Logging

Models (src/models.rs)

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,
}

Configuration

Environment Variables

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";

Authentication

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
    };
}

API Reference

Health Check

GET /health
Response: 200 OK with body "OK"

Proxy Endpoints

All requests to /api/*
Method: Any HTTP method
Headers Required:
  - Authorization: Bearer <token>
Rate Limit: 100 requests per 60 seconds

Testing Guide

Running Tests

# Run all tests
cargo test

# Run specific test module
cargo test --test integration_tests

# Run with logging
RUST_LOG=debug cargo test

Test Categories

  1. Unit Tests

    • Service tests (src/services/tests.rs)
    • Handler tests (src/handlers/tests.rs)
    • Middleware tests (src/middleware/tests.rs)
  2. Integration Tests (tests/integration_tests.rs)

    • Health check verification
    • Authentication flow
    • Rate limiting behavior
    • Proxy functionality

Development Guide

Prerequisites

  • Rust 1.75 or higher
  • Cargo package manager

Local Development

# Build the project
cargo build

# Run in development mode
cargo run

# Run with logging
RUST_LOG=debug cargo run

Adding New Features

  1. Add new modules in appropriate directories
  2. Update lib.rs with new module declarations
  3. Add corresponding tests
  4. Update documentation

Security Considerations

Authentication

  • Bearer token validation
  • Token management in VALID_AUTH_TOKENS
  • No sensitive data in logs

Rate Limiting

  • Per-client IP tracking
  • Configurable windows and limits
  • Protection against DoS attacks

CORS

  • Configurable CORS headers
  • Origin validation
  • Method restrictions

Performance Tuning

Caching

  • In-memory cache for GET requests
  • Configurable cache duration
  • Automatic cache cleanup

Connection Pooling

  • Reuse of HTTP client connections
  • Connection timeout handling
  • Request queuing

Rate Limiting

  • Efficient rate limit tracking
  • Window-based limiting
  • Automatic window reset

Troubleshooting

Common Issues

  1. Rate Limit Exceeded

    • Check client IP
    • Verify rate limit configuration
    • Monitor request patterns
  2. Authentication Failures

    • Verify token format
    • Check token validity
    • Inspect request headers
  3. Timeout Issues

    • Check backend service health
    • Verify timeout configuration
    • Monitor network connectivity

Logging

# Enable debug logging
RUST_LOG=debug cargo run

# Monitor specific components
RUST_LOG=api_gateway=debug cargo run

Diagnostics

  1. Health Check

    curl http://localhost:3030/health
  2. Rate Limit Status

    # Monitor rate limit headers in response
    curl -v -H "Authorization: Bearer example-token" \
         http://localhost:3030/api/test
  3. Cache Status

    # Verify cache headers
    curl -v -H "Authorization: Bearer example-token" \
         http://localhost:3030/api/cached-endpoint