# Rust + Axum + PostgreSQL (sqlx & Tokio) — AI Agent Guidelines & Architecture Rules

> High-concurrency systems architecture for Rust 2024, Axum 0.8, Tokio async runtime, compile-time SQL verification with sqlx, and Tower middleware.
> Technologies: Rust, Axum, PostgreSQL, sqlx, Tokio, Docker

---

## AGENTS.md
```markdown
# Project Architecture & Guidelines (Rust + Axum + PostgreSQL)

## 1. System Architecture
- **Language & Edition**: Rust (2021 / 2024 edition, stable compiler).
- **Async Runtime**: Tokio (`tokio = { version = "1", features = ["full"] }`).
- **Web Framework**: Axum 0.8 with Tower service ecosystem.
- **Database & Persistence**: PostgreSQL accessed via `sqlx` (`sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid", "chrono"] }`).
- **Serialization**: `serde` and `serde_json`.

## 2. Project Layout & Modular Separation
- `src/main.rs`: Runtime initialization, configuration loading, database pool creation, and router binding.
- `src/routes/`: Route handlers split by resource domain (e.g. `users.rs`, `health.rs`).
- `src/models/`: Domain structs deriving `Serialize`, `Deserialize`, and `sqlx::FromRow`.
- `src/db/`: Database connection pool management and migration runners (`sqlx::migrate!()`).
- `src/error.rs`: Unified `AppError` enum implementing `axum::response::IntoResponse`.

## 3. Handlers & Extractors
- Use Axum extractors (`State(pool)`, `Json(payload)`, `Path(id)`, `Query(params)`) in strict order (body extractors last).
- Manage application state via `axum::extract::State<Arc<AppState>>`.
- Validate all inbound requests using validator crates or custom domain constructors (`NewUser::validate()`).

## 4. Database & sqlx Compile-Time Checks
- Favor `sqlx::query_as!` and `sqlx::query!` macros to validate SQL syntax and types against the live database at compile time.
- Always configure connection pooling: `PgPoolOptions::new().max_connections(20).acquire_timeout(Duration::from_secs(3))`.
- Place migrations in `migrations/` folder as sequential `.sql` files (`YYYYMMDDHHMMSS_name.sql`).

## 5. Error Handling & Observability
- Never `unwrap()` or `panic!()` in route handlers. Propagate errors with the `?` operator into custom `AppError`.
- Implement `IntoResponse` for `AppError` to emit appropriate HTTP status codes (400, 401, 404, 500) and structured JSON bodies `{ "error": "message" }`.
- Integrate `tracing` and `tracing-subscriber` for structured JSON logging and distributed span tracking.

## 6. Testing Conventions
- Use `#[tokio::test]` for async integration tests; spin up a real Postgres instance with `testcontainers` rather than mocking `sqlx`.
- Run `cargo sqlx prepare` in CI to verify the offline query cache (`.sqlx/`) stays in sync with actual schema — a stale cache silently masks broken queries.
- Test `AppError` → HTTP status mapping explicitly; a wrong status code on an error path is a common silent regression.
- `cargo clippy -- -D warnings` treated as a test failure, not a style nit — Rust's linter catches real bugs (unused Results, needless clones).

## 7. Git Workflow & PR Conventions
- Conventional Commits (`feat:`, `fix:`, `refactor:`) scoped to the module, e.g. `fix(routes/users): return 404 instead of 500 on missing user`.
- New `migrations/*.sql` files ship in the same PR as the `sqlx::query!` changes that depend on them; commit the updated `.sqlx/` cache alongside.
- Require `cargo test`, `cargo clippy -- -D warnings`, and `cargo fmt --check` green before merge.
- Squash-merge; never merge with `unwrap()`/`panic!()` introduced in a route handler — `?` and `AppError` only.
```

---

## CLAUDE.md
```markdown
# CLAUDE.md — Rust + Axum + PostgreSQL Commands & Conventions

## Common Commands
- `cargo run` - Start development server locally
- `cargo check` - Fast compile-check without building binaries
- `cargo test` - Run full unit and integration test suite
- `cargo clippy -- -D warnings` - Run linter with strict warning denials
- `cargo fmt --check` - Verify code formatting
- `sqlx migrate run` - Execute pending database migrations
- `cargo sqlx prepare` - Update offline query metadata cache (.sqlx/)

## Code Style Guidelines
- Write idiomatic Rust: prefer pattern matching, `Option`/`Result` combinators, and custom newtype wrappers.
- Keep handlers lightweight: extract inputs, call domain services, and return typed JSON or status codes.
- Use `#[derive(Debug, Clone, Serialize, Deserialize)]` on API data transfer objects.
- Use 4 spaces for indentation adhering to standard `rustfmt` rules.
```

---

## .cursor/rules/stack.mdc
```markdown
---
description: Rust + Axum + PostgreSQL (sqlx & Tokio) architecture rules
globs: ["**/*.rs"]
alwaysApply: true
---

# Rust + Axum + PostgreSQL (sqlx & Tokio)

- Rust 2021/2024 edition, Tokio async runtime, Axum 0.8 + Tower, `sqlx` for compile-time-verified Postgres queries.
- `src/routes/` (handlers), `src/models/` (`sqlx::FromRow` structs), `src/db/` (pool + migrations), `src/error.rs` (unified `AppError`).
- Axum extractors in strict order: `State`, `Path`, `Query`, body extractors (`Json`) last.
- `sqlx::query_as!`/`sqlx::query!` macros only — they validate SQL against the live schema at compile time; run `cargo sqlx prepare` to keep the offline cache current.
- `PgPoolOptions::new().max_connections(20).acquire_timeout(...)` — explicit pool config, no defaults.
- Never `unwrap()`/`panic!()` in a route handler — propagate with `?` into `AppError`, implement `IntoResponse` for it.
- `tracing` + `tracing-subscriber` for structured JSON logs and span tracking.
```

---

## Architecture Overview & Best Practices
## Architecture Overview

High-throughput systems architecture using **Rust**, **Axum**, **Tokio**, and **sqlx** with compile-time verified database operations.

### Key Advantages

- **Zero Memory Leaks & Zero GC Pauses**: Memory safety guaranteed at compile time without garbage collector spikes.
- **Compile-Time Query Verification**: `sqlx` checks SQL queries against PostgreSQL schemas during `cargo build`, preventing runtime syntax errors.
- **Massive Concurrency**: Tokio lightweight asynchronous tasks handle tens of thousands of concurrent connections on minimal hardware.