use super::shared_cache;
use super::{EvaluateRequest, EvaluateResponse};
use crate::core::{CalcError, ErrorKind};
use crate::evaluate as eval_expr;
use sdforge::error::ApiError;
use sdforge::forge;
use std::time::Duration;
pub const REQUEST_TIMEOUT_SECS: u64 = 30;
#[forge(
name = "evaluate",
version = "v1",
path = "/evaluate",
method = "POST",
tool_name = "evaluate",
description = "Evaluate a math expression. Returns {result, domain, cache}. Supports vars and precision."
)]
pub(crate) async fn evaluate(req: EvaluateRequest) -> Result<EvaluateResponse, ApiError> {
evaluate_with_timeout(req, Duration::from_secs(REQUEST_TIMEOUT_SECS)).await
}
pub(crate) async fn evaluate_with_timeout(
req: EvaluateRequest,
timeout: Duration,
) -> Result<EvaluateResponse, ApiError> {
req.validate()?;
let ctx = req.to_eval_context();
let precision = req.precision;
let expr = req.expr.clone();
let join_handle = tokio::task::spawn_blocking(move || {
let cache = shared_cache();
eval_expr(&expr, &ctx, precision, cache)
});
let (result, domain, cache_hit, fmt_prec) =
match tokio::time::timeout(timeout, join_handle).await {
Ok(Ok(r)) => r,
Ok(Err(join_err)) => {
return Err(ApiError::internal_with_source(
"evaluate task failed",
"spawn_blocking",
join_err,
))
}
Err(_) => {
return Err(ApiError::service_unavailable(
"evaluate",
Some(timeout.as_secs()),
))
}
}
.map_err(calc_error_to_api_error)?;
Ok(EvaluateResponse::from_eval(
result, domain, cache_hit, fmt_prec,
))
}
pub fn calc_error_to_api_error(e: CalcError) -> ApiError {
match e.kind {
ErrorKind::Timeout => ApiError::service_unavailable("evaluate", Some(30)),
kind => ApiError::invalid_input(
format!("{}: {}", error_kind_prefix(kind), e.message),
None,
None,
),
}
}
fn error_kind_prefix(kind: ErrorKind) -> &'static str {
match kind {
ErrorKind::Parse => "Parse",
ErrorKind::Eval => "Eval",
ErrorKind::Overflow => "Overflow",
ErrorKind::DivisionByZero => "DivisionByZero",
ErrorKind::Domain => "Domain",
ErrorKind::Depth => "Depth",
ErrorKind::NaNOrInf => "NaNOrInf",
ErrorKind::UndefinedSymbol => "UndefinedSymbol",
ErrorKind::Timeout => "Timeout",
ErrorKind::Usage => "Usage",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calc_error_to_api_error_compute_kinds_map_to_invalid_input() {
let cases: [(&str, CalcError); 8] = [
("Parse", CalcError::parse("unexpected token '@'")),
("Eval", CalcError::eval("domain violation")),
("Overflow", CalcError::overflow()),
("DivisionByZero", CalcError::division_by_zero()),
("Domain", CalcError::domain("sqrt of negative")),
("Depth", CalcError::depth_exceeded()),
("NaNOrInf", CalcError::nan_or_inf()),
("UndefinedSymbol", CalcError::undefined_symbol("foo")),
];
for (prefix, err) in cases {
let api = calc_error_to_api_error(err);
match api {
ApiError::InvalidInput {
message,
field,
value,
} => {
let expected = format!("{}:", prefix);
assert!(
message.starts_with(&expected),
"kind {prefix:?}: message {message:?} 应以前缀 {expected:?} 开头"
);
assert!(field.is_none(), "kind {prefix:?}: field 应为 None");
assert!(value.is_none(), "kind {prefix:?}: value 应为 None");
}
other => panic!("kind {prefix:?}: 期望 InvalidInput,得到 {other:?}"),
}
}
}
#[test]
fn calc_error_to_api_error_usage_maps_to_invalid_input() {
let api = calc_error_to_api_error(CalcError::usage("invalid --var"));
match api {
ApiError::InvalidInput { message, .. } => {
assert!(message.starts_with("Usage:"));
assert!(message.contains("invalid --var"));
}
other => panic!("期望 InvalidInput,得到 {other:?}"),
}
}
#[test]
fn calc_error_to_api_error_timeout_maps_to_service_unavailable() {
let api = calc_error_to_api_error(CalcError::timeout());
match api {
ApiError::ServiceUnavailable {
service,
retry_after,
..
} => {
assert_eq!(service, "evaluate");
assert_eq!(retry_after, Some(30));
}
other => panic!("期望 ServiceUnavailable,得到 {other:?}"),
}
}
#[test]
fn calc_error_to_api_error_preserves_original_message() {
let api = calc_error_to_api_error(CalcError::parse("the @ token is bad"));
match api {
ApiError::InvalidInput { message, .. } => {
assert!(message.starts_with("Parse:"));
assert!(message.contains("the @ token is bad"));
}
_ => panic!("期望 InvalidInput"),
}
}
#[tokio::test]
async fn test_evaluate_with_timeout_succeeds_on_simple_expr() {
let req = EvaluateRequest {
expr: "2+3".into(),
vars: std::collections::HashMap::new(),
precision: None,
};
let result = evaluate_with_timeout(req, Duration::from_secs(5)).await;
assert!(result.is_ok(), "simple expr should succeed within 5s");
let resp = result.unwrap();
assert_eq!(resp.domain, "arithmetic");
assert!(resp.cache == "hit" || resp.cache == "miss");
}
#[tokio::test]
async fn test_evaluate_with_timeout_returns_service_unavailable_on_zero_timeout() {
let req = EvaluateRequest {
expr: "precision(10000, factorial(10000))".into(),
vars: std::collections::HashMap::new(),
precision: None,
};
let result = evaluate_with_timeout(req, Duration::from_nanos(1)).await;
assert!(result.is_err());
match result.unwrap_err() {
ApiError::ServiceUnavailable { service, .. } => {
assert_eq!(service, "evaluate");
}
other => panic!("期望 ServiceUnavailable,得到 {other:?}"),
}
}
#[tokio::test]
async fn test_evaluate_with_timeout_returns_service_unavailable_on_slow_expr() {
let req = EvaluateRequest {
expr: "precision(10000, factorial(10000))".into(),
vars: std::collections::HashMap::new(),
precision: None,
};
let result = evaluate_with_timeout(req, Duration::from_millis(1)).await;
assert!(result.is_err());
match result.unwrap_err() {
ApiError::ServiceUnavailable { service, .. } => {
assert_eq!(service, "evaluate");
}
other => panic!("期望 ServiceUnavailable(慢表达式超时),得到 {other:?}"),
}
}
#[tokio::test]
async fn test_evaluate_with_timeout_validates_before_timeout() {
let req = EvaluateRequest {
expr: String::new(),
vars: std::collections::HashMap::new(),
precision: None,
};
let result = evaluate_with_timeout(req, Duration::from_secs(5)).await;
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ApiError::ValidationError { .. }
));
}
#[test]
fn test_request_timeout_secs_is_30() {
assert_eq!(REQUEST_TIMEOUT_SECS, 30);
}
}