CodeSampleX

示例

axum-macros 0.5.1: debug_handler

已验证示例 — cargo axum-macros 0.5.1: debug_handler. contract 在 rust 1 · linux alpine/x64 · docker 上运行并通过: bare #[debug_handler] on a stateless module-level async…

sha256:76992b46b5c929ba3e2796a95974a08241c130445e94f46b1acff491865525a0

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux · alpine · musl x64 cargo

验证运行环境

环境 契约 阶段 运行日期
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-17

案例

HOW
目标
verify debug_handler in pkg:cargo/axum-macros@0.5.1
包
符号
  • debug_handler
创建时间
2026-11-17T01:04:19Z

契约

  1. bare #[debug_handler] on a stateless module-level async fn compiles and routes GET requests returning 200 OK
  2. #[debug_handler] validates FromRequestParts extractors (State, Path, HeaderMap) placed before a body-consuming String extractor on POST routes
  3. #[debug_handler(state = AppState)] validates sub-state extraction via FromRef<AppState> when the handler signature only names State<SubState>
  4. #[debug_handler] works on module-scoped free async fn items (whereas impl block methods cannot resolve generated sibling check functions)
  5. #[debug_handler(state = AppState)] accepts axum::extract::Request as trailing extractor without a body attribute argument (removed in axum-macros 0.5)
  6. extractor rejections under #[debug_handler] preserve axum status codes, returning 400 Bad Request on malformed Path<u32>

文件

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

下载源代码构件 (tar.gz)

源代码

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
 "axum-core",
 "bytes",
 "futures-util",
 "http",
 "http-body",
 "http-body-util",
 "itoa",
 "matchit",
 "memchr",
 "mime",
 "percent-encoding",
 "pin-project-lite",
 "serde_core",
 "sync_wrapper",
 "tower",
 "tower-layer",
 "tower-service",
]

[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
 "bytes",
 "futures-core",
 "http",
 "http-body",
 "http-body-util",
 "mime",
 "pin-project-lite",
 "sync_wrapper",
 "tower-layer",
 "tower-service",
]

[[package]]
name = "axum-macros"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"
dependencies = [
 "proc-macro2",
 "quote",
 "syn 2.0.119",
]

[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"

[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"

[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"

[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
 "futures-core",
 "futures-task",
 "pin-project-lite",
 "slab",
]

[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
 "bytes",
 "itoa",
]

[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
 "bytes",
 "http",
]

[[package]]
name = "http-body-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
dependencies = [
 "bytes",
 "futures-core",
 "http",
 "http-body",
 "pin-project-lite",
]

[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"

[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"

[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"

[[package]]
name = "mime"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"

[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"

[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "sample-axum-macros-debug-handler"
version = "1.0.0"
dependencies = [
 "axum",
 "axum-macros",
 "tower-service",
]

[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
 "serde_derive",
]

[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
 "proc-macro2",
 "quote",
 "syn 3.0.10",
]

[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"

[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"

[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
 "futures-core",
 "futures-util",
 "pin-project-lite",
 "sync_wrapper",
 "tower-layer",
 "tower-service",
]

[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"

[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"

[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
Cargo.toml
[package]
name = "sample-axum-macros-debug-handler"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
axum-macros = "=0.5.1"
axum = { version = "=0.8.9", default-features = false }
tower-service = "=0.3.3"

[[bin]]
name = "contract"
path = "test/contract.rs"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify debug_handler in pkg:cargo/axum-macros@0.5.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/axum-macros@0.5.1
Demonstrate these symbols/APIs:
  - debug_handler

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:7688880c9763574f8a1d8830b2dcb1ea8a9c2440358838af22c844cfac13c505","contract":["bare #[debug_handler] on a stateless module-level async fn compiles and routes GET requests returning 200 OK","#[debug_handler] validates FromRequestParts extractors (State, Path, HeaderMap) placed before a body-consuming String extractor on POST routes","#[debug_handler(state = AppState)] validates sub-state extraction via FromRef\u003cAppState\u003e when the handler signature only names State\u003cSubState\u003e","#[debug_handler] works on module-scoped free async fn items (whereas impl block methods cannot resolve generated sibling check functions)","#[debug_handler(state = AppState)] accepts axum::extract::Request as trailing extractor without a body attribute argument (removed in axum-macros 0.5)","extractor rejections under #[debug_handler] preserve axum status codes, returning 400 Bad Request on malformed Path\u003cu32\u003e"],"goal":"verify debug_handler in pkg:cargo/axum-macros@0.5.1","kind":"HOW","packages":["pkg:cargo/axum-macros@0.5.1"],"schemaVersion":1,"symbols":["debug_handler"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/axum-macros@0.5.1"],"schemaVersion":1,"subject":"pkg:cargo/axum-macros@0.5.1","symbols":["debug_handler"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify debug_handler in pkg:cargo/axum-macros@0.5.1",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/axum-macros@0.5.1"
  ],
  "symbols": [
    "debug_handler"
  ]
}
src/lib.rs
//! Clean-room verification sample for `axum_macros::debug_handler`.

use axum::{
    extract::{FromRef, Path, Request, State},
    http::{HeaderMap, StatusCode},
    routing::get,
    Router,
};
pub use axum_macros::debug_handler;

#[derive(Clone)]
pub struct AppState {
    pub prefix: String,
    pub sub: SubState,
}

#[derive(Clone)]
pub struct SubState {
    pub multiplier: u32,
}

impl FromRef<AppState> for SubState {
    fn from_ref(state: &AppState) -> Self {
        state.sub.clone()
    }
}

#[debug_handler]
pub async fn health_check() -> &'static str {
    "ok"
}

#[debug_handler]
pub async fn create_item(
    State(state): State<AppState>,
    Path(id): Path<u32>,
    headers: HeaderMap,
    body: String,
) -> (StatusCode, String) {
    let tag = headers
        .get("x-tag")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("none");
    (
        StatusCode::CREATED,
        format!("{}:{}:{}:{}", state.prefix, id, tag, body),
    )
}

#[debug_handler(state = AppState)]
pub async fn compute_scaled(
    State(sub): State<SubState>,
    Path(value): Path<u32>,
) -> String {
    (value * sub.multiplier).to_string()
}

#[debug_handler(state = AppState)]
pub async fn inspect_request(
    State(state): State<SubState>,
    req: Request,
) -> (StatusCode, String) {
    (
        StatusCode::OK,
        format!("{}@{}", state.multiplier, req.uri().path()),
    )
}

pub mod items {
    use axum::{extract::Path, http::StatusCode};
    use axum_macros::debug_handler;

    #[debug_handler]
    pub async fn describe(Path(id): Path<u32>) -> (StatusCode, String) {
        (StatusCode::OK, format!("item-{id}"))
    }
}

pub fn build_router(state: AppState) -> Router {
    Router::new()
        .route("/health", get(health_check))
        .route("/items/{id}", get(items::describe).post(create_item))
        .route("/scale/{value}", get(compute_scaled))
        .route("/inspect", get(inspect_request))
        .with_state(state)
}
test/contract.rs
use std::future::Future;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};

use axum::{
    body::{to_bytes, Body},
    http::{Method, Request, StatusCode},
};
use sample_axum_macros_debug_handler::{build_router, AppState, SubState};
use tower_service::Service;

struct NoopWake;

impl Wake for NoopWake {
    fn wake(self: Arc<Self>) {}
}

fn block_on<F: Future>(fut: F) -> F::Output {
    let waker = Waker::from(Arc::new(NoopWake));
    let mut cx = Context::from_waker(&waker);
    let mut fut = std::pin::pin!(fut);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(output) => return output,
            Poll::Pending => std::thread::yield_now(),
        }
    }
}

fn send_request(
    app: &mut axum::Router,
    req: Request<Body>,
) -> (StatusCode, String) {
    let resp = block_on(app.call(req)).expect("infallible router service");
    let status = resp.status();
    let bytes = block_on(to_bytes(resp.into_body(), 64 * 1024))
        .expect("collect response body");
    let text = String::from_utf8(bytes.to_vec()).expect("utf-8 body");
    (status, text)
}

fn main() {
    let state = AppState {
        prefix: "svc".to_string(),
        sub: SubState { multiplier: 7 },
    };
    let mut app = build_router(state);

    // 1. Bare #[debug_handler] on a stateless async handler returns 200 OK
    let (status, body) = send_request(
        &mut app,
        Request::builder()
            .method(Method::GET)
            .uri("/health")
            .body(Body::empty())
            .unwrap(),
    );
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "ok");

    // 2. #[debug_handler] with FromRequestParts (State, Path, HeaderMap) before body extractor (String)
    let (status, body) = send_request(
        &mut app,
        Request::builder()
            .method(Method::POST)
            .uri("/items/42")
            .header("x-tag", "alpha")
            .body(Body::from("payload"))
            .unwrap(),
    );
    assert_eq!(status, StatusCode::CREATED);
    assert_eq!(body, "svc:42:alpha:payload");

    // 3. #[debug_handler(state = AppState)] validates sub-state extraction via FromRef<AppState>
    let (status, body) = send_request(
        &mut app,
        Request::builder()
            .method(Method::GET)
            .uri("/scale/6")
            .body(Body::empty())
            .unwrap(),
    );
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "42");

    // 4. #[debug_handler] on a module-scoped free async fn routes and extracts Path<u32>
    let (status, body) = send_request(
        &mut app,
        Request::builder()
            .method(Method::GET)
            .uri("/items/99")
            .body(Body::empty())
            .unwrap(),
    );
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "item-99");

    // 5. #[debug_handler(state = AppState)] accepts full axum::extract::Request as trailing extractor
    let (status, body) = send_request(
        &mut app,
        Request::builder()
            .method(Method::GET)
            .uri("/inspect")
            .body(Body::empty())
            .unwrap(),
    );
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "7@/inspect");

    // 6. Invalid path parameter under #[debug_handler] rejects with 400 Bad Request
    let (status, _body) = send_request(
        &mut app,
        Request::builder()
            .method(Method::GET)
            .uri("/items/not-a-u32")
            .body(Body::empty())
            .unwrap(),
    );
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

原始种子者

匿名