xyz-rust 0.4.3

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
// httpapi 测试(Go httpapi_test.go 对应物):绑定合并、错误映射、healthz、
// openapi、Bearer/CORS 中间件。用 tower::ServiceExt::oneshot 直接调
// Router,不真起端口。

use std::sync::Arc;

use axum::body::Body;
use axum::http::Request;
use axum::response::Response;
use tower::ServiceExt;

use crate::Ctx;
use crate::errors;
use crate::httpapi;
use crate::registry::Registry;
use crate::spec::command::{Command, HTTPHints};
use xyz_rust::XyzArgs;

#[derive(XyzArgs)]
struct AddHTTPArgs {
    #[xyz(desc = "用户名", required, validate = "min=2", http = "path")]
    name: String,
    #[xyz(desc = "年龄", default = "18", http = "query")]
    age: i32,
    #[xyz(desc = "令牌", skip, http = "header", http_name = "X-Token")]
    token: String,
}

fn add_user(_: &Ctx, in_: &AddHTTPArgs) -> errors::Result<String> {
    Ok(format!("{}:{}:{}", in_.name, in_.age, in_.token))
}

async fn resp_body(resp: Response) -> (u16, String) {
    let status = resp.status().as_u16();
    let body = resp.into_body();
    let bytes = axum::body::to_bytes(body, 1 << 20).await.unwrap();
    (status, String::from_utf8_lossy(&bytes).into_owned())
}

async fn call(router: axum::routing::Router, req: Request<Body>) -> (u16, String) {
    let resp = router.oneshot(req).await.unwrap();
    resp_body(resp).await
}

fn add_reg() -> Registry {
    let reg = Registry::new();
    Command::new("user.add", add_user)
        .summary("加用户")
        .http(HTTPHints {
            method: "POST".into(),
            path: "/users/{name}".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    reg
}

#[tokio::test(flavor = "current_thread")]
async fn binding_merges_body_path_query_header() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let body = serde_json::json!({"age": 9}).to_string();
    let req = Request::builder()
        .method("POST")
        .uri("/users/alice?age=7")
        .header("X-Token", "tk")
        .header("content-type", "application/json")
        .body(Body::from(body))
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    // query 显式提供优先于 body 基底(body 先铺底,query 后覆盖——Go 同序)
    assert_eq!(out.trim(), "\"alice:7:tk\"");
}

#[tokio::test(flavor = "current_thread")]
async fn invalid_declared_json_body_is_400() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    // 显式声明 application/json 且解析失败 → 严格 400
    let req = Request::builder()
        .method("POST")
        .uri("/users/alice")
        .header("content-type", "application/json")
        .body(Body::from("{nope".to_string()))
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 400);
    assert!(out.contains("invalid JSON body"), "{out}");
}

#[tokio::test(flavor = "current_thread")]
async fn undeclared_body_is_not_rejected_as_json() {
    // 非 JSON 声明的不可解析体(如表单体)不提前判死:交给 form 绑定/其余字段。
    let reg = Registry::new();

    #[derive(XyzArgs)]
    struct F {
        #[xyz(desc = "n", http = "form")]
        note: String,
    }
    fn fh(_: &Ctx, in_: &F) -> errors::Result<String> {
        Ok(format!("note={}", in_.note))
    }
    Command::new("f.submit", fh)
        .http(HTTPHints {
            method: "POST".into(),
            path: "/f".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    // 无 Content-Type 的 form 体可以解出,不落 400
    let req = Request::builder()
        .method("POST")
        .uri("/f")
        .body(Body::from("note=hello%20form".to_string()))
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "\"note=hello form\"");
    // form 值只取请求体,不混入 query(与上游 v0.2.2 一致)
    let req = Request::builder()
        .method("POST")
        .uri("/f?note=fromquery")
        .body(Body::from("note=frombody".to_string()))
        .unwrap();
    let (_, out) = call(router, req).await;
    assert_eq!(out.trim(), "\"note=frombody\"");
}

#[tokio::test(flavor = "current_thread")]
async fn validation_error_maps_to_400() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("POST")
        .uri("/users/a") // min=2 失败
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 400);
    assert!(
        out.contains("invalid value for field \\\"name\\\": min"),
        "{out}"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn business_error_maps_to_404_with_error_body() {
    let reg = Registry::new();

    #[derive(XyzArgs)]
    struct N {
        #[xyz(desc = "n")]
        n: String,
    }
    fn nh(_: &Ctx, _: &N) -> errors::Result<String> {
        Err(errors::new(errors::Kind::NotFound, "no such user"))
    }
    Command::new("n.hit", nh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/n".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/n")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 404);
    // §8.6 共享错误体:扁平 error 键保留,kind 纯增量。
    assert_eq!(
        out.trim(),
        "{\"error\":\"no such user\",\"kind\":\"not_found\"}"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn rich_error_body_and_status_override() {
    use crate::errors;
    let reg = Registry::new();
    #[derive(xyz_rust::XyzArgs)]
    struct RichArgs {
        #[xyz(desc = "n")]
        n: String,
    }
    fn rich(_: &Ctx, _: &RichArgs) -> errors::Result<String> {
        Err(errors::new(errors::Kind::Conflict, "dup")
            .with_code("DUPLICATE")
            .with_detail("name", serde_json::json!("alice"))
            .with_status(410))
    }
    Command::new("n.rich", rich)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/n/rich".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/n/rich")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    // §8.5 status 覆盖优先于 Kind 推导(Conflict → 409 被 410 覆盖)。
    assert_eq!(status, 410);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    assert_eq!(v["error"], "dup");
    assert_eq!(v["kind"], "conflict");
    assert_eq!(v["code"], "DUPLICATE");
    assert_eq!(v["detail"]["name"], "alice");
}

#[tokio::test(flavor = "current_thread")]
async fn healthz_and_openapi() {
    let reg = add_reg();
    let router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    let req = Request::builder()
        .method("GET")
        .uri("/healthz")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router.clone(), req).await;
    assert_eq!(status, 200);
    assert_eq!(out, "{\"status\":\"ok\"}\n");
    let req = Request::builder()
        .method("GET")
        .uri("/openapi.json")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert_eq!(v["openapi"], "3.0.3");
    let path = v["paths"]["/users/{name}"]["post"].clone();
    assert_eq!(path["summary"], "加用户");
    // 参数表:path 里的 name + requestBody
    let params = path["parameters"].as_array().unwrap();
    assert!(
        params
            .iter()
            .any(|p| p["name"] == "name" && p["in"] == "path"),
        "{params:?}"
    );
    assert!(path["requestBody"]["content"]["application/json"]["schema"]["type"] == "object");
}

#[test]
fn conflicting_routes_rejected() {
    let reg = Registry::new();

    #[derive(XyzArgs)]
    struct X {}
    fn xh(_: &Ctx, _: &X) -> errors::Result<String> {
        Ok(String::new())
    }
    Command::new("x.one", xh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/dup".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    Command::new("x.two", xh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/dup".into(),
            ..Default::default()
        })
        .register(&reg)
        .unwrap();
    let err = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap_err();
    assert!(err.to_string().contains("conflicts"), "{err}");
    // 同路径不同方法不冲突
    let reg2 = Registry::new();
    Command::new("x.one", xh)
        .http(HTTPHints {
            method: "GET".into(),
            path: "/d".into(),
            ..Default::default()
        })
        .register(&reg2)
        .unwrap();
    Command::new("x.two", xh)
        .http(HTTPHints {
            method: "POST".into(),
            path: "/d".into(),
            ..Default::default()
        })
        .register(&reg2)
        .unwrap();
    assert!(httpapi::router(&reg2, Arc::new(Ctx::new())).is_ok());
}

#[tokio::test(flavor = "current_thread")]
async fn handler_for_binds_one_entry() {
    let reg = add_reg();
    let entry = reg.get("user.add").unwrap();
    let h = httpapi::handler_for(entry);
    let router: axum::routing::Router =
        axum::routing::Router::new().route("/users/{name}", axum::routing::post(h));
    let req = Request::builder()
        .method("POST")
        .uri("/users/some?age=3")
        .header("X-Token", "z")
        .body(Body::empty())
        .unwrap();
    let (status, out) = call(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(out.trim(), "\"some:3:z\""); // 挂载点沿用原路由模板,path 参数才能被摘出(Go HandlerFor 同契约)
}

#[tokio::test(flavor = "current_thread")]
async fn bearer_and_cors_middleware() {
    let reg = add_reg();
    let mut router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    router = crate::httpapi::middleware::apply(
        router,
        vec!["s3cret".into()],
        vec!["http://app.local".into()],
        std::time::Duration::ZERO,
    );
    // 无凭据 401 + WWW-Authenticate
    let req = Request::builder()
        .method("GET")
        .uri("/nope")
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 401);
    assert_eq!(resp.headers().get("www-authenticate").unwrap(), "Bearer");
    // 带凭据进入路由(404 因为 /nope 无路由——鉴权已通过)
    let req = Request::builder()
        .method("GET")
        .uri("/nope")
        .header("Authorization", "Bearer s3cret")
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 404);
    // CORS 预检(无凭据)在鉴权之前应答 204——顺序锁死
    let req = Request::builder()
        .method("OPTIONS")
        .uri("/nope")
        .header("Origin", "http://app.local")
        .body(Body::empty())
        .unwrap();
    let resp = router.oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 204);
}

#[tokio::test(flavor = "current_thread")]
async fn gzip_compresses_when_asked() {
    let reg = add_reg();
    let mut router = httpapi::router(&reg, Arc::new(Ctx::new())).unwrap();
    router = crate::httpapi::middleware::apply(router, vec![], vec![], std::time::Duration::ZERO);
    let req = Request::builder()
        .method("GET")
        .uri("/healthz")
        .header("Accept-Encoding", "gzip")
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    assert_eq!(resp.headers().get("content-encoding").unwrap(), "gzip");
}

#[test]
fn normalize_addr_port_shorthand() {
    use crate::httpapi::normalize_addr;
    assert_eq!(normalize_addr(":8080"), "0.0.0.0:8080");
    assert_eq!(normalize_addr("127.0.0.1:8080"), "127.0.0.1:8080");
    assert_eq!(normalize_addr("0.0.0.0:9090"), "0.0.0.0:9090");
    // IPv6 缩写不得被误当端口简写。
    assert_eq!(normalize_addr("::"), "::");
    assert_eq!(normalize_addr("[::1]:8080"), "[::1]:8080");
}

#[tokio::test(flavor = "current_thread")]
async fn server_context_headers_on_all_responses() {
    use axum::middleware::from_fn;
    use tower::ServiceExt;

    let router = httpapi::router(&add_reg(), Arc::new(Ctx::new())).unwrap();
    let with_ctx = router.layer(from_fn(crate::httpapi::middleware::server_context_mw(
        "appt".to_string(),
        "9.9".to_string(),
        vec![("X-Custom".to_string(), "c".to_string())],
        true,
    )));
    // 404(无路由)也带头:身份头全路由。
    let req = Request::builder()
        .method("GET")
        .uri("/nowhere")
        .body(Body::empty())
        .unwrap();
    let resp = with_ctx.oneshot(req).await.unwrap();
    let h = resp.headers();
    assert_eq!(h.get("x-app-name").unwrap(), "appt");
    assert_eq!(h.get("x-app-version").unwrap(), "9.9");
    assert_eq!(h.get("x-xyz-version").unwrap(), crate::version::SDK_VERSION);
    assert_eq!(h.get("x-custom").unwrap(), "c");

    // 关闭开关:自动头消失,自定义头保留。
    let router = httpapi::router(&add_reg(), Arc::new(Ctx::new())).unwrap();
    let no_auto = router
        .clone()
        .layer(from_fn(crate::httpapi::middleware::server_context_mw(
            "appt".to_string(),
            "9.9".to_string(),
            vec![("X-Custom".to_string(), "c".to_string())],
            false,
        )));
    let req = Request::builder()
        .method("GET")
        .uri("/nowhere")
        .body(Body::empty())
        .unwrap();
    let resp = no_auto.oneshot(req).await.unwrap();
    let h = resp.headers();
    assert!(h.get("x-app-name").is_none());
    assert_eq!(h.get("x-custom").unwrap(), "c");

    // 每路由头:命中真实命令时带 command/duration。
    let req = Request::builder()
        .method("GET")
        .uri("/users/alice?age=3")
        .body(Body::empty())
        .unwrap();
    let resp = router.oneshot(req).await.unwrap();
    assert!(resp.headers().get("x-xyz-command").is_none()); // 无 mw 时不留
}