import asyncio
from ri import (
RiGateway,
RiGatewayConfig,
RiRoute,
RiRouter,
RiRateLimiter,
RiRateLimitConfig,
RiRateLimitStats,
RiSlidingWindowRateLimiter,
RiCircuitBreaker,
RiCircuitBreakerConfig,
RiCircuitBreakerState,
RiCircuitBreakerMetrics,
RiBackendServer,
RiLoadBalancerServerStats,
RiLoadBalancer,
RiLoadBalancerStrategy,
)
async def main():
config = RiGatewayConfig()
config.host = "0.0.0.0"
config.port = 8080
config.enable_rate_limiting = True
config.enable_circuit_breaker = True
config.enable_load_balancing = True
config.max_request_size_mb = 10
config.timeout_seconds = 30
gateway = RiGateway(config)
router = RiRouter()
print("Defining routes...")
user_route = RiRoute()
user_route.path = "/api/users"
user_route.methods = ["GET", "POST", "PUT", "DELETE"]
user_route.handler = "user_service"
user_route.middleware = ["auth", "logging"]
order_route = RiRoute()
order_route.path = "/api/orders"
order_route.methods = ["GET", "POST"]
order_route.handler = "order_service"
order_route.middleware = ["auth", "rate_limit"]
health_route = RiRoute()
health_route.path = "/health"
health_route.methods = ["GET"]
health_route.handler = "health_check"
health_route.middleware = []
router.add_route(user_route)
router.add_route(order_route)
router.add_route(health_route)
print(f"Added {len(router.routes)} routes to router")
print("\nConfiguring rate limiting...")
rate_limit_config = RiRateLimitConfig()
rate_limit_config.requests_per_second = 100
rate_limit_config.burst_size = 150
rate_limit_config.window_size_seconds = 60
rate_limiter = RiRateLimiter(rate_limit_config)
client_id = "client_123"
is_allowed = rate_limiter.is_allowed(client_id)
print(f"Rate limit check for {client_id}: {is_allowed}")
rate_stats = RiRateLimitStats()
print(f"Rate limit stats: {rate_stats.total_requests} total requests")
print("\nConfiguring circuit breaker...")
cb_config = RiCircuitBreakerConfig()
cb_config.failure_threshold = 5
cb_config.success_threshold = 3
cb_config.timeout_seconds = 30
cb_config.half_open_max_calls = 3
circuit_breaker = RiCircuitBreaker(cb_config)
circuit_breaker.record_success()
circuit_breaker.record_failure()
cb_state = circuit_breaker.get_state()
print(f"Circuit breaker state: {cb_state}")
cb_metrics = RiCircuitBreakerMetrics()
print(f"Circuit breaker metrics:")
print(f" Success count: {cb_metrics.success_count}")
print(f" Failure count: {cb_metrics.failure_count}")
print("\nConfiguring load balancer...")
server1 = RiBackendServer()
server1.id = "server_1"
server1.host = "192.168.1.10"
server1.port = 8081
server1.weight = 3
server1.is_healthy = True
server2 = RiBackendServer()
server2.id = "server_2"
server2.host = "192.168.1.11"
server2.port = 8081
server2.weight = 2
server2.is_healthy = True
server3 = RiBackendServer()
server3.id = "server_3"
server3.host = "192.168.1.12"
server3.port = 8081
server3.weight = 1
server3.is_healthy = False
lb = RiLoadBalancer()
lb.strategy = RiLoadBalancerStrategy.WEIGHTED_ROUND_ROBIN
lb.add_server(server1)
lb.add_server(server2)
lb.add_server(server3)
print(f"Load balancer configured with strategy: {lb.strategy}")
print(f"Total servers: 3 (2 healthy)")
next_server = lb.get_next_server()
if next_server:
print(f"Next server: {next_server.id} ({next_server.host}:{next_server.port})")
lb_stats = RiLoadBalancerServerStats()
print(f"Load balancer stats:")
print(f" Active connections: {lb_stats.active_connections}")
print(f" Total requests: {lb_stats.total_requests}")
print("\nTesting route matching...")
matched_route = router.match("/api/users", "GET")
if matched_route:
print(f"Matched route: {matched_route.path}")
matched_route = router.match("/api/orders", "POST")
if matched_route:
print(f"Matched route: {matched_route.path}")
matched_route = router.match("/health", "GET")
if matched_route:
print(f"Matched route: {matched_route.path}")
print("\nGateway operations completed successfully!")
if __name__ == "__main__":
asyncio.run(main())