Skip to main content

ferrum_server/
traits.rs

1//! Core server traits
2//!
3//! This module defines the abstract interfaces for HTTP server implementation,
4//! middleware management, and request handling.
5
6use crate::types::*;
7use async_trait::async_trait;
8use ferrum_types::{InferenceRequest, Result};
9use std::time::Duration;
10
11/// Main HTTP server trait
12#[async_trait]
13pub trait HttpServer: Send + Sync {
14    /// Start the server
15    async fn start(&self, config: &ServerConfig) -> Result<()>;
16
17    /// Stop the server gracefully
18    async fn stop(&self, timeout: Duration) -> Result<()>;
19
20    /// Check if server is running
21    fn is_running(&self) -> bool;
22
23    /// Get server address
24    fn address(&self) -> Option<std::net::SocketAddr>;
25
26    /// Register a request handler
27    fn register_handler(
28        &mut self,
29        path: &str,
30        method: HttpMethod,
31        handler: Box<dyn RequestHandler>,
32    );
33
34    /// Register middleware
35    fn register_middleware(&mut self, middleware: Box<dyn Middleware>);
36
37    /// Get server metrics
38    fn get_metrics(&self) -> ServerMetrics;
39
40    /// Health check
41    async fn health_check(&self) -> HealthStatus;
42}
43
44/// Request handler trait for processing HTTP requests
45#[async_trait]
46pub trait RequestHandler: Send + Sync {
47    /// Handle an HTTP request
48    async fn handle(&self, request: HttpRequest, context: RequestContext) -> Result<HttpResponse>;
49
50    /// Get handler name for debugging
51    fn name(&self) -> &str;
52
53    /// Check if handler supports the request
54    fn can_handle(&self, request: &HttpRequest) -> bool;
55}
56
57/// Response builder trait for constructing HTTP responses
58pub trait ResponseBuilder: Send + Sync {
59    /// Create a successful response
60    fn ok(&self, body: serde_json::Value) -> HttpResponse;
61
62    /// Create an error response
63    fn error(&self, code: StatusCode, message: &str) -> HttpResponse;
64
65    /// Create a streaming response
66    fn streaming(&self, content_type: &str) -> HttpResponse;
67
68    /// Create a response with custom headers
69    fn with_headers(&self, body: serde_json::Value, headers: Headers) -> HttpResponse;
70
71    /// Create a redirect response
72    fn redirect(&self, location: &str, permanent: bool) -> HttpResponse;
73}
74
75/// Streaming response handler
76#[async_trait]
77pub trait StreamingHandler: Send + Sync {
78    /// Handle streaming inference request
79    async fn handle_stream(
80        &self,
81        request: InferenceRequest,
82        sender: Box<dyn StreamSender>,
83    ) -> Result<()>;
84
85    /// Get streaming configuration
86    fn stream_config(&self) -> &StreamConfig;
87}
88
89/// Stream sender for sending chunks
90#[async_trait]
91pub trait StreamSender: Send + Sync {
92    /// Send a chunk
93    async fn send_chunk(&self, chunk: &str) -> Result<()>;
94
95    /// Send JSON chunk
96    async fn send_json(&self, data: &serde_json::Value) -> Result<()>;
97
98    /// Close the stream
99    async fn close(&self) -> Result<()>;
100
101    /// Check if stream is closed
102    fn is_closed(&self) -> bool;
103}
104
105/// Middleware trait for request/response processing
106#[async_trait]
107pub trait Middleware: Send + Sync {
108    /// Process request before handler
109    async fn before_request(
110        &self,
111        request: &mut HttpRequest,
112        context: &mut RequestContext,
113    ) -> Result<()>;
114
115    /// Process response after handler
116    async fn after_response(
117        &self,
118        request: &HttpRequest,
119        response: &mut HttpResponse,
120        context: &RequestContext,
121    ) -> Result<()>;
122
123    /// Handle middleware errors
124    async fn on_error(
125        &self,
126        error: &ferrum_types::FerrumError,
127        context: &RequestContext,
128    ) -> Option<HttpResponse>;
129
130    /// Get middleware name
131    fn name(&self) -> &str;
132
133    /// Get middleware priority (lower numbers run first)
134    fn priority(&self) -> i32;
135}
136
137/// Middleware stack management
138pub trait MiddlewareStack: Send + Sync {
139    /// Add middleware to stack
140    fn add(&mut self, middleware: Box<dyn Middleware>);
141
142    /// Remove middleware by name
143    fn remove(&mut self, name: &str) -> bool;
144
145    /// Get middleware by name
146    fn get(&self, name: &str) -> Option<&dyn Middleware>;
147
148    /// Clear all middleware
149    fn clear(&mut self);
150
151    /// Get middleware count
152    fn len(&self) -> usize;
153}
154
155/// Authentication provider trait
156#[async_trait]
157pub trait AuthProvider: Send + Sync {
158    /// Authenticate a request
159    async fn authenticate(&self, request: &HttpRequest) -> Result<AuthResult>;
160
161    /// Validate API key
162    async fn validate_api_key(&self, api_key: &str) -> Result<ClientInfo>;
163
164    /// Validate JWT token
165    async fn validate_jwt(&self, token: &str) -> Result<TokenClaims>;
166
167    /// Get authentication scheme
168    fn scheme(&self) -> AuthScheme;
169}
170
171/// Rate limiter trait for server-side rate limiting
172#[async_trait]
173pub trait RateLimiter: Send + Sync {
174    /// Check if request is within limits
175    async fn check_limit(&self, client_id: &str, endpoint: &str) -> Result<RateLimitResult>;
176
177    /// Record request for rate limiting
178    async fn record_request(&self, client_id: &str, endpoint: &str) -> Result<()>;
179
180    /// Get rate limit status
181    async fn get_status(&self, client_id: &str) -> Result<RateLimitStatus>;
182
183    /// Reset rate limits for client
184    async fn reset_limits(&self, client_id: &str) -> Result<()>;
185}
186
187/// Request validator trait
188pub trait RequestValidator: Send + Sync {
189    /// Validate inference request
190    fn validate_inference_request(&self, request: &InferenceRequest) -> Result<()>;
191
192    /// Validate OpenAI chat request
193    fn validate_chat_request(&self, request: &crate::openai::ChatCompletionsRequest) -> Result<()>;
194
195    /// Validate request parameters
196    fn validate_parameters(&self, params: &serde_json::Value) -> Result<()>;
197
198    /// Get validation rules
199    fn get_rules(&self) -> &ValidationRules;
200}
201
202/// Health check provider
203#[async_trait]
204pub trait HealthChecker: Send + Sync {
205    /// Perform health check
206    async fn check_health(&self) -> HealthStatus;
207
208    /// Check specific component
209    async fn check_component(&self, component: &str) -> ComponentHealth;
210
211    /// Get health check configuration
212    fn config(&self) -> &HealthCheckConfig;
213}
214
215/// Metrics collector for server
216#[async_trait]
217pub trait MetricsCollector: Send + Sync {
218    /// Record request metrics
219    async fn record_request(
220        &self,
221        request: &HttpRequest,
222        response: &HttpResponse,
223        duration: Duration,
224    );
225
226    /// Record error metrics
227    async fn record_error(&self, error: &ferrum_types::FerrumError, endpoint: &str);
228
229    /// Get current metrics
230    fn get_metrics(&self) -> ServerMetrics;
231
232    /// Reset metrics
233    async fn reset_metrics(&self) -> Result<()>;
234}
235
236/// Server lifecycle manager
237#[async_trait]
238pub trait ServerLifecycle: Send + Sync {
239    /// Initialize server components
240    async fn initialize(&self) -> Result<()>;
241
242    /// Start all services
243    async fn start_services(&self) -> Result<()>;
244
245    /// Stop all services
246    async fn stop_services(&self, timeout: Duration) -> Result<()>;
247
248    /// Handle graceful shutdown
249    async fn graceful_shutdown(&self, signal: ShutdownSignal) -> Result<()>;
250
251    /// Get lifecycle state
252    fn get_state(&self) -> LifecycleState;
253}