

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1# Rust with Axum Web Framework — Cursor Rules23You are an expert Rust developer building web services with Axum, Tokio, and the Rust async ecosystem.45## Code Style67- Follow Rust naming conventions: `snake_case` for functions/variables/modules, `PascalCase` for types/traits, `SCREAMING_SNAKE_CASE` for constants and statics.8- Use `rustfmt` with default settings for all formatting. Run `cargo fmt` before every commit.9- Use `clippy` with `#![warn(clippy::all, clippy::pedantic)]`. Fix all warnings.10- Prefer descriptive names: `user_repository` not `ur`, `calculate_total_price` not `calc`.11- Keep functions under 50 lines. Extract helper functions for complex logic.12- Use `//!` doc comments for module-level documentation. Use `///` for public items.13- Group imports: `std`, external crates, internal modules. Use `use` blocks, not inline paths.14- Prefer `&str` over `String` for function parameters when you don't need ownership.15- Use `impl Into<String>` or `impl AsRef<str>` for flexible string parameters in public APIs.1617## Axum Architecture1819- Structure the app with a handler -> service -> repository layered architecture.20- Define routes in a `router()` function using `axum::Router`. Nest routers for different resources.21- Handlers are `async fn` that take extractors as parameters and return `impl IntoResponse`.22- Use state injection with `State<Arc<AppState>>` for shared state (database pool, config).23- Keep handlers thin: extract request data, call service functions, format response.24- Service functions contain business logic. They take typed inputs and return `Result<T, AppError>`.25- Repository functions handle database access. They take a database connection/pool and return domain types.2627## Extractors2829- Use `Json<T>` for JSON request bodies. `T` must implement `Deserialize`.30- Use `Path<T>` for path parameters. Use tuple types for multiple params: `Path((user_id, post_id))`.31- Use `Query<T>` for query string parameters.32- Use `State<T>` for shared application state. Wrap in `Arc` for thread-safe sharing.33- Use `Extension<T>` for request-scoped data set by middleware.34- Create custom extractors by implementing `FromRequestParts` or `FromRequest`.35- Order extractors correctly: `State` and `Path` before `Json` (which consumes the body).3637## Error Handling3839- NEVER use `.unwrap()` or `.expect()` in production code (except in tests or truly infallible cases).40- Define a custom `AppError` enum with variants for each error category:41```rust42 enum AppError {43 NotFound(String),44 Validation(Vec<ValidationError>),45 Unauthorized,46 Internal(anyhow::Error),47 }48```49- Implement `IntoResponse` for `AppError` to return proper HTTP status codes and JSON error bodies.50- Use `thiserror` for defining error enums with `#[error("...")]` display messages.51- Use `anyhow` for error propagation in application code. Use `thiserror` for library code.52- Use the `?` operator for error propagation. Never use match blocks just to propagate errors.53- Return `Result<T, AppError>` from all handlers and service functions.54- Log errors with `tracing::error!` including context. Return sanitized messages to clients.5556## Data Validation5758- Use `serde` for serialization/deserialization. Derive `Serialize` and `Deserialize` on all DTOs.59- Use `validator` crate for field-level validation. Derive `Validate` and call `.validate()` in handlers.60- Create separate structs for request input (`CreateUserRequest`) and response output (`UserResponse`).61- Use `#[serde(rename_all = "camelCase")]` for JSON field naming consistency.62- Use `#[serde(skip_serializing_if = "Option::is_none")]` for optional response fields.63- Validate input at the boundary (handler level). Do not pass unvalidated data to services.6465## Async Patterns6667- Use `tokio` as the async runtime. Use `#[tokio::main]` for the entry point.68- Use `tokio::spawn` for concurrent tasks. Use `tokio::select!` for racing multiple futures.69- Use `tokio::join!` or `futures::join_all` for parallel execution of independent tasks.70- Never block the async runtime. Use `tokio::task::spawn_blocking` for CPU-intensive or blocking operations.71- Use `tokio::time::timeout` for operations that might hang.72- Prefer `async fn` over returning `impl Future` for readability.73- Use `tokio::sync::Mutex` (not `std::sync::Mutex`) in async contexts when needed.7475## Database (SQLx)7677- Use `sqlx` with compile-time checked queries (`sqlx::query!` or `sqlx::query_as!`).78- Use `PgPool` (PostgreSQL connection pool) as shared state.79- Use migrations with `sqlx migrate`. Keep migrations in `migrations/` directory.80- Use transactions for multi-step operations: `pool.begin()`, `tx.commit()`.81- Define database models separate from API DTOs. Convert between them explicitly with `From`/`Into`.82- Use `RETURNING` clauses in INSERT/UPDATE queries to avoid separate SELECT calls.83- Use parameterized queries exclusively. Never format user input into SQL strings.8485## Middleware and Layers8687- Use `tower` middleware layers with Axum's `Router::layer()`.88- Use `tower_http::trace::TraceLayer` for request tracing.89- Use `tower_http::cors::CorsLayer` for CORS configuration.90- Use `tower_http::compression::CompressionLayer` for response compression.91- Create custom middleware using `tower::Service` trait or Axum's `middleware::from_fn`.92- Apply middleware to specific route groups using nested routers.9394## Logging and Observability9596- Use `tracing` crate for structured logging, not `log` or `println!`.97- Initialize with `tracing_subscriber` using `EnvFilter` for level control.98- Use span macros for request-scoped context: `#[tracing::instrument]` on handler functions.99- Log at appropriate levels: `error!` for failures, `warn!` for degraded states, `info!` for significant events, `debug!` for development.100- Include structured fields in log events: `tracing::info!(user_id = %id, "User created")`.101102## Testing103104- Use `#[tokio::test]` for async tests.105- Create test utilities: shared test database setup, factory functions for test data.106- Test handlers with `axum::test::TestClient` or by calling handler functions directly.107- Use `sqlx::test` attribute for database tests with automatic rollback.108- Write unit tests for service and repository functions.109- Write integration tests for full request -> response cycles.110- Place unit tests in a `#[cfg(test)] mod tests` block at the bottom of each file.111- Place integration tests in a `tests/` directory at the project root.112113## File Structure114115```116src/117 main.rs — Entry point, server startup118 lib.rs — App builder, router construction119 config.rs — Configuration (environment, database URL)120 error.rs — AppError enum, IntoResponse impl121 state.rs — AppState struct122 handlers/123 mod.rs124 users.rs — User route handlers125 items.rs — Item route handlers126 services/127 mod.rs128 user_service.rs — User business logic129 repositories/130 mod.rs131 user_repo.rs — User database queries132 models/133 mod.rs134 user.rs — Domain models and DTOs135 middleware/136 mod.rs137 auth.rs — Authentication middleware138migrations/139 001_create_users.sql140tests/141 common/142 mod.rs — Shared test utilities143 api/144 users_test.rs145Cargo.toml146```147148## Security149150- Use `argon2` for password hashing. Never use MD5, SHA-1, or plain bcrypt for new projects.151- Use `jsonwebtoken` for JWT handling. Validate all claims (expiry, issuer, audience).152- Set CORS origins explicitly. Never use `AllowOrigin::any()` in production.153- Validate and limit request body size with `DefaultBodyLimit::max()`.154- Use `tower_http::limit::RequestBodyLimitLayer` to prevent DoS via large payloads.155- Keep dependencies minimal and audited. Run `cargo audit` regularly.156- Use `secrecy` crate for sensitive values (passwords, tokens) to prevent accidental logging.157158## Performance159160- Use connection pooling (SQLx default). Configure pool size based on expected concurrency.161- Use `serde_json::to_string` over `format!` for JSON construction.162- Prefer stack allocation: use `ArrayVec`, `SmallVec` for small collections.163- Avoid unnecessary allocations: use `&str` instead of `String`, `&[T]` instead of `Vec<T>` in function parameters.164- Use `Arc` for shared immutable data. Avoid cloning large data structures.165- Profile with `cargo flamegraph` or `tokio-console` before optimizing.166
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| survivorforge/cursor-rulesrules/ai-ml-python/.cursorrules · 17 | .cursorrules | teststylearchdeployment+2 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/api-microservices/.cursorrules · 17 | .cursorrules | buildteststylearch+5 | 92/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/database-sql/.cursorrules · 17 | .cursorrules | styletypessecuritydatabase+3 | 65/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/devops-docker/.cursorrules · 17 | .cursorrules | setupbuildteststyle+4 | 93/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/devops-infrastructure/.cursorrules · 17 | .cursorrules | buildteststylesecurity+3 | 93/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/django-rest/.cursorrules · 17 | .cursorrules | buildteststylearch+5 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/docker-devops/.cursorrules · 17 | .cursorrules | setupteststylearch+6 | 85/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/flutter-dart/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 89/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/go-gin/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+5 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/langchain-ai/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+4 | 84/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/mobile-react-native/.cursorrules · 17 | .cursorrules | teststylearchtypes+7 | 89/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-14-app-router/.cursorrules · 17 | .cursorrules | teststyletypestesting-strategy+3 | 71/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-app-router/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs-typescript/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nextjs/.cursorrules · 17 | .cursorrules | teststylearchtypes+5 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nodejs-express-typescript/.cursorrules · 17 | .cursorrules | setupteststylearch+7 | 81/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/nodejs-express/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+7 | 92/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/performance-optimization/.cursorrules · 17 | .cursorrules | styledatabaseapiperformance+2 | 65/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/python-django/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+6 | 99/100 | 13 days ago | |
| survivorforge/cursor-rulesrules/python-fastapi/.cursorrules · 17 | .cursorrules | testlint-formatstylearch+6 | 99/100 | 13 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/survivorforge-cursor-rules-rules-rust-axum-cursorrules)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.