use std::time::Duration;
use super::EvaluateRequest;
use super::ServerError;
use super::evaluate::{REQUEST_TIMEOUT_SECS, evaluate_with_timeout};
use crate::i18n::I18n;
use axum::Router;
use axum::extract::DefaultBodyLimit;
use axum::routing::{get, post};
#[cfg(all(feature = "fx", feature = "mcp"))]
use super::fx_tools::{FxBudgetRequest, FxPricingRequest, fx_budget, fx_pricing};
#[cfg(feature = "ratelimit")]
use sdforge::security::HttpRequestRateLimiter;
#[cfg(feature = "ratelimit")]
use std::sync::Arc;
const MAX_BODY_SIZE: usize = 64 * 1024;
const DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub fn build_router() -> Router {
#[cfg(feature = "ratelimit")]
{
let limiter: Arc<dyn HttpRequestRateLimiter> =
Arc::new(super::ratelimit::FixedWindowLimiter::from_env());
finish_router(api_router().layer(sdforge::security::RateLimitLayer::new(limiter)))
}
#[cfg(not(feature = "ratelimit"))]
{
finish_router(api_router())
}
}
#[cfg(all(test, feature = "ratelimit"))]
pub(crate) fn build_router_with_limiter(limiter: Arc<dyn HttpRequestRateLimiter>) -> Router {
finish_router(api_router().layer(sdforge::security::RateLimitLayer::new(limiter)))
}
#[cfg_attr(not(all(feature = "fx", feature = "mcp")), allow(unused_mut))] fn api_router() -> Router {
let mut api = Router::new()
.route("/api/v1/evaluate", post(evaluate_http_handler))
.route("/api/v1/list_functions", post(list_functions_http_handler));
#[cfg(all(feature = "fx", feature = "mcp"))]
{
api = api
.route("/api/v1/fx_budget", post(fx_budget_http_handler))
.route("/api/v1/fx_pricing", post(fx_pricing_http_handler));
}
api
}
fn finish_router(api: Router) -> Router {
register_cache_readiness_check();
#[cfg(feature = "docs")]
let mut router = Router::new().merge(sdforge::docs::swagger_ui_router());
#[cfg(not(feature = "docs"))]
let mut router = Router::new();
router = router
.merge(api)
.route("/health", get(sdforge::health::readyz_handler))
.route("/ready", get(sdforge::health::readyz_handler))
.route("/live", get(sdforge::health::healthz_handler))
.route("/metrics", get(metrics_handler))
.layer(DefaultBodyLimit::max(MAX_BODY_SIZE))
.layer(axum::middleware::from_fn(request_count_middleware))
.layer(axum::middleware::from_fn(
sdforge::context::context_middleware,
));
router
}
const READINESS_TIMEOUT: Duration = Duration::from_secs(5);
fn register_cache_readiness_check() {
use std::sync::OnceLock;
static REGISTER: OnceLock<()> = OnceLock::new();
REGISTER.get_or_init(|| {
sdforge::health::register_async_readiness_check_fn("cache", || async {
run_readiness_with_timeout("cache", READINESS_TIMEOUT, cache_stats_outcome()).await
});
});
}
async fn cache_stats_outcome() -> sdforge::health::CheckOutcome {
match tokio::task::spawn_blocking(|| super::cache::shared_cache().stats()).await {
Ok(stats) => sdforge::health::CheckOutcome {
name: "cache".to_string(),
healthy: true,
details: Some(serde_json::json!({ "entry_count": stats.entry_count })),
},
Err(_) => sdforge::health::CheckOutcome::unhealthy(
"cache",
I18n::from_detected().t("server.cache_stats_task_failed"),
),
}
}
async fn run_readiness_with_timeout(
name: &str,
timeout: Duration,
check: impl std::future::Future<Output = sdforge::health::CheckOutcome>,
) -> sdforge::health::CheckOutcome {
match tokio::time::timeout(timeout, check).await {
Ok(outcome) => outcome,
Err(_) => {
let reason = I18n::from_detected().tf(
"server.readiness_check_timed_out",
&[("timeout", &format!("{timeout:?}"))],
);
sdforge::health::CheckOutcome::unhealthy(name, reason)
}
}
}
async fn evaluate_http_handler(
axum::extract::Json(req): axum::extract::Json<EvaluateRequest>,
) -> axum::response::Response {
use axum::response::IntoResponse;
match evaluate_with_timeout(req, Duration::from_secs(REQUEST_TIMEOUT_SECS)).await {
Ok(resp) => axum::Json(resp).into_response(),
Err(api_err) => api_err.into_response(),
}
}
async fn list_functions_http_handler(
axum::extract::Json(_req): axum::extract::Json<super::catalog::ListFunctionsRequest>,
) -> axum::response::Response {
use axum::response::IntoResponse;
match super::catalog::list_functions_inner().await {
Ok(resp) => axum::Json(resp).into_response(),
Err(api_err) => api_err.into_response(),
}
}
#[cfg(all(feature = "fx", feature = "mcp"))]
async fn fx_budget_http_handler(
axum::extract::Json(req): axum::extract::Json<FxBudgetRequest>,
) -> axum::response::Response {
use axum::response::IntoResponse;
match fx_budget(req).await {
Ok(resp) => axum::Json(resp).into_response(),
Err(api_err) => api_err.into_response(),
}
}
#[cfg(all(feature = "fx", feature = "mcp"))]
async fn fx_pricing_http_handler(
axum::extract::Json(req): axum::extract::Json<FxPricingRequest>,
) -> axum::response::Response {
use axum::response::IntoResponse;
match fx_pricing(req).await {
Ok(resp) => axum::Json(resp).into_response(),
Err(api_err) => api_err.into_response(),
}
}
async fn request_count_middleware(
req: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
let started = std::time::Instant::now();
let method = req.method().as_str().to_string();
let route = req.uri().path().to_string();
let resp = next.run(req).await;
sdforge::metrics::record_request(
&route,
&method,
resp.status().as_u16(),
started.elapsed().as_secs_f64(),
);
resp
}
#[derive(serde::Deserialize)]
struct MetricsQuery {
format: Option<String>,
}
async fn metrics_handler(query: axum::extract::Query<MetricsQuery>) -> axum::response::Response {
use axum::response::IntoResponse;
let stats = super::cache::shared_cache().stats();
if query.format.as_deref() == Some("json") {
let body = serde_json::json!({
"hits": stats.hits,
"misses": stats.misses,
"entry_count": stats.entry_count,
"http_route_count": sdforge::metrics::global_registry().route_count(),
});
(
[(axum::http::header::CONTENT_TYPE, "application/json")],
body.to_string(),
)
.into_response()
} else {
let prometheus = format!(
"# HELP calnexus_cache_hits Cache hit count.\n\
# TYPE calnexus_cache_hits counter\n\
calnexus_cache_hits {}\n\
# HELP calnexus_cache_misses Cache miss count.\n\
# TYPE calnexus_cache_misses counter\n\
calnexus_cache_misses {}\n\
# HELP calnexus_cache_entries Current number of cached entries.\n\
# TYPE calnexus_cache_entries gauge\n\
calnexus_cache_entries {}\n\
{}",
stats.hits,
stats.misses,
stats.entry_count,
sdforge::metrics::global_registry().render()
);
(
[(
axum::http::header::CONTENT_TYPE,
"text/plain; version=0.0.4",
)],
prometheus,
)
.into_response()
}
}
#[derive(Debug, Clone)]
pub struct HttpServer {
addr: String,
}
impl Default for HttpServer {
fn default() -> Self {
Self::new()
}
}
impl HttpServer {
pub fn new() -> Self {
Self {
addr: "127.0.0.1:3000".to_string(),
}
}
pub fn with_addr(mut self, addr: impl Into<String>) -> Self {
self.addr = addr.into();
self
}
pub fn addr(&self) -> &str {
&self.addr
}
pub fn run(&self) -> Result<(), ServerError> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|e| ServerError::Http(format!("failed to create tokio runtime: {}", e)))?;
let result = runtime.block_on(self.start_inner());
std::mem::forget(runtime);
result
}
async fn start_inner(&self) -> Result<(), ServerError> {
let listener = tokio::net::TcpListener::bind(&self.addr)
.await
.map_err(|e| ServerError::Http(format!("failed to bind {}: {}", self.addr, e)))?;
#[cfg(feature = "observability")]
match crate::server::init_observability().await {
Ok(()) => {}
Err(inklog::InklogError::ConfigError(_)) => {}
Err(e) => {
return Err(ServerError::Http(I18n::from_detected().tf(
"server.observability_init_failed",
&[("error", &e.to_string())],
)));
}
}
#[cfg(not(feature = "observability"))]
crate::server::init_observability().await;
let router = build_router();
sdforge::http::serve_with_graceful_shutdown_connect_info(
router,
listener,
sdforge::http::default_shutdown_signal(),
sdforge::http::GracefulShutdownConfig::with_drain_timeout(DRAIN_TIMEOUT),
)
.await
.map_err(|e| ServerError::Http(format!("server error: {}", e)))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_http_server_new_default_addr() {
let server = HttpServer::new();
assert_eq!(server.addr(), "127.0.0.1:3000");
}
#[test]
fn test_http_server_default_equals_new() {
let server = HttpServer::default();
assert_eq!(server.addr(), "127.0.0.1:3000");
}
#[test]
fn test_http_server_with_addr_custom() {
let server = HttpServer::new().with_addr("0.0.0.0:8080");
assert_eq!(server.addr(), "0.0.0.0:8080");
}
#[test]
fn test_http_server_run_bind_error() {
let server = HttpServer::new().with_addr("127.0.0.1:99999");
let result = server.run();
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, ServerError::Http(_)));
assert!(err.to_string().contains("failed to bind"));
}
#[tokio::test]
async fn test_http_start_inner_bind_error() {
let server = HttpServer::new().with_addr("127.0.0.1:99999");
let result = server.start_inner().await;
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), ServerError::Http(_)));
}
#[test]
fn test_default_shutdown_signal_is_send() {
fn assert_send<T: Send + ?Sized>(_: &T) {}
let fut = sdforge::http::default_shutdown_signal();
assert_send(&fut);
}
#[test]
fn test_drain_timeout_matches_sdforge_default() {
assert_eq!(
DRAIN_TIMEOUT,
sdforge::http::GracefulShutdownConfig::default().drain_timeout
);
}
#[cfg(feature = "http")]
#[tokio::test]
async fn test_sdforge_probe_shapes() {
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
use tower::ServiceExt;
let router = build_router();
for path in ["/health", "/ready"] {
let resp = router
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), 200, "{path} 应就绪");
let bytes = BodyExt::collect(resp.into_body()).await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["status"], "ready", "{path} 状态应为 ready");
let checks = json["checks"].as_array().unwrap();
assert!(
checks
.iter()
.any(|c| c["name"] == "cache" && c["healthy"] == true),
"{path} 应含 cache readiness check: {json}"
);
assert!(
checks[0]["details"]["entry_count"].is_u64(),
"cache check 应携带 entry_count 明细"
);
}
let resp = router
.oneshot(
Request::builder()
.method("GET")
.uri("/live")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), 200);
let bytes = BodyExt::collect(resp.into_body()).await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["status"], "healthy");
assert!(json.get("checks").is_none(), "/live 不应含检查器");
}
#[tokio::test]
async fn test_context_middleware_and_request_count() {
use axum::body::Body;
use axum::http::Request;
use tower::ServiceExt;
let router = build_router();
let resp = router
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/live")
.header("x-request-id", "my-trace-42")
.header(
"traceparent",
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
resp.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok()),
Some("my-trace-42"),
"入站 X-Request-ID 应透传"
);
assert_eq!(
resp.headers()
.get("x-trace-id")
.and_then(|v| v.to_str().ok()),
Some("4bf92f3577b34da6a3ce929d0e0e4736"),
"应从 W3C traceparent 提取 trace_id 回写 X-Trace-ID"
);
let registry = sdforge::metrics::global_registry();
registry.reset();
let _ = router
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/live")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(
registry.route_count() >= 1,
"请求后 sdforge registry 应记录路由序列(RED 计数取代手写 static)"
);
}
#[tokio::test]
async fn test_readiness_timeout_marks_unhealthy() {
let outcome =
run_readiness_with_timeout("cache", Duration::from_millis(10), std::future::pending())
.await;
assert!(!outcome.healthy, "超时应判不健康");
assert_eq!(outcome.name, "cache");
let expected =
I18n::from_detected().tf("server.readiness_check_timed_out", &[("timeout", "10ms")]);
assert_eq!(
outcome.details.as_ref().and_then(|d| d["error"].as_str()),
Some(expected.as_str()),
"超时原因应写入 details.error: {:?}",
outcome.details
);
}
#[test]
fn test_probe_error_messages_resolve_from_catalog() {
let en = I18n::new(crate::i18n::Lang::En);
assert_eq!(
en.t("server.cache_stats_task_failed"),
"cache stats task failed"
);
assert_eq!(
en.tf("server.readiness_check_timed_out", &[("timeout", "5s")]),
"readiness check timed out after 5s"
);
assert_eq!(
en.tf("server.observability_init_failed", &[("error", "boom")]),
"observability init failed: boom"
);
let zh = I18n::new(crate::i18n::Lang::Zh);
assert_eq!(zh.t("server.cache_stats_task_failed"), "缓存统计任务失败");
assert_eq!(
zh.tf("server.readiness_check_timed_out", &[("timeout", "5s")]),
"就绪检查在 5s 后超时"
);
assert_eq!(
zh.tf("server.observability_init_failed", &[("error", "boom")]),
"可观测性初始化失败: boom"
);
}
#[tokio::test]
async fn test_cache_stats_outcome_reports_entry_count() {
let cf = crate::core::CanonicalForm::new("(readiness-async 1)");
super::super::cache::shared_cache().insert(&cf, &Ok(crate::core::EvalResult::Scalar(1.0)));
let outcome = cache_stats_outcome().await;
assert!(outcome.healthy, "cache 检查应健康");
assert_eq!(outcome.name, "cache");
assert!(
outcome
.details
.as_ref()
.and_then(|d| d["entry_count"].as_u64())
.is_some_and(|n| n >= 1),
"插入条目后 entry_count 应 ≥1: {:?}",
outcome.details
);
}
#[cfg(feature = "ratelimit")]
mod ratelimit_mount {
use super::super::{HttpRequestRateLimiter, build_router_with_limiter};
use std::sync::Arc;
use tower::ServiceExt;
#[tokio::test]
async fn test_ratelimit_small_threshold_rejects_with_429() {
use crate::server::ratelimit::FixedWindowLimiter;
let limiter: Arc<dyn HttpRequestRateLimiter> =
Arc::new(FixedWindowLimiter::with_config(2, 60));
let router = build_router_with_limiter(limiter);
let request = || {
axum::http::Request::builder()
.method("POST")
.uri("/api/v1/list_functions")
.header("content-type", "application/json")
.body(axum::body::Body::from("{}"))
.unwrap()
};
for i in 0..2 {
let resp = router.clone().oneshot(request()).await.unwrap();
assert_eq!(resp.status(), 200, "第 {} 个请求应在阈值内放行", i + 1);
}
let resp = router.oneshot(request()).await.unwrap();
assert_eq!(resp.status(), 429, "超出阈值应返回 429");
assert_eq!(
resp.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok()),
Some("60"),
"429 应携带 Retry-After(秒)"
);
}
#[tokio::test]
async fn test_probes_exempt_from_ratelimit() {
use crate::server::ratelimit::FixedWindowLimiter;
let limiter: Arc<dyn HttpRequestRateLimiter> =
Arc::new(FixedWindowLimiter::with_config(1, 60));
let router = build_router_with_limiter(limiter);
let api_request = || {
axum::http::Request::builder()
.method("POST")
.uri("/api/v1/list_functions")
.header("content-type", "application/json")
.body(axum::body::Body::from("{}"))
.unwrap()
};
let _ = router.clone().oneshot(api_request()).await.unwrap();
for path in ["/live", "/metrics", "/health", "/ready"] {
let resp = router
.clone()
.oneshot(
axum::http::Request::builder()
.method("GET")
.uri(path)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), 200, "探针/metrics 应豁免限流: {path}");
}
}
}
}