calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! HTTP server 集成测试:`POST /api/v1/evaluate` 等端点(`#[forge]` 生成)。
//! 经 tower oneshot 直测 Router;错误契约 400 `BAD_REQUEST` / 422 `UNPROCESSABLE_ENTITY`(sdforge UnifiedError 体)。
use calnexus::build_router;
use http_body_util::BodyExt;
use sdforge::axum::Body;
use sdforge::axum::http::Request;
use sdforge::axum::http::status::StatusCode;
use serde_json::{Value, json};
use tower::ServiceExt;

/// 构建 POST /api/v1/evaluate 请求。
fn make_evaluate_request(body: Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri("/api/v1/evaluate")
        .header("content-type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

/// 发送请求并返回 (status, body_json)。
async fn send_request(body: Value) -> (StatusCode, Value) {
    let router = build_router();
    let response = router
        .oneshot(make_evaluate_request(body))
        .await
        .expect("router oneshot failed");
    let status = response.status();
    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("body collection failed")
        .to_bytes();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
    (status, json)
}

/// 标量求值:POST "2+3" → 200,result=5、cache=miss。
#[tokio::test]
async fn test_http_evaluate_scalar() {
    let (status, body) = send_request(json!({"expr": "2+3"})).await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["result"], 5);
    assert_eq!(body["domain"], "arithmetic");
    assert_eq!(body["cache"], "miss");
}

/// 带变量求值:vars{x:10} → 200,result=11。
#[tokio::test]
async fn test_http_evaluate_with_vars() {
    let (status, body) = send_request(json!({"expr": "x+1", "vars": {"x": 10.0}})).await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["result"], 11);
    assert_eq!(body["domain"], "arithmetic");
}

/// 精度模式:precision=5 → 200,domain=precision,result 为字符串。
#[tokio::test]
async fn test_http_evaluate_precision() {
    let (status, body) = send_request(json!({"expr": "1/3", "precision": 5})).await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["domain"], "precision");
    // precision 模式下 result 是字符串(BigRational 格式化)
    assert!(body["result"].as_str().is_some());
}

/// 缓存语义:相同表达式首次 miss、第二次 hit。
#[tokio::test]
async fn test_http_evaluate_cache_miss() {
    // 首次请求:缓存未命中
    let (status, body) = send_request(json!({"expr": "7+8"})).await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["cache"], "miss");
    assert_eq!(body["result"], 15);

    // 第二次请求相同表达式:缓存命中
    let (status, body) = send_request(json!({"expr": "7+8"})).await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["cache"], "hit");
    assert_eq!(body["result"], 15);
}

/// 计算错误(1/0)→ 400 code=BAD_REQUEST,message 含 ErrorKind 前缀。
#[tokio::test]
async fn test_http_evaluate_calc_error_invalid_input() {
    // lang=en 钉定:message 的 ErrorKind 前缀文本随语言渲染,与真机系统区域解耦
    let (status, body) = send_request(json!({"expr": "1/0", "lang": "en"})).await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["code"], "BAD_REQUEST");
    // message 含 ErrorKind 前缀(calc_error_to_api_error 注入 "DivisionByZero:")
    assert!(
        body["message"]
            .as_str()
            .is_some_and(|m| m.contains("DivisionByZero")),
        "message 应含 ErrorKind 前缀: {}",
        body["message"]
    );
}

/// precision 超限(>10000)→ 422 code=UNPROCESSABLE_ENTITY,field=precision。
#[tokio::test]
async fn test_http_evaluate_validation_error_oversized_precision() {
    let (status, body) = send_request(json!({"expr": "2+3", "precision": 10001})).await;

    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(body["code"], "UNPROCESSABLE_ENTITY");
    assert_eq!(body["field"], "precision");
    // 统一错误体只保留 field:限额明细自 sdforge 0.5.0-rc.6 起不再进 HTTP body
    assert!(
        body["message"]
            .as_str()
            .is_some_and(|m| m.contains("precision")),
        "message 应指明违规字段: {}",
        body["message"]
    );
}

/// vars 键数超限(>1024)→ 422 code=UNPROCESSABLE_ENTITY,field=vars。
#[tokio::test]
async fn test_http_evaluate_validation_error_oversized_vars() {
    // 构造 1025 个 vars(超过 MAX_VARS=1024)
    let mut vars = serde_json::Map::new();
    for i in 0..=1024u32 {
        vars.insert(format!("v{i}"), json!(0.0));
    }
    let (status, body) = send_request(json!({"expr": "v1", "vars": vars})).await;

    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(body["code"], "UNPROCESSABLE_ENTITY");
    assert_eq!(body["field"], "vars");
}

// ===== Health Check 端点测试 =====

/// 发送 GET 请求并返回 (status, body_json)。
async fn send_get_request(uri: &str) -> (StatusCode, Value) {
    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri(uri)
        .body(Body::empty())
        .unwrap();
    let response = router
        .oneshot(request)
        .await
        .expect("router oneshot failed");
    let status = response.status();
    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("body collection failed")
        .to_bytes();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
    (status, json)
}

/// GET /health → 200,checks 数组含 cache 的 entry_count 明细。
#[tokio::test]
async fn test_health_endpoint_healthy() {
    let (status, body) = send_get_request("/health").await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "ready");
    let checks = body["checks"].as_array().expect("checks 应为数组");
    let cache = checks
        .iter()
        .find(|c| c["name"] == "cache")
        .expect("应包含 cache 检查器");
    assert_eq!(cache["healthy"], true);
    assert!(
        cache["details"]["entry_count"].is_u64(),
        "cache 检查应携带 entry_count 明细"
    );
}

/// GET /live → 200 status=healthy,无 checks 字段。
#[tokio::test]
async fn test_liveness_endpoint_healthy() {
    let (status, body) = send_get_request("/live").await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "healthy");
    assert!(body.get("checks").is_none(), "/live 不应包含检查器");
}

/// GET /ready → 200,契约同 /health。
#[tokio::test]
async fn test_readiness_endpoint_healthy() {
    let (status, body) = send_get_request("/ready").await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "ready");
    let checks = body["checks"].as_array().expect("checks 应为数组");
    assert!(
        checks
            .iter()
            .any(|c| c["name"] == "cache" && c["healthy"] == true),
        "应包含健康的 cache 检查器"
    );
}

// ===== Metrics 端点测试 =====

/// GET /metrics → 200 + Prometheus 文本格式(默认)
#[tokio::test]
async fn test_metrics_prometheus_format() {
    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri("/metrics")
        .body(Body::empty())
        .unwrap();
    let response = router
        .oneshot(request)
        .await
        .expect("router oneshot failed");

    assert_eq!(response.status(), StatusCode::OK);
    let content_type = response
        .headers()
        .get("content-type")
        .map(|v| v.to_str().unwrap_or(""))
        .unwrap_or("");
    assert!(
        content_type.contains("text/plain"),
        "默认应为 text/plain: {}",
        content_type
    );

    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body = String::from_utf8_lossy(&bytes);
    assert!(
        body.contains("cache")
            || body.contains("operations")
            || body.is_empty()
            || body.contains("#"),
        "Prometheus 格式应包含缓存指标或为空注释: {}",
        &body[..body.len().min(200)]
    );
}

/// GET /metrics?format=json → 200 + JSON 格式
#[tokio::test]
async fn test_metrics_json_format() {
    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri("/metrics?format=json")
        .body(Body::empty())
        .unwrap();
    let response = router
        .oneshot(request)
        .await
        .expect("router oneshot failed");

    assert_eq!(response.status(), StatusCode::OK);
    let content_type = response
        .headers()
        .get("content-type")
        .map(|v| v.to_str().unwrap_or(""))
        .unwrap_or("");
    assert!(
        content_type.contains("application/json"),
        "JSON 格式应为 application/json: {}",
        content_type
    );

    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
    // JSON metrics 应包含缓存统计字段
    assert!(json.is_object(), "JSON metrics 应返回对象");
}

// ===== 服务化最小包 =====

/// 无标识请求 → 响应回写生成的 X-Request-ID(req-* 前缀)。
#[tokio::test]
async fn test_request_id_generated() {
    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri("/health")
        .body(Body::empty())
        .unwrap();
    let response = router.oneshot(request).await.expect("oneshot failed");
    let rid = response
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(rid.starts_with("req-"), "应生成 req-* 标识,实际: {}", rid);
}

/// 入站 X-Request-ID 头 → 响应透传同值。
#[tokio::test]
async fn test_request_id_passthrough() {
    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri("/health")
        .header("x-request-id", "my-trace-42")
        .body(Body::empty())
        .unwrap();
    let response = router.oneshot(request).await.expect("oneshot failed");
    assert_eq!(
        response
            .headers()
            .get("x-request-id")
            .and_then(|v| v.to_str().ok()),
        Some("my-trace-42"),
        "入站 X-Request-ID 应透传"
    );
}

/// /metrics 应含 sdforge RED 指标族 sdforge_http_requests_total。
#[tokio::test]
async fn test_metrics_http_requests_total() {
    let router = build_router();
    let _ = router
        .clone()
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    let response = router
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/metrics")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("oneshot failed");
    let bytes = http_body_util::BodyExt::collect(response.into_body())
        .await
        .unwrap()
        .to_bytes();
    let text = String::from_utf8_lossy(&bytes);
    assert!(
        text.contains("sdforge_http_requests_total"),
        "/metrics 应含 sdforge RED 指标族(T011 后取代 calnexus_http_requests_total): {}",
        &text[..text.len().min(300)]
    );
}

// === 语言协商(lang 请求字段)===

/// 缺省 lang:错误消息跟随系统语言检测链。
#[tokio::test]
async fn test_http_evaluate_default_lang_follows_detection() {
    let expect_zh = calnexus::I18n::from_detected().lang() == calnexus::Lang::Zh;
    let (status, body) = send_request(json!({"expr": "foo + 1"})).await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["code"], "BAD_REQUEST");
    let message = body["message"].as_str().expect("message field");
    if expect_zh {
        assert!(
            message.contains("求值错误") && message.contains("未绑定变量"),
            "检测为 zh 时缺省 lang 应输出中文: {message}"
        );
    } else {
        assert!(
            message.starts_with("Eval:") && message.contains("unbound variable: foo"),
            "检测为 en 时缺省 lang 应保持英文契约: {message}"
        );
    }
}

/// lang=zh 错误消息切换中文:kind 标签 + 参数化 detail 均本地化。
#[tokio::test]
async fn test_http_evaluate_zh_lang_localized_error() {
    let (status, body) = send_request(json!({"expr": "foo + 1", "lang": "zh"})).await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["code"], "BAD_REQUEST");
    assert!(
        body["message"]
            .as_str()
            .is_some_and(|m| m.contains("求值错误")
                && m.contains("未绑定变量")
                && m.contains("foo")),
        "zh 协商应返回中文消息: {}",
        body["message"]
    );
    // 机器可读错误码保持英文协议值
    assert_eq!(body["code"], "BAD_REQUEST");
}

/// lang=en 显式请求:恒为英文机器契约。
#[tokio::test]
async fn test_http_evaluate_explicit_en_matches_default() {
    let expect_zh = calnexus::I18n::from_detected().lang() == calnexus::Lang::Zh;
    let (_, default_body) = send_request(json!({"expr": "foo + 1"})).await;
    let (_, en_body) = send_request(json!({"expr": "foo + 1", "lang": "en"})).await;

    // 显式 en 恒为英文契约
    assert!(
        en_body["message"]
            .as_str()
            .is_some_and(|m| m.starts_with("Eval:") && m.contains("unbound variable")),
        "lang=en 应保持英文契约: {}",
        en_body["message"]
    );
    // 缺省 lang 仅在环境检测为 en 时与显式 en 逐字节一致
    if !expect_zh {
        assert_eq!(default_body["message"], en_body["message"]);
    }
}

/// 未知 lang 值宽松回退英文(与 CLI --lang 行为一致)。
#[tokio::test]
async fn test_http_evaluate_unknown_lang_falls_back_to_english() {
    let (status, body) = send_request(json!({"expr": "foo + 1", "lang": "xx-Klingon"})).await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["message"]
            .as_str()
            .is_some_and(|m| m.starts_with("Eval:") && m.contains("unbound variable")),
        "未知 lang 应回退英文: {}",
        body["message"]
    );
}

// ===== /metrics 委托 sdforge metrics(RED 采集 + route_count 读回) =====

/// /metrics 经 sdforge 全局 registry 记录路由序列,render 含 RED 指标族。
#[tokio::test]
async fn test_metrics_records_red_via_sdforge_registry() {
    let registry = sdforge::metrics::global_registry();

    // 预热:中间件在 handler 返回后才记录,先打 /health 让 registry 有序列。
    let warm = build_router()
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("warmup oneshot failed");
    assert_eq!(warm.status(), StatusCode::OK);

    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri("/metrics")
        .body(Body::empty())
        .unwrap();
    let response = router
        .oneshot(request)
        .await
        .expect("router oneshot failed");
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body = String::from_utf8_lossy(&bytes);

    assert!(
        registry.route_count() >= 2,
        "预热 + /metrics 两次请求后 registry 应至少两个路由序列"
    );
    assert!(
        registry.render().contains("sdforge_http_requests_total"),
        "registry render 应含 sdforge_http_requests_total 指标族"
    );
    assert!(
        body.contains("sdforge_http_requests_total"),
        "/metrics 文本输出应并入 sdforge RED 指标族: {}",
        &body[..body.len().min(300)]
    );
}

/// JSON 分支含 http_route_count 字段(替代原全局计数读回)。
#[tokio::test]
async fn test_metrics_json_branch_has_route_count() {
    let router = build_router();
    let request = Request::builder()
        .method("GET")
        .uri("/metrics?format=json")
        .body(Body::empty())
        .unwrap();
    let response = router
        .oneshot(request)
        .await
        .expect("router oneshot failed");

    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
    assert!(
        json.get("http_route_count").is_some(),
        "json 分支应含 http_route_count 字段,实际: {}",
        json
    );
}