xyz-rust 0.4.11

One definition, three interfaces(CLI / HTTP / MCP)— a command toolkit for Rust
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
// httpapi 是 HTTP 前端,构建于 axum(Rust 生态的事实标准 HTTP 栈——
// 官方 rmcp 的 streamable HTTP 服务同栈,serve 模式把 /mcp 挂同一端口时
// 零桥接)。职责对齐 Go 版:
//
//   - HTTPHints.method + path 定义路由;path 模板 {name} 映射到绑定了
//     http="path" 的字段;
//   - 未标注位置(或标注 http:"query")的字段默认从 query 绑定;
//     http:"header"(http_name)从请求头绑定;JSON body 合并为入参基底;
//   - 响应是裸 JSON(无信封),与 CLI --json 同形;错误经共享错误分类学
//     映射为 HTTP 状态码;
//   - GET /healthz 探活;GET /openapi.json 暴露与 MCP inputSchema 同源的
//     OpenAPI 3 文档。
//
// 没有 HTTP hints 的条目不路由。Go 版声称「纯标准库」——Rust std 无
// HTTP 服务器,这里的对等物是 axum(标注在 README 的差异节)。

pub mod middleware;
pub mod openapi;

#[cfg(test)]
mod httpapi_test;

use std::collections::HashSet;
use std::sync::Arc;

use axum::extract::Request;
use axum::http::{Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{Router, delete, get, head, options, patch, post, put};
use serde_json::{Map, Value};

use crate::config::Config;
use crate::ctx::Ctx;
use crate::errors;
use crate::registry::Registry;
use crate::spec::entry::Entry;

/// 请求体上限 1MiB(Go maxBodyBytes 同值)。
pub const MAX_BODY_BYTES: usize = 1 << 20;

/// Handler 构建 serve 模式的整表路由(REST + /healthz + /openapi.json)。
/// method+path 冲突是注册期错误(Go 用 recover 包 mux panic 转错误,
/// 这里显式前置检查,行为等价)。
pub fn router(reg: &Registry, ctx: Arc<Ctx>) -> errors::Result<Router> {
    router_with(
        reg,
        ctx,
        std::collections::HashMap::new(),
        false,
        &crate::cli::bin_name(),
        crate::version::version(),
    )
}

/// 带通道级默认参数的路由器(serve --default k=v:缺席键补上)。
pub(crate) fn router_with(
    reg: &Registry,
    ctx: Arc<Ctx>,
    defaults: std::collections::HashMap<String, String>,
    no_server_headers: bool,
    app_name: &str,
    app_version: &str,
) -> errors::Result<Router> {
    // 装配期 axum 可能因路由冲突 panic(例如用户命令占用 /healthz)——
    // 捕获并转为注册期错误(对齐 Go registerSafe 的 recover)。
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        router_inner(reg, ctx, defaults, no_server_headers, app_name, app_version)
    }))
    .unwrap_or_else(|p| {
        let msg = p
            .downcast_ref::<&str>()
            .map(|s| s.to_string())
            .or_else(|| p.downcast_ref::<String>().cloned())
            .unwrap_or_else(|| "route registration panic".to_string());
        Err(errors::Error::new(
            errors::Kind::Internal,
            format!("httpapi: route conflicts with an existing route ({msg})"),
        ))
    })
}

fn router_inner(
    reg: &Registry,
    ctx: Arc<Ctx>,
    defaults: std::collections::HashMap<String, String>,
    no_server_headers: bool,
    app_name: &str,
    app_version: &str,
) -> errors::Result<Router> {
    let mut r: Router = Router::new();
    let mut seen: HashSet<(String, String)> = HashSet::new();
    for e in reg.all() {
        if e.http.skip || e.cli.daemon {
            continue; // 通道层面整体移除;daemon 只属于 CLI
        }
        if e.http.path.is_empty() {
            continue; // 该命令没有声明 HTTP 路由(CLI/MCP 专用)
        }
        // 空 method = 同时注册 GET 与 POST(spec §11.1 默认;GET 绑 query、
        // POST 绑 body+query,同一 handler);method 可为逗号分隔多方法。
        for method in http_methods(&e) {
            if !seen.insert((method.clone(), e.http.path.clone())) {
                return Err(errors::Error::new(
                    errors::Kind::Internal,
                    format!(
                        "httpapi: route {:?} {:?} conflicts with an existing route",
                        method, e.http.path
                    ),
                ));
            }
            let h = handle_entry_c(
                e.clone(),
                Arc::clone(&ctx),
                Arc::new(defaults.clone()),
                no_server_headers,
            );
            let mr = method_router(&method, h)?;
            r = r.route(&e.http.path, mr);
        }
    }
    r = r
        .route("/healthz", get(healthz))
        .route(
            "/openapi.json",
            get(openapi::openapi_handler(reg, app_name, app_version)),
        )
        // 未匹配路由的统一 404(对齐 Go:{"error": <本地化 not found>},
        // 遵循 §11.7 的逐请求语言)。
        .fallback(missing_route);
    Ok(r)
}

/// 命令的注册方法集(spec §11.1):空 method → GET+POST 默认;否则按逗号
/// 分隔(trim、忽略空项)。router 与 openapi 生成共用。
pub(crate) fn http_methods(e: &crate::spec::Entry) -> Vec<String> {
    let m = e.http.method.trim();
    if m.is_empty() {
        return vec!["GET".to_string(), "POST".to_string()];
    }
    // 逗号分隔、大小写归一为大写(对齐 Go httpMethods 的 ToUpper)。
    m.split(',')
        .map(|s| s.trim().to_uppercase())
        .filter(|s| !s.is_empty())
        .collect()
}

/// 未匹配路由的 404:JSON 错误体 + 请求语言本地化。
async fn missing_route(req: Request) -> Response {
    let lang = req
        .headers()
        .get(header::ACCEPT_LANGUAGE)
        .and_then(|v| v.to_str().ok())
        .and_then(crate::lang::parse_accept_language);
    let msg = match lang {
        Some(l) => crate::lang::t_lang(l, "http.err_not_found"),
        None => crate::lang::t("http.err_not_found"),
    };
    write_error(StatusCode::NOT_FOUND, &msg)
}

fn method_router<H, T>(method: &str, h: H) -> errors::Result<axum::routing::MethodRouter>
where
    H: axum::handler::Handler<T, ()>,
    T: 'static,
{
    // axum 的 MethodRouter 覆盖常规动词;其余动词(Go net/http 的任意
    // 方法)在注册期给出清晰错误。
    Ok(match method {
        "GET" => get(h),
        "POST" => post(h),
        "PUT" => put(h),
        "PATCH" => patch(h),
        "DELETE" => delete(h),
        "HEAD" => head(h),
        "OPTIONS" => options(h),
        other => {
            return Err(errors::Error::new(
                errors::Kind::Internal,
                format!("httpapi: unsupported HTTP method {other:?}"),
            ));
        }
    })
}

/// 单条命令的完整绑定处理器(query/path/header/body + 错误映射),无
/// 路由。挂到任意 axum Router 上(docs/adapters.md 有示例)。
/// 轮询 Handler:axum 闭包 handler 的请求抽取元组带私有 ViaRequest
/// 标记、无法具名,这里以自实现 Handler 的具名类型给出清晰公开 API
/// (axum 文档支持的自定义 handler 路线)。
#[derive(Clone)]
pub struct EntryHandler {
    pub(crate) entry: Arc<Entry>,
    pub(crate) ctx: Arc<Ctx>,
    pub(crate) defaults: Arc<std::collections::HashMap<String, String>>,
    /// 关闭每路由的 X-XYZ-Command/X-XYZ-Duration-Ms(§11.6 单一开关)。
    pub(crate) no_server_headers: bool,
}

impl axum::handler::Handler<(), ()> for EntryHandler {
    type Future = std::pin::Pin<Box<dyn std::future::Future<Output = Response> + Send>>;
    fn call(self, req: Request, _state: ()) -> Self::Future {
        Box::pin(async move {
            handle_request(
                &self.entry,
                &self.ctx,
                &self.defaults,
                self.no_server_headers,
                req,
            )
            .await
        })
    }
}

pub fn handler_for(entry: Arc<Entry>) -> EntryHandler {
    handle_entry_c(
        entry,
        Arc::new(Ctx::new()),
        Arc::new(std::collections::HashMap::new()),
        false,
    )
}

/// 入口处理器构建(serve 模式注入取消上下文)。
fn handle_entry_c(
    entry: Arc<Entry>,
    ctx: Arc<Ctx>,
    defaults: Arc<std::collections::HashMap<String, String>>,
    no_server_headers: bool,
) -> EntryHandler {
    EntryHandler {
        entry,
        ctx,
        defaults,
        no_server_headers,
    }
}

async fn handle_request(
    entry: &Arc<Entry>,
    ctx: &Arc<Ctx>,
    defaults: &std::collections::HashMap<String, String>,
    no_server_headers: bool,
    req: Request,
) -> Response {
    let (parts, body) = req.into_parts();
    let method = parts.method.clone();
    let path = parts.uri.path().to_string();
    let query = parts.uri.query().unwrap_or_default().to_string();
    let headers = parts.headers.clone();

    // 逐请求语言(spec §11.7):Accept-Language 命中受支持语言则用之,否则
    // 回退进程默认;派生到请求 ctx 供 Invoke 管线、handler 与本地化框架
    // 消息共用(§14 item7 的 language_from_ctx 读取点)。
    let req_lang = headers
        .get(header::ACCEPT_LANGUAGE)
        .and_then(|v| v.to_str().ok())
        .and_then(crate::lang::parse_accept_language);
    let localize = |key: &str| match req_lang {
        Some(l) => crate::lang::t_lang(l, key),
        None => crate::lang::t(key),
    };

    let mut m: Map<String, Value> = Map::new();
    // 铺底:HTTP 专属默认值(全局默认由 Invoke 补齐)。
    for (k, v) in entry.http_defaults() {
        m.insert(k, v);
    }
    // 通道级默认参数(serve --default k=v):只补缺席键。
    for (k, v) in defaults.iter() {
        if !m.contains_key(k) {
            m.insert(k.clone(), Value::String(v.clone()));
        }
    }
    // JSON body 作为基础入参(非 GET/HEAD 且带体时解析)。
    let body_bytes: Vec<u8> = if method != Method::GET && method != Method::HEAD {
        collect_body(body, MAX_BODY_BYTES).await
    } else {
        Vec::new()
    };
    if !body_bytes.is_empty() {
        let json_declared = headers
            .get(header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|v| v.contains("application/json"))
            .unwrap_or(false);
        match serde_json::from_slice::<serde_json::Value>(&body_bytes) {
            Ok(Value::Object(parsed)) => {
                for (k, v) in parsed {
                    m.insert(k, v);
                }
            }
            Ok(_) => {
                return write_error(StatusCode::BAD_REQUEST, &localize("http.err_invalid_json"));
            }
            Err(_) if json_declared => {
                // 显式声明 application/json 却解析失败:严格 400。
                return write_error(StatusCode::BAD_REQUEST, &localize("http.err_invalid_json"));
            }
            Err(_) => {
                // 非 JSON 声明(如表单体)解析失败:交给 form 绑定,不提前判死。
            }
        }
    }
    // form 字段惰性解析:只在该条目确实有 http:"form" 字段时解析表单。
    let mut form_parsed: Option<Vec<(String, String)>> = None;

    for f in &entry.root.children {
        if f.skip {
            // json:"-" 的注入字段:header 值以 Rust 字段名为键送达。
            if f.http.location == "header"
                && let Some(v) = headers.get(http_name(f)).and_then(|v| v.to_str().ok())
                && !v.is_empty()
            {
                m.insert(f.name.clone(), Value::String(v.to_string()));
            }
            continue;
        }
        match f.http.location.as_str() {
            "" | "query" => {
                if let Some(vs) = query_values(&query, &f.json_name) {
                    if is_string_slice(f) {
                        m.insert(
                            f.json_name.clone(),
                            Value::Array(vs.iter().map(|s| Value::String(s.clone())).collect()),
                        );
                    } else if let Some(first) = vs.first() {
                        m.insert(f.json_name.clone(), Value::String(first.clone()));
                    }
                }
            }
            "header" => {
                if let Some(v) = headers.get(http_name(f)).and_then(|v| v.to_str().ok())
                    && !v.is_empty()
                {
                    m.insert(f.json_name.clone(), Value::String(v.to_string()));
                }
            }
            "path" => {
                if let Some(v) = path_param(&entry.http.path, &path, http_name(f)) {
                    m.insert(f.json_name.clone(), Value::String(v));
                }
            }
            "form" => {
                if form_parsed.is_none() {
                    // 与上游一致:form 值仅来自请求体(已读字节,避免二读 body)。
                    form_parsed = Some(crate::httpapi::parse_form_query(&String::from_utf8_lossy(
                        &body_bytes,
                    )));
                }
                if let Some((_, v)) = form_parsed
                    .as_ref()
                    .unwrap()
                    .iter()
                    .find(|(k, _)| k == &f.json_name)
                {
                    m.insert(f.json_name.clone(), Value::String(v.clone()));
                }
            }
            _ => {}
        }
    }

    let per_req_ctx = match req_lang {
        Some(l) => Arc::new(ctx.with_language(l.as_str())),
        None => Arc::clone(ctx),
    };
    let started = std::time::Instant::now();
    let mut resp = match (entry.invoke)(&per_req_ctx, &m) {
        Ok(out) => {
            let s = serde_json::to_string_pretty(&out).unwrap_or_else(|_| "null".to_string());
            json_response(StatusCode::OK, &s)
        }
        Err(e) => write_coded_error(&e),
    };
    // §11.6 per-route 上下文头(身份/自定义头由 serve 的全局层写)。
    if !no_server_headers {
        let h = resp.headers_mut();
        if let Ok(v) = header::HeaderValue::from_str(&entry.name) {
            let _ = h.insert(header::HeaderName::from_static("x-xyz-command"), v);
        }
        let dur = started.elapsed().as_millis().to_string();
        if let Ok(v) = header::HeaderValue::from_str(&dur) {
            let _ = h.insert(header::HeaderName::from_static("x-xyz-duration-ms"), v);
        }
    }
    resp
}

/// httpName 计算线上名:http_name 覆盖 > JSON 名 > Rust 字段名。
pub(crate) fn http_name(f: &crate::spec::FieldMeta) -> &str {
    if !f.http.name.is_empty() {
        return f.http.name.as_str();
    }
    if !f.json_name.is_empty() {
        return f.json_name.as_str();
    }
    f.name.as_str()
}

fn is_string_slice(f: &crate::spec::FieldMeta) -> bool {
    matches!(f.kind, crate::spec::FieldKind::Slice)
}

/// 手写 query/form 解析(零第三方依赖的 urlencoded 子集):按 & 拆对、
/// % 解码。
pub(crate) fn parse_form_query(s: &str) -> Vec<(String, String)> {
    s.split('&')
        .filter(|p| !p.is_empty())
        .map(|pair| match pair.split_once('=') {
            Some((k, v)) => (pct_decode(k), pct_decode(v)),
            None => (pct_decode(pair), String::new()),
        })
        .collect()
}

fn query_values(query: &str, key: &str) -> Option<Vec<String>> {
    let pairs = parse_form_query(query);
    let hit: Vec<String> = pairs
        .iter()
        .filter(|(k, _)| k == key)
        .map(|(_, v)| v.clone())
        .collect();
    if hit.is_empty() { None } else { Some(hit) }
}

/// 按模板段摘出 {name} 路径参数(路由已由 axum 匹配,这里只取值)。
fn path_param(template: &str, path: &str, name: &str) -> Option<String> {
    let tsegs: Vec<&str> = template.split('/').collect();
    let psegs: Vec<&str> = path.split('/').collect();
    if tsegs.len() != psegs.len() {
        return None;
    }
    for (t, p) in tsegs.iter().zip(psegs.iter()) {
        if let Some(inner) = t.strip_prefix('{').and_then(|s| s.strip_suffix('}'))
            && inner == name
        {
            return Some(pct_decode(p));
        }
    }
    None
}

fn pct_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() + 1 {
            let h = hex_val(bytes.get(i + 1));
            let l = hex_val(bytes.get(i + 2));
            if let (Some(h), Some(l)) = (h, l) {
                out.push(h * 16 + l);
                i += 3;
                continue;
            }
        }
        if bytes[i] == b'+' {
            out.push(b' ');
        } else {
            out.push(bytes[i]);
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn hex_val(b: Option<&u8>) -> Option<u8> {
    match b.copied()? {
        b'0'..=b'9' => Some(b.unwrap() - b'0'),
        b'a'..=b'f' => Some(b.unwrap() - b'a' + 10),
        b'A'..=b'F' => Some(b.unwrap() - b'A' + 10),
        _ => None,
    }
}

/// spec §8.6:HTTP 错误体 = 共享错误对象(紧凑 JSON),状态码遵循
/// §8.5 的显式 status 覆盖,否则按 Kind 推导。
fn write_coded_error(e: &errors::Error) -> Response {
    let status =
        StatusCode::from_u16(errors::error_status(e)).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    let mut body = errors::error_body(e);
    if body.error.is_empty() {
        body.error = status.canonical_reason().unwrap_or("error").to_string();
    }
    let s = serde_json::to_string(&body).unwrap_or_else(|_| "{\"error\":\"\"}".to_string());
    json_response(status, &s)
}

fn write_error(status: StatusCode, msg: &str) -> Response {
    let msg = if msg.is_empty() {
        status.canonical_reason().unwrap_or("error").to_string()
    } else {
        msg.to_string()
    };
    // Go writeError:紧凑 JSON(结果才走 pretty)。
    let body = serde_json::to_string(&serde_json::json!({ "error": msg }))
        .unwrap_or_else(|_| "{\"error\":\"\"}".to_string());
    json_response(status, &body)
}

fn json_response(status: StatusCode, body: &str) -> Response {
    let mut b = body.to_string();
    b.push('\n');
    (
        status,
        [(header::CONTENT_TYPE, "application/json; charset=utf-8")],
        b,
    )
        .into_response()
}

async fn healthz() -> Response {
    json_response(StatusCode::OK, "{\"status\":\"ok\"}")
}

/// 逐块收集 body 直到 cap 字节(Go 的 LimitReader + ReadAll 截断语义)。
async fn collect_body(body: axum::body::Body, cap: usize) -> Vec<u8> {
    use futures_util::StreamExt as _;
    let mut out = Vec::new();
    let mut stream = body.into_data_stream();
    while let Some(Ok(chunk)) = stream.next().await {
        let rem = cap.saturating_sub(out.len());
        if rem == 0 {
            break;
        }
        out.extend_from_slice(&chunk[..chunk.len().min(rem)]);
    }
    out
}

/// serve 模式:解析裸名 flag、装配路由与中间件、TLS/优雅关停。
/// `:8080` 简写 → `0.0.0.0:8080`(Go net.Listen 惯例;tokio 的
/// ToSocketAddrs 不接受略主机形态)。IPv6 缩写("::")原样保留。
pub(crate) fn normalize_addr(addr: &str) -> String {
    if let Some(rest) = addr.strip_prefix(':')
        && !rest.contains(':')
    {
        return format!("0.0.0.0:{rest}");
    }
    addr.to_string()
}

pub(crate) fn serve(
    ctx: &Ctx,
    reg: &Registry,
    args: &[String],
    cfg: Config,
    mount_mcp: bool,
) -> i32 {
    let cfg = crate::builtins::parse_serve_args(args, cfg);
    let sctx = Arc::new(ctx.clone());
    let mut router = match router_with(
        reg,
        Arc::clone(&sctx),
        cfg.channel_defaults.clone(),
        cfg.no_server_headers,
        &cfg.resolved_name(),
        &cfg.resolved_version(),
    ) {
        Ok(r) => r,
        Err(e) => {
            crate::logx::errorf(format_args!("{e}"));
            return 2;
        }
    };
    let mut mcp_note = String::new();
    #[cfg(feature = "mcp")]
    {
        if mount_mcp
            && let Some(m) = crate::mcp::mountable(
                reg,
                &crate::mcp::Options {
                    // serve 挂载的 /mcp 与独立 mcp 模式共用同一应用身份
                    // (spec §12.6 serverInfo):不继承 cfg 时挂载端回退到
                    // bin_name/"0.0.0",与 stdio/http 模式报告不一致。
                    name: cfg.resolved_name(),
                    version: cfg.resolved_version(),
                    bearer_tokens: cfg.bearer_tokens.clone(),
                    default_ctx: Some(sctx.clone()),
                    defaults: cfg.channel_defaults.clone(),
                    ..Default::default()
                },
            )
        {
            router = router.nest_service("/mcp", m);
            mcp_note = " + /mcp".to_string();
        }
    }
    if !cfg.cors_origins.is_empty() {
        crate::logx::debugf(format_args!(
            "{}",
            crate::lang::tf("log.cors_on", &[&format!("{:?}", cfg.cors_origins)])
        ));
    }
    // 中间件链(由外到内):CORS 预检(鉴权前,浏览器预检不带凭据)→
    // Bearer → Gzip → 路由。顺序语义在 middleware.rs 集中组装并有测试锁定。
    let router = middleware::apply(
        router,
        cfg.bearer_tokens.clone(),
        cfg.cors_origins.clone(),
        cfg.timeout,
    );
    // §11.6 服务器上下文头:最外层(含 401/预检等一切响应)。
    let router = router.layer(axum::middleware::from_fn(middleware::server_context_mw(
        cfg.resolved_name(),
        cfg.resolved_version(),
        cfg.response_headers.clone(),
        !cfg.no_server_headers,
    )));

    let tls_on = !cfg.cert_file.is_empty() || !cfg.key_file.is_empty();
    if tls_on && (cfg.cert_file.is_empty() || cfg.key_file.is_empty()) {
        crate::logx::errorf(format_args!("TLS requires both --tls-cert and --tls-key"));
        return 2;
    }
    let scheme = if tls_on { "https" } else { "http" };
    crate::logx::infof(format_args!(
        "{}",
        crate::lang::tf("log.serve_listening", &[scheme, &cfg.addr, &mcp_note])
    ));

    let rt = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(rt) => rt,
        Err(e) => {
            crate::logx::errorf(format_args!("{e}"));
            return 1;
        }
    };
    rt.block_on(async move {
        let listener =
            match tokio::net::TcpListener::bind(&crate::httpapi::normalize_addr(&cfg.addr)).await {
                Ok(l) => l,
                Err(e) => {
                    crate::logx::errorf(format_args!("{e}"));
                    return 1;
                }
            };
        let handle = axum_server::Handle::new();
        let cert_file = cfg.cert_file.clone();
        let key_file = cfg.key_file.clone();
        let serve = {
            let router = router.clone();
            let handle = handle.clone();
            move || async move {
                if tls_on {
                    let tls_config = match load_rustls_config(&cert_file, &key_file) {
                        Ok(c) => c,
                        Err(e) => {
                            crate::logx::errorf(format_args!("{e}"));
                            return 1;
                        }
                    };
                    let rustls_cfg = axum_server::tls_rustls::RustlsConfig::from_config(
                        std::sync::Arc::new(tls_config),
                    );
                    let server = match axum_server::from_tcp_rustls(
                        listener.into_std().unwrap(),
                        rustls_cfg,
                    ) {
                        Ok(s) => s,
                        Err(e) => {
                            crate::logx::errorf(format_args!("{e}"));
                            return 1;
                        }
                    };
                    let _ = server
                        .handle(handle.clone())
                        .serve(router.clone().into_make_service())
                        .await;
                } else {
                    let server = match axum_server::from_tcp(listener.into_std().unwrap()) {
                        Ok(s) => s,
                        Err(e) => {
                            crate::logx::errorf(format_args!("{e}"));
                            return 1;
                        }
                    };
                    let _ = server
                        .handle(handle.clone())
                        .serve(router.clone().into_make_service())
                        .await;
                };
                0
            }
        };
        let _ = &serve;
        let server_handle = handle.clone();
        let serve_fut = tokio::spawn(async move { serve().await });
        let cancel_fut = async move {
            sctx.cancelled_async().await;
            server_handle.graceful_shutdown(Some(std::time::Duration::from_secs(5)));
        };
        tokio::select! {
            join_res = serve_fut => join_res.unwrap_or(1),
            _ = cancel_fut => {
                crate::logx::infof(format_args!("{}", crate::lang::t("log.graceful")));
                0
            }
        }
    })
}

#[cfg(feature = "http-stack")]
fn load_rustls_config(cert_file: &str, key_file: &str) -> errors::Result<rustls::ServerConfig> {
    use std::io::BufReader;
    let certs = rustls_pemfile::certs(&mut BufReader::new(
        std::fs::File::open(cert_file).map_err(errors::Error::from)?,
    ))
    .collect::<Result<Vec<_>, _>>()
    .map_err(|e| errors::Error::new(errors::Kind::Internal, format!("cert parse: {e}")))?;
    let key = rustls_pemfile::private_key(&mut BufReader::new(
        std::fs::File::open(key_file).map_err(errors::Error::from)?,
    ))
    .map_err(|e| errors::Error::new(errors::Kind::Internal, format!("key parse: {e}")))?
    .ok_or_else(|| {
        errors::Error::new(errors::Kind::Internal, "no private key found".to_string())
    })?;
    // 嵌入方的依赖图可能同时编入多个 crypto provider(rustls 自动选择会
    // panic);显式安装 ring,重复安装(已装过)时忽略错误。
    let _ = rustls::crypto::ring::default_provider().install_default();
    let config = rustls::ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs, key)
        .map_err(|e| errors::Error::new(errors::Kind::Internal, format!("tls config: {e}")))?;
    Ok(config)
}