elif-http 0.2.0

HTTP server core for the elif.rs LLM-friendly web framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! JSON handling utilities for requests and responses
//! 
//! Provides enhanced JSON parsing, validation, and error handling.

use axum::{
    extract::{FromRequest, Request},
    response::{IntoResponse, Response},
    http::{StatusCode, HeaderMap},
    Json,
};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::ops::{Deref, DerefMut};
use crate::error::{HttpError, HttpResult};
use crate::response::ElifResponse;

/// Enhanced JSON extractor with better error handling
#[derive(Debug)]
pub struct ElifJson<T>(pub T);

impl<T> ElifJson<T> {
    /// Create new ElifJson wrapper
    pub fn new(data: T) -> Self {
        Self(data)
    }

    /// Extract inner data
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for ElifJson<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for ElifJson<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for ElifJson<T> {
    fn from(data: T) -> Self {
        Self(data)
    }
}

/// JSON request extraction with enhanced error handling
#[axum::async_trait]
impl<T, S> FromRequest<S> for ElifJson<T>
where
    T: DeserializeOwned,
    S: Send + Sync,
{
    type Rejection = JsonError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        match Json::<T>::from_request(req, state).await {
            Ok(Json(data)) => Ok(ElifJson(data)),
            Err(rejection) => Err(JsonError::from_axum_json_rejection(rejection)),
        }
    }
}

/// JSON response implementation
impl<T> IntoResponse for ElifJson<T>
where
    T: Serialize,
{
    fn into_response(self) -> Response {
        match serde_json::to_vec(&self.0) {
            Ok(bytes) => {
                let mut response = Response::new(bytes.into());
                response.headers_mut().insert(
                    axum::http::header::CONTENT_TYPE,
                    axum::http::HeaderValue::from_static("application/json"),
                );
                response
            }
            Err(err) => {
                tracing::error!("JSON serialization failed: {}", err);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Internal server error: JSON serialization failed"
                ).into_response()
            }
        }
    }
}

/// Enhanced JSON error handling
#[derive(Debug)]
pub struct JsonError {
    pub status: StatusCode,
    pub message: String,
    pub details: Option<String>,
}

impl JsonError {
    /// Create new JSON error
    pub fn new(status: StatusCode, message: String) -> Self {
        Self {
            status,
            message,
            details: None,
        }
    }

    /// Create JSON error with details
    pub fn with_details(status: StatusCode, message: String, details: String) -> Self {
        Self {
            status,
            message,
            details: Some(details),
        }
    }

    /// Create from Axum JSON rejection
    pub fn from_axum_json_rejection(rejection: axum::extract::rejection::JsonRejection) -> Self {
        use axum::extract::rejection::JsonRejection::*;
        
        match rejection {
            JsonDataError(err) => {
                Self::with_details(
                    StatusCode::BAD_REQUEST,
                    "Invalid JSON data".to_string(),
                    err.to_string(),
                )
            }
            JsonSyntaxError(err) => {
                Self::with_details(
                    StatusCode::BAD_REQUEST,
                    "JSON syntax error".to_string(),
                    err.to_string(),
                )
            }
            MissingJsonContentType(_) => {
                Self::new(
                    StatusCode::BAD_REQUEST,
                    "Missing 'Content-Type: application/json' header".to_string(),
                )
            }
            BytesRejection(err) => {
                Self::with_details(
                    StatusCode::BAD_REQUEST,
                    "Failed to read request body".to_string(),
                    err.to_string(),
                )
            }
            _ => {
                Self::new(
                    StatusCode::BAD_REQUEST,
                    "Invalid JSON request".to_string(),
                )
            }
        }
    }
}

impl IntoResponse for JsonError {
    fn into_response(self) -> Response {
        let error_body = if let Some(details) = self.details {
            serde_json::json!({
                "error": {
                    "code": self.status.as_u16(),
                    "message": self.message,
                    "details": details
                }
            })
        } else {
            serde_json::json!({
                "error": {
                    "code": self.status.as_u16(),
                    "message": self.message
                }
            })
        };

        match ElifResponse::with_status(self.status)
            .json_value(error_body)
            .build()
        {
            Ok(response) => response,
            Err(_) => {
                // Fallback error response
                (self.status, self.message).into_response()
            }
        }
    }
}

/// JSON response helpers
pub struct JsonResponse;

impl JsonResponse {
    /// Create successful JSON response
    pub fn ok<T: Serialize>(data: &T) -> HttpResult<Response> {
        ElifResponse::json_ok(data)
    }

    /// Create JSON response with custom status
    pub fn with_status<T: Serialize>(status: StatusCode, data: &T) -> HttpResult<Response> {
        ElifResponse::with_status(status).json(data)?.build()
    }

    /// Create paginated JSON response
    pub fn paginated<T: Serialize>(
        data: &[T],
        page: u32,
        per_page: u32,
        total: u64,
    ) -> HttpResult<Response> {
        let total_pages = (total as f64 / per_page as f64).ceil() as u32;
        
        let response_data = serde_json::json!({
            "data": data,
            "pagination": {
                "page": page,
                "per_page": per_page,
                "total": total,
                "total_pages": total_pages,
                "has_next": page < total_pages,
                "has_prev": page > 1
            }
        });

        ElifResponse::ok().json_value(response_data).build()
    }

    /// Create error response with JSON body
    pub fn error(status: StatusCode, message: &str) -> HttpResult<Response> {
        ElifResponse::json_error(status, message)
    }

    /// Create validation error response
    pub fn validation_error<T: Serialize>(errors: &T) -> HttpResult<Response> {
        ElifResponse::validation_error(errors)
    }

    /// Create API success response with message
    pub fn success_message(message: &str) -> HttpResult<Response> {
        let response_data = serde_json::json!({
            "success": true,
            "message": message
        });

        ElifResponse::ok().json_value(response_data).build()
    }

    /// Create created resource response
    pub fn created<T: Serialize>(data: &T) -> HttpResult<Response> {
        ElifResponse::created().json(data)?.build()
    }

    /// Create no content response (for DELETE operations)
    pub fn no_content() -> HttpResult<Response> {
        ElifResponse::no_content().build()
    }
}

/// Validation error types for JSON responses
#[derive(Debug, Serialize, Deserialize)]
pub struct ValidationErrors {
    pub errors: std::collections::HashMap<String, Vec<String>>,
}

impl ValidationErrors {
    /// Create new validation errors container
    pub fn new() -> Self {
        Self {
            errors: std::collections::HashMap::new(),
        }
    }

    /// Add error for a field
    pub fn add_error(&mut self, field: String, error: String) {
        self.errors.entry(field).or_insert_with(Vec::new).push(error);
    }

    /// Add multiple errors for a field
    pub fn add_errors(&mut self, field: String, errors: Vec<String>) {
        self.errors.entry(field).or_insert_with(Vec::new).extend(errors);
    }

    /// Check if there are any errors
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Get error count
    pub fn error_count(&self) -> usize {
        self.errors.values().map(|v| v.len()).sum()
    }

    /// Convert to JSON response
    pub fn to_response(self) -> HttpResult<Response> {
        JsonResponse::validation_error(&self)
    }
}

impl Default for ValidationErrors {
    fn default() -> Self {
        Self::new()
    }
}

/// API response wrapper for consistent JSON responses
#[derive(Debug, Serialize)]
pub struct ApiResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub message: Option<String>,
    pub errors: Option<serde_json::Value>,
}

impl<T: Serialize> ApiResponse<T> {
    /// Create successful API response
    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            message: None,
            errors: None,
        }
    }

    /// Create successful API response with message
    pub fn success_with_message(data: T, message: String) -> Self {
        Self {
            success: true,
            data: Some(data),
            message: Some(message),
            errors: None,
        }
    }

    /// Create error API response
    pub fn error(message: String) -> ApiResponse<()> {
        ApiResponse {
            success: false,
            data: None,
            message: Some(message),
            errors: None,
        }
    }

    /// Create error API response with validation errors
    pub fn validation_error(message: String, errors: serde_json::Value) -> ApiResponse<()> {
        ApiResponse {
            success: false,
            data: None,
            message: Some(message),
            errors: Some(errors),
        }
    }

    /// Convert to HTTP response
    pub fn to_response(self) -> HttpResult<Response> {
        let status = if self.success {
            StatusCode::OK
        } else {
            StatusCode::BAD_REQUEST
        };

        ElifResponse::with_status(status).json(&self)?.build()
    }
}

impl<T: Serialize> IntoResponse for ApiResponse<T> {
    fn into_response(self) -> Response {
        match self.to_response() {
            Ok(response) => response,
            Err(e) => {
                tracing::error!("Failed to create API response: {}", e);
                (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
    struct TestData {
        name: String,
        age: u32,
    }

    #[test]
    fn test_elif_json_wrapper() {
        let data = TestData {
            name: "John".to_string(),
            age: 30,
        };
        
        let json_data = ElifJson::new(data.clone());
        assert_eq!(json_data.name, data.name);
        assert_eq!(json_data.age, data.age);
        
        let extracted = json_data.into_inner();
        assert_eq!(extracted, data);
    }

    #[test]
    fn test_validation_errors() {
        let mut errors = ValidationErrors::new();
        errors.add_error("name".to_string(), "Name is required".to_string());
        errors.add_error("age".to_string(), "Age must be positive".to_string());
        
        assert!(errors.has_errors());
        assert_eq!(errors.error_count(), 2);
    }

    #[test]
    fn test_api_response() {
        let data = TestData {
            name: "Jane".to_string(),
            age: 25,
        };
        
        let success_response = ApiResponse::success(data);
        assert!(success_response.success);
        assert!(success_response.data.is_some());
        
        let error_response = ApiResponse::<()>::error("Something went wrong".to_string());
        assert!(!error_response.success);
        assert!(error_response.data.is_none());
        assert_eq!(error_response.message, Some("Something went wrong".to_string()));
    }

    #[test]
    fn test_json_response_helpers() {
        let data = vec![
            TestData { name: "User1".to_string(), age: 20 },
            TestData { name: "User2".to_string(), age: 25 },
        ];
        
        // Test paginated response
        let response = JsonResponse::paginated(&data, 1, 10, 25);
        assert!(response.is_ok());
    }
}