Expand description
API gateway with load balancing and rate limiting Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
This file is part of DMSC. The DMSC project belongs to the Dunimd Team.
Licensed under the Apache License, Version 2.0 (the “License”); You may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
§Gateway Module
This module provides a comprehensive API gateway functionality for DMSC, offering routing, middleware support, load balancing, rate limiting, and circuit breaking capabilities.
§Key Components
- DMSCGateway: Main gateway struct implementing the DMSCModule trait
- DMSCGatewayConfig: Configuration for gateway behavior
- DMSCGatewayRequest: Request structure for gateway operations
- DMSCGatewayResponse: Response structure for gateway operations
- DMSCRoute: Route definition for API endpoints
- DMSCRouter: Router for handling request routing
- DMSCMiddleware: Middleware interface for request processing
- DMSCMiddlewareChain: Chain of middleware for sequential execution
- DMSCLoadBalancer: Load balancing for distributing requests across multiple services
- DMSCLoadBalancerStrategy: Load balancing strategies (RoundRobin, LeastConnections, etc.)
- DMSCRateLimiter: Rate limiting for controlling request rates
- DMSCRateLimitConfig: Configuration for rate limiting
- DMSCCircuitBreaker: Circuit breaker for preventing cascading failures
- DMSCCircuitBreakerConfig: Configuration for circuit breakers
§Design Principles
- Modular Design: Separate components for routing, middleware, load balancing, rate limiting, and circuit breaking
- Async-First: All gateway operations are asynchronous
- Configurable: Highly configurable gateway behavior through DMSCGatewayConfig
- Middleware Support: Extensible middleware system for request processing
- Resilience: Built-in circuit breaker and rate limiting for service resilience
- Load Balancing: Support for distributing requests across multiple service instances
- CORS Support: Built-in CORS configuration for cross-origin requests
- Logging: Comprehensive logging support
- Service Integration: Implements DMSCModule trait for seamless integration into DMSC
- Thread-safe: Uses Arc and RwLock for safe concurrent access
§Usage
use dmsc::prelude::*;
use dmsc::gateway::{DMSCGateway, DMSCGatewayConfig, DMSCRoute};
use std::collections::HashMap;
async fn example() -> DMSCResult<()> {
// Create gateway configuration
let gateway_config = DMSCGatewayConfig {
listen_address: "0.0.0.0".to_string(),
listen_port: 8080,
max_connections: 10000,
request_timeout_seconds: 30,
enable_rate_limiting: true,
enable_circuit_breaker: true,
enable_load_balancing: true,
cors_enabled: true,
cors_origins: vec!["*".to_string()],
cors_methods: vec!["GET".to_string(), "POST".to_string()],
cors_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
enable_logging: true,
log_level: "info".to_string(),
};
// Create gateway instance
let gateway = DMSCGateway::new();
// Get router and add routes
let router = gateway.router();
// Add a simple GET route
router.add_route(DMSCRoute {
path: "/api/v1/health".to_string(),
method: "GET".to_string(),
handler: Arc::new(|req| Box::pin(async move {
Ok(DMSCGatewayResponse::json(200, &serde_json::json!({ "status": "ok" }), req.id.clone())?)
})),
..Default::default()
}).await?;
// Add middleware
let middleware_chain = gateway.middleware_chain();
middleware_chain.add_middleware(Arc::new(|req, next| Box::pin(async move {
// Log request
println!("Request: {} {}", req.method, req.path);
next(req).await
}))).await;
// Handle a sample request
let sample_request = DMSCGatewayRequest::new(
"GET".to_string(),
"/api/v1/health".to_string(),
HashMap::new(),
HashMap::new(),
None,
"127.0.0.1:12345".to_string(),
);
let response = gateway.handle_request(sample_request).await;
println!("Response: {} {}", response.status_code, String::from_utf8_lossy(&response.body));
Ok(())
}Re-exports§
pub use routing::DMSCRoute;pub use routing::DMSCRouter;pub use middleware::DMSCMiddleware;pub use middleware::DMSCMiddlewareChain;pub use load_balancer::DMSCLoadBalancer;pub use load_balancer::DMSCLoadBalancerStrategy;pub use rate_limiter::DMSCRateLimiter;pub use rate_limiter::DMSCRateLimitConfig;pub use circuit_breaker::DMSCCircuitBreaker;pub use circuit_breaker::DMSCCircuitBreakerConfig;pub use server::DMSCGatewayServer;pub use server::load_tls_config;
Modules§
- circuit_
breaker - Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
- load_
balancer - Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
- middleware
- Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
- rate_
limiter - Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
- routing
- Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
- server
- Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
Structs§
- DMSC
Gateway - Main gateway struct implementing the DMSCModule trait.
- DMSC
Gateway Config - Configuration for the DMSC Gateway.
- DMSC
Gateway Request - Request structure for gateway operations.
- DMSC
Gateway Response - Response structure for gateway operations.