Skip to main content

kotoba_server_core/
lib.rs

1//! # Kotoba Server Core
2//!
3//! Core HTTP server library for Kotoba providing basic HTTP/GraphQL server functionality.
4//! This crate contains the foundational server components without workflow dependencies.
5
6pub mod server;
7pub mod router;
8pub mod middleware;
9pub mod handlers;
10
11pub use server::{HttpServer, ServerConfig, ServerBuilder};
12pub use router::AppRouter;
13pub use middleware::{CorsConfig, LoggingConfig};
14pub use handlers::{HealthHandler, NotFoundHandler};
15
16use axum::{
17    Router,
18    response::IntoResponse,
19    http::StatusCode,
20};
21use tower_http::cors::{CorsLayer, Any};
22use tower_http::trace::TraceLayer;
23use std::net::SocketAddr;
24
25/// Core server error type
26#[derive(Debug, thiserror::Error)]
27pub enum ServerError {
28    #[error("HTTP server error: {0}")]
29    Http(#[from] hyper::Error),
30
31    #[error("IO error: {0}")]
32    Io(#[from] std::io::Error),
33
34    #[error("Configuration error: {0}")]
35    Config(String),
36
37    #[error("Handler error: {0}")]
38    Handler(String),
39}
40
41/// Result type for server operations
42pub type Result<T> = std::result::Result<T, ServerError>;
43
44/// Convert KotobaError to Axum response
45pub fn kotoba_error_to_response(err: &kotoba_errors::KotobaError) -> axum::response::Response {
46    let (status, message) = match err {
47        kotoba_errors::KotobaError::NotFound(resource) =>
48            (axum::http::StatusCode::NOT_FOUND, format!("Resource not found: {}", resource)),
49        kotoba_errors::KotobaError::Validation(details) =>
50            (axum::http::StatusCode::BAD_REQUEST, format!("Validation failed: {}", details)),
51        kotoba_errors::KotobaError::Security(details) =>
52            (axum::http::StatusCode::FORBIDDEN, format!("Forbidden: {}", details)),
53        kotoba_errors::KotobaError::InvalidArgument(details) =>
54            (axum::http::StatusCode::BAD_REQUEST, format!("Invalid argument: {}", details)),
55        _ => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, "An internal server error occurred".to_string()),
56    };
57
58    // Log the full error for debugging
59    tracing::error!("An error occurred: {:?}", err);
60
61    (status, message).into_response()
62}