Skip to main content

oxigeo_gateway/
lib.rs

1//! OxiGeo API Gateway
2//!
3//! Enterprise-grade API gateway for geospatial services, built on a real axum 0.8 HTTP
4//! serving layer that wires together every component below.
5//!
6//! # Features
7//!
8//! - **Rate Limiting**: Token bucket, leaky bucket, fixed/sliding window algorithms
9//! - **Authentication**: API keys, JWT, OAuth2, session management, MFA
10//! - **API Versioning**: Multiple version support with negotiation and migration
11//! - **GraphQL**: Full GraphQL server with subscriptions and DataLoader
12//! - **WebSocket**: Connection multiplexing and message routing
13//! - **Middleware**: CORS, compression, caching, logging, metrics
14//! - **Load Balancing**: Multiple strategies with health checks and circuit breaker
15//! - **Transformation**: Request/response transformation and format adaptation
16//! - **Serving Layer**: [`GatewayServer`] binds the above into an axum router
17//!
18//! # Routes
19//!
20//! | Method | Path               | Purpose                                            |
21//! |--------|--------------------|----------------------------------------------------|
22//! | GET    | `/health`          | Liveness plus a per-backend health snapshot        |
23//! | GET    | `/gateway/metrics` | Aggregate request/response/error counters (JSON)   |
24//! | POST   | `/graphql`         | GraphQL queries and mutations (when enabled)       |
25//! | GET    | `/graphql`         | GraphiQL playground (when introspection is enabled) |
26//! | *      | `/graphql/ws`      | GraphQL subscriptions (when subscriptions enabled) |
27//! | GET    | `/ws`              | WebSocket upgrade (when WebSockets are enabled)     |
28//! | *      | *(fallback)*       | Load-balanced reverse proxy to registered backends |
29//!
30//! # Example
31//!
32//! ```no_run
33//! use oxigeo_gateway::{Gateway, GatewayConfig};
34//!
35//! #[tokio::main]
36//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
37//!     let config = GatewayConfig::default();
38//!     let gateway = Gateway::new(config)?;
39//!     gateway.serve("0.0.0.0:8080").await?;
40//!     Ok(())
41//! }
42//! ```
43//!
44//! For finer control (backends, custom handlers, versioning, transformation), build a
45//! [`GatewayServer`] directly:
46//!
47//! ```no_run
48//! use oxigeo_gateway::{GatewayConfig, GatewayServer};
49//! use oxigeo_gateway::loadbalancer::Backend;
50//!
51//! #[tokio::main]
52//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
53//!     let server = GatewayServer::builder(GatewayConfig::default())
54//!         .with_backend(Backend::new("api".into(), "http://127.0.0.1:9000".into(), 1))
55//!         .require_auth(false)
56//!         .build()?;
57//!     server.serve("0.0.0.0:8080").await?;
58//!     Ok(())
59//! }
60//! ```
61
62#![warn(missing_docs)]
63#![deny(clippy::unwrap_used, clippy::panic)]
64
65pub mod auth;
66pub mod error;
67pub mod graphql;
68pub mod loadbalancer;
69pub mod middleware;
70pub mod rate_limit;
71pub mod server;
72pub mod transform;
73pub mod versioning;
74pub mod websocket;
75
76pub use error::{GatewayError, Result};
77pub use server::{GatewayServer, GatewayServerBuilder};
78
79use std::sync::Arc;
80
81/// Gateway configuration.
82#[derive(Debug, Clone)]
83pub struct GatewayConfig {
84    /// Rate limiting configuration
85    pub rate_limit: rate_limit::RateLimitConfig,
86    /// Authentication configuration
87    pub auth: auth::AuthConfig,
88    /// Load balancer configuration
89    pub loadbalancer: loadbalancer::LoadBalancerConfig,
90    /// Middleware configuration
91    pub middleware: middleware::MiddlewareConfig,
92    /// Maximum request body size in bytes
93    pub max_body_size: usize,
94    /// Request timeout in seconds
95    pub request_timeout: u64,
96    /// Enable GraphQL endpoint
97    pub enable_graphql: bool,
98    /// Enable WebSocket endpoint
99    pub enable_websocket: bool,
100}
101
102impl Default for GatewayConfig {
103    fn default() -> Self {
104        Self {
105            rate_limit: rate_limit::RateLimitConfig::default(),
106            auth: auth::AuthConfig::default(),
107            loadbalancer: loadbalancer::LoadBalancerConfig::default(),
108            middleware: middleware::MiddlewareConfig::default(),
109            max_body_size: 10 * 1024 * 1024, // 10MB
110            request_timeout: 30,
111            enable_graphql: true,
112            enable_websocket: true,
113        }
114    }
115}
116
117/// API Gateway instance.
118pub struct Gateway {
119    config: Arc<GatewayConfig>,
120}
121
122impl Gateway {
123    /// Creates a new gateway with the given configuration.
124    pub fn new(config: GatewayConfig) -> Result<Self> {
125        Ok(Self {
126            config: Arc::new(config),
127        })
128    }
129
130    /// Starts the gateway server on the given address.
131    ///
132    /// Delegates to the axum-based [`GatewayServer`], which serves the full route table
133    /// (health, metrics, GraphQL, WebSocket and the load-balanced reverse-proxy fallback)
134    /// with the configured rate limiting, authentication and middleware. Serves until a
135    /// shutdown signal (ctrl-c / SIGTERM) is received.
136    pub async fn serve(self, addr: &str) -> Result<()> {
137        GatewayServer::builder((*self.config).clone())
138            .build()?
139            .serve(addr)
140            .await
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn test_gateway_config_default() {
150        let config = GatewayConfig::default();
151        assert_eq!(config.max_body_size, 10 * 1024 * 1024);
152        assert_eq!(config.request_timeout, 30);
153        assert!(config.enable_graphql);
154        assert!(config.enable_websocket);
155    }
156
157    #[test]
158    fn test_gateway_creation() {
159        let config = GatewayConfig::default();
160        let gateway = Gateway::new(config);
161        assert!(gateway.is_ok());
162    }
163}