Rust Web Axum
Core Workflow
- Identify the Axum version, Tokio runtime flavour (
#[tokio::main]vs. manualBuilder), and project layout (src/main.rs,src/lib.rs,src/routes/,src/handlers/). - Keep transport (handlers/extractors), business logic (domain services), and persistence (repository traits + impls) in separate modules; never leak
axum::extractorhttptypes past the handler boundary. - Define application-wide shared resources in a typed
AppStatestruct passed viaRouter::with_state; useFromReffor sub-state extraction instead of wrapping everything inArc<Mutex<…>>. - Validate and deserialize request input through Axum extractors (
Json<T>,Query<T>,Path<T>) withserdederive; apply additional validation (e.g.,validatorcrate) before entering business logic. - Implement a unified error type that implements
IntoResponse; map internal errors to appropriate HTTP status codes in one place, never expose internal details or backtraces to clients. - Layer Tower middleware deliberately:
TraceLayer→ request-id → CORS → auth → rate-limit → body-limit → application middleware; apply layers viaRouter::layerorServiceBuilder. - Keep all I/O operations (
sqlx,reqwest, HTTP clients, file I/O) fullyasyncon Tokio; never call blocking code on the async executor — usetokio::task::spawn_blockingfor CPU-bound or synchronous FFI work. - Propagate cancellation through
CancellationTokenortokio::select!where long-running tasks need cooperative shutdown; respect request timeouts viatower_http::timeout::TimeoutLayer. - Emit structured traces with
tracingandtracing-subscriber; expose/healthand/readyendpoints; propagate OpenTelemetry context when distributed tracing is present. - Implement graceful shutdown: bind with
tokio::net::TcpListener, serve viaaxum::serve(…).with_graceful_shutdown(signal), and drain in-flight connections before exiting the Tokio runtime. - Run
cargo clippy -- -D warnings,cargo fmt --check, andcargo testbefore marking the task complete; confirm no newunsafeblocks without justification.
Reference Guide
| Topic | Reference | Load When |
|---|---|---|
| Delivery checklist | references/checklist.md |
Any Axum service feature, refactor, or review |
Constraints
- Do not mix HTTP transport concerns, domain logic, and persistence in one handler function or module.
- Do not hold
MutexGuardor any lock across.awaitpoints; prefer message passing ortokio::syncprimitives. - Do not use
unwrap()/expect()on fallible operations in handler paths; convert to the unified error type. - Do not spawn detached tasks (
tokio::spawn) from handlers without lifecycle tracking (e.g.,TaskTracker,JoinSet). - Do not expose raw
sqlx::Error,reqwest::Error, or panic backtraces in HTTP responses. - Treat dependency upgrades, middleware reordering, extractor ordering changes, and
Send/Syncbound modifications as high-risk.
Source: Shubchynskyi/garda-agent-orchestrator — distributed by TomeVault.