dmsc/c/gateway.rs
1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//! http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Gateway Module C API
19//!
20//! This module provides C language bindings for DMSC's API gateway subsystem. The gateway module
21//! delivers high-performance HTTP request routing, load balancing, rate limiting, and request/response
22//! transformation capabilities. This C API enables C/C++ applications to leverage DMSC's gateway
23//! functionality for building scalable API endpoints with enterprise-grade features.
24//!
25//! ## Module Architecture
26//!
27//! The gateway module comprises three primary components that together provide complete API gateway
28//! functionality:
29//!
30//! - **DMSCGateway**: Core gateway server implementation handling HTTP request processing,
31//! middleware composition, and response generation. The gateway acts as the entry point for
32//! all incoming API requests, applying configured middleware chains and routing requests to
33//! appropriate backend services.
34//!
35//! - **DMSCGatewayConfig**: Configuration container for gateway server parameters including listen
36//! address, thread pool sizing, TLS settings, and middleware configuration. The configuration
37//! object controls resource allocation, security settings, and behavioral characteristics.
38//!
39//! - **DMSCRouter**: Request routing component responsible for matching incoming requests to
40//! registered routes based on method, path, headers, and other request attributes. The router
41//! supports complex routing patterns including path parameters, wildcards, and regex matching.
42//!
43//! ## Gateway Features
44//!
45//! The API gateway provides comprehensive features for production API management:
46//!
47//! - **Request Routing**: Advanced routing capabilities including path matching, method-based
48//! routing, header-based routing, and query parameter routing. Supports route groups and
49//! hierarchical routing patterns.
50//!
51//! - **Load Balancing**: Distribution of requests across multiple backend instances with
52//! configurable algorithms including round-robin, least-connections, weighted distribution,
53//! and consistent hashing for session affinity.
54//!
55//! - **Rate Limiting**: Request rate control at multiple granularity levels including global,
56//! per-client, per-route, and per-user rate limits. Supports sliding window, token bucket,
57//! and leaky bucket algorithms.
58//!
59//! - **Middleware Chain**: Composable middleware for request/response processing including
60//! authentication, authorization, logging, compression, caching, and transformation.
61//! Middleware executes in configured order with early exit capabilities.
62//!
63//! - **Request/Response Transformation**: Content transformation between client and backend
64//! formats including JSON to XML conversion, header manipulation, body rewriting, and
65//! protocol translation.
66//!
67//! - **Circuit Breaker**: Automatic detection of backend failures with configurable thresholds
68//! for failure rates, timeout windows, and recovery strategies. Prevents cascade failures
69//! in distributed systems.
70//!
71//! - **WebSocket Support**: Full-duplex WebSocket connections with session management,
72//! heartbeat handling, and connection lifecycle events.
73//!
74//! - **TLS Termination**: Secure communication with configurable TLS settings including
75//! certificate management, cipher suite selection, and HTTP/2 support.
76//!
77//! ## Routing Capabilities
78//!
79//! The router supports sophisticated routing patterns:
80//!
81//! - **Static Paths**: Exact path matching for simple routes (e.g., /api/users)
82//!
83//! - **Path Parameters**: Variable path segments captured as parameters (e.g., /users/:id)
84//!
85//! - **Wildcard Matching**: Catch-all routes for static file serving (e.g., /static/*)
86//!
87//! - **Regex Patterns**: Complex matching rules using regular expressions
88//!
89//! - **Method Matching**: Route requests by HTTP method (GET, POST, PUT, DELETE, etc.)
90//!
91//! - **Header Matching**: Route based on request headers (e.g., X-API-Version)
92//!
93//! - **Query Matching**: Route based on query parameters
94//!
95//! ## Middleware Types
96//!
97//! The gateway supports various middleware categories:
98//!
99//! - **Authentication Middleware**: JWT validation, OAuth token verification, API key checking,
100//! and custom authentication schemes.
101//!
102//! - **Authorization Middleware**: Role-based access control, permission checking, and
103//! policy enforcement at route level.
104//!
105//! - **Logging Middleware**: Request/response logging, access logging, and structured logging
106//! for observability.
107//!
108//! - **Compression Middleware**: Gzip, Brotli, and Deflate compression for response bodies.
109//!
110//! - **Caching Middleware**: Response caching with TTL control, cache invalidation, and
111//! conditional requests (ETag, If-Modified-Since).
112//!
113//! - **Transformation Middleware**: Header addition/removal, body transformation, and content
114//! type conversion.
115//!
116//! - **Rate Limiting Middleware**: Request throttling with configurable limits and response
117//! handling.
118//!
119//! - **Circuit Breaker Middleware**: Failure detection and fallback handling for backend
120//! services.
121//!
122//! ## Load Balancing Strategies
123//!
124//! The gateway implements multiple load balancing algorithms:
125//!
126//! - **Round Robin**: Sequential distribution across available backends. Simple and effective
127//! for homogeneous backends with similar capacity.
128//!
129//! - **Least Connections**: Route to backend with fewest active connections. Adapts to
130//! varying request processing times.
131//!
132//! - **Weighted Distribution**: Proportional routing based on backend capacity or priority.
133//! Requires backend health and capacity configuration.
134//!
135//! - **Consistent Hashing**: Request affinity based on request attributes (e.g., user ID).
136//! Minimizes redistribution when backends change.
137//!
138//! - **Random**: Random selection among healthy backends. Simple and effective for
139//! homogeneous backends.
140//!
141//! ## Memory Management
142//!
143//! All C API objects use opaque pointers with manual memory management:
144//!
145//! - Constructor functions allocate new instances on the heap
146//! - Destructor functions must be called to release memory
147//! - Route handlers must be properly registered and unregistered
148//! - Connection handles must be properly closed
149//!
150//! ## Thread Safety
151//!
152//! The underlying implementations are thread-safe:
153//!
154//! - Gateway server handles concurrent requests using thread pool
155//! - Router operations are thread-safe for route lookups
156//! - Configuration changes may require gateway restart
157//! - Middleware should be stateless when possible
158//!
159//! ## Performance Characteristics
160//!
161//! Gateway operations have the following performance profiles:
162//!
163//! - Request routing: O(log n) for route lookup with path parameters
164//! - Middleware processing: O(m) where m is number of middleware
165//! - Load balancing: O(1) for most algorithms
166//! - Request throughput: Thousands of requests per second per core
167//!
168//! ## Usage Example
169//!
170//! ```c
171//! // Create gateway configuration
172//! DMSCGatewayConfig* config = dmsc_gateway_config_new();
173//! dmsc_gateway_config_set_address(config, "0.0.0.0", 8080);
174//! dmsc_gateway_config_set_workers(config, 4);
175//! dmsc_gateway_config_set_tls_enabled(config, false);
176//!
177//! // Create gateway instance
178//! DMSCGateway* gateway = dmsc_gateway_new(config);
179//!
180//! // Create router and configure routes
181//! DMSCRouter* router = dmsc_router_new();
182//!
183//! // Register routes
184//! dmsc_router_add_route(router, "GET", "/api/users", handle_users);
185//! dmsc_router_add_route(router, "POST", "/api/users", create_user);
186//! dmsc_router_add_route(router, "GET", "/api/users/:id", get_user_by_id);
187//!
188//! // Mount router on gateway
189//! dmsc_gateway_mount(gateway, "/api", router);
190//!
191//! // Start gateway
192//! dmsc_gateway_start(gateway);
193//!
194//! // Graceful shutdown on signal
195//! // dmsc_gateway_shutdown(gateway);
196//!
197//! // Cleanup
198//! dmsc_gateway_free(gateway);
199//! dmsc_gateway_config_free(config);
200//! ```
201//!
202//! ## Dependencies
203//!
204//! This module depends on the following DMSC components:
205//!
206//! - `crate::gateway`: Rust gateway module implementation
207//! - `crate::prelude`: Common types and traits
208//! - Hyper for HTTP server functionality
209//! - Redis for rate limiting and session storage
210//!
211//! ## Feature Flags
212//!
213//! The gateway module is enabled by default with the "gateway" feature flag.
214//! Disable this feature to reduce binary size when gateway functionality is not required.
215
216use crate::gateway::{DMSCGateway, DMSCGatewayConfig, DMSCRouter};
217
218
219c_wrapper!(CDMSCGateway, DMSCGateway);
220
221c_wrapper!(CDMSCGatewayConfig, DMSCGatewayConfig);
222
223c_wrapper!(CDMSCRouter, DMSCRouter);
224
225c_constructor!(dmsc_gateway_config_new, CDMSCGatewayConfig, DMSCGatewayConfig, DMSCGatewayConfig::default());
226
227c_destructor!(dmsc_gateway_config_free, DMSCGatewayConfig);