mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+366
-105
@@ -1,113 +1,374 @@
|
||||
---
|
||||
description: Comprehensive guidelines for developing robust and maintainable web applications with the Rocket web framework, covering code organization, security, performance, testing, and more.
|
||||
globs: *.rs
|
||||
description: Definitive guidelines for building robust, performant, and maintainable backend services with Rocket 0.5+, focusing on modern Rust async patterns, API design, and testing.
|
||||
globs: **/*.rs
|
||||
---
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:** Organize your project with a clear and maintainable directory structure. A common pattern is:
|
||||
- `src/`: Contains the main source code.
|
||||
- `main.rs`: Entry point of the application.
|
||||
- `lib.rs`: Defines library components.
|
||||
- `routes/`: Contains route handlers.
|
||||
- `mod.rs`: Defines and exports route modules.
|
||||
- `resource_name.rs`: Individual route files.
|
||||
- `models/`: Defines data structures and database interactions.
|
||||
- `mod.rs`: Defines and exports model modules.
|
||||
- `data_model.rs`: Individual model definitions.
|
||||
- `utils/`: Utility functions and modules.
|
||||
- `mod.rs`: Defines and exports utility modules.
|
||||
- `helper_functions.rs`: Individual utility function files.
|
||||
- `config/`: Configuration files and settings.
|
||||
- `static/`: Static assets like CSS, JavaScript, and images.
|
||||
- `templates/`: Templates for rendering dynamic content (using templating engines like Handlebars or Tera).
|
||||
- `tests/`: Unit and integration tests.
|
||||
- `migrations/`: Database migrations (if applicable).
|
||||
- **File Naming Conventions:** Use descriptive and consistent file names. Follow Rust's conventions, such as `snake_case` for file and module names. For example, `user_routes.rs`, `database_connection.rs`.
|
||||
- **Module Organization:** Break down your code into logical modules. Use `mod.rs` files to define and re-export modules within a directory.
|
||||
- **Component Architecture:** Design your application using a component-based architecture. This promotes reusability and maintainability. Consider using traits to define interfaces between components.
|
||||
- **Code Splitting Strategies:** For larger applications, split your code into smaller, manageable crates to improve compilation times and code organization.
|
||||
# rocket Best Practices
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Repository Pattern:** Abstract data access logic behind a repository interface.
|
||||
- **Service Layer Pattern:** Decouple route handlers from business logic using a service layer.
|
||||
- **State Pattern:** Manage complex state transitions within route handlers or components.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Database Interactions:** Use an ORM like Diesel or SeaORM to interact with databases. Use connection pooling to efficiently manage database connections.
|
||||
- **Authentication and Authorization:** Implement authentication using JWT (JSON Web Tokens) or sessions. Use role-based access control (RBAC) for authorization.
|
||||
- **Input Validation:** Thoroughly validate user input to prevent security vulnerabilities and data corruption.
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **Global Variables:** Avoid using global variables, as they can lead to unexpected side effects and make code harder to reason about. Use dependency injection instead.
|
||||
- **Tight Coupling:** Minimize dependencies between components. Use interfaces and abstractions to decouple components.
|
||||
- **Long Functions:** Break down long functions into smaller, more manageable functions.
|
||||
- **State Management:** Use Rocket's managed state feature (`#[rocket::State]`) to manage application-level state.
|
||||
- **Error Handling:** Use Rust's `Result` type for error handling. Provide informative error messages to the user.
|
||||
This document outlines the definitive best practices for developing with Rocket, Rust's async web framework. Adhere to these guidelines to ensure your Rocket applications are performant, secure, and easily maintainable.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- **Asynchronous Programming:** Use asynchronous programming (`async/await`) to handle concurrent requests efficiently.
|
||||
- **Caching:** Implement caching to reduce database load and improve response times.
|
||||
- **Connection Pooling:** Use connection pooling to reuse database connections.
|
||||
- **Memory Management:** Be mindful of memory allocation and deallocation. Use Rust's ownership and borrowing system to prevent memory leaks and data races.
|
||||
- **Rendering Optimization:** Optimize your templates to reduce rendering time. Use template caching.
|
||||
- **Bundle Size Optimization:** Minimize the size of your application's binary. Use release mode compilation (`cargo build --release`). Strip debug symbols.
|
||||
- **Lazy Loading Strategies:** Load resources on demand to improve initial page load time.
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection using tokens.
|
||||
- **Input Validation:** Validate all user input on both the client-side and server-side.
|
||||
- **Authentication and Authorization:**
|
||||
- Use strong password hashing algorithms (e.g., bcrypt or Argon2).
|
||||
- Implement two-factor authentication (2FA).
|
||||
- Use role-based access control (RBAC) to restrict access to resources.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- Store passwords securely using a strong hashing algorithm.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Use API keys or JWT for authentication.
|
||||
Organize your codebase by feature, not by file type. Each logical feature (e.g., `auth`, `posts`, `users`) should reside in its own module, encapsulating its routes, data structures, and business logic.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:** Write unit tests to verify the functionality of individual functions and modules. Use the `#[cfg(test)]` attribute to define test modules.
|
||||
- **Integration Testing:** Write integration tests to verify the interaction between different parts of your application. Test routes and database interactions.
|
||||
- **End-to-End Testing:** Write end-to-end tests to verify the complete functionality of your application. Use a testing framework like Selenium or Cypress.
|
||||
- **Test Organization:** Organize your tests in a clear and maintainable way. Create separate test modules for each component or module.
|
||||
- **Mocking and Stubbing:** Use mocking and stubbing to isolate units of code during testing. Use a mocking framework like Mockall.
|
||||
### ❌ BAD: Anemic `types.rs` and `impl.rs`
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- **Forgetting to handle errors:** Always handle errors properly using `Result` and provide informative error messages.
|
||||
- **Not validating user input:** Always validate user input to prevent security vulnerabilities.
|
||||
- **Using global state:** Avoid using global state, as it can lead to unexpected side effects.
|
||||
- **Edge Cases:**
|
||||
- **Handling concurrent requests:** Use asynchronous programming to handle concurrent requests efficiently.
|
||||
- **Dealing with large files:** Use streaming to process large files without loading them into memory.
|
||||
- **Handling database connection errors:** Implement retry logic to handle database connection errors.
|
||||
- **Version-Specific Issues:** Be aware of version-specific issues and compatibility concerns. Consult the Rocket documentation and release notes.
|
||||
- **Compatibility Concerns:** Ensure that your application is compatible with the target platform and browser versions.
|
||||
- **Debugging Strategies:**
|
||||
- Use the `println!` macro for debugging.
|
||||
- Use a debugger like GDB or LLDB.
|
||||
- Use logging to track the execution of your application.
|
||||
```rust
|
||||
// src/types.rs
|
||||
pub struct User { /* ... */ }
|
||||
pub struct Post { /* ... */ }
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Development Tools:**
|
||||
- **Rust toolchain:** Install the Rust toolchain using `rustup`.
|
||||
- **IDE:** Use an IDE like Visual Studio Code with the Rust Analyzer extension.
|
||||
- **Database client:** Use a database client like DBeaver or pgAdmin.
|
||||
- **Build Configuration:** Configure your build using `Cargo.toml`. Specify dependencies, build scripts, and other build settings.
|
||||
- **Linting and Formatting:**
|
||||
- Use `rustfmt` for code formatting.
|
||||
- Use `clippy` for linting.
|
||||
- Configure your IDE to automatically format and lint your code.
|
||||
- **Deployment Best Practices:**
|
||||
- Use a process manager like systemd or PM2 to manage your application.
|
||||
- Use a reverse proxy like Nginx or Apache to handle incoming requests.
|
||||
- Use a load balancer to distribute traffic across multiple instances of your application.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD platform like GitHub Actions or GitLab CI to automate your build, test, and deployment process.
|
||||
- Write tests to ensure that your application is working correctly before deploying.
|
||||
// src/impls.rs
|
||||
impl User { /* ... */ }
|
||||
impl Post { /* ... */ }
|
||||
|
||||
// src/routes.rs
|
||||
#[get("/users")]
|
||||
fn get_users() { /* ... */ }
|
||||
```
|
||||
|
||||
### ✅ GOOD: Feature-based Modules
|
||||
|
||||
```rust
|
||||
// src/main.rs
|
||||
mod auth;
|
||||
mod posts;
|
||||
mod users;
|
||||
|
||||
#[rocket::main]
|
||||
async fn main() -> Result<(), rocket::Error> {
|
||||
rocket::build()
|
||||
.mount("/auth", auth::routes())
|
||||
.mount("/posts", posts::routes())
|
||||
.mount("/users", users::routes())
|
||||
.launch()
|
||||
.await
|
||||
}
|
||||
|
||||
// src/users/mod.rs
|
||||
pub mod models;
|
||||
pub mod handlers;
|
||||
|
||||
pub fn routes() -> Vec<rocket::Route> {
|
||||
rocket::routes![
|
||||
handlers::get_all_users,
|
||||
handlers::get_user_by_id,
|
||||
// ...
|
||||
]
|
||||
}
|
||||
|
||||
// src/users/models.rs
|
||||
pub struct User {
|
||||
pub id: i32,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
// src/users/handlers.rs
|
||||
use super::models::User;
|
||||
use rocket::serde::json::Json;
|
||||
|
||||
#[get("/")]
|
||||
pub async fn get_all_users() -> Json<Vec<User>> {
|
||||
// Fetch users from DB
|
||||
Json(vec![User { id: 1, username: "test".to_string() }])
|
||||
}
|
||||
|
||||
#[get("/<id>")]
|
||||
pub async fn get_user_by_id(id: i32) -> Option<Json<User>> {
|
||||
// Fetch user from DB
|
||||
if id == 1 {
|
||||
Some(Json(User { id: 1, username: "test".to_string() }))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. API Design
|
||||
|
||||
Design APIs with clarity, explicitness, and robust error handling.
|
||||
|
||||
### 2.1 Declarative Routing
|
||||
|
||||
Leverage Rocket's attribute macros for clear, concise route definitions.
|
||||
|
||||
```rust
|
||||
// Define a GET route at /hello/<name>
|
||||
#[get("/hello/<name>")]
|
||||
async fn hello(name: String) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
// Define a POST route at /users with JSON body
|
||||
use rocket::serde::json::Json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct NewUser {
|
||||
username: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[post("/users", data = "<user>")]
|
||||
async fn create_user(user: Json<NewUser>) -> Json<NewUser> {
|
||||
// Save user to DB
|
||||
user
|
||||
}
|
||||
```
|
||||
|
||||
### 2.2 Request Guards for Validation and Authentication
|
||||
|
||||
Use custom request guards to centralize input validation, authentication, and authorization. This keeps handler logic clean and ensures consistent policy enforcement.
|
||||
|
||||
```rust
|
||||
use rocket::request::{self, Request, FromRequest};
|
||||
use rocket::outcome::Outcome;
|
||||
use rocket::http::Status;
|
||||
|
||||
pub struct AdminUser;
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for AdminUser {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
// Example: Check for a specific header or session token
|
||||
if request.headers().contains("X-Admin-Token") {
|
||||
Outcome::Success(AdminUser)
|
||||
} else {
|
||||
Outcome::Failure((Status::Unauthorized, ()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/admin")]
|
||||
async fn admin_panel(admin: AdminUser) -> &'static str {
|
||||
"Welcome, administrator!"
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 Responders for Consistent Responses
|
||||
|
||||
Implement `Responder` for custom response types to standardize API output, especially for errors.
|
||||
|
||||
```rust
|
||||
use rocket::http::{Status, ContentType};
|
||||
use rocket::response::{self, Responder, Response};
|
||||
use std::io::Cursor;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ApiError {
|
||||
pub code: u16,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl<'r, 'o: 'r> Responder<'r, 'o> for ApiError {
|
||||
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
|
||||
let json = serde_json::to_string(&self).unwrap();
|
||||
Response::build()
|
||||
.sized_body(self.message.len(), Cursor::new(json))
|
||||
.header(ContentType::new("application", "json"))
|
||||
.status(Status::new(self.code))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/fail")]
|
||||
async fn fail_route() -> Result<&'static str, ApiError> {
|
||||
Err(ApiError {
|
||||
code: 400,
|
||||
message: "Something went wrong!".to_string(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Common Patterns and Anti-patterns
|
||||
|
||||
### 3.1 Async Everywhere
|
||||
|
||||
Rocket 0.5+ is fully async. All handlers and I/O operations (database, templates) *must* be `async fn`.
|
||||
|
||||
### ❌ BAD: Blocking I/O in handlers
|
||||
|
||||
```rust
|
||||
// This will block the Rocket worker thread
|
||||
#[get("/")]
|
||||
fn index() -> String {
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
"Hello, world!".to_string()
|
||||
}
|
||||
```
|
||||
|
||||
### ✅ GOOD: Async I/O with `await`
|
||||
|
||||
```rust
|
||||
use rocket_db_pools::{sqlx, Database};
|
||||
|
||||
#[Database("my_db")]
|
||||
struct MyDatabase(sqlx::PgPool);
|
||||
|
||||
#[get("/")]
|
||||
async fn index(mut db: Connection<MyDatabase>) -> String {
|
||||
// Perform async DB operation
|
||||
sqlx::query!("SELECT 1").fetch_one(&mut *db).await.unwrap();
|
||||
"Hello, async world!".to_string()
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 `#[rocket::async_trait]` for Trait Implementations
|
||||
|
||||
When implementing Rocket traits (e.g., `FromRequest`), always use `#[rocket::async_trait]`.
|
||||
|
||||
### ❌ BAD: Missing `async_trait`
|
||||
|
||||
```rust
|
||||
// Will result in a compiler error
|
||||
impl<'r> FromRequest<'r> for MyType {
|
||||
type Error = ();
|
||||
async fn from_request(...) { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
### ✅ GOOD: Correct `async_trait` usage
|
||||
|
||||
```rust
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for MyType {
|
||||
type Error = ();
|
||||
async fn from_request(...) { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 Form and JSON Validation
|
||||
|
||||
Use `FromForm` for URL-encoded data and `Json` with `serde::Deserialize` for JSON. For strict form validation, wrap fields in `Strict<T>`.
|
||||
|
||||
```rust
|
||||
use rocket::form::{Form, Strict};
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct UserProfile {
|
||||
name: String,
|
||||
#[field(validate = len(min = 10))]
|
||||
bio: String,
|
||||
age: Strict<u8>, // Age must be present and valid
|
||||
}
|
||||
|
||||
#[post("/profile", data = "<profile>")]
|
||||
async fn update_profile(profile: Form<UserProfile>) -> String {
|
||||
format!("Profile updated for {}", profile.name)
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Error Handling
|
||||
|
||||
Always return `Result<T, E>` from handlers where `E` is a custom error type that implements `Responder`. This provides clear error messages and HTTP status codes.
|
||||
|
||||
```rust
|
||||
// src/errors.rs
|
||||
use super::api_response::ApiError; // Assuming ApiError from section 2.3
|
||||
|
||||
pub enum MyHandlerError {
|
||||
NotFound,
|
||||
InvalidInput(String),
|
||||
DatabaseError(String),
|
||||
}
|
||||
|
||||
impl From<MyHandlerError> for ApiError {
|
||||
fn from(err: MyHandlerError) -> Self {
|
||||
match err {
|
||||
MyHandlerError::NotFound => ApiError { code: 404, message: "Resource not found".to_string() },
|
||||
MyHandlerError::InvalidInput(msg) => ApiError { code: 400, message: format!("Invalid input: {}", msg) },
|
||||
MyHandlerError::DatabaseError(msg) => ApiError { code: 500, message: format!("Database error: {}", msg) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// src/handlers.rs
|
||||
use crate::errors::MyHandlerError;
|
||||
use crate::api_response::ApiError;
|
||||
|
||||
#[get("/item/<id>")]
|
||||
async fn get_item(id: i32) -> Result<String, ApiError> {
|
||||
if id == 0 {
|
||||
return Err(MyHandlerError::NotFound.into());
|
||||
}
|
||||
if id < 0 {
|
||||
return Err(MyHandlerError::InvalidInput("ID cannot be negative".to_string()).into());
|
||||
}
|
||||
Ok(format!("Item {}", id))
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Performance Considerations
|
||||
|
||||
### 5.1 Database Connection Pooling
|
||||
|
||||
Use `rocket_db_pools` for efficient, non-blocking database access. Configure pools in `Rocket.toml`.
|
||||
|
||||
```rust
|
||||
// Cargo.toml
|
||||
// rocket_db_pools = { version = "0.1.0", features = ["sqlx", "postgres"] }
|
||||
|
||||
// Rocket.toml
|
||||
[default.databases.my_db]
|
||||
url = "postgres://user:pass@host/db"
|
||||
|
||||
// src/main.rs
|
||||
use rocket_db_pools::{sqlx, Database, Connection};
|
||||
|
||||
#[Database("my_db")]
|
||||
struct MyDatabase(sqlx::PgPool);
|
||||
|
||||
#[get("/count")]
|
||||
async fn get_count(mut db: Connection<MyDatabase>) -> String {
|
||||
let count: i64 = sqlx::query_scalar!("SELECT COUNT(*) FROM items")
|
||||
.fetch_one(&mut *db)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
format!("Total items: {}", count)
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Security Best Practices
|
||||
|
||||
### 6.1 Configuration via `Rocket.toml`
|
||||
|
||||
Never hardcode sensitive information (database URLs, API keys) in your code. Use `Rocket.toml` for environment-specific settings. Version control only a template of `Rocket.toml` and use environment variables for actual secrets.
|
||||
|
||||
```toml
|
||||
# Rocket.toml
|
||||
[default]
|
||||
address = "0.0.0.0"
|
||||
port = 8000
|
||||
secret_key = { env = "ROCKET_SECRET_KEY" } # Load from env var
|
||||
|
||||
[default.databases.my_db]
|
||||
url = { env = "DATABASE_URL" }
|
||||
```
|
||||
|
||||
## 7. Testing Approaches
|
||||
|
||||
### 7.1 Integration Tests with `local::asynchronous::Client`
|
||||
|
||||
Write comprehensive integration tests that spin up an in-process Rocket instance. This ensures your routes, guards, and responders work together as expected.
|
||||
|
||||
```rust
|
||||
// tests/integration_test.rs
|
||||
use rocket::local::asynchronous::Client;
|
||||
use rocket::{build, routes};
|
||||
|
||||
#[rocket::async_test]
|
||||
async fn test_hello_world() {
|
||||
let rocket = build().mount("/", routes![crate::hello]); // Assuming `hello` from section 2.1
|
||||
let client = Client::tracked(rocket).await.expect("valid rocket instance");
|
||||
let response = client.get("/hello/world").dispatch().await;
|
||||
|
||||
assert_eq!(response.status(), rocket::http::Status::Ok);
|
||||
assert_eq!(response.into_string().await, Some("Hello, world!".to_string()));
|
||||
}
|
||||
```
|
||||
|
||||
### 7.2 CI Pipeline Checks
|
||||
|
||||
Integrate `cargo fmt -- --check`, `cargo clippy -- -D warnings`, and `cargo test --all-features` into your CI pipeline to enforce code quality and catch common issues automatically.
|
||||
Reference in New Issue
Block a user