diff --git a/rules-mdc/actix-web.mdc b/rules-mdc/actix-web.mdc index 1d54a47..c0364d1 100644 --- a/rules-mdc/actix-web.mdc +++ b/rules-mdc/actix-web.mdc @@ -1,318 +1,346 @@ --- -description: Comprehensive best practices for developing robust, efficient, and maintainable applications using the actix-web framework in Rust. This rule covers coding standards, project structure, performance, security, testing, and common pitfalls. -globs: *.rs +description: Definitive guidelines for building high-performance, maintainable, and secure web applications with actix-web 4, focusing on modern Rust best practices. +globs: **/*.rs --- -# Actix-web Best Practices: A Comprehensive Guide - -This guide provides a comprehensive overview of best practices for developing applications using the actix-web framework in Rust. It covers various aspects of development, including code organization, performance optimization, security, testing, and common pitfalls. - -## 1. Code Organization and Structure - -A well-organized codebase is crucial for maintainability and scalability. Here's how to structure your actix-web project effectively: - -### 1.1. Directory Structure Best Practices - -Adopt a modular and layered architecture. A common and recommended directory structure is as follows: - - -project_root/ -├── src/ -│ ├── main.rs # Entry point of the application -│ ├── lib.rs # Library file if extracting common functionality -│ ├── modules/ -│ │ ├── mod.rs # Module declaration -│ │ ├── auth/ # Authentication module -│ │ │ ├── mod.rs # Auth module declaration -│ │ │ ├── models.rs # Auth models -│ │ │ ├── routes.rs # Auth routes -│ │ │ ├── handlers.rs # Auth handlers -│ │ ├── users/ # User management module -│ │ │ ├── mod.rs # User module declaration -│ │ │ ├── models.rs # User models -│ │ │ ├── routes.rs # User routes -│ │ │ ├── handlers.rs # User handlers -│ ├── models/ # Data models -│ │ ├── mod.rs -│ │ ├── user.rs # User model -│ │ ├── post.rs # Post model -│ ├── routes/ # Route configurations -│ │ ├── mod.rs -│ │ ├── auth_routes.rs # Authentication routes -│ │ ├── user_routes.rs # User routes -│ ├── handlers/ # Request handlers (controllers) -│ │ ├── mod.rs -│ │ ├── auth_handlers.rs # Authentication handlers -│ │ ├── user_handlers.rs # User handlers -│ ├── middleware/ # Custom middleware components -│ │ ├── mod.rs -│ │ ├── logger.rs # Logging middleware -│ │ ├── auth.rs # Authentication middleware -│ ├── utils/ # Utility functions and modules -│ │ ├── mod.rs -│ │ ├── db.rs # Database connection utility -│ ├── errors/ # Custom error definitions -│ │ ├── mod.rs -│ │ ├── app_error.rs # Application-specific error types -├── tests/ # Integration and unit tests -│ ├── mod.rs -│ ├── api_tests.rs # Integration tests for API endpoints -├── .env # Environment variables -├── Cargo.toml # Project dependencies and metadata -├── Cargo.lock # Dependency lockfile - - -### 1.2. File Naming Conventions - -* **Modules:** Use lowercase, descriptive names (e.g., `auth`, `users`, `posts`). -* **Files:** Use lowercase with underscores (e.g., `user_routes.rs`, `auth_handlers.rs`). -* **Models:** Use singular nouns (e.g., `user.rs`, `post.rs`). -* **Handlers:** Use descriptive names indicating the action performed (e.g., `create_user`, `get_user`). -* **Routes:** Use names indicating the resource they handle (e.g., `user_routes`, `auth_routes`). - -### 1.3. Module Organization - -* **Explicit Module Declarations:** Always declare submodules in `mod.rs` files. This ensures proper module resolution and prevents naming conflicts. -* **Clear Boundaries:** Each module should have a well-defined responsibility. Avoid mixing unrelated functionalities within the same module. -* **Public vs. Private:** Use `pub` keyword judiciously to control visibility. Keep implementation details private to modules to prevent accidental external dependencies. - -### 1.4. Component Architecture - -* **Layered Architecture:** Separate concerns into distinct layers (e.g., data access, business logic, presentation). This improves testability and maintainability. -* **Dependency Injection:** Use dependency injection to provide dependencies to handlers. This makes it easier to test and configure your application. -* **Services:** Encapsulate business logic into services. Handlers should primarily focus on request/response handling and delegate business logic to services. - -### 1.5. Code Splitting Strategies - -* **Feature-Based Splitting:** Group code based on features (e.g., authentication, user management). This makes it easier to understand and maintain related code. -* **Module-Based Splitting:** Split code into modules based on functionality. This improves code organization and reusability. -* **Lazy Loading (Future Enhancement):** For very large applications, consider lazy loading modules or features to reduce initial startup time. This can be accomplished by dynamically enabling parts of your application based on configuration or runtime conditions. - -## 2. Common Patterns and Anti-patterns - -### 2.1. Design Patterns Specific to Actix-web - -* **Extractor Pattern:** Use extractors to handle different types of incoming data (e.g., `Path`, `Query`, `Json`, `Form`). Extractors simplify handler logic and provide type safety. -* **Middleware Pattern:** Implement custom middleware for tasks like logging, authentication, and request modification. Middleware allows you to intercept and process requests before they reach the handlers. -* **State Management Pattern:** Use `web::Data` to share application state across handlers. This provides a thread-safe way to access shared resources like database connections and configuration settings. -* **Error Handling Pattern:** Define custom error types and implement the `ResponseError` trait for centralized error handling and consistent error responses. - -### 2.2. Recommended Approaches for Common Tasks - -* **Database Integration:** Use an asynchronous database driver like `tokio-postgres` or `sqlx` for efficient database interactions. -* **Authentication:** Implement authentication using JWT (JSON Web Tokens) or other secure authentication mechanisms. -* **Authorization:** Implement role-based access control (RBAC) or attribute-based access control (ABAC) to restrict access to resources based on user roles or attributes. -* **Logging:** Use a logging framework like `tracing` or `log` for structured logging and monitoring. -* **Configuration Management:** Use a configuration library like `config` or `dotenv` to manage application settings from environment variables and configuration files. - -### 2.3. Anti-patterns and Code Smells to Avoid - -* **Long Handler Functions:** Keep handler functions short and focused. Delegate complex logic to services or helper functions. -* **Tight Coupling:** Avoid tight coupling between modules. Use interfaces and dependency injection to decouple components. -* **Ignoring Errors:** Always handle errors gracefully and provide informative error messages to the client. -* **Blocking Operations in Handlers:** Avoid performing blocking operations (e.g., synchronous I/O) in handler functions. Use asynchronous operations to prevent blocking the event loop. -* **Overusing Global State:** Minimize the use of global state. Prefer passing state as dependencies to handler functions. - -### 2.4. State Management Best Practices - -* **Immutable State:** Prefer immutable state whenever possible. This reduces the risk of race conditions and makes it easier to reason about the application. -* **Thread-Safe Data Structures:** Use thread-safe data structures like `Arc>` or `RwLock` to share mutable state across threads. -* **Avoid Direct Mutability:** Avoid directly mutating shared state. Instead, use atomic operations or message passing to coordinate state updates. -* **Dependency Injection:** Use dependency injection to provide state to handler functions. This makes it easier to test and configure the application. - -### 2.5. Error Handling Patterns - -* **Custom Error Types:** Define custom error types to represent different error scenarios in your application. -* **`ResponseError` Trait:** Implement the `ResponseError` trait for custom error types to generate appropriate HTTP responses. -* **Centralized Error Handling:** Use a centralized error handling mechanism (e.g., middleware) to catch and process errors consistently. -* **Informative Error Messages:** Provide informative error messages to the client to help them understand and resolve the issue. -* **Logging Errors:** Log errors with sufficient detail to help diagnose and debug issues. -* **`Result` Type:** Leverage the `Result` type effectively, propagating errors up the call stack using the `?` operator, and handle them at the appropriate level. - -## 3. Performance Considerations - -Optimizing performance is crucial for building scalable and responsive actix-web applications. - -### 3.1. Optimization Techniques - -* **Asynchronous Operations:** Use asynchronous operations for I/O-bound tasks (e.g., database access, network requests) to prevent blocking the event loop. -* **Connection Pooling:** Use connection pooling for database connections to reduce the overhead of establishing new connections. -* **Caching:** Implement caching for frequently accessed data to reduce database load and improve response times. -* **Compression:** Enable compression (e.g., gzip) for responses to reduce the amount of data transmitted over the network. -* **Keep-Alive Connections:** Use keep-alive connections to reuse existing TCP connections and reduce connection establishment overhead. - -### 3.2. Memory Management - -* **Avoid Unnecessary Cloning:** Minimize cloning of data to reduce memory allocations and copying. -* **Use References:** Use references instead of copying data whenever possible. -* **Smart Pointers:** Use smart pointers (e.g., `Box`, `Arc`, `Rc`) to manage memory efficiently. -* **String Handling:** Be mindful of string handling. Use `String` when ownership is needed, and `&str` when a read-only view is sufficient. - -### 3.3. Rendering Optimization - -* **Template Caching:** Cache templates to reduce the overhead of parsing and compiling templates on each request. -* **Minimize DOM Updates:** Minimize DOM updates in the client-side JavaScript code to improve rendering performance. -* **Efficient Serialization:** Ensure your data serialization is efficient, using appropriate data structures and serialization libraries (e.g., `serde_json`). - -### 3.4. Bundle Size Optimization - -* **Dependency Pruning:** Remove unused dependencies from your `Cargo.toml` file to reduce the bundle size. -* **Feature Flags:** Use feature flags to enable or disable optional features at compile time. -* **Code Minification:** Use code minification to reduce the size of your JavaScript and CSS files. - -### 3.5. Lazy Loading Strategies - -* **Lazy Initialization:** Use lazy initialization for expensive resources to defer their creation until they are actually needed. -* **On-Demand Loading:** Load resources on demand (e.g., images, data) to reduce the initial load time. - -## 4. Security Best Practices - -Security is paramount for building robust and reliable actix-web applications. - -### 4.1. Common Vulnerabilities and How to Prevent Them - -* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks. -* **Cross-Site Scripting (XSS):** Sanitize user input and escape output to prevent XSS attacks. -* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent unauthorized requests from other websites. -* **Authentication and Authorization:** Use strong authentication and authorization mechanisms to protect sensitive resources. -* **Denial-of-Service (DoS):** Implement rate limiting and other defense mechanisms to prevent DoS attacks. - -### 4.2. Input Validation - -* **Validate All Input:** Validate all user input to ensure that it conforms to the expected format and range. -* **Use Type Safety:** Use type safety to prevent invalid data from being processed. -* **Regular Expressions:** Use regular expressions to validate complex input patterns. -* **Whitelist vs. Blacklist:** Prefer whitelisting valid input over blacklisting invalid input. - -### 4.3. Authentication and Authorization Patterns - -* **JWT (JSON Web Tokens):** Use JWT for stateless authentication and authorization. -* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. -* **RBAC (Role-Based Access Control):** Use RBAC to restrict access to resources based on user roles. -* **ABAC (Attribute-Based Access Control):** Use ABAC to restrict access to resources based on user attributes. -* **Password Hashing:** Always hash passwords using a strong hashing algorithm (e.g., bcrypt, Argon2) and store them securely. - -### 4.4. Data Protection Strategies - -* **Encryption:** Encrypt sensitive data at rest and in transit. -* **Data Masking:** Mask sensitive data to prevent unauthorized access. -* **Data Anonymization:** Anonymize data to protect user privacy. -* **Access Control:** Implement strict access control policies to restrict access to sensitive data. - -### 4.5. Secure API Communication - -* **HTTPS:** Use HTTPS for all API communication to encrypt data in transit. -* **TLS Certificates:** Use valid TLS certificates from a trusted certificate authority. -* **API Keys:** Use API keys to authenticate API clients. -* **Rate Limiting:** Implement rate limiting to prevent abuse and DoS attacks. - -## 5. Testing Approaches - -Thorough testing is essential for ensuring the quality and reliability of actix-web applications. - -### 5.1. Unit Testing Strategies - -* **Test Individual Modules:** Unit test individual modules and functions in isolation. -* **Mock Dependencies:** Use mocking to isolate units from external dependencies (e.g., database, API). -* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that the code handles them correctly. -* **Table-Driven Tests:** Use table-driven tests to test multiple scenarios with different inputs and expected outputs. - -### 5.2. Integration Testing - -* **Test API Endpoints:** Integration test API endpoints to ensure that they function correctly together. -* **Test Database Interactions:** Test database interactions to ensure that data is read and written correctly. -* **Test Middleware:** Test middleware to ensure that they correctly process requests and responses. - -### 5.3. End-to-End Testing - -* **Simulate User Interactions:** End-to-end tests simulate user interactions to test the entire application flow. -* **Use a Testing Framework:** Use a testing framework (e.g., Selenium, Cypress) to automate end-to-end tests. - -### 5.4. Test Organization - -* **Test Directory:** Keep tests in a separate `tests` directory. -* **Test Modules:** Organize tests into modules that mirror the application structure. -* **Test Naming:** Use descriptive names for test functions to indicate what they are testing. - -### 5.5. Mocking and Stubbing - -* **Mock External Dependencies:** Mock external dependencies (e.g., database, API) to isolate units from external factors. -* **Use Mocking Libraries:** Use mocking libraries (e.g., `mockall`) to create mock objects and define their behavior. -* **Stub Data:** Use stub data to simulate different scenarios and test edge cases. - -## 6. Common Pitfalls and Gotchas - -Be aware of common pitfalls and gotchas when developing actix-web applications. - -### 6.1. Frequent Mistakes Developers Make - -* **Blocking Operations:** Performing blocking operations in handler functions can block the event loop and degrade performance. -* **Incorrect Error Handling:** Ignoring errors or not handling them correctly can lead to unexpected behavior and security vulnerabilities. -* **Not Validating Input:** Not validating user input can lead to security vulnerabilities and data corruption. -* **Overusing Global State:** Overusing global state can make the application difficult to reason about and test. -* **Not Using Asynchronous Operations:** Not using asynchronous operations for I/O-bound tasks can degrade performance. - -### 6.2. Edge Cases to be Aware Of - -* **Handling Large Requests:** Be mindful of handling large requests and implement appropriate size limits to prevent DoS attacks. -* **Handling Concurrent Requests:** Ensure that the application can handle concurrent requests efficiently and without race conditions. -* **Handling Network Errors:** Handle network errors gracefully and provide informative error messages to the client. -* **Handling Database Connection Errors:** Handle database connection errors gracefully and implement retry mechanisms. - -### 6.3. Version-Specific Issues - -* **Breaking Changes:** Be aware of breaking changes in actix-web and its dependencies. -* **Deprecated Features:** Avoid using deprecated features and migrate to the recommended alternatives. -* **Compatibility:** Ensure that the application is compatible with the target Rust version and operating system. - -### 6.4. Compatibility Concerns - -* **Rust Version:** Ensure compatibility with the supported Rust versions. -* **Operating System:** Test on different operating systems (Linux, macOS, Windows). -* **Browser Compatibility (if applicable):** If the application includes a front-end, test with various browsers. - -### 6.5. Debugging Strategies - -* **Logging:** Use logging to track the application's execution flow and identify potential issues. -* **Debugging Tools:** Use debugging tools (e.g., `gdb`, `lldb`) to inspect the application's state and step through the code. -* **Unit Tests:** Write unit tests to isolate and debug individual modules and functions. -* **Profiling:** Use profiling tools to identify performance bottlenecks. - -## 7. Tooling and Environment - -Using the right tools and environment can significantly improve the development experience and productivity. - -### 7.1. Recommended Development Tools - -* **Rust IDE:** Use a Rust IDE (e.g., Visual Studio Code with the Rust extension, IntelliJ Rust) for code completion, syntax highlighting, and debugging. -* **Cargo:** Use Cargo, the Rust package manager, for managing dependencies and building the application. -* **Rustup:** Use Rustup for managing Rust toolchains and versions. -* **Clippy:** Use Clippy, a Rust linter, for identifying potential code quality issues. -* **Formatter:** Use rustfmt to automatically format the code according to the Rust style guide. - -### 7.2. Build Configuration - -* **Release Mode:** Build the application in release mode for optimized performance. -* **Link-Time Optimization (LTO):** Enable link-time optimization to improve performance. -* **Codegen Units:** Experiment with different codegen unit settings to optimize compilation time and code size. - -### 7.3. Linting and Formatting - -* **Clippy:** Use Clippy to identify potential code quality issues and enforce coding standards. -* **Rustfmt:** Use rustfmt to automatically format the code according to the Rust style guide. -* **Pre-commit Hooks:** Use pre-commit hooks to automatically run Clippy and rustfmt before committing changes. - -### 7.4. Deployment Best Practices - -* **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies into a portable container. -* **Orchestration:** Use container orchestration (e.g., Kubernetes) to manage and scale the application. -* **Reverse Proxy:** Use a reverse proxy (e.g., Nginx, Apache) to handle incoming requests and route them to the application. -* **Load Balancing:** Use load balancing to distribute traffic across multiple instances of the application. -* **Monitoring:** Implement monitoring to track the application's health and performance. - -### 7.5. CI/CD Integration - -* **Continuous Integration (CI):** Use a CI system (e.g., GitHub Actions, GitLab CI, Jenkins) to automatically build, test, and lint the code on every commit. -* **Continuous Delivery (CD):** Use a CD system to automatically deploy the application to production after it passes all tests. -* **Automated Testing:** Automate unit, integration, and end-to-end tests in the CI/CD pipeline. - -By following these best practices, you can build robust, efficient, and maintainable actix-web applications that meet the highest standards of quality and security. Remember to stay up-to-date with the latest recommendations and adapt them to your specific project needs. \ No newline at end of file +# actix-web Best Practices + +Actix-web 4 is the premier choice for high-performance Rust web services. Adhere to these guidelines for clean, scalable, and production-ready code. Always run `cargo fmt` and `cargo clippy` before committing. + +## 1. Code Organization & Structure + +Organize your codebase by feature or domain, not by generic file types. This improves discoverability and maintainability. + +### ✅ GOOD: Modular by Feature + +```rust +// src/main.rs +mod db; // Database access logic +mod routes; // HTTP route handlers, grouped by resource +mod services; // Business logic layer +mod models; // Data structures (e.g., database models, DTOs) + +use actix_web::{web, App, HttpServer}; + +#[actix_web::main] +async fn main() -> std::io::Result<()> { + // Initialize logging early + env_logger::init_from_env(env_logger::Env::default().default_filter_or("info")); + + let db_pool = db::init_pool().await + .expect("Failed to create DB pool"); + + HttpServer::new(move || { + App::new() + .app_data(web::Data::new(db_pool.clone())) // Inject shared DB pool + .service( + web::scope("/api/v1") // API versioning and grouping + .configure(routes::users::config) // User-related routes + .configure(routes::products::config) // Product-related routes + ) + // Add global middleware here (e.g., Logger, Compress) + .wrap(actix_web::middleware::Logger::default()) + }) + .bind(("127.0.0.1", 8080))? + .run() + .await +} + +// src/routes/users.rs +use actix_web::{web, HttpResponse, Responder}; +use crate::db::PgPool; // Assuming PgPool is public in db module +use crate::services::users as user_service; // Business logic layer + +pub fn config(cfg: &mut web::ServiceConfig) { + cfg.service(web::resource("/users").route(web::get().to(get_all_users))); + cfg.service(web::resource("/users/{id}").route(web::get().to(get_user_by_id))); +} + +async fn get_all_users(pool: web::Data) -> impl Responder { + match user_service::find_all_users(&pool).await { + Ok(users) => HttpResponse::Ok().json(users), + Err(e) => { + log::error!("Failed to fetch users: {:?}", e); + HttpResponse::InternalServerError().finish() + }, + } +} + +// src/services/users.rs +use crate::db::PgPool; +use crate::models::User; // Assuming User model + +pub async fn find_all_users(pool: &PgPool) -> Result, sqlx::Error> { + sqlx::query_as::<_, User>("SELECT id, name, email FROM users") + .fetch_all(pool) + .await +} +``` + +### ❌ BAD: Monolithic `main.rs` or `types.rs`/`impl.rs` for everything + +```rust +// src/main.rs (all routes, models, db logic in one file) +// src/types.rs (all structs, regardless of domain) +// src/impls.rs (all impl blocks, regardless of domain) +``` +This approach quickly becomes unmanageable and hinders collaboration. + +## 2. Application State (`web::Data`) + +Use `web::Data` for dependency injection and sharing application-wide state. For mutable state, wrap it in `Arc>` or `Arc>` and ensure it's initialized *outside* the `HttpServer::new` closure. + +### ✅ GOOD: Shared Immutable and Mutable State + +```rust +use actix_web::{web, App, HttpServer, Responder, HttpResponse}; +use std::sync::{Arc, Mutex}; + +struct AppState { + app_name: String, + request_count: Arc>, // Shared mutable state +} + +async fn index(data: web::Data) -> impl Responder { + let mut count = data.request_count.lock().unwrap(); + *count += 1; + HttpResponse::Ok().body(format!( + "Hello from {}! Request count: {}", + data.app_name, count + )) +} + +#[actix_web::main] +async fn main() -> std::io::Result<()> { + // Initialize shared mutable state *outside* the closure + let request_count = Arc::new(Mutex::new(0)); + + HttpServer::new(move || { + App::new() + .app_data(web::Data::new(AppState { + app_name: "My Actix App".to_string(), + request_count: request_count.clone(), // Clone Arc for each worker + })) + .route("/", web::get().to(index)) + }) + .bind(("127.0.0.1", 8080))? + .run() + .await +} +``` + +### ❌ BAD: Mutable state initialized inside `HttpServer::new` + +```rust +// This will create a *new* Mutex for each worker thread, +// leading to desynchronized counts. +HttpServer::new(move || { + let request_count = Arc::new(Mutex::new(0)); // BAD: Each worker gets its own counter + App::new() + .app_data(web::Data::new(AppState { + app_name: "My Actix App".to_string(), + request_count: request_count.clone(), + })) + .route("/", web::get().to(index)) +}) +``` + +## 3. Extractors & Responders + +Leverage Actix-web's powerful, type-safe extractors (`web::Json`, `web::Path`, `web::Query`) and ensure your handlers return types that implement `Responder`. + +### ✅ GOOD: Type-Safe Request/Response Handling + +```rust +use actix_web::{web, HttpResponse, Responder}; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize)] +struct UserInfo { + name: String, + email: String, +} + +#[derive(Serialize)] +struct UserResponse { + id: u32, + name: String, +} + +// Handler with Path, Json extractors and Json response +async fn create_user( + path: web::Path, // Extracts from /users/{id} + user_info: web::Json, // Extracts and deserializes JSON body +) -> impl Responder { + let user_id = path.into_inner(); + log::info!("Creating user {} with name: {}", user_id, user_info.name); + // ... business logic ... + HttpResponse::Created().json(UserResponse { + id: user_id, + name: user_info.name.clone(), + }) +} +``` + +### ❌ BAD: Manual Request Body Parsing + +```rust +// Avoid manually reading and deserializing request bodies; it's error-prone and verbose. +async fn create_user_bad(mut payload: web::Payload) -> Result { + use futures::StreamExt; + let mut body = web::BytesMut::new(); + while let Some(chunk) = payload.next().await { + body.extend_from_slice(&chunk?) + } + let user_info: UserInfo = serde_json::from_slice(&body) + .map_err(actix_web::error::ErrorBadRequest)?; // Manual deserialization + // ... + Ok(HttpResponse::Ok().finish()) +} +``` + +## 4. Error Handling + +Define custom error types that implement `ResponseError` for consistent, structured error responses. Use `thiserror` for ergonomic error definition. + +### ✅ GOOD: Custom Error Types with `ResponseError` + +```rust +use actix_web::{error::ResponseError, http::StatusCode, HttpResponse}; +use derive_more::{Display, Error}; +use serde::Serialize; +use crate::models::User; // Assuming User model +use crate::db::PgPool; // Assuming PgPool + +#[derive(Debug, Display, Error, Serialize)] +#[display(fmt = "{}", message)] +pub enum AppError { + #[display(fmt = "User not found: {}", id)] + UserNotFound { id: u32, message: String }, + #[display(fmt = "Database error: {}", _0)] + DbError(#[from] sqlx::Error), + #[display(fmt = "Validation error: {}", message)] + ValidationError { message: String }, + #[display(fmt = "Internal server error")] + InternalError, +} + +impl ResponseError for AppError { + fn error_response(&self) -> HttpResponse { + let status_code = match self { + AppError::UserNotFound { .. } => StatusCode::NOT_FOUND, + AppError::DbError(_) => StatusCode::INTERNAL_SERVER_ERROR, + AppError::ValidationError { .. } => StatusCode::BAD_REQUEST, + AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR, + }; + HttpResponse::build(status_code).json(self) // Serialize error to JSON + } +} + +// Example handler using custom error +async fn get_user_handler( + path: web::Path, + pool: web::Data, +) -> Result { + let user_id = path.into_inner(); + let user = sqlx::query_as::<_, User>("SELECT id, name, email FROM users WHERE id = $1") + .bind(user_id) + .fetch_optional(pool.get_ref()) + .await? // Converts sqlx::Error to AppError::DbError + .ok_or(AppError::UserNotFound { id: user_id, message: format!("User with ID {} not found", user_id) })?; + + Ok(HttpResponse::Ok().json(user)) +} +``` + +### ❌ BAD: Generic `actix_web::Error` or `panic!` + +```rust +// Returns a generic 500 error without specific context, making debugging hard. +async fn get_user_bad(path: web::Path) -> Result { + let user_id = path.into_inner(); + if user_id == 0 { + return Err(actix_web::error::ErrorBadRequest("Invalid ID")); + } + // ... + Ok(HttpResponse::Ok().finish()) +} + +// Panicking in a handler is unacceptable for production; it crashes the worker. +async fn get_user_panic() -> impl Responder { + panic!("Something went terribly wrong!"); +} +``` + +## 5. Middleware & Security + +Employ `actix-web`'s robust middleware for logging, compression, CORS, and other cross-cutting concerns. Always include `Logger` for request tracing. + +### ✅ GOOD: Essential Middleware Stack + +```rust +use actix_web::{middleware, App, HttpServer}; +use actix_cors::Cors; +use env_logger::Env; + +#[actix_web::main] +async fn main() -> std::io::Result<()> { + env_logger::init_from_env(Env::default().default_filter_or("info")); + + HttpServer::new(move || { + let cors = Cors::default() + .allow_any_origin() // Configure specific origins for production + .allow_any_method() + .allow_any_header() + .max_age(3600); + + App::new() + .wrap(middleware::Logger::default()) // Request logging + .wrap(middleware::Compress::default()) // Response compression + .wrap(middleware::NormalizePath::trim()) // Trailing slash handling + .wrap(cors) // Cross-Origin Resource Sharing + // ... your routes ... + }) + .bind(("127.0.0.1", 8080))? + .run() + .await +} +``` + +### ❌ BAD: Missing Logging or Basic Security + +```rust +// Without Logger, debugging production issues is significantly harder. +// Without CORS, frontend apps on different origins will fail. +HttpServer::new(move || { + App::new() + // No .wrap(middleware::Logger::default()) + // No .wrap(Cors::default()) + // ... +}) +``` + +## 6. Performance & Blocking Operations + +Actix-web is asynchronous. Avoid blocking I/O or CPU-bound tasks directly in handlers. Use `web::block` for blocking operations or offload to a dedicated thread pool. + +### ✅ GOOD: Offloading Blocking Operations + +```rust +use actix_web::{web, HttpResponse, Responder}; +use std::thread; +use std::time::Duration; + +// A simulated blocking DB call or heavy computation +fn blocking_task(input: String) -> String { + thread::sleep(Duration::from_secs(1)); // Simulate blocking + format!("Processed: {}", input) +} + +async fn handle_blocking_request(body: web::Bytes) -> impl Responder { + let input = String::from_utf8(body.to_vec()).unwrap_or_default(); + // Use web::block to run the blocking task on a separate thread pool + let result = web::block(move || blocking_task(input)).await; + + match result { + Ok(output) => HttpResponse::Ok().body(output), + Err(e) => { \ No newline at end of file diff --git a/rules-mdc/aiohttp.mdc b/rules-mdc/aiohttp.mdc index e5302f5..0b41633 100644 --- a/rules-mdc/aiohttp.mdc +++ b/rules-mdc/aiohttp.mdc @@ -1,338 +1,197 @@ --- -description: Comprehensive guide for aiohttp development covering code organization, performance, security, testing, and deployment best practices. Provides actionable guidance for developers to build robust and maintainable aiohttp applications. -globs: *.py +description: This guide defines definitive best practices for using aiohttp, focusing on efficient, robust, and maintainable asynchronous HTTP client code. +globs: **/*.py --- -# Aiohttp Best Practices - -This document provides a comprehensive guide to aiohttp development, covering code organization, performance, security, testing, and deployment. - -Library Information: -- Name: aiohttp -- Tags: web, python, http-client, async - -## 1. Code Organization and Structure - -### 1.1. Directory Structure Best Practices: - -* **Project Root:** - * `src/`: Contains the main application code. - * `main.py`: Entry point of the application. - * `app.py`: Application factory and setup. - * `routes.py`: Defines application routes. - * `handlers/`: Contains request handlers. - * `user_handlers.py`: User-related handlers. - * `product_handlers.py`: Product-related handlers. - * `middlewares/`: Custom middleware components. - * `logging_middleware.py`: Logging middleware. - * `auth_middleware.py`: Authentication middleware. - * `utils/`: Utility modules. - * `db.py`: Database connection and utilities. - * `config.py`: Configuration management. - * `tests/`: Contains unit and integration tests. - * `conftest.py`: Pytest configuration file. - * `unit/`: Unit tests. - * `integration/`: Integration tests. - * `static/`: Static files (CSS, JavaScript, images). - * `templates/`: Jinja2 or other template files. - * `docs/`: Project documentation. - * `requirements.txt`: Python dependencies. - * `Dockerfile`: Docker configuration file. - * `docker-compose.yml`: Docker Compose configuration. - * `.env`: Environment variables. - * `README.md`: Project description and instructions. - * `.gitignore`: Specifies intentionally untracked files that Git should ignore. - * `.cursor/rules/`: Project specific Cursor AI rules. - -### 1.2. File Naming Conventions: - -* Python files: `snake_case.py` (e.g., `user_handlers.py`, `database_utils.py`). -* Class names: `CamelCase` (e.g., `UserHandler`, `DatabaseConnection`). -* Function names: `snake_case` (e.g., `get_user`, `create_product`). -* Variables: `snake_case` (e.g., `user_id`, `product_name`). -* Constants: `UPPER_SNAKE_CASE` (e.g., `DEFAULT_PORT`, `MAX_CONNECTIONS`). - -### 1.3. Module Organization: - -* Group related functionality into modules. -* Use clear and descriptive module names. -* Avoid circular dependencies. -* Keep modules focused and concise. -* Use packages to organize modules into a hierarchical structure. - -### 1.4. Component Architecture: - -* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access). -* **Microservices Architecture:** Decompose the application into small, independent services. -* **Hexagonal Architecture (Ports and Adapters):** Decouple the application core from external dependencies. -* **MVC (Model-View-Controller):** Organize the application into models (data), views (presentation), and controllers (logic). - -### 1.5. Code Splitting Strategies: - -* **Route-based splitting:** Load modules based on the requested route. -* **Feature-based splitting:** Divide the application into feature modules. -* **Component-based splitting:** Split the application into reusable components. -* **On-demand loading:** Load modules only when they are needed. -* **Asynchronous loading:** Use `asyncio.gather` or similar techniques to load modules concurrently. - -## 2. Common Patterns and Anti-patterns - -### 2.1. Design Patterns: - -* **Singleton:** For managing shared resources like database connections or configuration objects. -* **Factory:** For creating instances of classes with complex initialization logic. -* **Strategy:** For implementing different algorithms or behaviors. -* **Observer:** For implementing event-driven systems. -* **Middleware:** For handling cross-cutting concerns like logging, authentication, and error handling. - -### 2.2. Recommended Approaches for Common Tasks: - -* **Request Handling:** Use request handlers to process incoming requests. -* **Routing:** Use `aiohttp.web.RouteTableDef` for defining routes. -* **Middleware:** Implement middleware for request pre-processing and response post-processing. -* **Data Serialization:** Use `aiohttp.web.json_response` for serializing data to JSON. -* **Error Handling:** Implement custom error handlers to handle exceptions gracefully. -* **Session Management:** Use `aiohttp-session` for managing user sessions. -* **WebSockets:** Utilize `aiohttp.web.WebSocketResponse` for handling WebSocket connections. - -### 2.3. Anti-patterns and Code Smells: - -* **Creating a new `ClientSession` for each request:** This is a performance bottleneck. Reuse a single `ClientSession`. -* **Blocking operations in asynchronous code:** Avoid using blocking operations (e.g., `time.sleep`) in asynchronous code. -* **Ignoring exceptions:** Always handle exceptions properly to prevent unexpected behavior. -* **Overusing global variables:** Avoid using global variables as much as possible to maintain code clarity and testability. -* **Tight coupling:** Decouple components to improve maintainability and reusability. -* **Hardcoding configuration:** Use environment variables or configuration files to manage configuration settings. - -### 2.4. State Management: - -* **Application State:** Store application-level state in the `aiohttp.web.Application` instance. -* **Request State:** Store request-specific state in the `aiohttp.web.Request` instance. -* **Session State:** Use `aiohttp-session` to manage user session data. -* **Database:** Use a database like PostgreSQL, MySQL, or MongoDB to store persistent state. -* **Redis/Memcached:** Use in-memory data stores for caching frequently accessed data. - -### 2.5. Error Handling: - -* **Use `try-except` blocks:** Wrap code that may raise exceptions in `try-except` blocks. -* **Handle specific exceptions:** Catch specific exception types instead of using a generic `except Exception`. -* **Log exceptions:** Log exceptions with detailed information for debugging. -* **Return informative error responses:** Return appropriate HTTP status codes and error messages to the client. -* **Implement custom error handlers:** Create custom error handlers to handle specific exception types. -* **Use `aiohttp.web.HTTPException`:** Raise `aiohttp.web.HTTPException` to return HTTP error responses. - -## 3. Performance Considerations - -### 3.1. Optimization Techniques: - -* **Reuse `ClientSession`:** Always reuse a single `ClientSession` instance for making multiple requests. -* **Connection Pooling:** aiohttp automatically uses connection pooling, so reuse your session. -* **Keep-Alive Connections:** Keep-alive connections are enabled by default, reducing connection overhead. -* **Gzip Compression:** Enable Gzip compression for responses to reduce bandwidth usage. -* **Caching:** Implement caching for frequently accessed data to reduce database load. -* **Optimize Database Queries:** Optimize database queries to improve response times. -* **Use Indexes:** Use indexes in your database tables to speed up queries. -* **Limit Payload Size:** Keep request and response payloads as small as possible. -* **Background Tasks:** Use `asyncio.create_task` to offload long-running tasks to the background. -* **Profiling:** Use profiling tools to identify performance bottlenecks. - -### 3.2. Memory Management: - -* **Avoid Memory Leaks:** Ensure that all resources are properly released to prevent memory leaks. -* **Use Generators:** Use generators to process large datasets in chunks. -* **Limit Object Creation:** Minimize the creation of objects to reduce memory overhead. -* **Use Data Structures Efficiently:** Choose appropriate data structures to optimize memory usage. -* **Garbage Collection:** Understand how Python's garbage collection works and optimize your code accordingly. - -### 3.3. Rendering Optimization: - -* **Template Caching:** Cache templates to reduce rendering time. -* **Minimize Template Logic:** Keep template logic simple and move complex logic to request handlers. -* **Use Asynchronous Templates:** Use asynchronous template engines like `aiohttp-jinja2`. -* **Optimize Static Files:** Optimize static files (CSS, JavaScript, images) to reduce page load times. - -### 3.4. Bundle Size Optimization: - -* **Minimize Dependencies:** Reduce the number of dependencies in your project. -* **Tree Shaking:** Use tree shaking to remove unused code from your bundles. -* **Code Minification:** Minify your code to reduce bundle sizes. -* **Code Compression:** Compress your code to further reduce bundle sizes. - -### 3.5. Lazy Loading: - -* **Lazy Load Modules:** Load modules only when they are needed. -* **Lazy Load Images:** Load images only when they are visible in the viewport. -* **Use Asynchronous Loading:** Use `asyncio.gather` or similar techniques to load resources concurrently. - -## 4. Security Best Practices - -### 4.1. Common Vulnerabilities: - -* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM. -* **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates. -* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens. -* **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms. -* **Denial-of-Service (DoS) Attacks:** Implement rate limiting and other measures to prevent DoS attacks. -* **Insecure Dependencies:** Keep your dependencies up to date to prevent vulnerabilities. - -### 4.2. Input Validation: - -* **Validate all user input:** Validate all user input to prevent malicious data from entering your application. -* **Use a validation library:** Use a validation library like `marshmallow` or `voluptuous` to simplify input validation. -* **Sanitize user input:** Sanitize user input to remove potentially harmful characters. -* **Limit input length:** Limit the length of input fields to prevent buffer overflows. -* **Use regular expressions:** Use regular expressions to validate input patterns. - -### 4.3. Authentication and Authorization: - -* **Use a strong authentication scheme:** Use a strong authentication scheme like OAuth 2.0 or JWT. -* **Store passwords securely:** Store passwords securely using a hashing algorithm like bcrypt. -* **Implement role-based access control (RBAC):** Use RBAC to control access to resources based on user roles. -* **Use secure cookies:** Use secure cookies to protect session data. -* **Implement multi-factor authentication (MFA):** Use MFA to add an extra layer of security. - -### 4.4. Data Protection: - -* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit. -* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server. -* **Store data securely:** Store data in a secure location with appropriate access controls. -* **Regularly back up data:** Regularly back up data to prevent data loss. -* **Comply with data privacy regulations:** Comply with data privacy regulations like GDPR and CCPA. - -### 4.5. Secure API Communication: - -* **Use HTTPS:** Always use HTTPS for API communication. -* **Implement API authentication:** Use API keys or tokens to authenticate API requests. -* **Rate limit API requests:** Implement rate limiting to prevent abuse. -* **Validate API requests:** Validate API requests to prevent malicious data from entering your application. -* **Log API requests:** Log API requests for auditing and debugging. - -## 5. Testing Approaches - -### 5.1. Unit Testing: - -* **Test individual components:** Unit tests should test individual components in isolation. -* **Use a testing framework:** Use a testing framework like `pytest` or `unittest`. -* **Write clear and concise tests:** Write clear and concise tests that are easy to understand. -* **Test edge cases:** Test edge cases and boundary conditions. -* **Use mocks and stubs:** Use mocks and stubs to isolate components under test. - -### 5.2. Integration Testing: - -* **Test interactions between components:** Integration tests should test interactions between different components. -* **Test with real dependencies:** Integration tests should use real dependencies whenever possible. -* **Test the entire application flow:** Integration tests should test the entire application flow. -* **Use a testing database:** Use a testing database to isolate integration tests from the production database. - -### 5.3. End-to-End Testing: - -* **Test the entire system:** End-to-end tests should test the entire system from end to end. -* **Use a testing environment:** Use a testing environment that mimics the production environment. -* **Automate end-to-end tests:** Automate end-to-end tests to ensure that the system is working correctly. -* **Use a browser automation tool:** Use a browser automation tool like Selenium or Puppeteer. - -### 5.4. Test Organization: - -* **Organize tests by module:** Organize tests by module to improve test discovery and maintainability. -* **Use descriptive test names:** Use descriptive test names that clearly indicate what the test is verifying. -* **Use test fixtures:** Use test fixtures to set up and tear down test environments. -* **Use test markers:** Use test markers to categorize tests and run specific test suites. - -### 5.5. Mocking and Stubbing: - -* **Use mocks to simulate dependencies:** Use mocks to simulate the behavior of dependencies. -* **Use stubs to provide predefined responses:** Use stubs to provide predefined responses to API calls. -* **Use mocking libraries:** Use mocking libraries like `unittest.mock` or `pytest-mock`. -* **Avoid over-mocking:** Avoid over-mocking, as it can make tests less reliable. - -## 6. Common Pitfalls and Gotchas - -### 6.1. Frequent Mistakes: - -* **Not handling exceptions properly:** Always handle exceptions to prevent unexpected behavior. -* **Using blocking operations in asynchronous code:** Avoid using blocking operations in asynchronous code. -* **Not closing `ClientSession`:** Always close the `ClientSession` to release resources. -* **Not validating user input:** Always validate user input to prevent security vulnerabilities. -* **Not using HTTPS:** Always use HTTPS for secure communication. - -### 6.2. Edge Cases: - -* **Handling timeouts:** Implement proper timeout handling to prevent requests from hanging indefinitely. -* **Handling connection errors:** Handle connection errors gracefully to prevent application crashes. -* **Handling large payloads:** Handle large payloads efficiently to prevent memory issues. -* **Handling concurrent requests:** Handle concurrent requests properly to prevent race conditions. -* **Handling Unicode encoding:** Be aware of Unicode encoding issues when processing text data. - -### 6.3. Version-Specific Issues: - -* **aiohttp version compatibility:** Be aware of compatibility issues between different aiohttp versions. -* **asyncio version compatibility:** Be aware of compatibility issues between aiohttp and different asyncio versions. -* **Python version compatibility:** Be aware of compatibility issues between aiohttp and different Python versions. - -### 6.4. Compatibility Concerns: - -* **Compatibility with other libraries:** Be aware of compatibility issues between aiohttp and other libraries. -* **Compatibility with different operating systems:** Be aware of compatibility issues between aiohttp and different operating systems. -* **Compatibility with different web servers:** Be aware of compatibility issues between aiohttp and different web servers. - -### 6.5. Debugging Strategies: - -* **Use logging:** Use logging to track application behavior and identify issues. -* **Use a debugger:** Use a debugger to step through code and examine variables. -* **Use a profiler:** Use a profiler to identify performance bottlenecks. -* **Use error reporting tools:** Use error reporting tools to track and fix errors in production. -* **Use a network analyzer:** Use a network analyzer like Wireshark to capture and analyze network traffic. - -## 7. Tooling and Environment - -### 7.1. Recommended Development Tools: - -* **IDE:** Use an IDE like VS Code, PyCharm, or Sublime Text. -* **Virtual Environment:** Use a virtual environment to isolate project dependencies. -* **Package Manager:** Use a package manager like pip or poetry to manage dependencies. -* **Testing Framework:** Use a testing framework like pytest or unittest. -* **Linting Tool:** Use a linting tool like pylint or flake8 to enforce code style. -* **Formatting Tool:** Use a formatting tool like black or autopep8 to format code automatically. - -### 7.2. Build Configuration: - -* **Use a build system:** Use a build system like Make or tox to automate build tasks. -* **Define dependencies in `requirements.txt` or `pyproject.toml`:** Specify all project dependencies in a `requirements.txt` or `pyproject.toml` file. -* **Use a Dockerfile:** Use a Dockerfile to create a containerized build environment. -* **Use Docker Compose:** Use Docker Compose to manage multi-container applications. - -### 7.3. Linting and Formatting: - -* **Use a consistent code style:** Use a consistent code style throughout the project. -* **Configure linting tools:** Configure linting tools to enforce code style rules. -* **Configure formatting tools:** Configure formatting tools to format code automatically. -* **Use pre-commit hooks:** Use pre-commit hooks to run linters and formatters before committing code. - -### 7.4. Deployment: - -* **Use a web server:** Use a web server like Nginx or Apache to serve the application. -* **Use a process manager:** Use a process manager like Supervisor or systemd to manage the application process. -* **Use a reverse proxy:** Use a reverse proxy to improve security and performance. -* **Use a load balancer:** Use a load balancer to distribute traffic across multiple servers. -* **Use a monitoring system:** Use a monitoring system to track application health and performance. -* **Standalone Server:** aiohttp.web.run_app(), simple but doesn't utilize all CPU cores. -* **Nginx + Supervisord:** Nginx prevents attacks, allows utilizing all CPU cores, and serves static files faster. -* **Nginx + Gunicorn:** Gunicorn launches the app as worker processes, simplifying deployment compared to bare Nginx. - -### 7.5. CI/CD Integration: - -* **Use a CI/CD pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process. -* **Use a CI/CD tool:** Use a CI/CD tool like Jenkins, GitLab CI, or GitHub Actions. -* **Run tests in the CI/CD pipeline:** Run tests in the CI/CD pipeline to ensure that code changes don't break the application. -* **Automate deployment:** Automate deployment to reduce manual effort and improve consistency. - -## Additional Best Practices: - -* **Session Management:** Always create a `ClientSession` for making requests and reuse it across multiple requests to benefit from connection pooling. Avoid creating a new session for each request, as this can lead to performance issues. -* **Error Handling:** Implement robust error handling in your request handlers. Use try-except blocks to manage exceptions, particularly for network-related errors. For example, handle `ConnectionResetError` to manage client disconnections gracefully. -* **Middleware Usage:** Utilize middleware for cross-cutting concerns such as logging, error handling, and modifying requests/responses. Define middleware functions that accept a request and a handler, allowing you to process requests before they reach your main handler. -* **Graceful Shutdown:** Implement graceful shutdown procedures for your server to ensure that ongoing requests are completed before the application exits. This can be achieved by registering shutdown signals and cleaning up resources. -* **Security Practices:** When deploying, consider using a reverse proxy like Nginx for added security and performance. Configure SSL/TLS correctly to secure your application. -* **Character Set Detection:** If a response does not include the charset needed to decode the body, use `ClientSession` accepts a `fallback_charset_resolver` parameter which can be used to introduce charset guessing functionality. -* **Persistent Session:** Use `Cleanup Context` when creating a persistent session. - -By adhering to these practices, developers can enhance the reliability, performance, and security of their `aiohttp` applications. \ No newline at end of file +# `aiohttp` Best Practices + +`aiohttp` is our go-to for high-performance asynchronous HTTP client operations. These rules ensure our `aiohttp` code is consistent, efficient, and resilient. + +## 1. Manage `ClientSession` Lifecycle Properly + +Always use a single, long-lived `ClientSession` per application or logical component. This leverages connection pooling and keep-alive, drastically reducing overhead. Always use it as an `async` context manager to ensure connections are closed cleanly. + +❌ **BAD: Creating a new session for every request** +```python +import aiohttp +import asyncio + +async def fetch_data(url: str) -> str: + async with aiohttp.ClientSession() as session: # Session created and closed per call + async with session.get(url) as response: + return await response.text() + +async def main(): + await fetch_data("http://example.com/api/v1/data") + await fetch_data("http://example.com/api/v1/status") # New session, new connection +``` + +✅ **GOOD: Single, long-lived `ClientSession`** +```python +import aiohttp +import asyncio + +# Create the session once, typically at application startup +# or pass it down through dependencies. +_GLOBAL_HTTP_SESSION: aiohttp.ClientSession | None = None + +async def get_http_session() -> aiohttp.ClientSession: + global _GLOBAL_HTTP_SESSION + if _GLOBAL_HTTP_SESSION is None or _GLOBAL_HTTP_SESSION.closed: + _GLOBAL_HTTP_SESSION = aiohttp.ClientSession() + return _GLOBAL_HTTP_SESSION + +async def close_http_session(): + global _GLOBAL_HTTP_SESSION + if _GLOBAL_HTTP_SESSION and not _GLOBAL_HTTP_SESSION.closed: + await _GLOBAL_HTTP_SESSION.close() + _GLOBAL_HTTP_SESSION = None + +async def fetch_data(session: aiohttp.ClientSession, url: str) -> str: + async with session.get(url) as response: + response.raise_for_status() # Always raise for non-2xx statuses + return await response.text() + +async def main(): + session = await get_http_session() + try: + data = await fetch_data(session, "http://example.com/api/v1/data") + status = await fetch_data(session, "http://example.com/api/v1/status") + print(f"Data: {data[:20]}..., Status: {status[:20]}...") + finally: + await close_http_session() # Ensure session is closed on app shutdown +``` + +## 2. Install All Speedups + +Always install `aiohttp` with its `[speedups]` extra. This includes `aiodns` for faster DNS resolution and `backports.zstd` (for Python < 3.14) for modern compression, significantly boosting performance. + +```bash +pip install aiohttp[speedups] +``` + +## 3. Implement Robust Timeouts and Error Handling + +Explicitly define timeouts using `aiohttp.ClientTimeout` and enable `raise_for_status=True` for automatic HTTP error detection. Wrap requests in `try/except aiohttp.ClientError` to handle network and HTTP-level issues gracefully. + +❌ **BAD: No timeouts, generic exception handling** +```python +async def fetch_unreliable(session: aiohttp.ClientSession, url: str) -> str: + # This request could hang indefinitely + async with session.get(url) as response: + # 4xx/5xx responses won't raise an error, requiring manual check + return await response.text() +``` + +✅ **GOOD: Explicit timeouts, `raise_for_status`, and specific error handling** +```python +from aiohttp import ClientSession, ClientTimeout, ClientError, ClientResponseError +import asyncio + +async def fetch_reliable(session: ClientSession, url: str) -> str: + timeout = ClientTimeout(total=5, connect=1, sock_read=3) # 5s total, 1s connect, 3s read + try: + async with session.get(url, timeout=timeout, raise_for_status=True) as response: + return await response.text() + except ClientResponseError as e: + print(f"HTTP error for {url}: {e.status} - {e.message}") + raise + except ClientError as e: + print(f"Network or client error for {url}: {e}") + raise + except asyncio.TimeoutError: + print(f"Request to {url} timed out.") + raise +``` + +## 4. Use Typed, Reusable Request Helpers + +Encapsulate common request patterns in small, type-hinted `async` functions. This improves readability, maintainability, and enables better IDE support. + +❌ **BAD: Repeated request logic and untyped functions** +```python +async def get_user_data(session, user_id): + resp = await session.get(f"http://api.example.com/users/{user_id}") + return await resp.json() + +async def create_user(session, user_data): + resp = await session.post("http://api.example.com/users", json=user_data) + return await resp.json() +``` + +✅ **GOOD: Type-hinted, reusable functions with `json=` shortcut** +```python +from typing import Any, Dict +from aiohttp import ClientSession + +async def fetch_json(session: ClientSession, url: str) -> Dict[str, Any]: + """Fetches JSON from a URL, raises for status, and returns parsed data.""" + async with session.get(url, raise_for_status=True) as response: + return await response.json() + +async def post_json(session: ClientSession, url: str, payload: Dict[str, Any]) -> Dict[str, Any]: + """Posts JSON payload to a URL, raises for status, and returns parsed response.""" + async with session.post(url, json=payload, raise_for_status=True) as response: + return await response.json() + +async def get_user_data(session: ClientSession, user_id: str) -> Dict[str, Any]: + return await fetch_json(session, f"http://api.example.com/users/{user_id}") + +async def create_user(session: ClientSession, user_data: Dict[str, Any]) -> Dict[str, Any]: + return await post_json(session, "http://api.example.com/users", user_data) +``` + +## 5. Prefer Built-in Authentication and Session Headers + +Use the `auth` parameter for basic authentication or `DigestAuthMiddleware` for digest auth. For other authentication schemes or default headers, set them when initializing `ClientSession` or update `session.headers`. Avoid manual `Authorization` header manipulation where built-in options exist. + +❌ **BAD: Manually constructing `Authorization` headers** +```python +import base64 +async def fetch_with_basic_auth(session: ClientSession, url: str, user: str, password: str): + auth_str = base64.b64encode(f"{user}:{password}".encode()).decode() + headers = {"Authorization": f"Basic {auth_str}"} + async with session.get(url, headers=headers) as response: + return await response.text() +``` + +✅ **GOOD: Using `auth` parameter for basic auth** +```python +from aiohttp import ClientSession, BasicAuth + +async def fetch_with_basic_auth(session: ClientSession, url: str, user: str, password: str): + auth = BasicAuth(login=user, password=password) + async with session.get(url, auth=auth) as response: + response.raise_for_status() + return await response.text() + +# For session-wide default headers (e.g., Bearer tokens) +async def create_auth_session(token: str) -> ClientSession: + headers = {"Authorization": f"Bearer {token}"} + return ClientSession(headers=headers) +``` + +## 6. Leverage Client Middleware for Cross-Cutting Concerns + +For concerns like tracing, retries, or rate limiting that apply across many requests, implement client-side middleware. This keeps your request logic clean and separates concerns effectively. + +```python +from aiohttp import ClientSession, ClientRequest, ClientResponse +from aiohttp.typedefs import ClientHandler +import logging + +logging.basicConfig(level=logging.INFO) + +async def logging_middleware(req: ClientRequest, handler: ClientHandler) -> ClientResponse: + """Logs request and response details.""" + logging.info(f"Requesting: {req.method} {req.url}") + response = await handler(req) + logging.info(f"Received: {response.status} for {req.method} {req.url}") + return response + +async def main_with_middleware(): + async with ClientSession(middlewares=(logging_middleware,)) as session: + await fetch_json(session, "http://httpbin.org/get") + await post_json(session, "http://httpbin.org/post", {"key": "value"}) + +# Example usage with the `fetch_json` and `post_json` helpers from above. +``` \ No newline at end of file diff --git a/rules-mdc/amazon-ec2.mdc b/rules-mdc/amazon-ec2.mdc index 4465bc6..8cc1e53 100644 --- a/rules-mdc/amazon-ec2.mdc +++ b/rules-mdc/amazon-ec2.mdc @@ -1,318 +1,330 @@ --- -description: This rule file provides best practices, coding standards, and security guidelines for developing, deploying, and maintaining applications using the amazon-ec2 library within the AWS ecosystem. It focuses on infrastructure as code (IaC), resource management, performance, and security considerations for robust and scalable EC2-based solutions. -globs: *.tf,*.json,*.yml,*.yaml,*.py,*.js,*.ts,*.sh,*.java,*.go,*.rb,*.m -alwaysApply: false +description: This guide provides definitive best practices for deploying and managing Amazon EC2 instances, focusing on security, cost optimization, and operational excellence through Infrastructure as Code (IaC). +globs: **/* --- -- ## General Principles - - **Infrastructure as Code (IaC):** Treat your infrastructure as code. Define and provision AWS resources (EC2 instances, security groups, networks) using code (e.g., AWS CloudFormation, AWS CDK, Terraform). This ensures consistency, repeatability, and version control. - - **Security First:** Integrate security best practices into every stage of development, from IaC template creation to instance configuration. Implement the principle of least privilege, regularly patch instances, and utilize security assessment tools. - - **Modularity and Reusability:** Design your infrastructure and application code in modular components that can be reused across multiple projects or environments. - - **Automation:** Automate as much of the infrastructure provisioning, deployment, and management processes as possible. Use CI/CD pipelines for automated testing and deployment. - - **Monitoring and Logging:** Implement comprehensive monitoring and logging to track the health, performance, and security of your EC2 instances and applications. +# amazon-ec2 Best Practices -- ## 1. Code Organization and Structure +Treat every EC2 instance as versioned, secured, and continuously optimized code. Adhere strictly to the AWS Well-Architected Framework and Foundational Security Best Practices (FSBP). - - **Directory Structure Best Practices:** - - Adopt a logical directory structure that reflects the architecture of your application and infrastructure. - - Example: - - project-root/ - ├── modules/ # Reusable infrastructure modules (e.g., VPC, security groups) - │ ├── vpc/ # VPC module - │ │ ├── main.tf # Terraform configuration for the VPC - │ │ ├── variables.tf # Input variables for the VPC module - │ │ ├── outputs.tf # Output values for the VPC module - │ ├── security_group/ # Security Group module - │ │ ├── ... - ├── environments/ # Environment-specific configurations - │ ├── dev/ # Development environment - │ │ ├── main.tf # Terraform configuration for the Dev environment - │ │ ├── variables.tf # Environment specific variables - │ ├── prod/ # Production environment - │ │ ├── ... - ├── scripts/ # Utility scripts (e.g., deployment scripts, automation scripts) - │ ├── deploy.sh # Deployment script - │ ├── update_ami.py # Python script to update AMI - ├── application/ # Application code - │ ├── src/ # Source code - │ ├── tests/ # Unit and integration tests - ├── README.md - └── ... - - - **File Naming Conventions:** - - Use consistent and descriptive file names. - - Examples: - - `main.tf`: Main Terraform configuration file - - `variables.tf`: Terraform variables file - - `outputs.tf`: Terraform output values file - - `deploy.sh`: Deployment script - - `instance.py`: Python module for instance management - - **Module Organization:** - - Encapsulate reusable infrastructure components into modules (e.g., VPC, security groups, load balancers). - - Each module should have: - - A clear purpose. - - Well-defined input variables and output values. - - Comprehensive documentation. - - Keep modules small and focused. - - **Component Architecture:** - - Design your application as a collection of loosely coupled components. - - Each component should have: - - A well-defined interface. - - Clear responsibilities. - - Independent deployment lifecycle. - - **Code Splitting:** - - Break down large application codebases into smaller, manageable modules. - - Use lazy loading to load modules on demand, reducing initial load time. - - Example (Python): - python - # main.py - import importlib +## 1. Code Organization and Structure - def load_module(module_name): - module = importlib.import_module(module_name) - return module +**Always define EC2 resources using Infrastructure as Code (IaC).** CloudFormation is the standard for AWS-native deployments. Break down templates into modular, reusable components. - # Load the module when needed - my_module = load_module('my_module') - my_module.my_function() - +### 1.1. Modular CloudFormation Templates -- ## 2. Common Patterns and Anti-patterns +Organize your CloudFormation templates logically. Separate networking, IAM, and EC2 instance definitions into distinct, composable stacks or modules. - - **Design Patterns:** - - **Singleton:** Use when exactly one instance of a class is needed (e.g., a configuration manager). - - **Factory:** Use to create objects without specifying their concrete classes (e.g., creating different types of EC2 instances). - - **Strategy:** Use to define a family of algorithms, encapsulate each one, and make them interchangeable (e.g., different instance termination strategies). - - **Common Tasks:** - - **Creating an EC2 Instance (AWS CLI):** - bash - aws ec2 run-instances --image-id ami-xxxxxxxxxxxxxxxxx --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-xxxxxxxxxxxxxxxxx - - - **Creating an EC2 Instance (AWS CDK): - typescript - import * as ec2 from 'aws-cdk-lib/aws-ec2'; +❌ **BAD: Monolithic Template** +```yaml +# all-in-one-stack.yaml +Resources: + VPC: # ... + Subnet: # ... + SecurityGroup: # ... + IAMRole: # ... + EC2Instance: # ... +``` - const vpc = new ec2.Vpc(this, 'TheVPC', { maxAzs: 3 }); +✅ **GOOD: Modular Stacks** +```yaml +# network-stack.yaml +Resources: + VPC: # ... + Subnet: # ... +Outputs: # Export VPC ID, Subnet IDs +# iam-stack.yaml +Resources: + IAMRole: # ... +Outputs: # Export Role ARN +# ec2-instance-stack.yaml +Resources: + EC2Instance: + Type: AWS::EC2::Instance + Properties: + ImageId: ami-0abcdef1234567890 + InstanceType: !Ref InstanceTypeParam + SecurityGroupIds: [!ImportValue MySecurityGroup] + IamInstanceProfile: !ImportValue MyInstanceProfile + # ... +``` - const instance = new ec2.Instance(this, 'EC2Instance', { - vpc: vpc, - instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO), - machineImage: new ec2.AmazonLinux2023Image({generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2}), - }); - - - **Attaching an EBS Volume:** - - Ensure the EBS volume is in the same Availability Zone as the EC2 instance. - - Use the `aws ec2 attach-volume` command or the equivalent SDK call. - - **Anti-patterns:** - - **Hardcoding AWS Credentials:** Never hardcode AWS credentials in your code. Use IAM roles for EC2 instances and IAM users with restricted permissions for local development. - - **Creating Publicly Accessible S3 Buckets:** Avoid creating S3 buckets that are publicly accessible without proper security controls. - - **Ignoring Error Handling:** Always handle exceptions and errors gracefully. Provide meaningful error messages and logging. - - **Over-Permissive Security Groups:** Implement the principle of least privilege. Grant only the minimum necessary permissions to your security groups. - - **State Management:** - - Use state files (e.g., Terraform state) to track the current state of your infrastructure. - - Store state files securely (e.g., in an S3 bucket with encryption and versioning). - - Use locking mechanisms to prevent concurrent modifications to the state file. - - **Error Handling:** - - Implement robust error handling to catch exceptions and prevent application crashes. - - Use try-except blocks to handle potential errors. - - Log error messages with sufficient detail for debugging. +### 1.2. Enforce Consistent Tagging -- ## 3. Performance Considerations +Implement a unified tagging strategy from your IaC templates. Tags are critical for cost allocation, resource discovery, and automation. - - **Optimization Techniques:** - - **Instance Type Selection:** Choose the appropriate EC2 instance type based on your application's requirements (CPU, memory, network). - - **EBS Optimization:** Use Provisioned IOPS (PIOPS) EBS volumes for high-performance applications. - - **Caching:** Implement caching mechanisms to reduce database load and improve response times (e.g., using Amazon ElastiCache). - - **Load Balancing:** Distribute traffic across multiple EC2 instances using an Elastic Load Balancer (ELB). - - **Auto Scaling:** Use Auto Scaling groups to automatically scale your EC2 instances based on demand. - - **Memory Management:** - - Monitor memory usage on your EC2 instances. - - Optimize application code to reduce memory consumption. - - Use memory profiling tools to identify memory leaks. - - **Bundle Size Optimization:** - - Minimize the size of your application's deployment package. - - Remove unnecessary dependencies. - - Use code minification and compression. - - Example (Python): - bash - # Create a virtual environment - python3 -m venv .venv - source .venv/bin/activate +❌ **BAD: Missing or Inconsistent Tags** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + # ... no tags or only a few +``` - # Install only necessary dependencies - pip install --no-cache-dir -r requirements.txt +✅ **GOOD: Mandatory Tags via IaC** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + # ... + Tags: + - Key: Environment + Value: !Ref EnvironmentTag + - Key: Project + Value: !Ref ProjectTag + - Key: Owner + Value: !Ref OwnerTag + - Key: CostCenter + Value: !Ref CostCenterTag +``` - # Create deployment package - zip -r deployment_package.zip * - - - **Lazy Loading:** - - Load application modules on demand to reduce initial load time. - - Use code splitting to break down large modules into smaller chunks. - - Example (JavaScript): - javascript - // main.js - async function loadModule() { - const module = await import('./my_module.js'); - module.myFunction(); +## 2. Common Patterns and Anti-patterns + +### 2.1. Right-Sizing Instances + +**Analyze workloads to select the optimal instance family and size.** This is the single biggest driver for performance efficiency and cost optimization. + +❌ **BAD: Defaulting to `t2.micro` or Over-provisioning** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + InstanceType: t2.micro # For a production database! +``` + +✅ **GOOD: Workload-Specific Instance Types** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + InstanceType: m5.large # General purpose, balanced CPU/memory + # or c5.xlarge for compute-intensive, r5.large for memory-intensive +``` + +### 2.2. Least Privilege IAM Instance Profiles + +**Attach IAM roles to EC2 instances via Instance Profiles, granting only the minimum necessary permissions.** Never embed AWS credentials directly on an instance. + +❌ **BAD: Over-privileged IAM Role** +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": "*" + } + ] +} +``` + +✅ **GOOD: Tightly Scoped IAM Role** +```yaml +# CloudFormation IAM Role for EC2 +BastionHostRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: { Service: [ 'ec2.amazonaws.com' ] } + Action: [ 'sts:AssumeRole' ] + ManagedPolicyArns: + - arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM # For SSM access + Policies: + - PolicyName: S3ReadAccess + PolicyDocument: + Statement: + - Effect: Allow + Action: [ 's3:GetObject' ] + Resource: !Sub 'arn:${AWS::Partition}:s3:::my-config-bucket/*' +``` + +### 2.3. Strict Security Group Rules + +**Security groups must enforce the principle of least privilege.** Restrict inbound and outbound traffic to only what is absolutely required. + +❌ **BAD: Open Ingress/Egress** +```yaml +SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 # SSH open to the world! +``` + +✅ **GOOD: Restricted Access** +```yaml +SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: !Ref RemoteAccessCIDR # Parameter for specific IP range + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + SourceSecurityGroupId: !Ref LoadBalancerSecurityGroup # Only allow from LB +``` + +### 2.4. Require IMDSv2 + +**Always configure EC2 instances to require Instance Metadata Service Version 2 (IMDSv2).** This prevents SSRF vulnerabilities. + +❌ **BAD: Relying on IMDSv1** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + # ... no MetadataOptions specified +``` + +✅ **GOOD: Enforce IMDSv2** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + # ... + MetadataOptions: + HttpPutResponseHopLimit: 1 + HttpTokens: required +``` + +## 3. Performance Considerations + +### 3.1. Leverage Launch Templates for Auto Scaling + +**Use EC2 Launch Templates with Auto Scaling Groups.** This ensures consistent configuration, supports multiple instance types, and simplifies updates. + +❌ **BAD: Launch Configurations (deprecated)** +```yaml +AutoScalingGroup: + Type: AWS::AutoScaling::AutoScalingGroup + Properties: + LaunchConfigurationName: !Ref MyLaunchConfig # Avoid +``` + +✅ **GOOD: Launch Templates** +```yaml +AutoScalingGroup: + Type: AWS::AutoScaling::AutoScalingGroup + Properties: + LaunchTemplate: + LaunchTemplateId: !Ref MyLaunchTemplate + Version: !GetAtt MyLaunchTemplate.LatestVersionNumber + # ... +``` + +### 3.2. EBS Optimization and Encryption + +**Use EBS-optimized instances for I/O-intensive workloads and encrypt all EBS volumes by default.** + +❌ **BAD: Unencrypted Volumes, Non-EBS Optimized** +```yaml +BlockDeviceMappings: + - DeviceName: /dev/sdh + Ebs: + VolumeSize: 100 + Encrypted: false # Never! +``` + +✅ **GOOD: Encrypted, EBS-Optimized** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + InstanceType: m5.large # Often EBS-optimized by default or configurable + BlockDeviceMappings: + - DeviceName: /dev/sdh + Ebs: + VolumeSize: 100 + Encrypted: true # Always! + KmsKeyId: !Ref MyEBSKMSKey # Use a customer-managed key +``` + +## 4. Common Pitfalls and Gotchas + +### 4.1. Avoid Hardcoding Sensitive Information + +**Never hardcode secrets, ARNs, or environment-specific values.** Use CloudFormation parameters, SSM Parameter Store, or AWS Secrets Manager. + +❌ **BAD: Hardcoded S3 Bucket Name** +```bash +#!/bin/bash +aws s3 cp /var/log/app.log s3://my-prod-bucket-123/logs/ +``` + +✅ **GOOD: Parameterized Values** +```yaml +# CloudFormation UserData +UserData: + Fn::Base64: !Sub | + #!/bin/bash + aws s3 cp /var/log/app.log s3://${LogBucketName}/logs/ +Parameters: + LogBucketName: + Type: String + Description: S3 bucket for application logs +``` + +### 4.2. Enable Termination Protection + +**Enable termination protection for critical EC2 instances.** This prevents accidental deletion. + +❌ **BAD: No Termination Protection** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + # ... no DisableApiTermination +``` + +✅ **GOOD: Termination Protection Enabled** +```yaml +EC2Instance: + Type: AWS::EC2::Instance + Properties: + # ... + DisableApiTermination: true +``` + +## 5. Testing Approaches + +### 5.1. IaC Linting and Validation + +**Integrate IaC linting and validation into your CI/CD pipeline.** Catch policy violations and syntax errors *before* deployment. + +❌ **BAD: Deploying without Pre-checks** +```bash +aws cloudformation deploy --template-file my-ec2-stack.yaml --stack-name my-app +``` + +✅ **GOOD: CI/CD with CloudFormation Guard** +```bash +# In CI/CD pipeline +cfn-guard validate --template my-ec2-stack.yaml --rules policies/ec2-rules.guard +aws cloudformation deploy --template-file my-ec2-stack.yaml --stack-name my-app +``` + +### 5.2. Automated Security Hub Compliance + +**Ensure your CI/CD pipeline includes checks against AWS Foundational Security Best Practices (FSBP) via AWS Security Hub.** + +❌ **BAD: Manual Security Audits Post-Deployment** +```bash +# Hope for the best, check manually later +``` + +✅ **GOOD: Proactive Security Checks** +```bash +# Example rule in CloudFormation Guard to enforce IMDSv2 +rule imdsv2_required { + EC2_Instance { + Properties { + MetadataOptions { + HttpTokens == "required" + HttpPutResponseHopLimit == 1 } - - loadModule(); - - -- ## 4. Security Best Practices - - - **Common Vulnerabilities:** - - **SQL Injection:** Prevent SQL injection by using parameterized queries and input validation. - - **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and encoding output. - - **Remote Code Execution (RCE):** Prevent RCE by validating user input and using secure coding practices. - - **Unsecured API endpoints:** Secure API endpoints using authentication and authorization mechanisms. - - **Input Validation:** - - Validate all user input to prevent malicious code from being injected into your application. - - Use regular expressions and data type validation. - - **Authentication and Authorization:** - - Use strong authentication mechanisms (e.g., multi-factor authentication). - - Implement role-based access control (RBAC) to restrict access to sensitive resources. - - Use AWS IAM roles for EC2 instances to grant access to AWS resources. - - **Data Protection:** - - Encrypt sensitive data at rest and in transit. - - Use HTTPS for all API communication. - - Store sensitive data in secure storage (e.g., AWS Secrets Manager). - - **Secure API Communication:** - - Use HTTPS for all API communication. - - Validate API requests and responses. - - Implement rate limiting to prevent abuse. - - Use AWS API Gateway to manage and secure your APIs. - -- ## 5. Testing Approaches - - - **Unit Testing:** - - Write unit tests for individual components to verify their functionality. - - Use mocking and stubbing to isolate components from external dependencies. - - Example (Python): - python - import unittest - from unittest.mock import Mock - - class MyComponent: - def __init__(self, external_dependency): - self.dependency = external_dependency - - def my_function(self, input_data): - result = self.dependency.process_data(input_data) - return result - - class TestMyComponent(unittest.TestCase): - def test_my_function(self): - # Create a mock for the external dependency - mock_dependency = Mock() - mock_dependency.process_data.return_value = "Mocked Result" - - # Create an instance of MyComponent with the mock dependency - component = MyComponent(mock_dependency) - - # Call the function to be tested - result = component.my_function("Test Input") - - # Assert the expected behavior - self.assertEqual(result, "Mocked Result") - mock_dependency.process_data.assert_called_once_with("Test Input") - - if __name__ == '__main__': - unittest.main() - - - **Integration Testing:** - - Write integration tests to verify the interaction between components. - - Test the integration of your application with AWS services. - - **End-to-End Testing:** - - Write end-to-end tests to verify the entire application flow. - - Simulate real user scenarios. - - **Test Organization:** - - Organize your tests into a logical directory structure. - - Use meaningful test names. - - Keep tests independent of each other. - - **Mocking and Stubbing:** - - Use mocking and stubbing to isolate components from external dependencies. - - Example (AWS CDK): - typescript - // Mocking AWS SDK calls in Jest - jest.mock('aws-sdk', () => { - const mEC2 = { - describeInstances: jest.fn().mockReturnValue({ - promise: jest.fn().mockResolvedValue({ Reservations: [] }), - }), - }; - return { - EC2: jest.fn().mockImplementation(() => mEC2), - }; - }); - - -- ## 6. Common Pitfalls and Gotchas - - - **Frequent Mistakes:** - - **Incorrect Security Group Configuration:** Incorrectly configured security groups can expose your EC2 instances to security risks. - - **Insufficient Resource Limits:** Exceeding AWS resource limits can cause application failures. - - **Not Using Auto Scaling:** Not using Auto Scaling can lead to performance bottlenecks and outages during periods of high demand. - - **Forgetting to Terminate Unused Instances:** Forgetting to terminate unused EC2 instances can lead to unnecessary costs. - - **Edge Cases:** - - **Spot Instance Interruptions:** Spot instances can be interrupted with short notice. Design your application to handle spot instance interruptions gracefully. - - **Network Connectivity Issues:** Network connectivity issues can prevent your application from accessing AWS services or other resources. - - **Version-Specific Issues:** - - Be aware of version-specific issues with the amazon-ec2 library or AWS services. - - Consult the documentation for the specific versions you are using. - - **Compatibility Concerns:** - - Ensure compatibility between your application and the underlying operating system and libraries. - - Test your application on different operating systems and browsers. - - **Debugging Strategies:** - - Use logging and monitoring to track the behavior of your application. - - Use debugging tools to identify and fix errors. - - Consult the AWS documentation and community forums for help. - -- ## 7. Tooling and Environment - - - **Recommended Tools:** - - **AWS CLI:** Command-line interface for interacting with AWS services. - - **AWS Management Console:** Web-based interface for managing AWS resources. - - **AWS CloudFormation:** Infrastructure as code service for provisioning and managing AWS resources. - - **AWS CDK:** Cloud Development Kit for defining cloud infrastructure in code. - - **Terraform:** Infrastructure as code tool for provisioning and managing cloud resources. - - **Packer:** Tool for creating machine images. - - **Ansible:** Configuration management tool. - - **Build Configuration:** - - Use a build tool (e.g., Make, Gradle, Maven) to automate the build process. - - Define dependencies and build steps in a build file. - - Example (Python): - makefile - # Makefile - venv: - python3 -m venv .venv - . .venv/bin/activate - pip install -r requirements.txt - - deploy: - zip -r deployment_package.zip * - aws s3 cp deployment_package.zip s3://my-bucket/deployment_package.zip - aws lambda update-function-code --function-name my-function --s3-bucket my-bucket --s3-key deployment_package.zip - - - **Linting and Formatting:** - - Use a linter (e.g., pylint, eslint) to enforce code style and identify potential errors. - - Use a formatter (e.g., black, prettier) to automatically format your code. - - **Deployment Best Practices:** - - Use a deployment pipeline to automate the deployment process. - - Deploy to a staging environment before deploying to production. - - Use blue/green deployments to minimize downtime. - - **CI/CD Integration:** - - Integrate your application with a CI/CD system (e.g., Jenkins, CircleCI, GitLab CI). - - Automate testing, building, and deployment. - -- ## Additional Considerations - - - **Cost Optimization:** Regularly review your AWS resource usage and identify opportunities for cost savings. Consider using Reserved Instances or Spot Instances to reduce costs. - - **Disaster Recovery:** Implement a disaster recovery plan to ensure business continuity in the event of an outage. Use AWS Backup or other backup solutions to protect your data. - - **Compliance:** Ensure that your application complies with relevant regulations and standards (e.g., PCI DSS, HIPAA). - -- ## References - - - [AWS EC2 Best Practices](mdc:https:/docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-best-practices.html) - - [AWS CDK Best Practices](mdc:https:/docs.aws.amazon.com/cdk/v2/guide/best-practices.html) - - [Terraform AWS Provider Best Practices](mdc:https:/docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/structure.html) \ No newline at end of file + } + } +} +``` \ No newline at end of file diff --git a/rules-mdc/amazon-s3.mdc b/rules-mdc/amazon-s3.mdc index de26fac..314e50c 100644 --- a/rules-mdc/amazon-s3.mdc +++ b/rules-mdc/amazon-s3.mdc @@ -1,367 +1,312 @@ --- -description: This rule file provides comprehensive best practices, coding standards, and security guidelines for developing applications using Amazon S3. It aims to ensure secure, performant, and maintainable S3 integrations. -globs: *S3*.js,*S3*.ts,*S3*.jsx,*S3*.tsx,*S3*.py,*S3*.java,*S3*.go,*S3*.csharp +description: This guide provides definitive best practices for interacting with Amazon S3, focusing on security, performance, cost optimization, and maintainable code in modern AWS applications. +globs: **/* --- -- Always disable public access to S3 buckets unless explicitly needed. Use AWS Identity and Access Management (IAM) policies and bucket policies for access control instead of Access Control Lists (ACLs), which are now generally deprecated. -- Implement encryption for data at rest using Server-Side Encryption (SSE), preferably with AWS Key Management Service (KMS) for enhanced security. -- Use S3 Transfer Acceleration for faster uploads over long distances and enable versioning to protect against accidental deletions. Monitor performance using Amazon CloudWatch and enable logging for auditing. Additionally, consider using S3 Storage Lens for insights into storage usage and activity trends. -- Leverage S3's lifecycle policies to transition objects to cheaper storage classes based on access patterns, and regularly review your storage usage to optimize costs. Utilize S3 Intelligent-Tiering for automatic cost savings based on changing access patterns. +# amazon-s3 Best Practices -## Amazon S3 Best Practices and Coding Standards +Amazon S3 is the backbone of object storage in AWS. Adhering to these guidelines ensures your S3 implementations are secure, performant, cost-effective, and maintainable. -This document provides comprehensive best practices, coding standards, and security guidelines for developing applications using Amazon S3. Following these guidelines will help ensure that your S3 integrations are secure, performant, maintainable, and cost-effective. +## 1. Security First -### 1. Code Organization and Structure +Security is paramount. Always assume your S3 buckets contain sensitive data and configure them defensively. -#### 1.1. Directory Structure Best Practices +### 1.1. Encryption at Rest -Organize your code related to Amazon S3 into logical directories based on functionality. +Always encrypt objects at rest. Default to AWS-managed keys (SSE-S3) or KMS (SSE-KMS) for stronger control. - -project/ -├── src/ -│ ├── s3/ -│ │ ├── utils.js # Utility functions for S3 operations -│ │ ├── uploader.js # Handles uploading files to S3 -│ │ ├── downloader.js # Handles downloading files from S3 -│ │ ├── config.js # Configuration for S3 (bucket name, region, etc.) -│ │ ├── errors.js # Custom error handling for S3 operations -│ │ └── index.js # Entry point for S3 module -│ ├── ... -│ └── tests/ -│ ├── s3/ -│ │ ├── uploader.test.js # Unit tests for uploader.js -│ │ └── ... -│ └── ... -├── ... - - -#### 1.2. File Naming Conventions - -Use descriptive and consistent file names. - -* `uploader.js`: Module for uploading files to S3. -* `downloader.js`: Module for downloading files from S3. -* `s3_service.py`: (Python Example) Defines S3 related services. -* `S3Manager.java`: (Java Example) Manages S3 client and configurations. - -#### 1.3. Module Organization - -* **Single Responsibility Principle:** Each module should have a clear and specific purpose (e.g., uploading, downloading, managing bucket lifecycle). -* **Abstraction:** Hide complex S3 operations behind simpler interfaces. -* **Configuration:** Store S3 configuration details (bucket name, region, credentials) in a separate configuration file. - -Example (JavaScript): -javascript -// s3/uploader.js -import AWS from 'aws-sdk'; -import config from './config'; - -const s3 = new AWS.S3(config.s3); - -export const uploadFile = async (file, key) => { - const params = { - Bucket: config.s3.bucketName, - Key: key, - Body: file - }; - try { - await s3.upload(params).promise(); - console.log(`File uploaded successfully: ${key}`); - } catch (error) { - console.error('Error uploading file:', error); - throw error; // Re-throw for handling in the caller. - } -}; - - -#### 1.4. Component Architecture - -For larger applications, consider a component-based architecture. This can involve creating distinct components for different S3-related tasks. For example: - -* **Upload Component:** Handles file uploads, progress tracking, and error handling. -* **Download Component:** Handles file downloads, progress tracking, and caching. -* **Management Component:** Manages bucket creation, deletion, and configuration. - -#### 1.5. Code Splitting - -If you have a large application using S3, consider using code splitting to reduce the initial load time. This involves breaking your code into smaller chunks that can be loaded on demand. This is especially relevant for front-end applications using S3 for asset storage. - -* **Dynamic Imports:** Use dynamic imports to load S3-related modules only when needed. -* **Webpack/Rollup:** Configure your bundler to create separate chunks for S3 code. - -### 2. Common Patterns and Anti-patterns - -#### 2.1. Design Patterns - -* **Strategy Pattern:** Use a strategy pattern to handle different storage classes or encryption methods. -* **Factory Pattern:** Use a factory pattern to create S3 clients with different configurations. -* **Singleton Pattern:** Use a singleton pattern if you want to use one s3 instance for all the s3 interactions. - -#### 2.2. Recommended Approaches for Common Tasks - -* **Uploading large files:** Use multipart upload for files larger than 5 MB. This allows you to upload files in parallel and resume interrupted uploads. -* **Downloading large files:** Use byte-range fetches to download files in chunks. This is useful for resuming interrupted downloads and for accessing specific portions of a file. -* **Deleting multiple objects:** Use the `deleteObjects` API to delete multiple objects in a single request. This is more efficient than deleting objects one by one. - -#### 2.3. Anti-patterns and Code Smells - -* **Hardcoding credentials:** Never hardcode AWS credentials in your code. Use IAM roles or environment variables. -* **Insufficient error handling:** Always handle errors from S3 operations gracefully. Provide informative error messages and retry failed operations. -* **Ignoring bucket access control:** Properly configure bucket policies and IAM roles to restrict access to your S3 buckets. -* **Overly permissive bucket policies:** Avoid granting overly broad permissions in your bucket policies. Follow the principle of least privilege. -* **Not using versioning:** Failing to enable versioning can lead to data loss if objects are accidentally deleted or overwritten. -* **Assuming immediate consistency:** S3 provides eventual consistency for some operations. Be aware of this and design your application accordingly. -* **Polling for object existence:** Instead of polling, use S3 events to trigger actions when objects are created or modified. -* **Inefficient data retrieval:** Avoid retrieving entire objects when only a portion of the data is needed. Use byte-range fetches or S3 Select to retrieve only the necessary data. - -#### 2.4. State Management - -* **Stateless operations:** Design your S3 operations to be stateless whenever possible. This makes your application more scalable and resilient. -* **Caching:** Use caching to reduce the number of requests to S3. Consider using a CDN (Content Delivery Network) to cache frequently accessed objects. -* **Session management:** If you need to maintain state, store session data in a separate database or cache, not in S3. - -#### 2.5. Error Handling - -* **Retry mechanism:** Implement retry logic with exponential backoff for transient errors. -* **Specific error handling:** Handle different S3 errors differently (e.g., retry 503 errors, log 403 errors). -* **Centralized error logging:** Log all S3 errors to a centralized logging system for monitoring and analysis. - -Example (Python): -python +❌ **BAD: Unencrypted objects or relying on client-side encryption without server-side enforcement.** +```python import boto3 -from botocore.exceptions import ClientError -import time s3 = boto3.client('s3') - -def upload_file(file_name, bucket, object_name=None): - """Upload a file to an S3 bucket""" - if object_name is None: - object_name = file_name - - for attempt in range(3): # Retry up to 3 times - try: - response = s3.upload_file(file_name, bucket, object_name) - return True - except ClientError as e: - if e.response['Error']['Code'] == 'NoSuchBucket': - print(f"The bucket {bucket} does not exist.") - return False - elif e.response['Error']['Code'] == 'AccessDenied': - print("Access denied. Check your credentials and permissions.") - return False - else: - print(f"An error occurred: {e}") - if attempt < 2: # Wait and retry - time.sleep(2 ** attempt) - else: - return False - except Exception as e: - print(f"An unexpected error occurred: {e}") - return False - return False # Reached max retries and failed - - -### 3. Performance Considerations - -#### 3.1. Optimization Techniques - -* **Use S3 Transfer Acceleration:** If you are uploading or downloading files from a geographically distant location, use S3 Transfer Acceleration to improve performance. S3 Transfer Acceleration utilizes Amazon CloudFront's globally distributed edge locations. -* **Use multipart upload:** For large files, use multipart upload to upload files in parallel. The documentation states the best practice is to use this for files larger than 5MB. -* **Enable gzip compression:** Compress objects before uploading them to S3 to reduce storage costs and improve download times. Set the `Content-Encoding` header to `gzip` when uploading compressed objects. -* **Use HTTP/2:** Enable HTTP/2 on your S3 bucket to improve performance. -* **Optimize object sizes:** Store related data in a single object to reduce the number of requests to S3. - -#### 3.2. Memory Management - -* **Stream data:** Avoid loading entire files into memory. Use streams to process data in chunks. -* **Release resources:** Release S3 client objects when they are no longer needed. - -#### 3.3. Bundle Size Optimization - -* **Tree shaking:** Use a bundler that supports tree shaking to remove unused code from your bundle. -* **Code splitting:** Split your code into smaller chunks that can be loaded on demand. - -#### 3.4. Lazy Loading - -* **Load images on demand:** Load images from S3 only when they are visible on the screen. -* **Lazy load data:** Load data from S3 only when it is needed. - -### 4. Security Best Practices - -#### 4.1. Common Vulnerabilities - -* **Publicly accessible buckets:** Ensure that your S3 buckets are not publicly accessible. -* **Insufficient access control:** Properly configure bucket policies and IAM roles to restrict access to your S3 buckets. -* **Cross-site scripting (XSS):** Sanitize user input to prevent XSS attacks if you are serving content directly from S3. -* **Data injection:** Validate all data before storing it in S3 to prevent data injection attacks. - -#### 4.2. Input Validation - -* **Validate file types:** Validate the file types of uploaded objects to prevent malicious files from being stored in S3. -* **Validate file sizes:** Limit the file sizes of uploaded objects to prevent denial-of-service attacks. -* **Sanitize file names:** Sanitize file names to prevent directory traversal attacks. - -#### 4.3. Authentication and Authorization - -* **Use IAM roles:** Use IAM roles to grant permissions to applications running on EC2 instances or other AWS services. -* **Use temporary credentials:** Use temporary credentials for applications that need to access S3 from outside of AWS. You can use AWS STS (Security Token Service) to generate temporary credentials. -* **Principle of least privilege:** Grant only the minimum permissions required for each user or application. - -#### 4.4. Data Protection - -* **Encrypt data at rest:** Use server-side encryption (SSE) or client-side encryption to encrypt data at rest in S3. -* **Encrypt data in transit:** Use HTTPS to encrypt data in transit between your application and S3. -* **Enable versioning:** Enable versioning to protect against accidental data loss. -* **Enable MFA Delete:** Require multi-factor authentication to delete objects from S3. -* **Object locking:** Use S3 Object Lock to prevent objects from being deleted or overwritten for a specified period of time. - -#### 4.5. Secure API Communication - -* **Use HTTPS:** Always use HTTPS to communicate with the S3 API. -* **Validate certificates:** Validate the SSL/TLS certificates of the S3 endpoints. -* **Restrict access:** Restrict access to the S3 API using IAM policies and bucket policies. - -### 5. Testing Approaches - -#### 5.1. Unit Testing - -* **Mock S3 client:** Mock the S3 client to isolate your unit tests. -* **Test individual functions:** Test individual functions that interact with S3. -* **Verify error handling:** Verify that your code handles S3 errors correctly. - -Example (JavaScript with Jest): -javascript -// s3/uploader.test.js -import { uploadFile } from './uploader'; -import AWS from 'aws-sdk'; - -jest.mock('aws-sdk', () => { - const mS3 = { - upload: jest.fn().mockReturnThis(), - promise: jest.fn(), - }; - return { - S3: jest.fn(() => mS3), - }; -}); - -describe('uploadFile', () => { - it('should upload file successfully', async () => { - const mockS3 = new AWS.S3(); - mockS3.promise.mockResolvedValue({}); - const file = 'test file content'; - const key = 'test.txt'; - - await uploadFile(file, key); - - expect(AWS.S3).toHaveBeenCalledTimes(1); - expect(mockS3.upload).toHaveBeenCalledWith({ - Bucket: 'your-bucket-name', - Key: key, - Body: file - }); - }); - - it('should handle upload error', async () => { - const mockS3 = new AWS.S3(); - mockS3.promise.mockRejectedValue(new Error('Upload failed')); - const file = 'test file content'; - const key = 'test.txt'; - - await expect(uploadFile(file, key)).rejects.toThrow('Upload failed'); - }); -}); - - -#### 5.2. Integration Testing - -* **Test with real S3 buckets:** Create a dedicated S3 bucket for integration tests. -* **Test end-to-end flows:** Test complete workflows that involve S3 operations. -* **Verify data integrity:** Verify that data is correctly stored and retrieved from S3. - -#### 5.3. End-to-End Testing - -* **Simulate user scenarios:** Simulate real user scenarios to test your application's S3 integration. -* **Monitor performance:** Monitor the performance of your S3 integration under load. - -#### 5.4. Test Organization - -* **Separate test directories:** Create separate test directories for unit tests, integration tests, and end-to-end tests. -* **Descriptive test names:** Use descriptive test names that clearly indicate what is being tested. - -#### 5.5. Mocking and Stubbing - -* **Mock S3 client:** Use a mocking library (e.g., Jest, Mockito) to mock the S3 client. -* **Stub S3 responses:** Stub S3 API responses to simulate different scenarios. -* **Use dependency injection:** Use dependency injection to inject mocked S3 clients into your components. - -### 6. Common Pitfalls and Gotchas - -#### 6.1. Frequent Mistakes - -* **Forgetting to handle errors:** Failing to handle S3 errors can lead to unexpected behavior and data loss. -* **Using incorrect region:** Using the wrong region can result in connection errors and data transfer costs. -* **Exposing sensitive data:** Storing sensitive data in S3 without proper encryption can lead to security breaches. -* **Not cleaning up temporary files:** Failing to delete temporary files after uploading them to S3 can lead to storage waste. -* **Overusing public read access:** Granting public read access to S3 buckets can expose sensitive data to unauthorized users. - -#### 6.2. Edge Cases - -* **Eventual consistency:** S3 provides eventual consistency for some operations. Be aware of this and design your application accordingly. -* **Object size limits:** Be aware of the object size limits for S3. -* **Request rate limits:** Be aware of the request rate limits for S3. -* **Special characters in object keys:** Handle special characters in object keys correctly. - -#### 6.3. Version-Specific Issues - -* **SDK compatibility:** Ensure that your AWS SDK is compatible with the S3 API version. -* **API changes:** Be aware of any API changes that may affect your application. - -#### 6.4. Compatibility Concerns - -* **Browser compatibility:** Ensure that your application is compatible with different browsers if you are using S3 directly from the browser. -* **Serverless environments:** Be aware of any limitations when using S3 in serverless environments (e.g., Lambda). - -#### 6.5. Debugging Strategies - -* **Enable logging:** Enable logging to track S3 API calls and errors. -* **Use S3 monitoring tools:** Use S3 monitoring tools to monitor the performance and health of your S3 buckets. -* **Check S3 access logs:** Analyze S3 access logs to identify potential security issues. -* **Use AWS CloudTrail:** Use AWS CloudTrail to track API calls to S3. -* **Use AWS X-Ray:** Use AWS X-Ray to trace requests through your application and identify performance bottlenecks. - -### 7. Tooling and Environment - -#### 7.1. Recommended Development Tools - -* **AWS CLI:** The AWS Command Line Interface (CLI) is a powerful tool for managing S3 resources. -* **AWS SDK:** The AWS SDK provides libraries for interacting with S3 from various programming languages. -* **S3 Browser:** S3 Browser is a Windows client for managing S3 buckets and objects. -* **Cyberduck:** Cyberduck is a cross-platform client for managing S3 buckets and objects. -* **Cloudberry Explorer:** Cloudberry Explorer is a Windows client for managing S3 buckets and objects. - -#### 7.2. Build Configuration - -* **Use environment variables:** Store S3 configuration details (bucket name, region, credentials) in environment variables. -* **Use a build tool:** Use a build tool (e.g., Maven, Gradle, Webpack) to manage your project dependencies and build your application. - -#### 7.3. Linting and Formatting - -* **Use a linter:** Use a linter (e.g., ESLint, PyLint) to enforce code style and best practices. -* **Use a formatter:** Use a code formatter (e.g., Prettier, Black) to automatically format your code. - -#### 7.4. Deployment - -* **Use infrastructure as code:** Use infrastructure as code (e.g., CloudFormation, Terraform) to automate the deployment of your S3 resources. -* **Use a deployment pipeline:** Use a deployment pipeline to automate the deployment of your application. -* **Use blue/green deployments:** Use blue/green deployments to minimize downtime during deployments. - -#### 7.5. CI/CD Integration - -* **Integrate with CI/CD tools:** Integrate your S3 deployment process with CI/CD tools (e.g., Jenkins, CircleCI, Travis CI). -* **Automate testing:** Automate your unit tests, integration tests, and end-to-end tests as part of your CI/CD pipeline. -* **Automate deployments:** Automate the deployment of your application to S3 as part of your CI/CD pipeline. - -By following these best practices and coding standards, you can ensure that your Amazon S3 integrations are secure, performant, maintainable, and cost-effective. \ No newline at end of file +s3.put_object(Bucket='my-unencrypted-bucket', Key='data.txt', Body=b'sensitive data') +# Data is stored unencrypted by default if bucket policy doesn't enforce it. +``` + +✅ **GOOD: Enforce server-side encryption (SSE-S3 or SSE-KMS).** +```python +import boto3 + +s3 = boto3.client('s3') +# Option 1: SSE-S3 (AWS-managed keys) +s3.put_object( + Bucket='my-secure-bucket', + Key='data.txt', + Body=b'sensitive data', + ServerSideEncryption='AES256' # SSE-S3 +) + +# Option 2: SSE-KMS (Customer Master Key) +# Ensure 'my-kms-key-id' exists and bucket has permissions. +s3.put_object( + Bucket='my-secure-bucket', + Key='more-data.txt', + Body=b'more sensitive data', + ServerSideEncryption='aws:kms', + SSEKMSKeyId='arn:aws:kms:us-east-1:123456789012:key/my-kms-key-id' +) +``` +> **Note on SSE-C:** As of April 2026, SSE-C is disabled for new buckets by default. Only enable it via `PutBucketEncryption` API *after* bucket creation if explicitly required for legacy or specific compliance needs. Prefer SSE-S3 or SSE-KMS. + +### 1.2. Access Control: Policies over ACLs + +Manage access exclusively through IAM and Bucket Policies. Disable ACLs for simplified, auditable permissions. + +❌ **BAD: Relying on ACLs for granular object access.** +```python +# Avoid this pattern. ACLs are disabled by default for new buckets. +s3.put_object_acl( + Bucket='my-bucket', + Key='object.txt', + GrantRead='id="some-aws-account-id"' +) +``` + +✅ **GOOD: Disable ACLs and use IAM/Bucket Policies.** +```python +# Ensure S3 Object Ownership is set to "Bucket owner enforced" to disable ACLs. +# This is the default for new buckets. +# Example Bucket Policy (IaC recommended): +# This policy grants read-only access to a specific IAM role for a specific prefix. +bucket_policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::123456789012:role/MyReadOnlyRole" + }, + "Action": ["s3:GetObject"], + "Resource": ["arn:aws:s3:::my-secure-bucket/data/*"] + } + ] +} +# Apply this via IaC (e.g., Terraform, CloudFormation) or boto3.put_bucket_policy +``` + +### 1.3. Block Public Access + +Always enable S3 Block Public Access at the account or organization level. Buckets should never be public unless explicitly required for static website hosting (and even then, use CloudFront with OAC). + +✅ **GOOD: Enable S3 Block Public Access.** +```python +# This is typically configured via AWS Console, AWS CLI, or IaC at the account level. +# Example for a specific bucket (via boto3, but IaC is preferred): +s3.put_public_access_block( + Bucket='my-secure-bucket', + PublicAccessBlockConfiguration={ + 'BlockPublicAcls': True, + 'IgnorePublicAcls': True, + 'BlockPublicPolicy': True, + 'RestrictPublicBuckets': True + } +) +``` + +## 2. Code Organization & Data Governance + +Structured naming, versioning, and lifecycle rules are crucial for manageability and cost control. + +### 2.1. Bucket & Object Naming + +Adopt clear, hierarchical naming conventions, especially for data lakes. This simplifies governance and policy application. + +❌ **BAD: Generic or flat naming.** +``` +my-app-bucket/customerdata_20230101.csv +my-app-bucket/logs_server1_access.log +``` + +✅ **GOOD: Hierarchical, environment-aware naming.** +``` +# Bucket name (globally unique, often includes org/env/purpose) +# e.g., myorg-prod-datalake-raw-us-east-1 + +# Object keys (within the bucket) +# For data lakes: +# /////// +# e.g., prod/raw/ecommerce/orders/2025/01/15/order_batch_1.json +# e.g., dev/curated/analytics/user_sessions/2025/01/15/session_summary.parquet + +# For application assets: +# //// +# e.g., prod/webapp/images/user-123/profile.jpg +# e.g., dev/backend/configs/service-a/config.yaml +``` + +### 2.2. Versioning & Tagging + +Enable versioning on all critical buckets. Use object tags for cost allocation, lifecycle management, and audit trails. + +❌ **BAD: No versioning, untagged objects.** +```python +# Accidental deletion or overwrite means data loss. +s3.delete_object(Bucket='my-bucket', Key='important-report.csv') +# Oops, gone forever. +``` + +✅ **GOOD: Enable versioning and tag objects.** +```python +# Terraform example for bucket versioning: +# resource "aws_s3_bucket" "my_bucket" { +# bucket = "myorg-prod-data" +# versioning { +# enabled = true +# } +# # ... other configurations +# } + +# Python example for tagging an object: +s3.put_object( + Bucket='myorg-prod-data', + Key='reports/monthly/sales-2025-01.csv', + Body=b'sales data', + Tagging='department=finance&project=sales-reporting' +) +``` + +### 2.3. Lifecycle Management + +Automate object transitions to cheaper storage classes (e.g., Glacier, Intelligent-Tiering) or deletion based on access patterns. Use S3 Inventory to gain insights. + +✅ **GOOD: Define lifecycle rules.** +```python +# Terraform example for a lifecycle rule: +# resource "aws_s3_bucket_lifecycle_configuration" "my_bucket_lifecycle" { +# bucket = aws_s3_bucket.my_bucket.id +# +# rule { +# id = "archive_old_logs" +# status = "Enabled" +# +# filter { +# prefix = "logs/" +# } +# +# transition { +# days = 30 +# storage_class = "STANDARD_IA" # Infrequent Access +# } +# transition { +# days = 90 +# storage_class = "GLACIER_FLEXIBLE_RETRIEVAL" +# } +# expiration { +# days = 365 +# } +# } +# # ... other rules +# } +``` + +## 3. Performance Optimization + +Design your S3 interactions for maximum throughput and minimal latency. + +### 3.1. Multipart Uploads + +For files larger than 100MB, always use multipart uploads. This improves upload speed, resilience, and allows for parallelization. + +❌ **BAD: Uploading large files in a single PUT operation.** +```python +# This can be slow and prone to failure for large files. +s3.put_object(Bucket='my-bucket', Key='large-video.mp4', Body=open('large-video.mp4', 'rb')) +``` + +✅ **GOOD: Use `transfer_manager` or `upload_fileobj` for multipart uploads.** +```python +import boto3 +from boto3.s3.transfer import TransferConfig + +s3 = boto3.client('s3') +config = TransferConfig(multipart_threshold=1024 * 25, max_concurrency=10, multipart_chunksize=1024 * 25) # 25MB parts + +with open('large-video.mp4', 'rb') as data: + s3.upload_fileobj(data, 'my-bucket', 'large-video.mp4', Config=config) +``` + +### 3.2. Request Rate & Prefixes + +Distribute high-throughput workloads across multiple S3 prefixes. S3 scales performance based on prefixes. Aim for at least 3-4 x 10^4 requests per second per prefix. + +❌ **BAD: Concentrating all high-volume reads/writes on a single prefix.** +``` +my-bucket/logs/all_access_logs_YYYY-MM-DD.log # Single hot prefix +``` + +✅ **GOOD: Spread workloads across multiple prefixes.** +``` +my-bucket/logs/webserver1/access_logs_YYYY-MM-DD.log +my-bucket/logs/webserver2/access_logs_YYYY-MM-DD.log +my-bucket/logs/appserver1/access_logs_YYYY-MM-DD.log +# Or use hash-based prefixes for even distribution: +# my-bucket/data/hash_prefix_A/object_id.json +# my-bucket/data/hash_prefix_B/object_id.json +``` + +## 4. Infrastructure as Code (IaC) with Terraform + +When using S3 as a Terraform backend, follow these critical best practices. + +❌ **BAD: Using local state or deprecated DynamoDB locking.** +```terraform +# backend "s3" { +# bucket = "myorg-tf-states" +# key = "myapp/prod.tfstate" +# region = "us-east-1" +# # Missing versioning, encryption, and using deprecated DynamoDB for locking +# dynamodb_table = "terraform-locks" # DEPRECATED! +# } +``` + +✅ **GOOD: Enable versioning, encryption, and S3 native locking.** +```terraform +terraform { + backend "s3" { + bucket = "myorg-tf-states" + key = "myapp/prod.tfstate" + region = "us-east-1" + encrypt = true # Always encrypt state file + versioning_enabled = true # Critical for state recovery + use_lockfile = true # RECOMMENDED: S3 native locking (Terraform 1.10+) + } +} +``` + +## 5. Testing Approaches + +Thoroughly test your S3 interactions, especially security and data integrity. + +### 5.1. Local Integration Testing + +Use tools like LocalStack to simulate S3 locally, allowing for rapid integration testing without incurring AWS costs or affecting production resources. + +✅ **GOOD: Use LocalStack for local S3 emulation.** +```python +# Example with boto3 and LocalStack (ensure LocalStack is running) +s3_local = boto3.client( + 's3', + endpoint_url='http://localhost:4566', + aws_access_key_id='test', + aws_secret_access_key='test', + region_name='us-east-1' +) +s3_local.create_bucket(Bucket='test-bucket') +s3_local.put_object(Bucket='test-bucket', Key='test-object.txt', Body=b'hello') +``` + +### 5.2. Policy Validation + +Programmatically validate IAM and bucket policies to ensure least privilege and prevent unintended access. + +✅ **GOOD: Use AWS IAM Policy Simulator or `boto3` for validation.** +```python +# Example: Check if an IAM role can perform a specific S3 action +iam_client = boto3.client('iam') +response = iam_client.simulate_principal_policy( + PolicySourceArn='arn:aws:iam::123456789012:role/MyReadOnlyRole', + ActionNames=['s3:GetObject'], + ResourceArns=['arn:aws:s3:::my-secure-bucket/data/report.csv'] +) +# Assert that 'Effect' is 'Allow' for the action. +``` \ No newline at end of file diff --git a/rules-mdc/android-sdk.mdc b/rules-mdc/android-sdk.mdc index ba86080..3d5041f 100644 --- a/rules-mdc/android-sdk.mdc +++ b/rules-mdc/android-sdk.mdc @@ -1,311 +1,540 @@ --- -description: This rule file provides comprehensive best practices for Android SDK development, encompassing code organization, performance, security, testing, and common pitfalls. It aims to guide developers in creating robust, maintainable, and efficient Android applications and libraries. -globs: *.java,*.kt,*.xml,*.gradle,*.properties +description: This guide provides definitive best practices for Android SDK development in Java, focusing on modern architecture, Jetpack libraries, performance, security, and testing. +globs: **/*.java --- -- MUST be under source control management (SCM). RECOMMENDED source control management is git -- If you intend your source repo to be public ensure you have received the necessary management and legal approval -- MUST use a .gitignore configuration tailored for Android projects (e.g., ignoring `local.properties`, `build/`, `.gradle/`) -- Source code repositories SHOULD follow the naming convention `[platform]-[library name]`, e.g., `android-analytics`, `java-datastore` -- MUST NOT restrict read access to source code repositories unnecessarily -- RECOMMEND to not have source file header comment blocks as these easily get out of date - -## Code Organization and Structure - -- SHOULD follow the standard project layout for Android projects. Key directories: - - `src/main/java`: Java/Kotlin source code - - `src/main/res`: Resources (layouts, drawables, strings, etc.) - - `src/test/java`: Unit tests - - `src/androidTest/java`: Instrumentation tests -- MUST prefix all exported resources (layout files, XML files, drawable IDs, color IDs, dimension IDs, string IDs, etc.) with a unique prefix for the library using `resourcePrefix` in the Gradle build file. Example: `sug` for a Suggestion Module. This avoids naming conflicts when the library is used in other projects. -- Use package names that are descriptive and follow the reverse domain name convention (e.g., `com.example.myapp.feature`). -- Organize code into logical modules or features. Each module should have a clear responsibility and be loosely coupled with other modules. -- Use Kotlin for new projects. If working with Java, target Java 8 or higher to utilize modern language features. -- Consider using a multi-module project structure for larger projects to improve build times and code organization. Modules can represent different features, libraries, or build variants. -- Employ a layered architecture (e.g., presentation, domain, data) to separate concerns and improve testability. - -### Directory Structure Best Practices: - - -root/ -├── app/ -│ ├── build.gradle -│ └── src/ -│ ├── androidTest/ -│ │ └── java/ -│ ├── main/ -│ │ ├── AndroidManifest.xml -│ │ ├── java/ -│ │ │ └── com/example/app/ -│ │ │ ├── MainActivity.kt -│ │ │ ├── model/ -│ │ │ ├── view/ -│ │ │ └── viewmodel/ -│ │ └── res/ -│ │ ├── layout/ -│ │ ├── drawable/ -│ │ ├── values/ -│ │ └── mipmap-xxhdpi/ -│ └── test/ -│ └── java/ -├── library_module/ -│ ├── build.gradle -│ └── src/ -│ ├── main/ -│ │ ├── java/ -│ │ └── res/ -│ └── test/ -├── build.gradle -├── settings.gradle - - -### File Naming Conventions: - -- **Kotlin/Java:** `PascalCase` for class names (e.g., `MainActivity`), `camelCase` for variables and method names (e.g., `userName`, `calculateTotal`). -- **Layout XML:** `snake_case` (e.g., `activity_main.xml`). Use descriptive names reflecting the layout's purpose. -- **Drawable XML:** `snake_case` (e.g., `ic_launcher.xml`). Prefix icons with `ic_`, backgrounds with `bg_`, and other drawables accordingly. -- **Values XML:** `snake_case` (e.g., `strings.xml`, `colors.xml`, `dimens.xml`). -- **Gradle:** `build.gradle` (module-level), `settings.gradle` (project-level). - -### Component Architecture Recommendations: - -- MVVM (Model-View-ViewModel) is the recommended architecture pattern. Use Android Architecture Components (LiveData, ViewModel, Room) to implement it effectively. -- For complex UI logic, consider using a ViewBindingDelegate to simplify view access and reduce boilerplate. -- Use dependency injection (Hilt or Dagger) to manage dependencies and improve testability. - -## Common Patterns and Anti-patterns - -- Use `LiveData` and `Flow` for reactive data streams. -- Utilize coroutines for asynchronous operations to simplify threading and avoid callback hell. -- Avoid performing long-running operations on the main thread (UI thread). Use `Dispatchers.IO` or `Dispatchers.Default` with coroutines or `AsyncTask` for background tasks. -- Don't use `AsyncTask` if possible, prefer coroutines. -- Prefer `ConstraintLayout` over other layout types for complex UIs as it is more flexible and performant. -- Use `RecyclerView` for displaying large lists of data efficiently. Implement view holder pattern correctly for optimal performance. -- Apply data binding to reduce boilerplate code in UI updates. -- Use sealed classes for representing state to ensure exhaustive handling of all possible states. -- Implement proper error handling with try-catch blocks and report errors gracefully to the user. -- Log errors and exceptions using a logging framework (Timber) for debugging and analysis. - -### Anti-patterns and Code Smells to Avoid: - -- **God Classes:** Classes that are too large and have too many responsibilities. Break them down into smaller, more focused classes. -- **Spaghetti Code:** Code that is difficult to read and understand due to complex control flow. Refactor it to improve readability and maintainability. -- **Copy-Paste Programming:** Duplicating code across multiple locations. Extract the common code into reusable functions or classes. -- **Hardcoding Values:** Avoid hardcoding values directly in the code. Use resources (strings, colors, dimensions) for better maintainability and localization. -- **Leaking Context:** Holding onto `Activity` or `Context` instances for longer than necessary, leading to memory leaks. - -### State Management Best Practices: - -- Use `ViewModel` to store UI-related data that survives configuration changes. -- Utilize `SavedStateHandle` in `ViewModel` to persist data across process death. -- Consider using a state management library (e.g., Redux, MVI) for complex applications with complex state. -- Implement appropriate caching strategies to reduce network requests and improve performance. - -### Error Handling Patterns: - -- Use try-catch blocks to handle potential exceptions and prevent app crashes. -- Report errors gracefully to the user with informative error messages. -- Log errors and exceptions using a logging framework (Timber) for debugging and analysis. -- Implement retry mechanisms for transient errors (e.g., network connection issues). - -## Performance Considerations - -- Optimize image loading using libraries like Glide or Coil. Resize images to the required dimensions before loading them into `ImageViews`. -- Use efficient data structures (e.g., `SparseArray` instead of `HashMap` for integer keys). -- Avoid creating unnecessary objects, especially in loops or frequently called methods. -- Use `StringBuilder` instead of string concatenation for building strings efficiently. -- Minimize network requests and optimize data transfer using compression and pagination. -- Analyze app performance using profiling tools (Android Profiler) to identify bottlenecks. -- Utilize the LeakCanary library to detect memory leaks during development. -- Use ProGuard or R8 to shrink, obfuscate, and optimize the code for release builds. - -### Memory Management Considerations: - -- Avoid creating memory leaks by properly managing object lifecycles and releasing resources when they are no longer needed. -- Use `WeakReference` to hold references to objects that may be garbage collected to prevent memory leaks. -- Monitor memory usage using the Android Profiler and identify potential memory leaks. - -### Rendering Optimization: - -- Minimize overdraw by reducing the number of layers that are drawn on top of each other. -- Use hardware acceleration to improve rendering performance. -- Optimize custom views by implementing `onDraw()` method efficiently and avoiding unnecessary allocations. - -### Bundle Size Optimization: - -- Remove unused resources using `shrinkResources` in the Gradle build file. -- Use vector drawables instead of raster images for icons and other simple graphics. -- Enable code shrinking and obfuscation using ProGuard or R8. -- Compress images using tools like TinyPNG or ImageOptim. -- Use app bundles to deliver optimized APKs for different device configurations. -- Utilize dynamic feature modules to defer the download of non-essential features. - -### Lazy Loading Strategies: - -- Implement lazy loading for images and other resources that are not immediately visible on the screen. -- Use pagination or infinite scrolling to load data in chunks as the user scrolls down the list. - -## Security Best Practices - -- MUST use Kotlin or Java. Kotlin is RECOMMENDED -- SHOULD use static code analysis, such as detekt or SwiftLint to minimise errors and minimise debates and formatting fix-up commits in PRs. It is RECOMMENDED to integrate these tools with the CI workflow. SHOULD use quality tools available in common config: Android and iOS -- Android: MUST use the Android Support Annotations for public APIs. Non-Android Java code MUST use the Jetbrains Annotations for public APIs -- Secure API communication and proper permission handling are vital to protect user data. -- MUST use a `consumerProguardFiles` file if obfuscation breaks the libraries function. -- SHOULD NOT have unnecessary exported dependencies, in particular SHOULD NOT leak networking library to consumers. SHOULD NOT leak serialization library to consumers. An exception to this rule are optional adapters for popular libraries. - -### Common Vulnerabilities and Prevention: - -- **SQL Injection:** Avoid using raw SQL queries. Use parameterized queries or an ORM like Room to prevent SQL injection attacks. -- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. -- **Man-in-the-Middle (MITM) Attacks:** Use HTTPS for all network communication to encrypt data in transit and prevent MITM attacks. -- **Insecure Data Storage:** Encrypt sensitive data before storing it on the device. -- **Improper Platform Usage:** Ensure that permissions are properly requested and handled. Review and minimize the permissions your app requests. - -### Input Validation: - -- Validate all user input on both the client and server sides to prevent malicious data from being processed. -- Use regular expressions or validation libraries to enforce input constraints. - -### Authentication and Authorization: - -- Use secure authentication protocols (e.g., OAuth 2.0, OpenID Connect) for user authentication. -- Implement proper authorization mechanisms to control access to resources based on user roles. -- Store user credentials securely using hashing and salting. - -### Data Protection: - -- Encrypt sensitive data at rest using AES or other strong encryption algorithms. -- Securely transmit data over the network using HTTPS. -- Implement data masking or anonymization techniques to protect user privacy. - -### Secure API Communication: - -- Use HTTPS for all API communication. -- Verify the server's SSL certificate to prevent MITM attacks. -- Implement API rate limiting to prevent denial-of-service attacks. - -## Testing Approaches - -- All library (sub-)projects MUST generate coverage test reports (e.g. jacoco, Xcode/slather). -- Unit test coverage MUST be at least 80% and SHOULD be above 85% -- Unit tests MUST NOT rely on reflection to expose otherwise private/internal classes or members. -- Tests SHOULD use JUnit, and MAY use helper libraries such as Mockito or Robolectric - -### Unit Testing Strategies: - -- Write unit tests for all critical components, including `ViewModels`, repositories, and use cases. -- Use mocking frameworks (Mockito) to isolate units under test and mock dependencies. -- Follow the AAA (Arrange, Act, Assert) pattern for writing clear and concise unit tests. - -### Integration Testing Approaches: - -- Write integration tests to verify the interaction between different components, such as `ViewModels` and repositories. -- Use dependency injection to provide mock dependencies for integration tests. - -### End-to-End Testing: - -- Use UI testing frameworks (Espresso, UI Automator) to write end-to-end tests that simulate user interactions. - -### Test Organization: - -- Organize tests into separate directories based on the type of tests (unit, integration, UI). -- Use descriptive names for test classes and methods to clearly indicate what is being tested. - -### Mocking and Stubbing: - -- Use mocking frameworks (Mockito) to create mock objects for dependencies. -- Use stubbing to define the behavior of mock objects for specific test cases. - -## Common Pitfalls and Gotchas - -- Frequent mistakes developers make when using android-sdk -- Edge cases to be aware of when using android-sdk -- Version-specific issues with android-sdk -- Compatibility concerns between android-sdk and other technologies -- Debugging strategies for android-sdk applications - -### Frequent Mistakes: - -- Not handling configuration changes properly, leading to data loss or unexpected behavior. -- Performing long-running operations on the main thread, causing the UI to freeze. -- Leaking `Context` objects, leading to memory leaks. -- Not properly validating user input, leading to security vulnerabilities. -- Not handling exceptions properly, leading to app crashes. -- Overusing `AsyncTask` and not managing thread pools correctly. - -### Edge Cases: - -- Handling network connectivity issues gracefully. -- Managing different screen sizes and densities. -- Dealing with low-memory conditions. -- Handling background tasks properly to avoid ANRs (Application Not Responding). -- Handling different Android versions and API levels. - -### Version-Specific Issues: - -- Be aware of API level differences and use `@TargetApi` and `@RequiresApi` annotations to handle them correctly. -- Test your app on different Android versions to ensure compatibility. - -### Compatibility Concerns: - -- Ensure compatibility with different device manufacturers and hardware configurations. -- Test your app on different screen sizes and densities. - -### Debugging Strategies: - -- Use the Android Debug Bridge (ADB) to connect to devices and emulators for debugging. -- Use the Android Profiler to analyze app performance and identify bottlenecks. -- Use logging statements to track the flow of execution and identify errors. -- Use the debugger to step through the code and inspect variables. - -## Tooling and Environment - -### Recommended Tools: - -- Android Studio: The official IDE for Android development. -- Gradle: The build system for Android projects. -- ADB (Android Debug Bridge): A command-line tool for communicating with Android devices and emulators. -- Android Profiler: A tool for analyzing app performance. -- LeakCanary: A library for detecting memory leaks. -- Timber: A logging library for Android. - -### Build Configuration: - -- MUST use gradle with gradle wrapper to build Android library or Java library -- MUST have consistent minSdk and supportLib versions with other SDKs -- SHOULD use shared build configuration for consistent version with other SDKs/libraries -- MAY use manual configuration with values (same as in shared build configuration), if so SHOULD use a recent minSdk version unless there is an engineering or product decision to support older versions -- SHOULD use latest versions of Android X libraries (if required) - -- Configure build variants for different environments (debug, release, staging). -- Use ProGuard or R8 to shrink, obfuscate, and optimize the code for release builds. -- Configure signing configurations to sign the APK for distribution. - -### Linting and Formatting: - -- Enforce code style guidelines using lint and code formatters (e.g., ktlint for Kotlin). -- Configure lint to run automatically during the build process. -- Resolve lint warnings and errors to improve code quality. - -### Deployment: - -- Publish libraries to a Maven repository (Maven Central or a private repository). -- Deploy apps to the Google Play Store. -- Implement beta testing using Google Play Console. - -### CI/CD Integration: - -- Integrate the build process with a CI/CD system (e.g., Jenkins, CircleCI, GitHub Actions). -- Automate testing, linting, and code formatting as part of the CI/CD pipeline. -- Automate deployment to the Google Play Store. - -## Additional Considerations -- Limit impact on consumers. SHOULD limit dependencies as much as possible primarily due to risk of version clashes -- RECOMMENDED not to have any exported dependency on other SDK modules e.g. if your module needs authentication, do not depend on Authentication SDK. Instead, require your library consumer to pass an access token string to your API instead. -- Expose minimal Surface area. Keep everything private unless it needs to be public. Every public class, method, property & resource MUST have a strong reason for being public. MAY keep internal source code in a /Private folder to allow tools to more easily ignore those files -- MUST hide classes from generated API documentation that are required to be public solely for technical reasons and are not intended for SDK consumers -- SHOULD declare classes as final to avoid unexpected high-jacking of SDK behavior by subclasses -- For better testability of your library it is RECOMMENDED to use dependency injection -- MUST follow Semantic Versioning -- MUST tag source control management revision/commit that is published -- RECOMMENDED For Android: Use gradle-versions-plugin for automated versioning by git tag \ No newline at end of file +# android-sdk Best Practices (Java) + +This guide outlines the essential practices for building robust, performant, and maintainable Android applications using Java, adhering to modern standards and leveraging the AndroidX ecosystem. + +## 1. Code Organization and Structure + +**1.1 Modular Architecture (MVVM)** +Adopt a clean, modular architecture, with MVVM (Model-View-ViewModel) as the standard. This promotes separation of concerns, testability, and scalability. + +❌ **BAD: Tight Coupling** +```java +// Activity directly fetching data and updating UI +public class UserProfileActivity extends AppCompatActivity { + private TextView userName; + // ... other UI elements + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_user_profile); + userName = findViewById(R.id.user_name); + // Direct network call on UI thread (or poorly managed background thread) + new Thread(() -> { + String name = fetchUserNameFromNetwork(); // Blocking call + runOnUiThread(() -> userName.setText(name)); + }).start(); + } + // ... +} +``` + +✅ **GOOD: MVVM with Repository Pattern** +```java +// ui/UserProfileActivity.java +public class UserProfileActivity extends AppCompatActivity { + private UserProfileViewModel viewModel; + private TextView userName; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_user_profile); + userName = findViewById(R.id.user_name); + + viewModel = new ViewModelProvider(this).get(UserProfileViewModel.class); + viewModel.getUserName().observe(this, name -> { + userName.setText(name); + }); + } +} + +// ui/UserProfileViewModel.java +public class UserProfileViewModel extends AndroidViewModel { + private UserRepository userRepository; + private MutableLiveData userName = new MutableLiveData<>(); + + public UserProfileViewModel(@NonNull Application application) { + super(application); + this.userRepository = new UserRepository(application); // Injected via Hilt in real app + loadUserName(); + } + + public LiveData getUserName() { + return userName; + } + + private void loadUserName() { + // Use ExecutorService or RxJava for background work + Executors.newSingleThreadExecutor().execute(() -> { + String name = userRepository.fetchUserName(); + userName.postValue(name); // Post value to main thread + }); + } +} + +// data/UserRepository.java +public class UserRepository { + // In a real app, this would interact with Room, Retrofit, etc. + public String fetchUserName() { + // Simulate network call + try { Thread.sleep(2000); } catch (InterruptedException e) {} + return "John Doe"; + } +} +``` + +**1.2 Package Structure** +Organize packages by feature or layer, not by Android component type. + +❌ **BAD: Component-based** +``` +com.example.app +├── activities +│ └── UserProfileActivity.java +├── fragments +│ └── SettingsFragment.java +├── adapters +│ └── UserListAdapter.java +└── utils + └── NetworkUtils.java +``` + +✅ **GOOD: Feature-based (or Layer-based for larger apps)** +``` +com.example.app +├── userprofile +│ ├── UserProfileActivity.java +│ ├── UserProfileViewModel.java +│ └── UserProfileFragment.java +├── settings +│ ├── SettingsActivity.java +│ └── SettingsViewModel.java +├── data +│ ├── UserRepository.java +│ ├── UserApiService.java +│ └── UserDatabase.java +└── common + ├── adapters + │ └── UserListAdapter.java + └── utils + └── NetworkUtils.java +``` + +## 2. Common Patterns and Anti-patterns + +**2.1 Jetpack Libraries** +Always prefer AndroidX Jetpack libraries for modern, backward-compatible, and lifecycle-aware components. + +* **Room for Persistence:** Use Room for all local database storage. + ❌ **BAD: Raw SQLiteOpenHelper** + ```java + // Manual SQLite table creation and query management + public class MyDbHelper extends SQLiteOpenHelper { /* ... */ } + ``` + ✅ **GOOD: Room Database** + ```java + @Database(entities = {User.class}, version = 1) + public abstract class AppDatabase extends RoomDatabase { + public abstract UserDao userDao(); + } + + @Entity + public class User { + @PrimaryKey public int id; + public String name; + } + + @Dao + public interface UserDao { + @Query("SELECT * FROM user WHERE id = :userId") + LiveData getUserById(int userId); + + @Insert + void insert(User user); + } + ``` + +* **View Binding (or Data Binding):** Eliminate `findViewById` boilerplate. + ❌ **BAD: Manual View Lookup** + ```java + public class MyActivity extends AppCompatActivity { + private Button myButton; + @Override protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_my); + myButton = findViewById(R.id.my_button); + myButton.setOnClickListener(v -> /* ... */); + } + } + ``` + ✅ **GOOD: View Binding** + ```java + public class MyActivity extends AppCompatActivity { + private ActivityMyBinding binding; // Generated binding class + @Override protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = ActivityMyBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + binding.myButton.setOnClickListener(v -> /* ... */); + } + } + ``` + +* **Navigation Component:** Manage in-app navigation consistently. + ❌ **BAD: Manual Fragment Transactions** + ```java + getSupportFragmentManager().beginTransaction() + .replace(R.id.fragment_container, new DetailFragment()) + .addToBackStack(null) + .commit(); + ``` + ✅ **GOOD: Navigation Graph** + ```java + // In Activity/Fragment + NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); + navController.navigate(R.id.action_homeFragment_to_detailFragment); + // Define navigation in res/navigation/nav_graph.xml + ``` + +**2.2 Dependency Injection (Hilt)** +Use Hilt (built on Dagger) for robust dependency injection, simplifying object creation and improving testability. + +❌ **BAD: Manual Dependency Management** +```java +public class MyRepository { + private MyApiService apiService = new MyApiService(); // Hardcoded dependency + // ... +} +``` +✅ **GOOD: Hilt** +```java +@Module +@InstallIn(SingletonComponent.class) +public abstract class AppModule { + @Provides + @Singleton + public static MyApiService provideMyApiService() { + return new MyApiService(); // Or provide Retrofit instance + } +} + +@Singleton +public class MyRepository { + private final MyApiService apiService; + + @Inject // Hilt injects MyApiService + public MyRepository(MyApiService apiService) { + this.apiService = apiService; + } + // ... +} + +@HiltAndroidApp +public class MyApplication extends Application {} +``` + +## 3. Performance Considerations + +**3.1 Layout Optimization** +Flatten view hierarchies using `ConstraintLayout` and `ViewStub` to reduce layout inflation time and memory usage. + +❌ **BAD: Deeply Nested Layouts** +```xml + + + + + + + + + + + +
+ +
+``` \ No newline at end of file diff --git a/rules-mdc/ansible.mdc b/rules-mdc/ansible.mdc index 3325f4e..6e96e8f 100644 --- a/rules-mdc/ansible.mdc +++ b/rules-mdc/ansible.mdc @@ -1,553 +1,293 @@ --- -description: This rule file provides comprehensive best practices and coding standards for Ansible projects, covering code organization, common patterns, performance, security, testing, pitfalls, and tooling. It aims to improve maintainability, reusability, and efficiency in Ansible automation. -globs: *.yml,*.yaml,*.j2 +description: This guide defines definitive best practices for writing maintainable, performant, and robust Ansible code, focusing on modern YAML hygiene, role design, and CI/CD integration. +globs: **/* --- -- Adopt and adhere to the following Ansible best practices to ensure maintainable, reusable, and efficient automation code. This guide provides standards for code organization, common patterns, performance optimization, security, testing, tooling, and common pitfalls to avoid. +# ansible Best Practices + +Ansible excels when treated as infrastructure-as-code. These guidelines ensure your playbooks, roles, and modules are consistent, idempotent, and production-ready. ## 1. Code Organization and Structure -- Structure your Ansible projects in a clear and consistent manner to enhance readability and maintainability. - -### 1.1 Directory Structure Best Practices - -- **Root Directory:** - - `ansible.cfg`: Ansible configuration file. This should live in the root directory of your project. - - `inventory/`: Contains your inventory files (hosts, groups, and variables). - - `hosts`: Main inventory file. - - `group_vars/`: Directory for group-specific variables. - - `all/`: Contains variables that apply to all hosts. - - `vars.yml`: Primary file for common variables. - - `vault.yml`: Encrypted variables. - - `/`: Directory for variables specific to a group. - - `vars.yml`: Group-specific variables. - - `vault.yml`: Encrypted group variables. - - `host_vars/`: Directory for host-specific variables. - - `/`: Directory for a specific host. - - `vars.yml`: Host-specific variables. - - `vault.yml`: Encrypted host variables. - - `playbooks/`: Directory for your Ansible playbooks. - - `site.yml`: Main playbook, orchestrating other playbooks. - - `.yml`: Playbooks tailored to different environments (e.g., staging.yml, production.yml). - - `.yml`: Playbooks for specific components (e.g., webservers.yml, databases.yml). - - `roles/`: Directory for reusable Ansible roles. - - `/`: - - `tasks/`: Contains tasks for the role. - - `main.yml`: Entry point for the role's tasks. - - `handlers/`: Contains handlers for the role. - - `main.yml`: Entry point for the role's handlers. - - `defaults/`: Contains default variable values for the role. - - `main.yml`: Default variable values. - - `vars/`: Contains role-specific variables. - - `main.yml`: Role-specific variables. - - `meta/`: Contains metadata about the role. - - `main.yml`: Role metadata (e.g., dependencies, author). - - `templates/`: Contains Jinja2 templates for the role. - - `files/`: Contains static files used by the role. - - `library/`: (Optional) Custom Ansible modules. - - `filter_plugins/`: (Optional) Custom Jinja2 filter plugins. - - `lookup_plugins/`: (Optional) Custom lookup plugins. - - `plugins/`: All of the above (library, filter, lookup, etc) should be placed in respective subfolders in this directory - - `requirements.yml`: Lists roles to be downloaded from Ansible Galaxy. - - `README.md`: Project documentation. - -### 1.2 File Naming Conventions - -- **Playbooks:** - - Use lowercase with hyphens for readability (e.g., `webservers.yml`, `database-setup.yml`). - - Name your main playbook `site.yml` for consistency. -- **Roles:** - - Use lowercase with underscores (e.g., `common_setup`, `nginx_configuration`). - - Role names should be descriptive and concise. -- **Variables Files:** - - Use `vars.yml` for general variables and `defaults.yml` for role defaults. - - Use `vault.yml` for encrypted variables. - - Group-specific variables: `.yml`. - - Host-specific variables: `.yml`. -- **Tasks and Handlers:** - - `main.yml` as the entry point for tasks and handlers within roles. -- **Templates:** - - Give descriptive names to templates, using the `.j2` extension (e.g., `nginx.conf.j2`, `application.properties.j2`). -- **Inventory:** - - Name your inventory file `hosts` or follow a consistent naming convention, such as `_hosts` (e.g., `staging_hosts`, `production_hosts`). - -### 1.3 Module Organization - -- Keep custom modules in the `library/` directory at the project root. -- Organize modules into subdirectories based on functionality (e.g., `library/custom_modules/database`, `library/custom_modules/monitoring`). -- Document each custom module with clear usage examples and return values. -- Utilize `module_utils` to create shared code used by multiple modules. -- Follow a consistent naming convention for custom modules (e.g., `my_custom_module.py`). -- All modules should contain argument spec and proper return values (changed, failed, original_message, message, etc). - -### 1.4 Component Architecture Recommendations - -- **Roles as Building Blocks:** - - Divide your infrastructure into logical components (e.g., web servers, databases, load balancers) and create roles for each. - - Keep roles single-purposed and focused on specific functionality to promote reusability. -- **Playbooks for Orchestration:** - - Use playbooks to orchestrate roles and define the desired state of your infrastructure. - - The main `site.yml` playbook should act as the entry point, calling other component-specific playbooks. -- **Variables for Configuration:** - - Externalize configuration data using variables in `group_vars/` and `host_vars/`. - - Use default variables within roles to provide sane defaults and allow for customization. -- **Handlers for Event-Driven Configuration:** - - Use handlers to manage service restarts and other event-driven tasks. - - Ensure handlers are idempotent and only triggered when necessary. - -### 1.5 Code Splitting Strategies - -- **Role Decomposition:** - - Break down complex roles into smaller, more manageable roles to improve reusability and maintainability. -- **Task Includes:** - - Use `include_tasks` to split long task lists into smaller, more focused files. -- **Dynamic Includes:** - - Employ `include_vars`, `include_role`, and `include_tasks` with dynamic variables to load configuration data or tasks based on conditions. -- **Blocks for Logical Grouping:** - - Use blocks to group related tasks, providing better error handling and readability. - -## 2. Common Patterns and Anti-patterns - -- Learn and apply common Ansible design patterns to solve infrastructure automation problems efficiently while avoiding pitfalls. - -### 2.1 Design Patterns - -- **Idempotency:** - - Design tasks to be idempotent, meaning they should produce the same result regardless of how many times they are executed. - - Use the `changed_when` and `failed_when` directives to customize task result conditions. -- **Variable Prioritization:** - - Understand Ansible's variable precedence and use it effectively to override default values. - - Variable precedence order (highest to lowest): extra vars (-e), command line arguments (-e), role vars, include vars, block vars, task vars, role defaults, inventory vars, registered vars, facts. -- **Handlers for Service Management:** - - Utilize handlers to restart services when configuration files change. Use `notify` directive in tasks to trigger handlers. -- **Template Management:** - - Use the `template` module to manage configuration files. Keep templates simple and focused on configuration logic. -- **Looping with `with_items`:** - - Use `with_items` or `loop` to iterate over lists of items, such as packages to install or users to create. -- **Conditions with `when`:** - - Use the `when` directive to conditionally execute tasks based on variables or facts. -- **Delegation with `delegate_to`:** - - Use the `delegate_to` directive to run tasks on a specific host, such as when managing a load balancer or database server. -- **Error Handling with `block` and `rescue`:** - - Wrap tasks in `block` directives and use `rescue` to handle errors gracefully. -- **Register variables for complex tasks:** - - Register variables to capture output from a task and use it in subsequent tasks. -- **Meta Tasks for Role Management:** - - Use meta tasks (e.g., `meta: clear_host_errors`, `meta: end_play`) to manage role execution and handle errors. -- **Facts for dynamic configuration:** - - Utilize facts to gather system information and dynamically configure tasks. -- **Loops for repetitive tasks:** - - Use loops to perform repetitive tasks, such as creating multiple users or installing multiple packages. Always name the loop so the end user can identify the tasks better. - -### 2.2 Recommended Approaches for Common Tasks - -- **Package Management:** - - Use the appropriate package manager module (e.g., `apt`, `yum`, `dnf`, `homebrew`) for the target system. - - Always specify the `state` (e.g., `present`, `latest`, `absent`) when managing packages. -- **File Management:** - - Use the `file` module to create, modify, or delete files and directories. - - Use the `copy` module to copy files from the control node to the target nodes. - - Use the `template` module to manage configuration files with Jinja2 templates. -- **Service Management:** - - Use the `service` or `systemd` module to manage services. - - Always specify the `state` (e.g., `started`, `stopped`, `restarted`) when managing services. - - Use handlers to restart services when configuration files change. -- **User Management:** - - Use the `user` module to create, modify, or delete users. - - Use the `group` module to manage groups. - - Use the `authorized_key` module to manage SSH keys. -- **Cron Job Management:** - - Use the `cron` module to create, modify, or delete cron jobs. -- **Firewall Management:** - - Use the `firewalld` or `ufw` module to manage firewalls. -- **SELinux Management:** - - Use the `selinux` module to manage SELinux policies. -- **Line-in-File management:** - - Use the `lineinfile` module to ensure a specific line exists in a file. - - Use the `blockinfile` module to ensure a block of lines exist in a file. - -### 2.3 Anti-patterns and Code Smells - -- **Shell and Command Modules:** - - Avoid using the `shell` and `command` modules unless absolutely necessary. - - Prefer Ansible's built-in modules for specific tasks, as they provide idempotency and better error handling. -- **Hardcoded Values:** - - Avoid hardcoding values in your playbooks or roles. - - Use variables in `group_vars/` and `host_vars/` to externalize configuration data. -- **Inconsistent Naming Conventions:** - - Follow a consistent naming convention for variables, tasks, roles, and files. - - This improves readability and maintainability. -- **Unnecessary Complexity:** - - Keep your playbooks and roles as simple as possible. - - Avoid over-engineering or introducing unnecessary complexity. -- **Lack of Idempotency:** - - Ensure your tasks are idempotent to avoid unintended side effects. - - Use the `changed_when` and `failed_when` directives to customize task result conditions. -- **Ignoring Errors:** - - Always handle errors gracefully by using `block` and `rescue` directives. - - Use the `fail` module to explicitly fail a playbook when a critical error occurs. -- **Storing Secrets in Plain Text:** - - Never store sensitive data in plain text. - - Use Ansible Vault to encrypt variables and files. -- **Lack of Documentation:** - - Always document your playbooks, roles, and custom modules. - - This improves collaboration and makes it easier to maintain your automation code. -- **Copying the same block of code:** - - Refactor and call the common tasks using `include_tasks` to improve readability and maintainability -- **Using loops when a module can handle multiple arguments:** - - Some modules can perform multiple tasks by passing a list of arguments (e.g. `yum` module), so avoid using loops as much as possible. -- **Creating complex templates:** - - Templates should be simple and contain logic that is easy to read and maintain. - - Avoid implementing complex functionality that increases maintenance cost and reduces code readability. -- **Writing unoptimized Jinja expressions:** - - Use Jinja filters for data manipulation, rather than implementing the logic using Ansible modules - -### 2.4 State Management - -- **Use Ansible to manage the desired state of your infrastructure.** Avoid manual changes outside of Ansible. -- **Leverage facts to gather system information and dynamically configure tasks.** -- **Use handlers to react to state changes and ensure services are restarted or reconfigured when necessary.** -- **Use variables to store configuration data and customize the desired state for different environments.** - -### 2.5 Error Handling Patterns - -- **Use `block` and `rescue` to handle errors gracefully.** -- **Use the `fail` module to explicitly fail a playbook when a critical error occurs.** -- **Register variables to capture the output of tasks and use the output in error handling logic.** -- **Use the `ignore_errors` directive to continue playbook execution even when a task fails (use with caution).** -- **Use the `meta: clear_host_errors` task to clear errors on a host and continue playbook execution.** -- **Implement rollback mechanisms to revert changes in case of failures.** - -## 3. Performance Considerations - -- Optimize your Ansible code to improve execution speed and resource utilization. - -### 3.1 Optimization Techniques - -- **Use SSH multiplexing:** - - Enable SSH multiplexing in your `ansible.cfg` file to reduce the overhead of establishing SSH connections. - - `pipelining = True` -- **Use ControlPersist:** - - Enable ControlPersist in your SSH configuration to keep SSH connections alive for longer periods of time. -- **Optimize Inventory:** - - Use a dynamic inventory to manage large numbers of hosts. - - Cache the inventory data to reduce the time it takes to load the inventory. -- **Minimize Fact Gathering:** - - Disable fact gathering for tasks that don't require them. - - Use the `gather_facts: false` directive in your playbooks or tasks. -- **Parallel Execution:** - - Increase the number of forks to execute tasks in parallel. - - Use the `-f` or `--forks` option when running Ansible playbooks. - - Be mindful of resource limitations and avoid overloading your control node or target hosts. -- **Avoid Loops When Possible:** - - Prefer modules that can handle lists of items instead of using loops. - - For example, use the `yum` or `apt` module with a list of packages to install instead of using a loop with the `package` module. -- **Optimize Jinja2 Templates:** - - Use Jinja2 filters to perform data manipulation instead of using Ansible modules. - - Cache the results of Jinja2 filters to avoid recomputing them repeatedly. -- **Use Async Tasks:** - - Use async tasks with poll to execute tasks in the background and reduce the time it takes to run your playbooks. -- **Use Connection Type `smart` or `persistent`:** - - These connection types are optimized for performance, especially for larger deployments. -- **Use Caching:** - - Utilize Ansible's fact caching to avoid gathering the same facts repeatedly. -- **Use strategy plugins:** - - Use plugins such as free, debug and host_pinned in your Ansible configuration file to maximize execution performance and concurrency. - -### 3.2 Memory Management - -- **Limit the number of forks:** - - Reduce the number of forks if your control node is running out of memory. -- **Use smaller inventories:** - - Split large inventories into smaller inventories to reduce memory usage. -- **Avoid loading large files into variables:** - - Use the `slurp` module to read large files into variables only when necessary. -- **Compress large files before transferring them:** - - Use the `compress` module to compress large files before transferring them to target hosts. - -### 3.3 Rendering Optimization - -- **Cache Jinja2 templates:** - - Enable Jinja2 template caching to reduce the time it takes to render templates. -- **Use filters and tests:** - - Instead of modules, use filters and tests to avoid calling Ansible tasks. -- **Limit Variable Scope:** - - Declare variables in the narrowest scope possible to minimize memory usage and improve performance. - -## 4. Security Best Practices - -- Secure your Ansible environment and protect sensitive data. - -### 4.1 Common Vulnerabilities and Prevention - -- **Plaintext Secrets:** - - *Vulnerability:* Storing passwords, API keys, and other sensitive data in plaintext in playbooks or variable files. - - *Prevention:* Use Ansible Vault to encrypt sensitive data. - - Example: - - # Encrypt a variable file - ansible-vault encrypt group_vars/all/vault.yml - - # Use the variable in a playbook - - name: Deploy application with secret key - template: - src: app.conf.j2 - dest: /etc/app/app.conf - -- **Unprotected SSH Keys:** - - *Vulnerability:* Leaving private SSH keys unprotected on the control node or target hosts. - - *Prevention:* Restrict access to the control node and use SSH key-based authentication with proper permissions. -- **Command Injection:** - - *Vulnerability:* Using user-supplied data directly in shell commands without proper sanitization. - - *Prevention:* Avoid using the `shell` and `command` modules unless absolutely necessary. - - Use Ansible's built-in modules whenever possible. - - If you must use `shell` or `command`, sanitize user input properly. -- **Privilege Escalation:** - - *Vulnerability:* Granting unnecessary privileges to Ansible users or tasks. - - *Prevention:* Use the `become` directive only when necessary. - - Grant the minimum required privileges to Ansible users. -- **Unvalidated Input:** - - *Vulnerability:* Using unvalidated input from external sources (e.g., APIs, user input) without proper sanitization. - - *Prevention:* Validate all input from external sources before using it in your playbooks or tasks. - - Use the `assert` module to validate input. -- **Insecure Communication:** - - *Vulnerability:* Using insecure communication protocols (e.g., HTTP) to transfer sensitive data. - - *Prevention:* Use HTTPS for all communication with APIs and other external services. -- **Weak SSH Keys:** - - *Vulnerability:* Using weak or compromised SSH keys. - - *Prevention:* Generate strong SSH keys with a key length of at least 2048 bits. - - Rotate SSH keys regularly. -- **Unauthorized Access:** - - *Vulnerability:* Allowing unauthorized access to the control node or target hosts. - - *Prevention:* Use strong passwords and multi-factor authentication. - - Restrict access to the control node and target hosts to authorized users only. - -### 4.2 Input Validation - -- **Validate all input from external sources before using it in your playbooks or tasks.** -- **Use the `assert` module to validate input.** -- **Use regular expressions to validate input strings.** -- **Use the `int` and `float` filters to validate numeric input.** -- **Use the `bool` filter to validate boolean input.** -- **Use the `list` and `dict` filters to validate list and dictionary input.** - -### 4.3 Authentication and Authorization - -- **Use SSH key-based authentication instead of passwords.** -- **Restrict access to the control node and target hosts to authorized users only.** -- **Use the `become` directive to escalate privileges only when necessary.** -- **Use the `sudo` module to execute tasks with elevated privileges.** -- **Use the `acl` module to manage access control lists (ACLs) on files and directories.** -- **Integrate with external authentication providers (e.g., LDAP, Active Directory) for centralized user management.** - -### 4.4 Data Protection - -- **Use Ansible Vault to encrypt sensitive data.** -- **Use HTTPS for all communication with APIs and other external services.** -- **Use the `slurp` module to read sensitive data from files into variables only when necessary.** -- **Use the `compress` module to compress sensitive data before transferring it to target hosts.** -- **Use the `hash` filter to hash sensitive data before storing it in files or databases.** -- **Implement data masking and tokenization techniques to protect sensitive data at rest and in transit.** - -### 4.5 Secure API Communication - -- **Use HTTPS for all communication with APIs.** -- **Use strong authentication mechanisms (e.g., API keys, OAuth 2.0) to protect your APIs.** -- **Validate all input from APIs before using it in your playbooks or tasks.** -- **Use the `uri` module to interact with APIs securely.** -- **Implement rate limiting and throttling to protect your APIs from abuse.** -- **Monitor your APIs for security vulnerabilities and performance issues.** - -## 5. Testing Approaches - -- Implement a comprehensive testing strategy to ensure your Ansible code is reliable and error-free. - -### 5.1 Unit Testing - -- **Unit test custom modules, filter plugins, and lookup plugins.** -- **Use a testing framework such as `pytest` to write and run unit tests.** -- **Mock external dependencies to isolate the code being tested.** -- **Write tests for all possible scenarios, including edge cases and error conditions.** -- **Use continuous integration to run unit tests automatically on every commit.** -- **Test modules for different possible input arguments and check their results.** - -### 5.2 Integration Testing - -- **Integration test your playbooks and roles to ensure they work together correctly.** -- **Use a testing framework such as `Molecule` to automate integration testing.** -- **Create a test environment that closely resembles your production environment.** -- **Test all critical functionality, including package installation, configuration management, and service management.** -- **Use continuous integration to run integration tests automatically on every commit.** -- **Use an ephemeral infrastructure using Vagrant or Docker to test the playbooks on a fresh machine.** -- **Test for idempotency by running the same playbook multiple times.** - -### 5.3 End-to-End Testing - -- **End-to-end test your entire infrastructure to ensure all components work together correctly.** -- **Use a testing framework such as `Testinfra` or `Inspec` to write and run end-to-end tests.** -- **Create a test environment that is as close as possible to your production environment.** -- **Test all critical business processes to ensure they work as expected.** -- **Use continuous integration to run end-to-end tests automatically on every commit.** - -### 5.4 Test Organization - -- **Organize your tests into a directory structure that mirrors your Ansible code.** -- **Create separate directories for unit tests, integration tests, and end-to-end tests.** -- **Use descriptive names for your test files and test functions.** -- **Document your tests with clear explanations of what they are testing.** -- **Use a consistent naming convention for your tests to improve readability and maintainability.** - -### 5.5 Mocking and Stubbing Techniques - -- **Use mocking and stubbing to isolate your code during unit testing.** -- **Mock external dependencies such as APIs, databases, and operating system commands.** -- **Use a mocking framework such as `unittest.mock` (Python) to create mocks and stubs.** -- **Write tests that verify that your code interacts with the mocked dependencies correctly.** -- **Avoid mocking Ansible modules, instead create a module that is a wrapper around it.** - -## 6. Common Pitfalls and Gotchas - -- Be aware of common mistakes and edge cases when working with Ansible. - -### 6.1 Frequent Mistakes - -- **Incorrect YAML Syntax:** - - YAML is whitespace-sensitive. Incorrect indentation or missing colons can cause syntax errors. - - Use a YAML linter to validate your syntax. -- **Variable Scope Issues:** - - Variables can be defined at different levels (e.g., playbook, role, inventory). Understanding variable precedence is crucial. - - Use the `vars_prompt` directive to prompt users for variables. -- **Incorrect Module Usage:** - - Using the wrong module for a task can lead to unexpected results or errors. - - Refer to the Ansible documentation for module usage examples and best practices. -- **Lack of Idempotency:** - - Tasks that are not idempotent can cause unintended side effects when run repeatedly. - - Use the `changed_when` and `failed_when` directives to customize task result conditions. -- **Ignoring Errors:** - - Ignoring errors can lead to cascading failures or inconsistent state. - - Use the `block` and `rescue` directives to handle errors gracefully. -- **Misunderstanding Facts:** - - Facts are variables that contain information about the target hosts. Misunderstanding or misusing facts can lead to incorrect behavior. - - Use the `ansible_facts` variable to access all available facts. -- **Over-reliance on the `shell` module:** - - Avoid the shell module unless absolutely necessary as using it hinders the playbook's idempotency. -- **Not testing playbooks:** - - Always test your playbooks before running them in production to avoid any unexpected issues. - -### 6.2 Edge Cases - -- **Handling Large Files:** - - Transferring large files can be slow and consume a lot of resources. Use the `synchronize` module or the `archive` and `unarchive` modules to optimize file transfers. -- **Managing Complex Dependencies:** - - Managing complex dependencies between tasks and roles can be challenging. Use the `block` and `rescue` directives to handle errors gracefully. -- **Working with Dynamic Inventories:** - - Dynamic inventories can be complex to set up and maintain. Use a dynamic inventory plugin or script to manage your inventory automatically. -- **Handling Network Latency:** - - Network latency can affect the performance of your playbooks. Use the `async` directive to execute tasks asynchronously. -- **Special characters in variables:** - - Avoid using special characters that can interfere with playbook's execution. - -### 6.3 Version-Specific Issues - -- **Module Compatibility:** - - Some modules may not be compatible with all versions of Ansible. - - Check the module documentation for compatibility information. -- **Deprecated Features:** - - Some features may be deprecated in newer versions of Ansible. - - Be aware of deprecated features and migrate to the recommended alternatives. -- **Behavioral Changes:** - - Some modules may have different behavior in different versions of Ansible. - - Test your playbooks with different versions of Ansible to ensure they behave as expected. - -### 6.4 Compatibility Concerns - -- **Operating System Compatibility:** - - Some playbooks and roles may only be compatible with specific operating systems. - - Check the playbook or role documentation for compatibility information. -- **Python Version Compatibility:** - - Ansible requires Python to be installed on the target hosts. Ensure that the target hosts have a compatible version of Python installed. -- **Module Dependencies:** - - Some modules may have external dependencies that need to be installed on the target hosts. - - Check the module documentation for dependency information. - -### 6.5 Debugging Strategies - -- **Use the `-v` or `--verbose` option to increase the verbosity of Ansible output.** -- **Use the `-C` or `--check` option to perform a dry run of your playbook.** -- **Use the `--diff` option to see the changes that will be made to the target hosts.** -- **Use the `debug` module to print variables and facts.** -- **Use the `assert` module to validate variables and facts.** -- **Use the `pause` module to pause playbook execution and inspect the target hosts.** -- **Use the `register` directive to capture the output of tasks and use the output in debugging logic.** -- **Check the Ansible logs on the control node and the target hosts for error messages.** - -## 7. Tooling and Environment - -- Utilize recommended tools and environment configurations to streamline your Ansible development and deployment processes. - -### 7.1 Recommended Development Tools - -- **Text Editor or IDE:** - - Use a text editor or IDE with YAML and Jinja2 syntax highlighting and auto-completion. - - Popular options include VS Code, Sublime Text, Atom, and PyCharm. - - Install Ansible-specific plugins for improved code completion and linting. -- **Ansible Lint:** - - Use `ansible-lint` to check your playbooks and roles for common errors and best practices violations. - - Configure `ansible-lint` to use a custom style guide or to enforce specific rules. -- **Molecule:** - - Use `Molecule` to test your roles in a Docker or Vagrant environment. - - Molecule provides a framework for writing and running integration tests for your roles. -- **Vagrant:** - - Use `Vagrant` to create virtual machines for testing your playbooks and roles. - - Vagrant allows you to easily create and destroy test environments. -- **Docker:** - - Use `Docker` to containerize your Ansible control node and target hosts. - - Docker provides a lightweight and portable environment for running your Ansible code. -- **Testinfra:** - - Use `Testinfra` to write and run end-to-end tests for your infrastructure. - - Testinfra allows you to verify the state of your target hosts after running your playbooks. - -### 7.2 Build Configuration - -- **Use a build tool such as `Make` or `Grunt` to automate your build process.** -- **Create a `Makefile` or `Gruntfile.js` that defines the tasks for linting, testing, and deploying your Ansible code.** -- **Use environment variables to configure your build process.** -- **Use a version control system such as `Git` to track changes to your build configuration.** -- **Keep your build configuration simple and easy to understand.** - -### 7.3 Linting and Formatting - -- **Use `ansible-lint` to check your playbooks and roles for common errors and best practices violations.** -- **Configure `ansible-lint` to use a custom style guide or to enforce specific rules.** -- **Use a YAML linter to validate your YAML syntax.** -- **Use a Jinja2 linter to validate your Jinja2 syntax.** -- **Automate linting and formatting as part of your build process.** -- **Use auto-formatting tools such as `Prettier` to automatically format your YAML and Jinja2 code.** -- **Follow a consistent naming convention for your variables, tasks, roles, and files.** - -### 7.4 Deployment Best Practices - -- **Use a deployment tool such as `Ansible Tower` or `AWX` to manage your deployments.** -- **Use a continuous integration and continuous delivery (CI/CD) pipeline to automate your deployments.** -- **Use a version control system such as `Git` to track changes to your playbooks and roles.** -- **Use a rollback mechanism to revert changes in case of failures.** -- **Use a monitoring tool such as `Nagios` or `Zabbix` to monitor your infrastructure.** -- **Use a logging tool such as `ELK Stack` or `Splunk` to collect and analyze your logs.** -- **Always test your playbooks in a staging environment before deploying them to production.** - -### 7.5 CI/CD Integration - -- **Integrate your Ansible code into your CI/CD pipeline to automate testing and deployment.** -- **Use a CI/CD tool such as `Jenkins`, `GitLab CI`, or `Travis CI` to automate your pipeline.** -- **Create a CI/CD pipeline that includes linting, testing, and deployment steps.** -- **Use environment variables to configure your CI/CD pipeline.** -- **Use a version control system such as `Git` to trigger your CI/CD pipeline on every commit.** -- **Use automated testing to verify that your infrastructure changes work as expected.** -- **Use automated deployment to deploy your infrastructure changes to your target environment.** -- **Automate configuration management:** - - Ensure consistent configurations for servers and applications. -- **Implement infrastructure as code:** - - Track and manage infrastructure in source control. -- **Automate application deployments:** - - Deploy new versions of software reliably and efficiently. -- **Orchestrate multi-tier deployments:** - - Coordinate deployments across various layers of infrastructure. \ No newline at end of file +**Always structure your Ansible content into roles and collections.** Roles encapsulate specific functionalities, while collections group related roles, modules, and plugins, promoting reusability and discoverability. + +- **Role Scoping:** Each role or module must focus on a single, well-defined task. Avoid monolithic roles. + ❌ BAD: + ```yaml + # roles/webserver/tasks/main.yml + - name: Install Nginx + ansible.builtin.apt: name=nginx state=present + - name: Configure Nginx + ansible.builtin.template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf + - name: Start Nginx + ansible.builtin.service: name=nginx state=started + - name: Install PHP-FPM + ansible.builtin.apt: name=php-fpm state=present + # ... and more + ``` + ✅ GOOD: + ```yaml + # roles/nginx/tasks/main.yml + - name: Ensure Nginx is installed and configured + ansible.builtin.include_tasks: setup.yml + - name: Ensure Nginx service is running + ansible.builtin.service: name=nginx state=started enabled=true + + # roles/php-fpm/tasks/main.yml + - name: Ensure PHP-FPM is installed and configured + ansible.builtin.include_tasks: setup.yml + ``` +- **Fact Modules:** Create dedicated `_info` or `_facts` modules/tasks for gathering information, rather than overloading existing ones. + ✅ GOOD: + ```yaml + # roles/system_facts/tasks/main.yml + - name: Gather custom system facts + ansible.builtin.set_fact: + custom_os_version: "{{ ansible_facts['distribution_major_version'] }}" + ``` + +## 2. YAML Hygiene and Syntax + +**Enforce strict YAML formatting.** Consistent syntax improves readability and prevents subtle parsing errors. + +- **File Start:** All YAML files must begin with `---`. +- **Indentation:** Use two spaces for indentation, never tabs. +- **Quotes:** Quote strings only when necessary (e.g., when they contain special characters or Jinja map references). Prefer single quotes. Use double quotes for escaping characters or multi-line strings. + ❌ BAD: + ```yaml + - name: "Install a package" + ansible.builtin.apt: name="my-package" state="present" + - name: Set fact + set_fact: + myvar: '{{ item["key"] }}' # Incorrect quoting for Jinja map + ``` + ✅ GOOD: + ```yaml + --- + - name: Install a package + ansible.builtin.apt: + name: my-package + state: present + - name: Set fact + ansible.builtin.set_fact: + my_var: "{{ item['key'] }}" # Double quotes for Jinja map + - name: Print multi-line message + ansible.builtin.debug: + msg: | + This is line one. + This is line two. + ``` +- **Colon Spacing:** Use exactly one space after a colon in key-value pairs. + ❌ BAD: + ```yaml + - name : start service + service: + name : my_service + state : started + ``` + ✅ GOOD: + ```yaml + - name: start service + ansible.builtin.service: + name: my_service + state: started + ``` +- **Structured Map Style:** Always use the structured map style for module parameters, not the legacy `key=value` style. + ❌ BAD: + ```yaml + - name: Create directory + ansible.builtin.file: path=/opt/app state=directory mode=0755 + ``` + ✅ GOOD: + ```yaml + - name: Create directory + ansible.builtin.file: + path: /opt/app + state: directory + mode: '0755' # Quote octal modes + ``` +- **Booleans:** Standardize on `true`/`false`. + ❌ BAD: + ```yaml + - name: Enable service + ansible.builtin.service: name=my_service enabled=yes + become: True + ``` + ✅ GOOD: + ```yaml + - name: Enable service + ansible.builtin.service: name=my_service enabled=true + become: true + ``` + +## 3. Naming Conventions + +**Adopt consistent `snake_case` naming.** This applies to variables, tasks, files, and role names. Prefix role names with the collection namespace to prevent collisions. + +- **Variables, Tasks, Files:** + ❌ BAD: + ```yaml + # vars/main.yml + myVariable: "value" + My_Task_Name: "Install Software" + ``` + ✅ GOOD: + ```yaml + # vars/main.yml + my_variable: "value" + # tasks/install_software.yml + - name: Install software + ansible.builtin.apt: name=software state=present + ``` +- **Role Names:** + ✅ GOOD: `my_namespace.my_collection.webserver` + +## 4. Idempotency and Declarative Style + +**Write idempotent tasks.** Running a playbook multiple times should yield the same result without unintended side effects. Favor declarative modules over imperative `command` or `shell`. + +- **Declarative Modules:** + ❌ BAD: + ```yaml + - name: Check if file exists and create if not + ansible.builtin.shell: | + if [ ! -f /etc/myapp.conf ]; then + cp /etc/myapp.conf.template /etc/myapp.conf + fi + args: + creates: /etc/myapp.conf # Still imperative logic + ``` + ✅ GOOD: + ```yaml + - name: Ensure myapp.conf exists + ansible.builtin.copy: + src: myapp.conf.template + dest: /etc/myapp.conf + owner: root + group: root + mode: '0644' + backup: true # Idempotent file management + ``` +- **Atomic File Operations:** Always use `atomic_move` (implicitly via `copy`, `template` modules) for file modifications to prevent data corruption. + +## 5. Configuration Management + +**Manage configurations with templates and structured variables.** + +- **Templates:** Use Jinja2 templates (`template` module) for dynamic configuration files. +- **Variables:** Define role variables in `defaults/main.yml` (overridable) and `vars/main.yml` (not overridable by inventory/extra-vars). Prefer inventory variables for host-specific data. + ❌ BAD: + ```yaml + # playbook.yml + - hosts: webservers + vars: + nginx_port: 8080 # Hardcoded in playbook + tasks: + - name: Configure Nginx + ansible.builtin.template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf + ``` + ✅ GOOD: + ```yaml + # roles/nginx/defaults/main.yml + nginx_port: 80 # Default port + + # inventory/group_vars/webservers.yml + nginx_port: 8080 # Override default for webservers group + + # roles/nginx/templates/nginx.conf.j2 + listen {{ nginx_port }}; + ``` + +## 6. Performance Considerations + +**Optimize playbook execution for speed.** + +- **Fact Gathering:** Disable fact gathering (`gather_facts: false`) if not explicitly needed. Use `setup` or `ansible.builtin.gather_facts` module selectively. + ❌ BAD: + ```yaml + - hosts: all + # gather_facts: true by default, even if not used + tasks: + - name: Ping all hosts + ansible.builtin.ping: + ``` + ✅ GOOD: + ```yaml + - hosts: all + gather_facts: false # No facts needed for ping + tasks: + - name: Ping all hosts + ansible.builtin.ping: + ``` +- **Parallelism:** Leverage Ansible's parallelism by default, but be mindful of resource constraints. + +## 7. Error Handling and Logging + +**Implement robust error handling and informative logging.** + +- **Fail Gracefully:** Use `fail_json` (in custom modules) or `ansible.builtin.fail` for clear error messages. Avoid raw tracebacks. + ✅ GOOD: + ```yaml + - name: Ensure critical variable is defined + ansible.builtin.fail: + msg: "Required variable 'app_version' is not defined." + when: app_version is not defined + ``` +- **Debug Verbosity:** Use the `ansible.builtin.debug` module with verbosity levels for controlled output. + ✅ GOOD: + ```yaml + - name: Show debug info + ansible.builtin.debug: + var: my_variable + when: ansible_verbosity >= 2 # Only show with -vv or higher + ``` + +## 8. Testing and Linting + +**Integrate linting and testing into your development workflow.** + +- **Ansible Lint:** Run `ansible-lint` on every pull request. It enforces the official style guide and detects common issues. +- **Ansible Test:** Use `ansible-test` for unit and integration testing of custom modules and roles. + ✅ GOOD: + ```bash + # In your CI pipeline or pre-commit hook + ansible-lint . + ansible-test sanity --test flake8 --test ansible-doc --test pep8 # For custom modules + ``` + +## 9. CI/CD Integration + +**Embed Ansible into your automated CI/CD pipelines.** + +- **Git Triggers:** Trigger playbook runs on Git pushes to automatically provision or update infrastructure. +- **Collections:** Store reusable roles and modules in Ansible Collections (Galaxy or private registries) for easy dependency management. +- **Pipeline Checks:** Include `ansible-lint` and collection dependency checks in your CI pipeline. + ✅ GOOD: + ```yaml + # .github/workflows/ansible.yml + name: Ansible CI/CD + + on: [push, pull_request] + + jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install Ansible and dependencies + run: pip install ansible ansible-lint + - name: Run Ansible Lint + run: ansible-lint . + + deploy: + runs-on: ubuntu-latest + needs: lint + if: github.ref == 'refs/heads/main' + steps: + - uses: actions/checkout@v4 + - name: Install Ansible Collections + run: ansible-galaxy collection install -r requirements.yml + - name: Run Playbook + env: + ANSIBLE_VAULT_PASSWORD: ${{ secrets.ANSIBLE_VAULT_PASSWORD }} + run: ansible-playbook -i inventory/prod.yml site.yml --vault-password-file /dev/stdin + ``` \ No newline at end of file diff --git a/rules-mdc/ant-design.mdc b/rules-mdc/ant-design.mdc index f949dae..8457d81 100644 --- a/rules-mdc/ant-design.mdc +++ b/rules-mdc/ant-design.mdc @@ -1,311 +1,299 @@ --- -description: This rule enforces best practices and coding standards for projects using the Ant Design (antd) UI library within React applications. It covers code organization, performance, security, testing, and common pitfalls to ensure maintainable and efficient applications. -globs: *.js,*.jsx,*.ts,*.tsx +description: Definitive guidelines for building consistent, performant, and maintainable UIs with Ant Design v6.x, focusing on design tokens, layout, and component usage. +globs: **/* --- -# Ant Design (antd) Best Practices and Coding Standards +# ant-design Best Practices -This document outlines the recommended best practices for developing React applications using the Ant Design (antd) UI library. Following these guidelines will lead to more maintainable, performant, and secure applications. +This guide outlines the definitive best practices for using Ant Design v6.x in our projects. Adhering to these standards ensures consistency, accessibility, and maintainability across our codebase. -## 1. Code Organization and Structure +## 1. Theming: Design Token Driven -### 1.1. Directory Structure +Always customize Ant Design's appearance using its design token system via `ConfigProvider`. Avoid direct CSS overrides for visual properties that can be controlled by tokens. -- **`src/components/`**: Contains reusable React components, including those utilizing antd components. -- **`src/pages/`**: Contains components representing different application routes or pages. -- **`src/layouts/`**: Contains layout components that provide a consistent structure across pages. -- **`src/services/`**: Contains modules for interacting with APIs and handling data fetching. -- **`src/utils/`**: Contains utility functions and helper modules. -- **`src/styles/`**: Contains global styles, theme customizations, and component-specific stylesheets. -- **`src/assets/`**: Contains static assets such as images, fonts, and icons. -- **`src/context/`**: (Optional) If using context API, store all context definition files here. +### ✅ GOOD: Centralized Token Customization -Example: +Create a `theme.ts` file to export your theme configuration and apply it at the root of your application. Prefer `seedToken` adjustments for global changes and `componentToken` for specific component overrides. Utilize preset algorithms for light/dark mode. +```typescript +// src/theme.ts +import { theme } from 'antd'; +import type { ThemeConfig } from 'antd'; -my-app/ -├── src/ -│ ├── components/ -│ │ ├── Button.jsx -│ │ ├── Input.jsx -│ │ └── ... -│ ├── pages/ -│ │ ├── HomePage.jsx -│ │ ├── LoginPage.jsx -│ │ └── ... -│ ├── layouts/ -│ │ ├── MainLayout.jsx -│ │ └── ... -│ ├── services/ -│ │ ├── api.js -│ │ └── ... -│ ├── utils/ -│ │ ├── date-formatter.js -│ │ └── ... -│ ├── styles/ -│ │ ├── global.css -│ │ ├── theme.js -│ │ └── ... -│ ├── App.jsx -│ └── index.js -└── ... +export const appTheme: ThemeConfig = { + algorithm: theme.defaultAlgorithm, // Or theme.darkAlgorithm, [theme.defaultAlgorithm, theme.darkAlgorithm] + token: { + colorPrimary: '#0050B3', // Our primary brand color + colorSuccess: '#52C41A', + fontSize: 14, + borderRadius: 4, + // Disable motion globally for accessibility/performance + motion: false, + }, + components: { + Button: { + colorPrimary: '#1890FF', // Override primary button color + algorithm: true, // Enable algorithm for component token derivation + }, + Layout: { + headerBg: '#001529', + footerBg: '#F0F2F5', + }, + }, +}; +``` +```tsx +// src/App.tsx (or root layout) +import React from 'react'; +import { ConfigProvider, App as AntdApp } from 'antd'; +import { appTheme } from './theme'; +import HomePage from './pages/HomePage'; -### 1.2. File Naming Conventions - -- **Components**: Use PascalCase for component file names (e.g., `MyComponent.jsx`, `UserProfile.tsx`). -- **Styles**: Use kebab-case for style file names (e.g., `my-component.css`, `user-profile.module.scss`). -- **Modules**: Use camelCase for module file names (e.g., `api.js`, `dateFormatter.ts`). - -### 1.3. Module Organization - -- Group related components, styles, and assets within the same directory. -- Create separate modules for API interactions, data transformations, and utility functions. - -### 1.4. Component Architecture - -- **Presentational Components**: Focus on rendering UI elements and receiving data via props. -- **Container Components**: Handle data fetching, state management, and logic, passing data to presentational components. -- Use functional components with hooks whenever possible for simplicity and reusability. - -### 1.5. Code Splitting - -- Utilize React.lazy and Suspense to load components on demand, improving initial load time. -- Split routes into separate chunks to minimize the initial bundle size. -- Consider using dynamic imports for less frequently used components or modules. - -Example: - -jsx -import React, { Suspense } from 'react'; - -const MyComponent = React.lazy(() => import('./MyComponent')); - -function MyPage() { +const App: React.FC = () => { return ( - Loading...}> - - + + {/* Use AntdApp for context-aware static methods (message, Modal, notification) */} + + + + ); +}; + +export default App; +``` + +### ❌ BAD: Direct CSS Overrides + +Avoid overriding Ant Design component styles with custom CSS classes or inline styles for properties that are themeable. This leads to inconsistent UIs and breaks theme updates. + +```css +/* ❌ BAD: Avoid this for themeable properties */ +.ant-btn-primary { + background-color: #f00 !important; /* Breaks theme */ + border-color: #f00 !important; } +``` + +## 2. Layout: Unified Grid System + +Adhere to Ant Design's 8-pixel grid unit and the unified 1440px canvas width. Use `Row` and `Col` components for structural layout, leveraging their `span` and `gutter` props. + +### ✅ GOOD: Responsive Layout with Grid + +```tsx +import React from 'react'; +import { Layout, Row, Col } from 'antd'; + +const { Header, Content, Footer } = Layout; + +const MyLayout: React.FC = () => ( + +
+ {/* Header content */} +
+ + {/* 16px horizontal and vertical gutter */} + +

Welcome to our Application

+ + {/* Responsive columns */} +
+ Card 1 +
+ + +
+ Card 2 +
+ + +
+ Card 3 +
+ +
+
+
+ Ant Design ©{new Date().getFullYear()} Created by Ant UED +
+
+); + +export default MyLayout; +``` + +### ❌ BAD: Hardcoding Layout Dimensions + +Avoid using fixed pixel values or custom CSS for spacing and alignment that should be handled by the grid system or design tokens. + +```tsx +// ❌ BAD: Avoid custom margins for layout +
+ {/* Content */} +
+``` + +## 3. Component Usage: Standardized & Accessible + +Import components directly from `antd`. Always use TypeScript and configure ESLint with `eslint-plugin-antd` to enforce best practices. Prioritize accessibility by providing necessary `aria-*` attributes. + +### ✅ GOOD: Proper Imports and Accessibility + +```tsx +import React from 'react'; +import { Button, Space, Typography } from 'antd'; +import { PlusOutlined } from '@ant-design/icons'; + +const { Text } = Typography; + +const MyComponent: React.FC = () => { + const handleClick = () => { + console.log('Button clicked'); + }; + + return ( + + + Important information. + + ); +}; + +export default MyComponent; +``` + +### ❌ BAD: Missing Accessibility Attributes + +Interactive components must have appropriate `aria-*` attributes for screen reader users. + +```tsx +// ❌ BAD: Missing aria-label for icon-only button + + + ); +}; -- **Try-Catch Blocks**: Use for handling synchronous errors. -- **Error Boundaries**: Use to catch errors during rendering and prevent the entire application from crashing. -- **Global Error Handling**: Implement a global error handler to log errors and provide user feedback. +// Wrap components that use static methods or useToken inside +const RootComponent: React.FC = () => ( + + + +); + +export default RootComponent; +``` + +### ❌ BAD: Static Methods Without Context + +Calling `message.info()` or `Modal.confirm()` directly without `App` component or `useMessage`/`useModal` hooks will result in them not inheriting `ConfigProvider` context (e.g., theme, locale). -Example (Error Boundary): +```tsx +// ❌ BAD: This message will not inherit ConfigProvider context +import { message, Button } from 'antd'; -jsx -class ErrorBoundary extends React.Component { - constructor(props) { - super(props); - this.state = { hasError: false }; - } - - static getDerivedStateFromError(error) { - return { hasError: true }; - } - - componentDidCatch(error, errorInfo) { - console.error('Caught error: ', error, errorInfo); - } - - render() { - if (this.state.hasError) { - return

Something went wrong.

; - } - - return this.props.children; - } -} - -export default ErrorBoundary; - -// Usage: - - - - - -## 3. Performance Considerations - -### 3.1. Optimization Techniques - -- **Memoization**: Use `React.memo` to prevent unnecessary re-renders of components with the same props. -- **Pure Components**: Extend `React.PureComponent` for class components to perform shallow prop comparisons. -- **Virtualization**: Use `antd`'s `Table` and `List` components with virtualization for large datasets. -- **Debouncing/Throttling**: Use for event handlers that trigger frequent updates (e.g., search input). - -### 3.2. Memory Management - -- **Avoid Memory Leaks**: Properly clean up event listeners and timers in `useEffect` hooks. -- **Release Resources**: Release unused objects and data structures to free up memory. - -### 3.3. Rendering Optimization - -- **ShouldComponentUpdate**: Implement `shouldComponentUpdate` (for class components) or use `React.memo` (for functional components) to prevent unnecessary re-renders. -- **Immutable Data**: Use immutable data structures to simplify change detection. - -### 3.4. Bundle Size Optimization - -- **Modular Imports**: Import only the necessary components from `antd` to reduce bundle size (e.g., `import { Button } from 'antd';`). Use `babel-plugin-import` for automatic modular imports. -- **Tree Shaking**: Ensure your build process supports tree shaking to remove unused code. -- **Code Splitting**: As mentioned earlier, split your code into smaller chunks to reduce the initial bundle size. - -### 3.5. Lazy Loading - -- Use `React.lazy` and `Suspense` to load components on demand. -- Implement lazy loading for images and other assets using libraries like `react-lazyload`. - -## 4. Security Best Practices - -### 4.1. Common Vulnerabilities - -- **Cross-Site Scripting (XSS)**: Prevent XSS by sanitizing user input and encoding output. -- **Cross-Site Request Forgery (CSRF)**: Protect against CSRF attacks by implementing CSRF tokens. -- **SQL Injection**: Avoid directly embedding user input in SQL queries; use parameterized queries or ORMs. - -### 4.2. Input Validation - -- **Server-Side Validation**: Always validate user input on the server-side. -- **Client-Side Validation**: Use `antd`'s `Form` component for client-side validation to provide immediate feedback to the user. -- **Sanitize Input**: Sanitize user input to remove potentially harmful characters or code. - -### 4.3. Authentication and Authorization - -- **Secure Authentication**: Use secure authentication mechanisms like JWT (JSON Web Tokens) or OAuth. -- **Role-Based Access Control (RBAC)**: Implement RBAC to control access to different parts of the application based on user roles. - -### 4.4. Data Protection - -- **Encryption**: Encrypt sensitive data both in transit and at rest. -- **Data Masking**: Mask sensitive data in the UI to prevent unauthorized access. - -### 4.5. Secure API Communication - -- **HTTPS**: Use HTTPS to encrypt communication between the client and the server. -- **API Rate Limiting**: Implement rate limiting to prevent abuse and denial-of-service attacks. - -## 5. Testing Approaches - -### 5.1. Unit Testing - -- Test individual components in isolation to ensure they function correctly. -- Use testing libraries like Jest and React Testing Library. -- Mock dependencies to isolate the component being tested. - -### 5.2. Integration Testing - -- Test the interaction between multiple components or modules. -- Use testing libraries like React Testing Library and Cypress. - -### 5.3. End-to-End Testing - -- Test the entire application from the user's perspective. -- Use testing frameworks like Cypress or Playwright. - -### 5.4. Test Organization - -- Create a `tests/` directory at the root of your project. -- Place test files alongside the components or modules they test (e.g., `MyComponent.test.jsx`). -- Use descriptive test names to clearly indicate what is being tested. - -### 5.5. Mocking and Stubbing - -- Use mocking libraries like Jest's `jest.mock()` to mock external dependencies. -- Use stubbing to replace functions or methods with predefined behavior. - -## 6. Common Pitfalls and Gotchas - -### 6.1. Frequent Mistakes - -- **Not using modular imports**: Importing the entire `antd` library can significantly increase bundle size. -- **Ignoring TypeScript errors**: Failing to address TypeScript errors can lead to runtime issues. -- **Not handling asynchronous operations correctly**: Failing to handle promises or async/await can lead to unhandled rejections and unexpected behavior. -- **Not localizing strings correctly**: Hardcoding strings instead of using `antd` i18n features. - -### 6.2. Edge Cases - -- **Handling different screen sizes and devices**: Ensuring responsive design using `antd` grid system. -- **Accessibility**: Consider accessibility when using components, making sure to include `aria` attributes. -- **Browser compatibility**: Test the app on various browsers (Chrome, Firefox, Safari, Edge, etc). - -### 6.3. Version-Specific Issues - -- **Breaking changes**: Be aware of breaking changes when upgrading `antd` versions. -- **Deprecated APIs**: Avoid using deprecated APIs and migrate to the recommended alternatives. -- **CSS class conflicts:** Potential issues with CSS specificity or conflicts with global styles. Use CSS Modules or Styled Components for more robust style isolation. - -### 6.4. Compatibility Concerns - -- **React version**: Ensure compatibility between `antd` and your React version. -- **Other UI libraries**: Avoid conflicts with other UI libraries by using consistent styling and naming conventions. - -### 6.5. Debugging - -- **Use browser developer tools**: Inspect the DOM, network requests, and console output. -- **Use React DevTools**: Inspect the component tree, props, and state. -- **Use logging and debugging statements**: Add `console.log` statements to trace the execution flow and inspect variable values. - -## 7. Tooling and Environment - -### 7.1. Recommended Tools - -- **IDE**: VS Code, WebStorm. -- **Build Tool**: Webpack, Parcel, Rollup, esbuild. -- **Testing Libraries**: Jest, React Testing Library, Cypress. -- **Linting**: ESLint, Prettier. - -### 7.2. Build Configuration - -- **Optimize for production**: Use production-specific build configurations to minimize bundle size and improve performance. -- **Configure code splitting**: Set up code splitting to load components on demand. -- **Enable tree shaking**: Ensure your build process supports tree shaking to remove unused code. - -### 7.3. Linting and Formatting - -- **ESLint**: Use ESLint with recommended React and `antd` plugins to enforce coding standards and detect potential errors. -- **Prettier**: Use Prettier to automatically format your code for consistency. -- **Stylelint:** Use Stylelint to enforce consistent style practices. - -### 7.4. Deployment - -- **Choose a hosting platform**: Netlify, Vercel, AWS, Google Cloud, Azure. -- **Configure environment variables**: Set up environment variables for API keys, database credentials, and other sensitive information. -- **Use a CDN**: Use a Content Delivery Network (CDN) to cache static assets and improve loading times. - -### 7.5. CI/CD Integration - -- **Set up a CI/CD pipeline**: Use tools like Jenkins, Travis CI, CircleCI, or GitHub Actions to automate testing, building, and deployment. -- **Automate testing**: Run unit, integration, and end-to-end tests in your CI/CD pipeline. -- **Automate deployment**: Automate the deployment process to reduce manual effort and errors. \ No newline at end of file +const BadComponent: React.FC = () => ( + +); +``` \ No newline at end of file diff --git a/rules-mdc/anyio.mdc b/rules-mdc/anyio.mdc index 269810b..ce87eb3 100644 --- a/rules-mdc/anyio.mdc +++ b/rules-mdc/anyio.mdc @@ -1,169 +1,36 @@ --- -description: This rule provides best practices and coding standards for developing with the AnyIO library, focusing on structured concurrency, task management, and proper use of synchronization primitives to create robust, cross-backend asynchronous applications. -globs: *.py +description: Definitive guidelines for writing robust, maintainable, and backend-agnostic asynchronous Python code using AnyIO. Prioritize structured concurrency and native AnyIO primitives. +globs: **/*.py --- -# AnyIO Best Practices and Coding Standards +# AnyIO Best Practices -This document provides comprehensive guidelines for developing with the AnyIO library, covering code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and recommended tooling. +AnyIO is the definitive choice for modern asynchronous Python development. It provides a unified, Trio-inspired API on top of `asyncio` or `Trio`, fixing critical design shortcomings of `asyncio` and enforcing structured concurrency. Adhere to these rules to build reliable, high-performance async applications. -## Library Information: -- Name: anyio -- Tags: python, async, compatibility-layer +## 1. Entry Point and Backend Selection -## 1. Code Organization and Structure +Always use `anyio.run()` as your application's entry point. Explicitly select your preferred backend and leverage backend-specific optimizations. -- **Directory Structure:** Organize your project to separate concerns clearly. - - `src/`: Contains the main application code. - - `tests/`: Contains unit, integration, and end-to-end tests. - - `examples/`: Contains example code showcasing AnyIO features. - - `docs/`: Contains project documentation (using Sphinx, for example). - - `tasks.py`: Invoke tasks for building, testing, and deploying (using Invoke). -- **File Naming Conventions:** - - Use descriptive and consistent file names. - - `my_component.py` for a component's source code. - - `my_component_test.py` for its tests. - - `conftest.py` in the `tests/` directory for test fixtures. -- **Module Organization:** - - Group related functionality into modules. - - Use packages to further structure your code. - - Employ clear and concise module-level docstrings. -- **Component Architecture:** - - Design components with clear responsibilities. - - Use interfaces or abstract base classes for decoupling. - - Consider using dependency injection to improve testability. -- **Code Splitting:** - - Break down large functions into smaller, more manageable ones. - - Decompose complex modules into simpler sub-modules. - - Consider lazy-loading modules or components to improve startup time. +❌ **BAD**: Relying on default backend or `asyncio.run()`. +```python +import asyncio +from anyio import run, sleep -## 2. Common Patterns and Anti-patterns +async def main(): + print("Running on default backend (asyncio) without uvloop.") + await sleep(0.1) -- **Design Patterns:** - - **Task Groups (Nurseries):** Use task groups (`anyio.create_task_group()`) for structured concurrency. This is the most crucial pattern in AnyIO. - - **Resource Acquisition Is Initialization (RAII):** Use `async with` statements for managing resources (e.g., sockets, files) to ensure proper cleanup, even in case of exceptions or cancellations. - - **Observer Pattern:** Use AnyIO's `Event` or `Condition` primitives to implement observer patterns for asynchronous communication. - - **Producer-Consumer Pattern:** Use `anyio.Queue` for implementing producer-consumer patterns with asynchronous tasks. -- **Recommended Approaches:** - - Use `anyio.sleep()` for non-blocking delays. - - Employ `anyio.to_thread.run_sync()` to run blocking code in a separate thread to avoid blocking the event loop. - - Utilize `anyio.Path` for asynchronous file I/O operations. -- **Anti-patterns:** - - **Blocking the Event Loop:** Avoid performing long-running synchronous operations in the main event loop. Use `anyio.to_thread.run_sync()` to offload such tasks to worker threads. - - **Ignoring Exceptions:** Always handle exceptions gracefully within tasks and task groups. Unhandled exceptions can crash your application. - - **Unstructured Concurrency:** Avoid creating tasks without a task group. This can lead to resource leaks and difficult-to-debug issues. - - **Spin Locks:** Do not use busy-waiting or spin locks in asynchronous code. Use synchronization primitives like `Lock` or `Condition` instead. -- **State Management:** - - Use immutable data structures whenever possible to avoid race conditions. - - Employ `Lock` or `Condition` objects to protect shared mutable state. - - Consider using atomic operations for simple state updates. -- **Error Handling:** - - Wrap code in `try...except` blocks to catch exceptions. - - Use `try...finally` blocks to ensure cleanup, even in case of exceptions. - - Leverage task groups to handle exceptions across multiple tasks. - - Implement retry mechanisms for transient errors. +asyncio.run(main) # Bypasses AnyIO's entry point +run(main) # Implicit backend, no optimizations +``` -## 3. Performance Considerations +✅ **GOOD**: Explicit backend selection and performance enhancements. +```python +from anyio import run, sleep +import sniffio -- **Optimization Techniques:** - - **Asynchronous I/O:** Utilize AnyIO's asynchronous I/O functions (e.g., `anyio.Path`, `anyio.open_file`) for optimal performance when dealing with I/O-bound operations. - - **Connection Pooling:** Implement connection pooling for database connections or other network resources to reduce overhead. - - **Caching:** Cache frequently accessed data to minimize I/O operations. - - **Minimize Context Switching:** Reduce unnecessary context switching by batching operations and avoiding excessive `await` calls. -- **Memory Management:** - - Avoid creating large, unnecessary data structures. - - Use generators or iterators to process large datasets in a memory-efficient manner. - - Properly close resources (e.g., sockets, files) to release memory. - - Use the `del` statement or `weakref` to break circular references and allow garbage collection. -- **Rendering Optimization:** N/A (AnyIO is not directly involved in rendering). -- **Bundle Size Optimization:** N/A (AnyIO itself is a dependency, not a frontend bundle). -- **Lazy Loading:** - - Use lazy loading to defer the initialization of components until they are needed. - - Implement code splitting to load modules on demand. +async def main(): + backend = sniffio.current_async_library() + print(f"Hello from {backend}!") + await sleep(0.1) -## 4. Security Best Practices - -- **Common Vulnerabilities:** - - **Denial of Service (DoS):** Protect against DoS attacks by limiting the number of concurrent connections or requests. - - **Injection Attacks:** Sanitize user inputs to prevent injection attacks (e.g., SQL injection, command injection). - - **Cross-Site Scripting (XSS):** N/A (AnyIO is not directly involved in front-end development). -- **Input Validation:** - - Validate all user inputs to ensure they conform to expected formats and ranges. - - Use input validation libraries to simplify the process. - - Escape or sanitize user inputs before using them in database queries or system commands. -- **Authentication and Authorization:** - - Implement authentication to verify the identity of users. - - Implement authorization to control access to resources based on user roles. - - Use secure password hashing algorithms (e.g., bcrypt, Argon2). -- **Data Protection:** - - Use encryption to protect sensitive data at rest and in transit. - - Store cryptographic keys securely. - - Comply with relevant data privacy regulations (e.g., GDPR, CCPA). -- **Secure API Communication:** - - Use HTTPS for all API communication to encrypt data in transit. - - Implement proper authentication and authorization mechanisms for API endpoints. - - Protect against Cross-Site Request Forgery (CSRF) attacks if your API is used by web applications. - -## 5. Testing Approaches - -- **Unit Testing:** - - Write unit tests for individual components to verify their functionality. - - Use mocking or stubbing to isolate components from their dependencies. - - Aim for high test coverage to ensure that all code paths are tested. -- **Integration Testing:** - - Write integration tests to verify the interaction between different components. - - Test the integration with external services (e.g., databases, APIs). -- **End-to-End Testing:** - - Write end-to-end tests to verify the entire application flow. - - Simulate real user interactions to test the application from a user's perspective. -- **Test Organization:** - - Organize tests into separate modules based on the components or features they test. - - Use a consistent naming convention for test files and functions. - - Employ test fixtures to set up and tear down test environments. -- **Mocking and Stubbing:** - - Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to replace dependencies with mock objects. - - Stub external services or APIs to simulate different scenarios. - - Verify that mock objects are called with the expected arguments. - -## 6. Common Pitfalls and Gotchas - -- **Frequent Mistakes:** - - **Not using `async with` for resources:** Forgetting to use `async with` for resources that require asynchronous cleanup can lead to resource leaks. - - **Mixing asyncio and Trio idioms:** Avoid mixing idioms from different asynchronous frameworks. Stick to AnyIO's API. - - **Incorrectly using `to_thread.run_sync`:** Ensure that the code passed to `to_thread.run_sync` is actually blocking. -- **Edge Cases:** - - **Cancellation:** Be aware of how cancellation works in AnyIO and handle it gracefully. - - **Timeouts:** Implement timeouts to prevent tasks from running indefinitely. - - **Signal Handling:** Properly handle signals (e.g., `SIGINT`, `SIGTERM`) to ensure graceful shutdown. -- **Version-Specific Issues:** - - Consult the AnyIO changelog for known issues and breaking changes in different versions. -- **Compatibility Concerns:** - - Ensure that AnyIO is compatible with the versions of asyncio or Trio you are using. - - Be aware of potential compatibility issues with other libraries that use asynchronous programming. -- **Debugging Strategies:** - - Use logging to trace the execution flow of your code. - - Employ debuggers (e.g., `pdb`, `ipdb`) to step through your code and inspect variables. - - Use asynchronous debugging tools to debug asynchronous code. - -## 7. Tooling and Environment - -- **Recommended Development Tools:** - - **Python:** Use the latest stable version of Python (3.10+ recommended). - - **Poetry/Pip:** Use Poetry or Pip for dependency management. - - **Pytest:** Use Pytest for testing. - - **Black/Ruff:** Use Black and Ruff for code formatting and linting. - - **VS Code/PyCharm:** Use VS Code or PyCharm as your IDE. -- **Build Configuration:** - - Use a `pyproject.toml` file to configure Poetry or Pip. - - Specify dependencies and build settings in the `pyproject.toml` file. - - Use a `setup.py` file for projects that need to be installed with `pip install -e .` -- **Linting and Formatting:** - - Configure Black and Ruff to enforce consistent code formatting and style. - - Use a pre-commit hook to automatically format and lint code before committing. -- **Deployment:** - - Package your application into a Docker container for easy deployment. - - Use a process manager (e.g., systemd, Supervisor) to manage your application. - - Deploy your application to a cloud platform (e.g., AWS, Azure, GCP). -- **CI/CD Integration:** - - Use a CI/CD pipeline to automate the build, test, and deployment process. - - Integrate your CI/CD pipeline with your version control system (e.g., GitHub, GitLab, Bitbucket). - - Use automated testing to ensure that code changes do not introduce regressions. \ No newline at end of file +# For production, prefer \ No newline at end of file diff --git a/rules-mdc/apollo-client.mdc b/rules-mdc/apollo-client.mdc index 3bf155f..29bbf6e 100644 --- a/rules-mdc/apollo-client.mdc +++ b/rules-mdc/apollo-client.mdc @@ -1,178 +1,419 @@ --- -description: This rule provides comprehensive best practices for using Apollo Client in your projects, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers in building robust and maintainable GraphQL-powered applications. -globs: *.js,*.jsx,*.ts,*.tsx,*.gql,*.graphql +description: This guide defines the definitive best practices for using Apollo Client 3.x in our React applications, focusing on cache hygiene, type safety, performance, and maintainability. +globs: **/*.{js,jsx} --- -- **Code Organization and Structure:** - - **Directory Structure:** - - Organize GraphQL queries and mutations in a dedicated directory (e.g., `graphql` or `queries`). - - Group related queries and mutations into subdirectories based on features or modules. - - Consider a separate directory for GraphQL types/schemas if you're managing them locally. - - Example: - - src/ - graphql/ - user/ - getUser.gql - createUser.gql - product/ - getProduct.gql - updateProduct.gql - - - **File Naming Conventions:** - - Use descriptive names for GraphQL query and mutation files (e.g., `getUser.gql`, `updateProduct.gql`). - - Employ a consistent naming scheme (e.g., `[operationName].[operationType].gql`). - - **Module Organization:** - - Encapsulate Apollo Client logic (e.g., initialization, hooks) within reusable modules. - - Create custom hooks for common data fetching patterns (e.g., `useUser`, `useProduct`). - - **Component Architecture:** - - Favor a component-based architecture for UI development. - - Decouple data fetching logic from UI components using hooks or render props. - - Utilize higher-order components (HOCs) or render props for cross-cutting concerns (e.g., authentication, error handling). - - **Code Splitting:** - - Use dynamic imports to lazy-load components and queries, improving initial load time. - - Split large queries into smaller fragments to reduce bundle size. +# apollo-client Best Practices -- **Common Patterns and Anti-patterns:** - - **Design Patterns:** - - **Repository Pattern:** Abstract data access logic behind a repository interface. - - **Facade Pattern:** Provide a simplified interface to a complex subsystem (e.g., Apollo Client). - - **Hook Composition:** Combine multiple custom hooks to create more complex data fetching logic. - - **Recommended Approaches:** - - Use the `useQuery` and `useMutation` hooks for data fetching and manipulation. - - Leverage Apollo Client's cache for improved performance and offline capabilities. - - Implement optimistic updates to provide a better user experience. - - Use GraphQL fragments to reuse common data structures across multiple queries and mutations. - - **Anti-patterns:** - - Avoid directly manipulating the Apollo Client cache outside of mutations. - - Don't fetch the entire schema unnecessarily; only fetch what you need. - - Avoid deeply nested components with complex data fetching logic. - - **State Management:** - - Use Apollo Client's cache as the primary source of truth for application state. - - Integrate with external state management libraries (e.g., Redux, Zustand) when necessary for complex state requirements. - - Consider using Apollo Link State for managing local client-side state. - - **Error Handling:** - - Implement global error handling with Apollo Link. - - Display user-friendly error messages to the user. - - Retry failed queries or mutations automatically. +Apollo Client is our standard for GraphQL state management. Adhering to these guidelines ensures predictable data flow, optimal performance, and a scalable codebase. -- **Performance Considerations:** - - **Optimization Techniques:** - - Use the `fetchPolicy` option in `useQuery` to control cache behavior. - - Implement pagination for large datasets. - - Use batching and caching at the server-side to reduce network requests. - - **Memory Management:** - - Unsubscribe from subscriptions when components unmount to prevent memory leaks. - - Avoid storing large amounts of data in the Apollo Client cache. - - **Rendering Optimization:** - - Use React's `memo` or `useMemo` to prevent unnecessary re-renders. - - Implement virtualization for rendering large lists. - - **Bundle Size Optimization:** - - Use code splitting to reduce the initial bundle size. - - Remove unused dependencies. - - Minify and compress your code. - - **Lazy Loading:** - - Lazy-load components and queries using dynamic imports. +--- -- **Security Best Practices:** - - **Common Vulnerabilities:** - - **GraphQL Injection:** Prevent injection attacks by validating user input and using parameterized queries. - - **Denial of Service (DoS):** Limit query complexity and depth to prevent DoS attacks. - - **Information Disclosure:** Avoid exposing sensitive data in error messages. - - **Input Validation:** - - Validate all user input on both the client and server sides. - - Use GraphQL's built-in validation capabilities. - - **Authentication and Authorization:** - - Implement proper authentication and authorization mechanisms. - - Use JWT (JSON Web Tokens) or other secure authentication protocols. - - Follow the principle of least privilege when granting access to data. - - **Data Protection:** - - Encrypt sensitive data at rest and in transit. - - Use HTTPS for all API communication. - - **Secure API Communication:** - - Use Apollo Link to add security headers to API requests. - - Implement CORS (Cross-Origin Resource Sharing) to prevent cross-site scripting (XSS) attacks. +## 1. Client Setup & Initialization -- **Testing Approaches:** - - **Unit Testing:** - - Test individual components and hooks in isolation. - - Mock Apollo Client's API to control data fetching behavior. - - **Integration Testing:** - - Test the integration of components with Apollo Client. - - Use a test GraphQL server to simulate real API interactions. - - **End-to-end Testing:** - - Test the entire application flow from the user interface to the backend. - - Use tools like Cypress or Puppeteer for end-to-end testing. - - **Test Organization:** - - Organize tests in a directory structure that mirrors the source code. - - Use descriptive names for test files and test cases. - - **Mocking and Stubbing:** - - Use mocking libraries (e.g., Jest, Sinon) to mock Apollo Client's API. - - Create stub GraphQL responses for testing different scenarios. +**Always instantiate `ApolloClient` as a singleton.** Avoid creating multiple client instances, as each client manages its own `InMemoryCache`, leading to inconsistent state and wasted resources. -- **Common Pitfalls and Gotchas:** - - **Frequent Mistakes:** - - Incorrect cache configuration leading to stale data. - - Over-fetching data in GraphQL queries. - - Ignoring error handling in `useQuery` and `useMutation`. - - **Edge Cases:** - - Handling network errors and offline scenarios. - - Dealing with large datasets and complex queries. - - Managing cache invalidation and updates. - - **Version-Specific Issues:** - - Be aware of breaking changes between Apollo Client versions. - - Consult the Apollo Client documentation for migration guides. - - **Compatibility Concerns:** - - Ensure compatibility with different browsers and devices. - - Test your application on different platforms. - - **Debugging Strategies:** - - Use Apollo Client DevTools to inspect queries, mutations, and cache state. - - Log API requests and responses for debugging purposes. +❌ **BAD:** Multiple `ApolloClient` instances -- **Tooling and Environment:** - - **Recommended Tools:** - - Apollo Client DevTools for debugging and inspecting the cache. - - GraphQL Playground or GraphiQL for exploring and testing GraphQL APIs. - - Apollo VS Code extension for syntax highlighting and autocompletion. - - **Build Configuration:** - - Use a build tool like Webpack or Parcel to bundle your code. - - Configure Babel to transpile your code to compatible JavaScript versions. - - **Linting and Formatting:** - - Use ESLint and Prettier to enforce code style and best practices. - - Configure linting rules specific to Apollo Client and GraphQL. - - **Deployment:** - - Use a deployment platform like Netlify, Vercel, or AWS Amplify. - - Configure environment variables for API endpoints and other sensitive data. - - **CI/CD Integration:** - - Use a CI/CD pipeline to automate testing and deployment. - - Integrate linters, formatters, and test runners into the pipeline. +```javascript +// In multiple files +const client = new ApolloClient({ /* ... */ }); +``` -- **Specific Best Practices based on Exa Search Results:** - - Ensure all queries for a specific type return an ID for normalization and caching (RedwoodJS Community). - - Store queries in separate `.gql` files and use tools like `graphql-import` for better organization (Reddit). - - Use Apollo Client's `watchQuery` method for real-time data updates (Medium). - - Follow GraphQL query best practices for efficient API design (Apollo GraphQL). +✅ **GOOD:** Singleton `ApolloClient` -- **Additional considerations** - - When creating queries and mutations, follow best practices to get the most out of both GraphQL and Apollo tooling. +```javascript +// src/apolloClient.js +import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client'; +import { onError } from '@apollo/client/link/error'; +import { RetryLink } from '@apollo/client/link/retry'; -- **Example Directory Structure** +const httpLink = new HttpLink({ + uri: process.env.GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql', + headers: { + authorization: localStorage.getItem('token') || '', + 'client-name': 'OurApp [web]', + 'client-version': '1.0.0', + }, +}); -src/ - components/ - UserCard.tsx - ProductDetails.tsx - graphql/ - queries/ - getUser.gql - getProduct.gql - mutations/ - createUser.gql - updateProduct.gql - hooks/ - useUser.ts - useProduct.ts - utils/ - apolloClient.ts // Initialize Apollo Client here +const errorLink = onError(({ graphQLErrors, networkError }) => { + if (graphQLErrors) + graphQLErrors.forEach(({ message, locations, path }) => + console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`) + ); + if (networkError) console.error(`[Network error]: ${networkError}`); +}); +const retryLink = new RetryLink({ + delay: { + initial: 300, + max: Infinity, + jitter: true + }, + attempts: { + max: 5, + retryIf: (error, _operation) => !!error + } +}); -This is a comprehensive guide for using Apollo Client. Please adapt these guidelines to your specific project requirements and coding style. \ No newline at end of file +export const client = new ApolloClient({ + link: from([errorLink, retryLink, httpLink]), + cache: new InMemoryCache({ + typePolicies: { + // Define type policies here for custom cache behavior + User: { + keyFields: ['id'], // Ensure consistent identification + }, + Query: { + fields: { + // Example: Custom merge for a paginated list + users: { + keyArgs: false, // Don't include arguments in cache key + merge(existing = [], incoming) { + return [...existing, ...incoming]; + }, + }, + }, + }, + }, + }), + // Enable Automatic Persisted Queries for performance + persistedQueries: { + ttl: 3600, // 1 hour + }, +}); + +// src/App.js +import { ApolloProvider } from '@apollo/client'; +import { client } from './apolloClient'; + +function App() { + return ( + + {/* Your application */} + + ); +} +``` + +## 2. Data Fetching with React Hooks + +**Always use Apollo Client's React hooks (`useQuery`, `useMutation`, `useSubscription`) for data operations within components.** These hooks provide declarative data fetching, automatic UI updates, and robust state management. Avoid direct `client.query()` or `client.mutate()` calls in components unless for specific server-side rendering or pre-fetching scenarios outside the React lifecycle. + +❌ **BAD:** Imperative data fetching in components + +```javascript +import { client } from '../apolloClient'; + +function MyComponent() { + const [data, setData] = useState(null); + useEffect(() => { + client.query({ query: GET_USERS }).then(res => setData(res.data)); + }, []); + // ... +} +``` + +✅ **GOOD:** Declarative data fetching with `useQuery` + +```javascript +import { useQuery, gql } from '@apollo/client'; + +const GET_USERS = gql` + query GetUsers($limit: Int!) { + users(limit: $limit) { + id + name + } + } +`; + +function UserList({ limit }) { + const { loading, error, data } = useQuery(GET_USERS, { + variables: { limit }, + fetchPolicy: 'cache-and-network', // Recommended for most lists + }); + + if (loading) return

Loading users...

; + if (error) return

Error: {error.message}

; + + return ( +
    + {data.users.map(user => ( +
  • {user.name}
  • + ))} +
+ ); +} +``` + +## 3. Cache Hygiene & Management + +**Prioritize immutable cache updates and configure `InMemoryCache` with `TypePolicy` and `FieldPolicy`.** This prevents stale data, ensures garbage collection, and customizes merging logic for complex data structures. + +**`fetchPolicy` Strategy:** +* `cache-first` (default): Use for stable data that rarely changes. +* `cache-and-network`: Use for data that might change frequently, providing instant UI feedback while fetching fresh data. +* `network-only`: Use for critical, real-time data or mutations where the latest server state is paramount. +* `no-cache`: Use for one-off data (e.g., authentication tokens) that should *never* be stored in the cache. + +❌ **BAD:** Mutating cache objects directly or neglecting `keyFields` + +```javascript +// This can lead to inconsistent cache state +cache.data.data.User:123.name = 'New Name'; +``` + +✅ **GOOD:** Immutable cache updates with `cache.modify` or `writeFragment` + +```javascript +import { useMutation, gql } from '@apollo/client'; + +const UPDATE_USER_NAME = gql` + mutation UpdateUserName($id: ID!, $name: String!) { + updateUserName(id: $id, name: $name) { + id + name + } + } +`; + +function UserProfile({ userId, currentName }) { + const [updateName] = useMutation(UPDATE_USER_NAME); + + const handleUpdate = async (newName) => { + await updateName({ + variables: { id: userId, name: newName }, + update: (cache, { data: { updateUserName } }) => { + cache.modify({ + id: cache.identify(updateUserName), // Get normalized cache ID + fields: { + name() { + return updateUserName.name; // Update the name field + }, + }, + }); + }, + }); + }; + + return ( +
+

Current Name: {currentName}

+ +
+ ); +} +``` + +## 4. Type Safety & Code Generation + +**Mandate `@graphql-codegen` for all GraphQL operations.** This generates TypeScript types for queries, mutations, and subscriptions, along with typed React hooks, ensuring end-to-end type safety and reducing runtime errors. + +❌ **BAD:** Manual type definitions or `any` + +```javascript +// Manually defining types is error-prone and tedious +interface UserData { + users: Array<{ id: string; name: string }>; +} +const { data } = useQuery(GET_USERS); +``` + +✅ **GOOD:** Generated types and hooks + +```javascript +// graphql.config.js (example) +module.exports = { + schema: 'http://localhost:4000/graphql', + documents: 'src/**/*.graphql', + overwrite: true, + generates: { + './src/generated/graphql.tsx': { + plugins: [ + 'typescript', + 'typescript-operations', + 'typescript-react-apollo', + ], + config: { + withHooks: true, + withHOC: false, + withComponent: false, + }, + }, + }, +}; + +// src/components/UserList.graphql (separate file for GraphQL document) +// query GetUsers($limit: Int!) { +// users(limit: $limit) { +// id +// name +// } +// } + +// src/components/UserList.tsx +import { useGetUsersQuery } from '../generated/graphql'; // Generated hook + +function UserList({ limit }) { + const { loading, error, data } = useGetUsersQuery({ variables: { limit } }); + + if (loading) return

Loading users...

; + if (error) return

Error: {error.message}

; + + return ( +
    + {data?.users.map(user => ( // Data is now fully typed +
  • {user.name}
  • + ))} +
+ ); +} +``` + +## 5. Error Handling & Resilience + +**Implement centralized error handling using Apollo Link's `onError` and `RetryLink`.** This provides a consistent way to log, display, and recover from network and GraphQL errors. + +❌ **BAD:** Inconsistent error handling across components + +```javascript +// Every component handles errors differently +if (error) { + alert(error.message); +} +``` + +✅ **GOOD:** Centralized error handling with `onError` link (see Section 1 for example) and component-level display. + +```javascript +// In a component using useQuery or useMutation +function MyComponent() { + const { loading, error, data } = useQuery(MY_QUERY); + + if (loading) return

Loading...

; + if (error) { + // Specific UI for this component's error + return

Failed to load data: {error.message}

; + } + // ... +} +``` + +## 6. Code Organization & Naming Conventions + +**Colocate GraphQL documents (`.graphql` files) with the components that use them.** Follow GraphQL schema naming conventions (`camelCase` for fields/arguments, `PascalCase` for types, `SCREAMING_SNAKE_CASE` for enum values) and enforce them with GraphOS schema linting. + +❌ **BAD:** Inline GraphQL strings, generic naming + +```javascript +// In a large component file +const MY_HUGE_QUERY = gql`query { /* ... */ }`; +``` + +✅ **GOOD:** Dedicated GraphQL files, clear naming + +``` +// src/components/UserList/ +// ├── UserList.tsx +// └── UserList.graphql +``` + +```graphql +# src/components/UserList/UserList.graphql +query GetUsers($limit: Int!) { + users(limit: $limit) { + id + firstName # Use camelCase for fields + lastName + } +} +``` + +## 7. Performance Considerations + +**Utilize fragments for query reuse and to avoid over-fetching.** Consider Automatic Persisted Queries (APQ) for production environments to reduce network payload sizes. Optimize `fetchPolicy` based on data volatility. + +❌ **BAD:** Repeated field selections, large monolithic queries + +```graphql +query GetUserAndPosts { + user(id: "1") { id name email } + posts(userId: "1") { id title content } +} +``` + +✅ **GOOD:** Use fragments for modularity and reuse + +```graphql +# src/fragments/UserFragment.graphql +fragment UserDetails on User { + id + name + email +} + +# src/components/UserPosts/UserPosts.graphql +query GetUserAndPosts($userId: ID!) { + user(id: $userId) { + ...UserDetails + } + posts(userId: $userId) { + id + title + content + } +} +``` + +## 8. Testing Approaches + +**Use `@apollo/client/testing`'s `MockedProvider` for unit and integration tests of components that use Apollo hooks.** This allows you to mock GraphQL operations and control the data returned, ensuring consistent and isolated tests. + +❌ **BAD:** Relying on a live GraphQL API for component tests + +```javascript +// This makes tests slow, flaky, and dependent on external services +render(); +``` + +✅ **GOOD:** Mocking GraphQL responses with `MockedProvider` + +```javascript +import { render, screen, waitFor } from '@testing-library/react'; +import { MockedProvider } from '@apollo/client/testing'; +import { GET_USERS } from './UserList.graphql'; // Import your GraphQL document +import UserList from './UserList'; + +const mocks = [ + { + request: { + query: GET_USERS, + variables: { limit: 10 }, + }, + result: { + data: { + users: [ + { id: '1', name: 'Alice' }, + { id: '2', name: 'Bob' }, + ], + }, + }, + }, +]; + +test('renders user list', async () => { + render( + + + + ); + + expect(screen.getByText(/loading users.../i)).toBeInTheDocument(); + + await waitFor(() => { + expect(screen.getByText('Alice')).toBeInTheDocument(); + expect(screen.getByText('Bob')).toBeInTheDocument(); + }); +}); +``` \ No newline at end of file diff --git a/rules-mdc/apollo-graphql.mdc b/rules-mdc/apollo-graphql.mdc index 56e4e02..898793a 100644 --- a/rules-mdc/apollo-graphql.mdc +++ b/rules-mdc/apollo-graphql.mdc @@ -1,217 +1,42 @@ --- -description: This rule provides comprehensive best practices and coding standards for developing with Apollo GraphQL. It covers schema design, security, performance, testing, and deployment. -globs: *.js,*.jsx,*.ts,*.tsx,*.graphql +description: Definitive guidelines for building robust, performant, and maintainable apollo-graphql applications using modern best practices and tooling. +globs: **/*.{js,jsx} --- -- Always use UV when installing dependencies -- Always use python 3.12 -- Always use classes instead of function +# apollo-graphql Best Practices -# Apollo GraphQL Best Practices +This guide outlines our definitive best practices for developing with Apollo GraphQL, covering both server-side (Apollo Server 5) and client-side (Apollo Client) implementations. Adhering to these rules ensures consistency, performance, and maintainability across our GraphQL ecosystem. -This document provides a comprehensive guide to best practices and coding standards for developing GraphQL APIs and applications using the Apollo ecosystem. +## 1. Schema Design and Organization -## Library Information: -- Name: apollo-graphql -- Tags: web, api, graphql, javascript +Your GraphQL schema is the contract. Design it meticulously, document it thoroughly, and organize it logically. -## 1. Schema Design +### 1.1 Schema-First Development with SDL -- **Clarity and Consistency:** - - Use descriptive naming conventions for types, fields, and arguments (e.g., `getUserById` instead of `getUser`). - - Maintain consistency across the schema in terms of naming and structure. - - Define a clear schema that reflects your business domain and data model. +Always start by defining your schema using Schema Definition Language (SDL). This forces clear API design before implementation. -- **Interfaces and Unions:** - - Implement interfaces and unions for shared features and common data structures. - - Use interfaces to define contracts for types that implement shared behaviors. - - Use unions when a field can return different object types that don't share a common interface. +❌ BAD +```javascript +// Implicit schema definition through resolvers +const resolvers = { + Query: { + users: () => [{ id: '1', name: 'Alice' }], + }, +}; +// Schema is inferred or built programmatically, harder to review +``` -- **Nullability:** - - Every field is nullable by default unless explicitly marked as non-null using `!`. Carefully consider nullability for each field. - - Use non-null types (`!`) only when you can guarantee that the field will always return a value. - - Handle potential errors gracefully and return `null` for nullable fields when appropriate. +✅ GOOD +```graphql +# schema/user.graphql +"""Represents a user in the system.""" +type User { + id: ID! + name: String! + email: String +} -- **Demand-Driven Schema Design:** - - Design your schema to serve client use cases and product requirements. - - Intentionally design your schema to serve client use cases and product requirements. - -- **Avoid Autogenerated Schemas:** - - Avoid autogenerating schemas, especially the fields on the root operation types - -## 2. Security - -- **Disable Introspection in Production:** - - Disable introspection in production environments to prevent unauthorized access to your schema. - - Restrict access to staging environments where introspection is enabled. - -- **Input Validation:** - - Validate all user inputs to prevent injection attacks and data corruption. - - Use custom scalars or directives to enforce validation rules on input types. - - Sanitize and escape user inputs before using them in resolvers. - -- **Authentication and Authorization:** - - Implement robust authentication and authorization mechanisms to protect your API. - - Use industry-standard protocols like OAuth 2.0 or JWT for authentication. - - Implement fine-grained authorization checks at the field level. - - Enforcing authentication and authorization in the router protects your underlying APIs from malicious operations - -- **Rate Limiting and Depth Limiting:** - - Implement rate limiting to prevent abuse and denial-of-service attacks. - - Limit query depth to prevent complex queries from overwhelming your server. - -- **Whitelisting Queries:** - - Consider whitelisting queries to restrict the operations that can be executed against your API. - -- **Obfuscate Error Details:** - - Remove verbose error details from API responses in your production graph. - - Only selectively expose error details to clients in production. - -- **Data Validation and Sanitization:** - - As a schema design best practice, you should deliberately design your schema to serve client use cases and product requirements. - -## 3. Performance Optimization - -- **Batching and Caching:** - - Utilize batching techniques (e.g., DataLoader) to reduce the number of requests to backend data sources. - - Implement caching at different levels (e.g., server-side, client-side) to improve response times. - -- **Pagination:** - - Implement pagination strategies to manage large datasets effectively. - - Use cursor-based pagination for efficient retrieval of paginated data. - -- **N+1 Problem:** - - Use tools like DataLoader to address the N+1 query problem and ensure efficient data fetching. - -- **Server-Side Batching & Caching:** - - GraphQL is designed in a way that allows you to write clean code on the server, where every field on every type has a focused single-purpose function for resolving that value. - -- **Automatic Persisted Queries (APQ):** - - Consider implementing automatic persisted queries (APQ) to optimize network usage and improve security - -## 4. Code Organization and Structure - -- **Directory Structure:** - - src/ - schema/ - types/ - *.graphql - resolvers/ - *.js - dataSources/ - *.js - utils/ - *.js - index.js // Entry point - - -- **File Naming Conventions:** - - Use PascalCase for type definitions (e.g., `UserType.graphql`). - - Use camelCase for resolver functions (e.g., `getUserById.js`). - -- **Module Organization:** - - Organize your code into reusable modules based on functionality (e.g., user management, product catalog). - - Create separate modules for schema definitions, resolvers, and data sources. - -- **Component Architecture:** - - Follow a component-based architecture for building GraphQL applications. - - Create reusable components for common UI elements and data fetching logic. - -- **Code Splitting:** - - Use code splitting to reduce the initial bundle size and improve page load times. - - Consider splitting your application into smaller chunks based on routes or features. - -## 5. Common Patterns and Anti-patterns - -- **Design Patterns:** - - **Data Source Pattern:** Decouple data fetching logic from resolvers using data sources. - - **Schema Stitching:** Combine multiple GraphQL APIs into a single, unified schema. - -- **Recommended Approaches:** - - Use a GraphQL client library (e.g., Apollo Client, Relay) for efficient data fetching and caching. - - Implement custom directives to add additional functionality to your schema. - -- **Anti-patterns:** - - **Over-fetching/Under-fetching:** Avoid returning more or less data than required by the client. - - **Chatty APIs:** Reduce the number of round trips between the client and the server. - - **God Objects:** Avoid creating large, monolithic types with too many fields. - -- **State Management:** - - Use a state management library (e.g., Redux, Zustand, Jotai) to manage client-side state. - - Consider using Apollo Client's local state management features for simple state requirements. - -- **Error Handling:** - - Use a consistent error handling mechanism across your application. - - Return informative error messages to the client. - - Log errors on the server for debugging purposes. - -## 6. Testing Approaches - -- **Unit Testing:** - - Unit test individual resolvers and data sources. - - Mock external dependencies to isolate the code under test. - -- **Integration Testing:** - - Integrate test your GraphQL API with your database and other backend services. - - Use a testing framework like Jest or Mocha for writing integration tests. - -- **End-to-End Testing:** - - Use end-to-end testing to verify the entire application flow. - - Use a testing tool like Cypress or Puppeteer for writing end-to-end tests. - -- **Test Organization:** - - Organize your tests into separate directories based on functionality. - - Use descriptive names for your test files and test cases. - -- **Mocking and Stubbing:** - - Use mocking and stubbing techniques to isolate the code under test and simulate external dependencies. - -## 7. Common Pitfalls and Gotchas - -- **N+1 Problem:** Be aware of the N+1 query problem and use DataLoader or other batching techniques to solve it. -- **Schema Evolution:** Plan for schema evolution and use techniques like adding new fields and deprecating old ones to avoid breaking changes. -- **Performance Bottlenecks:** Monitor your API for performance bottlenecks and use profiling tools to identify slow resolvers. -- **Nullability:** Ensure that non-null fields never return `null` to avoid unexpected errors. - -## 8. Tooling and Environment - -- **Development Tools:** - - Use a GraphQL IDE like GraphiQL or Apollo Studio for exploring and testing your API. - - Use code generation tools to generate types and resolvers from your schema. - -- **Build Configuration:** - - Use a build tool like Webpack or Parcel to bundle your code for production. - - Configure your build tool to optimize your code and reduce bundle size. - -- **Linting and Formatting:** - - Use a linter like ESLint or Prettier to enforce code style and prevent errors. - -- **Deployment:** - - Deploy your GraphQL API to a production environment like AWS Lambda, Google Cloud Functions, or a Node.js server. - - Use a serverless platform for easy scaling and management. - -- **CI/CD Integration:** - - Integrate your GraphQL API with a CI/CD pipeline for automated testing and deployment. - -## 9. Additional Best Practices - -- **Versioning:** While GraphQL promotes continuous evolution, consider versioning your API if you need to make breaking changes. -- **Documentation:** Provide comprehensive documentation for your GraphQL API using tools like GraphQL Docs. -- **Monitoring:** Monitor your GraphQL API for performance and errors using tools like Apollo Studio or New Relic. -- **Error Messages and Notifications:** You can also opt for union types to represent an error and to prompt suggestions to users, though this is a more expensive choice. - -## 10. Global Identification - -- Another way to organize components, besides Pagination, is by using a global identification. Originally proposed on Relay and similar to URIs, this method has become a more general good practice though it is not considered mandatory — especially if you are not planning on supporting Relay in your application - -## 11. Rate Limiting - -- Like any other web API, setting limits is a good strategy to avoid, for example, an overload of requests per minute. There are a few ways this can be done in GraphQL - -## 12. Authentication and Authorization - -- Often interchanged in their meaning, authentication is the act of determining who a user is and whether they are logged in or not. Authorization, on the other hand, is the act of determining if a user is allowed to do an action or see something. - -## 13. Safelisting with Persisted queries - -- Beyond operation limits, GraphOS enables first-party apps to register trusted operations in a persisted query list ( PQL) or safelist. \ No newline at end of file +type Query { + """Fetches a list of all users.""" + users: [User!]! + """Fetches a single user by their ID.""" + user(id: ID \ No newline at end of file diff --git a/rules-mdc/asp-net.mdc b/rules-mdc/asp-net.mdc index 460e7cc..676a5e8 100644 --- a/rules-mdc/asp-net.mdc +++ b/rules-mdc/asp-net.mdc @@ -1,363 +1,358 @@ --- -description: This rule file provides best practices and coding standards for ASP.NET Core development, covering various aspects from code organization to security and performance optimization. -globs: *.cs +description: This guide provides opinionated, actionable best practices for building high-performance, maintainable, and secure ASP.NET Core 9+ applications, focusing on modern C# patterns and common pitfalls. +globs: **/* --- -# ASP.NET Core Best Practices and Coding Standards +# asp-net Best Practices -This document outlines recommended best practices and coding standards for developing ASP.NET Core applications. Following these guidelines will help ensure code clarity, maintainability, performance, and security. +This document outlines the definitive best practices for developing ASP.NET Core applications within our team. Adhere to these guidelines to ensure consistent, performant, and maintainable backend services. ## 1. Code Organization and Structure -### Directory Structure Best Practices: +Organize your projects by feature or bounded context, not by technical layer. This improves cohesion and reduces coupling. -A well-defined directory structure is crucial for maintaining a scalable and organized ASP.NET Core project. Here's a suggested structure: +### ✅ GOOD: Feature-First Organization +```csharp +// Project structure for a "Product" feature +src/ +├── MyProject.Api/ +│ ├── Program.cs +│ ├── Features/ +│ │ ├── Products/ +│ │ │ ├── ProductEndpoints.cs // Minimal API definitions +│ │ │ ├── ProductController.cs // API Controller (if used) +│ │ │ ├── GetProduct.cs // Request/Response DTOs, Handler (e.g., MediatR) +│ │ │ ├── CreateProduct.cs +│ │ │ └── ProductService.cs // Feature-specific business logic +│ ├── Common/ // Shared infrastructure, middleware, extensions +│ │ ├── Filters/ +│ │ ├── Middleware/ +│ │ └── Extensions/ +├── MyProject.Application/ // Application-specific services, interfaces, DTOs +│ ├── Interfaces/ +│ ├── Services/ +│ └── DTOs/ +├── MyProject.Domain/ // Core domain entities, value objects, interfaces +├── MyProject.Infrastructure/ // Data access (EF Core), external services +│ ├── Data/ +│ ├── Repositories/ +│ └── ExternalServices/ +└── MyProject.Tests/ // Unit and Integration tests +``` -ProjectName/ -├── src/ -│ ├── ProjectName.Web/ -│ │ ├── Controllers/ -│ │ ├── Models/ -│ │ ├── Views/ -│ │ ├── Pages/ (for Razor Pages) -│ │ ├── wwwroot/ -│ │ ├── appsettings.json -│ │ ├── Program.cs -│ │ ├── Startup.cs -│ ├── ProjectName.Data/ -│ │ ├── Models/ -│ │ ├── Contexts/ -│ │ ├── Repositories/ -│ │ ├── Migrations/ -│ ├── ProjectName.Services/ -│ │ ├── Interfaces/ -│ │ ├── Implementations/ -│ ├── ProjectName.Models/ (if different from Data Models) -├── tests/ -│ ├── ProjectName.UnitTests/ -│ ├── ProjectName.IntegrationTests/ -├── artifacts/ -├── .editorconfig -├── .gitignore -├── ProjectName.sln +### ❌ BAD: Layer-First Organization +```csharp +// Avoid this structure for larger applications +src/ +├── MyProject.Api/ +│ ├── Controllers/ // All controllers here +│ ├── Services/ // All services here +│ ├── Repositories/ // All repositories here +│ └── DTOs/ // All DTOs here +``` -* **src:** Contains the source code of the application. -* **ProjectName.Web:** The main web application project. This can also be named `API` for web API projects. -* **Controllers:** Contains ASP.NET Core controllers. -* **Models:** Contains view models and other data transfer objects (DTOs) specific to the web layer. -* **Views:** Contains Razor views (.cshtml files). -* **Pages:** Contains Razor Pages (if using Razor Pages model). -* **wwwroot:** Contains static files like CSS, JavaScript, and images. -* **ProjectName.Data:** Contains data access logic, Entity Framework Core contexts, and models representing database entities. -* **Models (Data):** Defines entity models that correspond to database tables. -* **Contexts:** Contains the DbContext class. -* **Repositories:** Contains repositories for data access. -* **Migrations:** Contains Entity Framework Core migrations. -* **ProjectName.Services:** Contains business logic and application services. -* **Interfaces:** Defines interfaces for services. -* **Implementations:** Contains concrete implementations of service interfaces. -* **ProjectName.Models:** (Optional) Contains domain models that are shared across multiple layers. This layer promotes separation of concerns if your data layer models should not be exposed at the API or Web layer. -* **tests:** Contains unit and integration tests. -* **ProjectName.UnitTests:** Contains unit tests. -* **ProjectName.IntegrationTests:** Contains integration tests. -* **artifacts:** Contains build artifacts. -* **.editorconfig:** Defines code style rules. -* **.gitignore:** Specifies intentionally untracked files that Git should ignore. -* **ProjectName.sln:** The solution file. +## 2. API Design: Minimal APIs vs. API Controllers -### File Naming Conventions: +**Always prefer Minimal APIs** for new endpoints due to their simplicity and directness. Use API Controllers only when you require advanced features like automatic model binding from multiple sources, built-in validation attributes, or complex attribute routing that Minimal APIs don't easily provide. -* **Classes:** PascalCase (e.g., `UserController`, `ProductService`) -* **Interfaces:** IPascalCase (e.g., `IProductService`, `IUserRepository`) -* **Methods:** PascalCase (e.g., `GetProduct`, `CreateUser`) -* **Variables (local):** camelCase (e.g., `productName`, `userId`) -* **Parameters:** camelCase (e.g., `productId`, `userName`) -* **Constants:** PascalCase (e.g., `DefaultPageSize`, `MaxRetries`) -* **Enums:** PascalCase (e.g., `OrderStatus`, `UserRole`) -* **Namespaces:** PascalCase, mirroring the directory structure (e.g., `ProjectName.Web.Controllers`, `ProjectName.Services.Implementations`) -* **Files:** Match the class/interface name (e.g., `UserController.cs`, `IProductService.cs`) +### ✅ GOOD: Minimal API for Simplicity -### Module Organization: +```csharp +// Program.cs or dedicated endpoint file +app.MapGet("/products/{id}", async (Guid id, IProductService service) => +{ + var product = await service.GetProductByIdAsync(id); + return product is not null ? Results.Ok(product) : Results.NotFound(); +}) +.WithName("GetProductById") +.Produces(StatusCodes.Status200OK) +.Produces(StatusCodes.Status404NotFound); +``` -* **Feature-based Modules:** Group related functionality into modules based on features (e.g., `Authentication`, `Products`, `Orders`). Each feature can have its own folder within the `src` directory, containing its own controllers, models, services, and data access components. This enhances cohesion and reduces coupling. -* **Vertical Slices:** Organize modules around specific use cases or user stories. Each slice contains all the code necessary to implement a particular feature, from the UI to the data access layer. This promotes faster development and easier maintenance. +### ✅ GOOD: API Controller for Complex Scenarios -### Component Architecture: +```csharp +[ApiController] +[Route("api/[controller]")] +public class OrdersController : ControllerBase +{ + private readonly IOrderService _orderService; -* **Layered Architecture:** Divide the application into layers (e.g., Presentation, Application, Domain, Infrastructure) to separate concerns and promote testability. Each layer has a specific responsibility and interacts with other layers through well-defined interfaces. -* **Microservices:** For larger applications, consider breaking down the application into smaller, independent microservices. Each microservice handles a specific business capability and can be deployed and scaled independently. + public OrdersController(IOrderService orderService) => _orderService = orderService; -### Code Splitting Strategies: - -* **Feature-based Splitting:** Split code based on features, loading modules only when they are needed. This can improve initial load time and reduce memory consumption. -* **Route-based Splitting:** Load code only when a specific route is accessed. This is especially useful for large applications with many routes. -* **On-Demand Loading:** Load code dynamically when a user interacts with a specific component. This can improve perceived performance and reduce the initial download size. - -## 2. Common Patterns and Anti-patterns - -### Design Patterns: - -* **Dependency Injection (DI):** Use the built-in DI container to manage dependencies and promote loose coupling. -* **Repository Pattern:** Abstract data access logic behind repositories to improve testability and maintainability. Avoid exposing EF Core `IQueryable` outside of the repository. -* **Unit of Work Pattern:** Encapsulate multiple operations into a single transaction to ensure data consistency. -* **CQRS (Command Query Responsibility Segregation):** Separate read and write operations into separate models to optimize performance and scalability. -* **Mediator Pattern:** Decouple components by routing messages through a central mediator. Libraries like MediatR are excellent for this. -* **Specification Pattern:** Encapsulate complex query logic into reusable specification objects. -* **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable. - -### Recommended Approaches for Common Tasks: - -* **Configuration:** Use the `IOptions` pattern to access configuration settings in a strongly-typed manner. -* **Logging:** Use the `ILogger` interface for logging. Configure logging providers in `appsettings.json` and leverage structured logging. -* **Exception Handling:** Implement global exception handling middleware to handle unhandled exceptions and return appropriate error responses. -* **Data Validation:** Use data annotations and the `ModelState` property for validating user input. Implement custom validation attributes for complex validation rules. -* **Asynchronous Programming:** Use `async` and `await` for I/O-bound operations to avoid blocking threads. -* **HTTP Requests:** Utilize `HttpClientFactory` for creating and managing `HttpClient` instances. -* **Background Tasks:** Use hosted services or background worker services for running long-running tasks asynchronously. - -### Anti-patterns and Code Smells: - -* **Tight Coupling:** Avoid tight coupling between components. Use interfaces and dependency injection to promote loose coupling. -* **God Classes:** Avoid creating large classes with too many responsibilities. Break down large classes into smaller, more manageable classes. -* **Shotgun Surgery:** Avoid making changes to multiple classes when a single responsibility changes. This indicates poor separation of concerns. -* **Primitive Obsession:** Avoid using primitive types to represent domain concepts. Create value objects to encapsulate domain logic and validation rules. -* **Feature Envy:** Avoid classes that access the data of another class more than their own. Move the method to the class where the data resides. -* **Sync-over-Async:** Avoid using `Task.Wait()` or `Task.Result` in asynchronous methods, as this can lead to thread pool starvation. Always use `await`. -* **Ignoring Exceptions:** Avoid catching exceptions and not logging or handling them appropriately. -* **Magic Strings/Numbers:** Avoid hardcoding values directly in the code. Use constants or configuration settings instead. -* **Returning raw Entities:** Do not expose EF Core entities directly to the client. Create DTOs or View Models to represent the data that needs to be returned. - -### State Management Best Practices: - -* **Stateless Controllers:** Design controllers to be stateless. Avoid storing state in controller fields. -* **Session State:** Use session state sparingly. Session state can impact scalability. Consider using a distributed cache for session state. -* **Cookies:** Use cookies for storing small amounts of non-sensitive data. Be mindful of cookie size limits and security concerns. -* **TempData:** Use TempData for passing data between redirects. TempData is stored in session or cookies. -* **Caching:** Use caching (memory cache, distributed cache, response caching) to improve performance and reduce database load. Cache aggressively, but invalidate appropriately. - -### Error Handling Patterns: - -* **Global Exception Handling:** Implement global exception handling middleware to catch unhandled exceptions and return consistent error responses. -* **Exception Filters:** Use exception filters to handle exceptions at the controller level. -* **Try-Catch Blocks:** Use try-catch blocks for handling expected exceptions. -* **Problem Details:** Return problem details (RFC 7807) in error responses to provide more detailed information about the error. -* **Idempotency:** Design APIs to be idempotent where possible, so that retries are safe. + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task CreateOrder([FromBody] CreateOrderRequest request) + { + if (!ModelState.IsValid) return BadRequest(ModelState); + var order = await _orderService.CreateOrderAsync(request); + return CreatedAtAction(nameof(GetOrderById), new { id = order.Id }, order); + } +} +``` ## 3. Performance Considerations -### Optimization Techniques: +### 3.1. Avoid Blocking Calls -* **Asynchronous Programming:** Use `async` and `await` for I/O-bound operations. -* **Caching:** Implement caching strategies to reduce database load and improve response times. -* **Response Compression:** Enable response compression to reduce the size of HTTP responses. -* **Minification and Bundling:** Minify and bundle CSS and JavaScript files to reduce the number of HTTP requests and improve load times. -* **Image Optimization:** Optimize images to reduce their file size without sacrificing quality. -* **Database Optimization:** Optimize database queries and indexing to improve data access performance. -* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead. -* **HTTP/2:** Use HTTP/2 for improved performance and reduced latency. -* **Precompiled Views:** Precompile Razor views to improve startup time. -* **Use Span and Memory:** Utilize these types for efficient memory manipulation, reducing allocations and copies. -* **Object Pooling:** Employ object pooling for frequently created and destroyed objects to reduce garbage collection overhead. `ArrayPool` is especially effective for large arrays. -* **Optimize LINQ Usage:** Use LINQ effectively, avoiding unnecessary iterations and allocations. Utilize `AsNoTracking()` for read-only queries and be mindful of client-side evaluation. -* **Use System.Text.Json:** Prefer `System.Text.Json` over `Newtonsoft.Json` where possible, as it offers better performance and is designed for UTF-8 text. +**Always use `async/await`** for I/O-bound operations (database, network, file system). Never block the thread pool. -### Memory Management: +### ❌ BAD: Blocking Calls -* **Minimize Object Allocations:** Reduce object allocations, especially in hot code paths. Consider using object pooling and value types. -* **Avoid Large Objects:** Avoid allocating large objects (>= 85,000 bytes) as they are stored on the large object heap and can cause performance issues. -* **Dispose of Resources:** Dispose of disposable resources (e.g., database connections, file streams) properly to prevent memory leaks. -* **Garbage Collection:** Understand how the garbage collector works and avoid patterns that trigger frequent garbage collections. +```csharp +// Synchronous I/O in an async context +public Product GetProduct(Guid id) +{ + // This blocks the calling thread while waiting for the DB + return _dbContext.Products.Find(id); +} -### Rendering Optimization: +// Blocking on an async task +var result = SomeAsyncTask().Result; // Blocks! +SomeAsyncTask().Wait(); // Blocks! +``` -* **Partial Views:** Use partial views to reuse code and reduce code duplication. -* **View Components:** Use view components to encapsulate complex rendering logic. -* **Tag Helpers:** Use tag helpers to create reusable UI components. -* **Client-Side Rendering:** Consider using client-side rendering frameworks (e.g., React, Angular, Vue.js) for complex UI interactions. -* **Lazy Loading:** Implement lazy loading for images and other assets to improve initial load time. +### ✅ GOOD: Asynchronous I/O -### Bundle Size Optimization: +```csharp +public async Task GetProductAsync(Guid id) +{ + return await _dbContext.Products.FindAsync(id); +} -* **Tree Shaking:** Use tree shaking to remove unused code from JavaScript bundles. -* **Code Splitting:** Split code into smaller chunks that can be loaded on demand. -* **Compression:** Compress JavaScript and CSS files using gzip or Brotli. -* **Dead Code Elimination:** Remove unused code from the application. +// Correctly awaiting an async task +var result = await SomeAsyncTask(); +``` -### Lazy Loading Strategies: +### 3.2. Return Paged Collections -* **Lazy Loading of Images:** Load images only when they are visible in the viewport. -* **Lazy Loading of Modules:** Load modules only when they are needed. -* **Lazy Loading of Data:** Load data only when it is requested. +**Always paginate large collections** to prevent `OutOfMemoryException` and slow responses. -## 4. Security Best Practices +### ❌ BAD: Returning Large Collections Unpaged -### Common Vulnerabilities and Prevention: +```csharp +app.MapGet("/products", async (IProductService service) => +{ + var allProducts = await service.GetAllProductsAsync(); // Potentially huge + return Results.Ok(allProducts); +}); +``` -* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks. -* **Cross-Site Scripting (XSS):** Sanitize user input and encode output to prevent XSS attacks. -* **Cross-Site Request Forgery (CSRF):** Use anti-forgery tokens to prevent CSRF attacks. -* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data and functionality. -* **Clickjacking:** Protect against clickjacking attacks by using the X-Frame-Options header. -* **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks. -* **Open Redirects:** Validate redirect URLs to prevent open redirect vulnerabilities. -* **Insecure Direct Object References (IDOR):** Implement proper authorization checks to prevent unauthorized access to resources. +### ✅ GOOD: Paging Collections -### Input Validation: +```csharp +app.MapGet("/products", async (int page = 1, int pageSize = 20, IProductService service) => +{ + var pagedProducts = await service.GetPagedProductsAsync(page, pageSize); + return Results.Ok(pagedProducts); +}); +``` -* **Server-Side Validation:** Always validate user input on the server-side. -* **Whitelisting:** Use whitelisting to allow only valid characters and data formats. -* **Data Annotations:** Use data annotations to validate model properties. -* **Custom Validation:** Implement custom validation attributes for complex validation rules. -* **Sanitization:** Sanitize user input to remove potentially harmful characters. +### 3.3. Minimize Large Object Allocations -### Authentication and Authorization: +Cache frequently used large objects. Avoid creating large objects (>= 85KB) in hot code paths to reduce GC pressure. Use `ArrayPool` for large arrays. -* **Authentication Schemes:** Choose an appropriate authentication scheme (e.g., cookies, JWT, OAuth2) based on the application requirements. -* **Authorization Policies:** Use authorization policies to define access control rules. -* **Role-Based Access Control (RBAC):** Implement RBAC to grant users access to specific resources based on their roles. -* **Claims-Based Authorization:** Use claims-based authorization to grant users access to specific resources based on their claims. -* **Secure Password Storage:** Use strong password hashing algorithms (e.g., bcrypt, Argon2) to store passwords securely. -* **Multi-Factor Authentication (MFA):** Implement MFA to enhance security. -* **Implement OWASP Recommendations:** Follow the OWASP (Open Web Application Security Project) guidelines for secure authentication and authorization. +## 4. Dependency Injection (DI) -### Data Protection: +**Always use ASP.NET Core's built-in DI container.** Register services with the correct lifetime. -* **Encryption:** Encrypt sensitive data at rest and in transit. -* **Data Protection API:** Use the Data Protection API to protect sensitive data. -* **Key Management:** Implement proper key management practices to protect encryption keys. -* **HTTPS:** Use HTTPS to encrypt communication between the client and the server. +* **Singleton**: For stateless services, configuration objects, or services that manage shared state. +* **Scoped**: For services tied to a single HTTP request (e.g., `DbContext`, `IUnitOfWork`). +* **Transient**: For lightweight services that should be new for every injection (rarely needed for typical backend services). -### Secure API Communication: +### ✅ GOOD: Correct Service Lifetimes -* **API Keys:** Use API keys to authenticate API clients. -* **OAuth 2.0:** Use OAuth 2.0 to authorize API clients. -* **JWT (JSON Web Tokens):** Use JWT for secure API authentication and authorization. -* **Rate Limiting:** Implement rate limiting to prevent API abuse. -* **Input Validation:** Implement proper input validation on the server-side to prevent injection attacks. -* **Output Encoding:** Encode API responses to prevent XSS attacks. -* **CORS (Cross-Origin Resource Sharing):** Configure CORS to allow only authorized domains to access the API. +```csharp +public void ConfigureServices(IServiceCollection services) +{ + // Caching service can be shared across the app + services.AddSingleton(); -## 5. Testing Approaches + // Database context is scoped to the request + services.AddDbContext(options => /* ... */, ServiceLifetime.Scoped); + services.AddScoped(); -### Unit Testing: + // Business logic service, typically scoped + services.AddScoped(); +} +``` -* **Test-Driven Development (TDD):** Write unit tests before writing the code. -* **Arrange, Act, Assert (AAA):** Follow the AAA pattern in unit tests. -* **Mocking:** Use mocking frameworks (e.g., Moq, NSubstitute) to isolate the code being tested. -* **Code Coverage:** Aim for high code coverage. -* **Focus on Business Logic:** Unit test the business logic of the application. +## 5. Security Best Practices -### Integration Testing: +### 5.1. Authentication and Authorization -* **Test Data Access:** Test the interaction between the application and the database. -* **Test External Services:** Test the interaction between the application and external services. -* **Use a Test Database:** Use a separate test database for integration tests. -* **Seed the Database:** Seed the test database with test data before running integration tests. +**Always secure your API endpoints.** Use JWT Bearer tokens for API authentication. Define and enforce authorization policies. -### End-to-End Testing: +### ✅ GOOD: Policy-Based Authorization -* **Test the Entire Application Flow:** Test the entire application flow from the user interface to the database. -* **Use Automation Tools:** Use automation tools (e.g., Selenium, Cypress) to automate end-to-end tests. -* **Test in a Production-Like Environment:** Test in a production-like environment to ensure that the application works as expected in production. +```csharp +// Program.cs +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => { /* ... configure JWT ... */ }); +builder.Services.AddAuthorization(options => +{ + options.AddPolicy("CanManageProducts", policy => + policy.RequireRole("Admin", "ProductManager")); +}); -### Test Organization: +// Minimal API endpoint +app.MapPost("/products", async (CreateProductRequest request, IProductService service) => +{ + // ... +}).RequireAuthorization("CanManageProducts"); -* **Separate Test Projects:** Create separate test projects for unit tests, integration tests, and end-to-end tests. -* **Organize Tests by Feature:** Organize tests by feature or module. -* **Use Naming Conventions:** Use consistent naming conventions for test classes and methods. +// Controller action +[Authorize(Policy = "CanManageProducts")] +[HttpPost] +public async Task CreateProduct([FromBody] CreateProductRequest request) +{ /* ... */ } +``` -### Mocking and Stubbing: +### 5.2. Input Validation -* **Use Mocking Frameworks:** Use mocking frameworks to create mock objects and stubs. -* **Mock Dependencies:** Mock external dependencies to isolate the code being tested. -* **Verify Interactions:** Verify that the code being tested interacts with its dependencies as expected. -* **Avoid Over-Mocking:** Avoid mocking too many dependencies. Focus on mocking external dependencies and complex objects. +**Always validate all incoming request data.** Use Data Annotations or FluentValidation for robust validation. -## 6. Common Pitfalls and Gotchas +### ✅ GOOD: DTO Validation -### Frequent Mistakes: +```csharp +public record CreateProductRequest( + [Required] [StringLength(100)] string Name, + [Range(0.01, 10000.00)] decimal Price, + [Url] string? ImageUrl +); -* **Incorrect Dependency Injection Configuration:** Incorrectly configuring dependency injection can lead to runtime errors. -* **Not Handling Exceptions Properly:** Not handling exceptions properly can lead to application crashes. -* **Blocking Calls:** Making blocking calls in asynchronous methods can lead to thread pool starvation. -* **Incorrect Data Validation:** Incorrect data validation can lead to security vulnerabilities and data corruption. -* **Over-Engineering:** Over-engineering the application can lead to unnecessary complexity. -* **Premature Optimization:** Optimizing the application too early can lead to wasted effort and code that is difficult to maintain. -* **Ignoring Security Best Practices:** Ignoring security best practices can lead to security vulnerabilities. -* **Not Writing Tests:** Not writing tests can lead to code that is difficult to maintain and prone to errors. -* **Leaking Database Connections:** Failing to properly dispose of database connections can exhaust connection resources and cause performance issues. -* **Using Sync over Async:** Blocking asynchronous operations can lead to thread pool starvation and performance degradation. -* **Not using HttpClientFactory correctly:** Improper disposal of `HttpClient` instances leads to socket exhaustion. Always use `HttpClientFactory`. +// In Minimal API or Controller, validation is often automatic with [ApiController] +// For Minimal APIs, you might explicitly check if not using a framework that handles it: +app.MapPost("/products", (CreateProductRequest request) => +{ + var validationContext = new ValidationContext(request); + var validationResults = new List(); + if (!Validator.TryValidateObject(request, validationContext, validationResults, true)) + { + return Results.ValidationProblem(validationResults.ToDictionary(r => r.MemberNames.First(), r => new[] { r.ErrorMessage })); + } + // ... process valid request +}); +``` -### Edge Cases: +## 6. Error Handling -* **Handling Null Values:** Handle null values properly to prevent null reference exceptions. -* **Handling Empty Collections:** Handle empty collections properly to prevent unexpected behavior. -* **Handling Large Data Sets:** Handle large data sets efficiently to prevent performance issues. -* **Handling Time Zones:** Handle time zones correctly to prevent data inconsistencies. +**Implement global exception handling middleware.** Provide consistent, developer-friendly error responses without exposing sensitive details. -### Version-Specific Issues: +### ✅ GOOD: Global Exception Handler -* **Breaking Changes:** Be aware of breaking changes between different versions of ASP.NET Core. -* **Deprecated Features:** Be aware of deprecated features and plan to migrate to newer features. -* **Performance Improvements:** Take advantage of performance improvements in newer versions of ASP.NET Core. -* **Security Patches:** Stay up-to-date with security patches to protect against vulnerabilities. +```csharp +// Program.cs +app.UseExceptionHandler(appBuilder => +{ + appBuilder.Run(async context => + { + var exceptionHandlerPathFeature = context.Features.Get(); + var exception = exceptionHandlerPathFeature?.Error; -### Compatibility Concerns: + var problemDetails = new ProblemDetails + { + Status = StatusCodes.Status500InternalServerError, + Title = "An error occurred while processing your request.", + Detail = "Please try again later. If the problem persists, contact support.", + Instance = context.Request.Path + }; -* **.NET Framework vs .NET Core:** Be aware of the differences between .NET Framework and .NET Core and choose the appropriate framework for the application. -* **Operating System Compatibility:** Ensure that the application is compatible with the target operating system. -* **Browser Compatibility:** Ensure that the application is compatible with the target browsers. + // Log the exception details for internal monitoring + var logger = context.RequestServices.GetRequiredService>(); + logger.LogError(exception, "Unhandled exception for request {Path}", context.Request.Path); -### Debugging Strategies: + context.Response.StatusCode = problemDetails.Status.Value; + context.Response.ContentType = "application/problem+json"; + await context.Response.WriteAsJsonAsync(problemDetails); + }); +}); +``` -* **Logging:** Use logging to track down errors and unexpected behavior. -* **Debugging Tools:** Use debugging tools (e.g., Visual Studio debugger) to step through the code and examine variables. -* **Profiling Tools:** Use profiling tools to identify performance bottlenecks. -* **Remote Debugging:** Use remote debugging to debug applications running on remote servers. -* **Diagnostic Tools:** Use diagnostic tools (e.g., Application Insights) to monitor the health and performance of the application. +## 7. Structured Logging -## 7. Tooling and Environment +**Always use structured logging** to enable easy querying and analysis of logs. Prefer `ILogger` for context-specific logging. -### Recommended Development Tools: +### ✅ GOOD: Structured Logging -* **Visual Studio:** A comprehensive IDE for developing ASP.NET Core applications. -* **Visual Studio Code:** A lightweight and versatile code editor for developing ASP.NET Core applications. -* **.NET CLI:** A command-line tool for creating, building, and running ASP.NET Core applications. -* **NuGet Package Manager:** A package manager for managing dependencies in ASP.NET Core applications. -* **Postman:** A tool for testing APIs. -* **Fiddler:** A tool for debugging HTTP traffic. +```csharp +public class ProductService : IProductService +{ + private readonly ILogger _logger; -### Build Configuration: + public ProductService(ILogger logger) => _logger = logger; -* **Use a Build Server:** Use a build server (e.g., Azure DevOps, Jenkins) to automate the build process. -* **Configure Build Configurations:** Configure build configurations (e.g., Debug, Release) to optimize the application for different environments. -* **Use NuGet Package Restore:** Use NuGet package restore to automatically download dependencies during the build process. -* **Version Control:** Use version control (e.g., Git) to track changes to the code. + public async Task CreateProductAsync(CreateProductRequest request) + { + _logger.LogInformation("Creating product {ProductName} with price {ProductPrice}", request.Name, request.Price); + // ... + _logger.LogInformation("Product {ProductId} created successfully.", newProduct.Id); + return newProductDto; + } +} +``` -### Linting and Formatting: +### ❌ BAD: Unstructured Logging -* **.editorconfig:** Use an .editorconfig file to define code style rules. -* **Code Analyzers:** Use code analyzers to enforce code style rules and detect potential errors. -* **StyleCop:** Use StyleCop to enforce coding style guidelines. -* **ReSharper:** Use ReSharper to improve code quality and productivity. -* **Format on Save:** Configure the IDE to format code on save. +```csharp +_logger.LogInformation("Creating product with name: " + request.Name + " and price: " + request.Price); +``` -### Deployment Best Practices: +## 8. Testing Approaches -* **Choose a Hosting Environment:** Choose an appropriate hosting environment (e.g., Azure, AWS, on-premises server) based on the application requirements. -* **Configure Application Settings:** Configure application settings (e.g., connection strings, API keys) for the production environment. -* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server. -* **Enable Logging:** Enable logging to track errors and unexpected behavior in the production environment. -* **Monitor the Application:** Monitor the health and performance of the application in the production environment. -* **Use a Deployment Pipeline:** Automate the deployment process with a CI/CD pipeline. -* **Consider Containerization:** Deploy your application using containers (e.g., Docker) to ensure consistency across environments. -* **Implement Health Checks:** Use ASP.NET Core's built-in health checks endpoint to monitor the health of your application. +**Prioritize unit and integration tests.** -### CI/CD Integration: +* **Unit Tests**: Focus on isolated business logic (services, domain models). Mock all external dependencies. +* **Integration Tests**: Verify API endpoints, middleware, and database interactions. Use `WebApplicationFactory` for in-memory testing. -* **Use a CI/CD Pipeline:** Use a CI/CD pipeline (e.g., Azure DevOps, GitHub Actions, GitLab CI) to automate the build, test, and deployment process. -* **Automate Testing:** Automate unit tests, integration tests, and end-to-end tests in the CI/CD pipeline. -* **Automate Deployment:** Automate the deployment process in the CI/CD pipeline. -* **Implement Rollbacks:** Implement rollbacks to quickly revert to a previous version of the application if there are problems with the new deployment. \ No newline at end of file +### ✅ GOOD: Unit Test Example + +```csharp +public class ProductServiceTests +{ + [Fact] + public async Task CreateProductAsync_ValidRequest_ReturnsProductDto() + { + // Arrange + var mockRepo = new Mock(); + mockRepo.Setup(r => r.AddAsync(It.IsAny())).ReturnsAsync(new Product { Id = Guid.NewGuid(), Name = "Test", Price = 10m }); + var service = new ProductService(mockRepo.Object, Mock.Of>()); + var request = new CreateProductRequest("Test Product", 10.00m, null); + + // Act + var result = await service.CreateProductAsync(request); + + // Assert + Assert.NotNull(result); + Assert.Equal("Test Product", result.Name); + mockRepo.Verify(r => r.AddAsync(It.IsAny()), Times.Once); + } +} +``` + +### ✅ GOOD: Integration Test Example + +```csharp +public class ProductsApiTests : IClassFixture> +{ + private readonly HttpClient _client; + + public ProductsApiTests(CustomWebApplicationFactory factory) + { + _client = factory.CreateClient(); + } + + [Fact] + public async Task GetProducts_ReturnsSuccessAndCorrectContentType() + { + // Act + var response = await _client.GetAsync("/products"); + + // Assert + response.EnsureSuccessStatusCode(); // Status Code 200-299 + Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + } +} +``` \ No newline at end of file diff --git a/rules-mdc/astro.mdc b/rules-mdc/astro.mdc index a258e57..87a917b 100644 --- a/rules-mdc/astro.mdc +++ b/rules-mdc/astro.mdc @@ -1,176 +1,437 @@ --- -description: This rule provides comprehensive best practices and coding standards for developing Astro projects. It covers code organization, performance, security, testing, and common pitfalls. -globs: *.astro +description: This guide provides opinionated, actionable best practices for building high-performance Astro applications, focusing on zero-JavaScript by default, island architecture, and type safety. +globs: **/*.{js,jsx,ts,tsx,astro} --- -# Astro Library Best Practices and Coding Standards +# Astro Best Practices -This document outlines the recommended best practices and coding standards for developing Astro projects to ensure maintainability, performance, and security. +Astro is a "disappearing" framework designed for shipping zero JavaScript by default, adding interactivity only where needed. Our team leverages Astro for its unparalleled performance and developer experience, especially for content-focused sites. Adhere to these guidelines to maintain a consistent, high-performing, and maintainable codebase. ## 1. Code Organization and Structure -### 1.1 Project Structure +Maintain a predictable and logical file structure for easy navigation and scaling. -- **`src/` Directory:** This directory contains the core source code of your Astro project. - - **`src/pages/`:** This directory is crucial for routing. Every `.astro`, `.md`, or `.mdx` file in this directory automatically becomes a route. Use a clear and consistent naming convention for your pages (e.g., `about.astro`, `blog/index.astro`, `blog/[slug].astro`). - - **`src/components/`:** Store reusable UI components in this directory. Organize components into subdirectories based on their functionality or feature area (e.g., `src/components/Header/`, `src/components/Card/`). - - **`src/layouts/`:** Layouts define the overall structure of your pages (e.g., header, footer, navigation). Use layouts to maintain a consistent look and feel across your website. - - **`src/content/`:** (Recommended for content-driven sites) Use the Content Collections feature to manage structured content like blog posts, documentation, or product listings. Define schemas for your content types to ensure data consistency. - - **`src/styles/`:** Store global styles and CSS variables in this directory. Consider using CSS Modules or a CSS-in-JS solution for component-specific styling. - - **`src/scripts/`:** Place client-side JavaScript files in this directory. Use modules and avoid polluting the global scope. - - **`src/assets/`:** Store static assets like images, fonts, and other media files in this directory. -- **`public/` Directory:** This directory contains static assets that don't need processing, such as `robots.txt`, `favicon.ico`, and other files that should be served directly. Avoid placing images that require optimization in this directory; use the `src/assets/` directory instead. -- **`astro.config.mjs`:** This file contains the Astro configuration options, including integrations, build settings, and more. Keep this file well-organized and documented. -- **`.env`:** Store environment variables in this file. Use a library like `dotenv` to load environment variables into your application. +### 1.1 Standard Project Structure -### 1.2 Component Design +Always scaffold new projects with the official Astro starter and maintain the following structure: -- **Atomic Design Principles:** Consider using Atomic Design principles to structure your components into atoms, molecules, organisms, templates, and pages. This promotes reusability and maintainability. -- **Single Responsibility Principle:** Each component should have a single, well-defined responsibility. Avoid creating large, complex components that do too much. -- **Props and Slots:** Use props to pass data to components and slots to allow components to accept children. Define prop types using TypeScript to ensure type safety. +``` +src/ +├── components/ # Reusable UI components (Astro or UI framework islands) +│ ├── ui/ # Generic, framework-agnostic components +│ └── react/ # React-specific components +├── content/ # Markdown/MDX files for Content Collections +├── layouts/ # Base page layouts +├── pages/ # Top-level routes +├── styles/ # Global CSS, utility classes, Tailwind config +├── env.d.ts # Global type declarations +└── astro.config.ts # Type-safe Astro configuration +``` -## 2. Common Patterns and Anti-patterns +### 1.2 Naming Conventions -### 2.1 UI Framework Integration +- **Astro Components (`.astro`):** Use `kebab-case`. +- **UI Framework Components (e.g., React `.jsx`, `.tsx`):** Use `PascalCase`. +- **Pages (`.astro`):** Use `kebab-case` for file names. -- **Island Architecture:** Embrace Astro's island architecture to minimize JavaScript and improve performance. Only hydrate interactive components. -- **Client Directives:** Use `client:load`, `client:idle`, `client:visible`, `client:media`, and `client:only` directives appropriately to control when components are hydrated. Avoid over-hydrating components. -- **Framework Component Composition:** Compose components from different frameworks (React, Vue, Svelte, etc.) within the same Astro page. This allows you to leverage the strengths of different frameworks. -- **Passing Props and Children:** Pass props and children to framework components from Astro components. Use named slots to organize children. -- **Anti-pattern: Mixing Astro and Framework Components:** Do not import `.astro` components directly into UI framework components (e.g., `.jsx` or `.svelte`). Use slots to pass static content from Astro components to framework components. +❌ BAD +```astro + +
...
+``` +```jsx +// src/components/Mycard.jsx +export default function Mycard() { return
...
; } +``` -### 2.2 Data Fetching +✅ GOOD +```astro + +
...
+``` +```jsx +// src/components/react/MyCard.tsx +export default function MyCard() { return
...
; } +``` -- **`fetch` API:** Use the `fetch` API to fetch data from external sources or internal APIs. Handle errors appropriately. -- **Content Collections API:** Use the Content Collections API to manage structured content like blog posts or documentation. Define schemas for your content types. -- **CMS Integration:** Integrate with a headless CMS like Hygraph, Contentful, or Strapi to manage content. Use the CMS's API to fetch data and display it on your website. -- **GraphQL:** When using a CMS that supports GraphQL (like Hygraph), use GraphQL queries to fetch only the data you need. This can improve performance and reduce data transfer. +### 1.3 TypeScript Configuration -### 2.3 Routing +Leverage TypeScript throughout the codebase for type safety, even in `.astro` components. -- **File-Based Routing:** Use Astro's file-based routing to create routes automatically. Follow a consistent naming convention for your pages. -- **Dynamic Routes:** Use dynamic routes (e.g., `[slug].astro`) to handle variable segments in the URL. Access the route parameters using `Astro.params`. -- **Nested Routes:** Use nested folders within `src/pages/` to create nested routes. -- **Anti-pattern: Overly Complex Routing:** Avoid creating overly complex routing structures. Keep your routes simple and intuitive. +**`tsconfig.json`** +```json +{ + "extends": "astro/tsconfigs/strict", + "compilerOptions": { + "verbatimModuleSyntax": true, // Enforce explicit type imports + "plugins": [ + { + "name": "@astrojs/ts-plugin" // Essential for editor support + } + ], + "paths": { + "@components/*": ["./src/components/*"], + "@layouts/*": ["./src/layouts/*"], + "@content/*": ["./src/content/*"], + "@styles/*": ["./src/styles/*"] + } + }, + "include": [".astro/types.d.ts", "**/*"], + "exclude": ["dist"] +} +``` -### 2.4 Styling +**`astro.config.ts`** +Always use a `.ts` extension for your Astro configuration for type safety. +```ts +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; // Example integration -- **Scoped CSS:** Use scoped CSS within Astro components to avoid style conflicts. This ensures that component styles are isolated. -- **Global Styles:** Use global styles for site-wide styling. Store global styles in `src/styles/global.css`. -- **CSS Frameworks:** Use CSS frameworks like Tailwind CSS, Bootstrap, or Materialize to speed up development and maintain a consistent look and feel. Install the appropriate integration for your chosen CSS framework. -- **CSS Modules:** Consider using CSS Modules for component-specific styling. CSS Modules generate unique class names to avoid naming collisions. +export default defineConfig({ + integrations: [react()], + // ... other config +}); +``` + +## 2. Component Architecture: Astro Islands + +Astro's "islands" architecture is fundamental. Prioritize static HTML and introduce interactivity only when and where needed. + +### 2.1 Astro Components for Static Content & Layouts + +Use `.astro` files for pages, layouts, and components that are primarily static or orchestrate other components. They render to HTML on the server and ship zero JavaScript by default. + +```astro +--- +import Layout from '@layouts/Layout.astro'; +import MyReactCounter from '@components/react/MyReactCounter'; +--- + + +
+

Hello, Astro!

+

This is static content.

+ + +
+
+``` + +### 2.2 UI Framework Components for Interactivity (Islands) + +Use React, Vue, Svelte, etc., components *only* for interactive UI pieces. These are your "islands." + +```tsx +// src/components/react/MyReactCounter.tsx +import { useState } from 'react'; + +export default function MyReactCounter() { + const [count, setCount] = useState(0); + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +### 2.3 Client Directives for Selective Hydration + +Explicitly tell Astro *when* to hydrate an island. Avoid `client:load` unless the component is critical for initial interaction. + +❌ BAD (Hydrates immediately, even if not needed) +```astro + +``` + +✅ GOOD (Hydrates only when visible, saving bandwidth and CPU) +```astro + +``` ## 3. Performance Considerations -### 3.1 Minimizing JavaScript +Astro's primary strength is performance. Ensure every decision aligns with shipping minimal JavaScript. -- **Static-First Architecture:** Embrace Astro's static-first architecture to minimize JavaScript and improve performance. Render as much as possible as static HTML. -- **Island Architecture:** Only hydrate interactive components. Avoid over-hydrating components. -- **Code Splitting:** Use code splitting to break up your JavaScript into smaller chunks. This can improve initial load times. -- **Lazy Loading:** Use lazy loading for images and other assets that are not immediately visible. This can improve initial load times. +### 3.1 Zero JavaScript by Default -### 3.2 Image Optimization +Always assume components are static unless explicitly told otherwise. If a component doesn't need client-side JS, don't add it. -- **Astro's `` Component:** Use Astro's built-in `` component to optimize images. The `` component automatically optimizes images, resizes them, and generates responsive versions. -- **Image Formats:** Use modern image formats like WebP to reduce file sizes. Use AVIF for even better compression, where supported. -- **Compression:** Compress images to reduce file sizes. Use tools like ImageOptim or TinyPNG. -- **Lazy Loading:** Use lazy loading for images that are not immediately visible. -- **Responsive Images:** Use responsive images to serve different image sizes based on the user's screen size. +❌ BAD (Unnecessary client-side script for a simple toggle) +```astro + + +``` -### 3.3 Font Optimization +✅ GOOD (Pure CSS or server-rendered state for simple interactions) +```astro + + +``` -- **Web Font Formats:** Use modern web font formats like WOFF2. These formats offer better compression and performance. -- **Font Loading:** Use font loading strategies to avoid blocking rendering. Consider using `font-display: swap`. -- **Preloading:** Preload important fonts to improve loading times. +### 3.2 Optimize Client Directives -### 3.4 Caching +- **`client:visible`**: Default for most interactive components that appear lower on the page. +- **`client:idle`**: For non-critical interactivity that can wait until the main thread is free. +- **`client:load`**: Only for critical, above-the-fold interactions (e.g., main navigation, search bar). +- **`client:media={query}`**: For components that only become interactive on specific screen sizes. -- **Browser Caching:** Configure browser caching to cache static assets like images, fonts, and JavaScript files. This can improve performance for returning users. -- **CDN:** Use a Content Delivery Network (CDN) to serve static assets from geographically distributed servers. This can improve performance for users around the world. +### 3.3 Image Optimization -## 4. Security Best Practices +Use Astro's built-in image optimization for responsive, performant images. -### 4.1 Input Validation +```astro +--- +import { Image } from 'astro:assets'; +import myImage from '@assets/my-image.jpg'; // Import local images +--- +A descriptive alt text +``` -- **Validate User Input:** Validate all user input to prevent injection attacks and other security vulnerabilities. Use server-side validation in addition to client-side validation. -- **Sanitize User Input:** Sanitize user input to remove potentially malicious code. Use a library like DOMPurify to sanitize HTML. +## 4. Common Pitfalls and Anti-patterns -### 4.2 Cross-Site Scripting (XSS) +Avoid these common mistakes that undermine Astro's performance benefits. -- **Escape Output:** Escape all output to prevent XSS attacks. Use Astro's built-in escaping mechanisms or a library like Handlebars.js. -- **Content Security Policy (CSP):** Implement a Content Security Policy (CSP) to control the resources that the browser is allowed to load. This can help prevent XSS attacks. +### 4.1 Over-Hydration -### 4.3 Cross-Site Request Forgery (CSRF) +Do not wrap entire pages or large sections in a single interactive component. This defeats the purpose of islands. -- **CSRF Tokens:** Use CSRF tokens to protect against CSRF attacks. Generate a unique CSRF token for each user session and include it in all forms. +❌ BAD (Treating Astro like an SPA) +```astro + +``` -### 4.4 Authentication and Authorization +✅ GOOD (Granular islands) +```astro +
...
+ +
+ + +
+
...
+``` -- **Secure Authentication:** Use secure authentication mechanisms to protect user accounts. Use a library like Passport.js or Auth0. -- **Authorization:** Implement authorization to control access to resources. Use roles and permissions to define what users are allowed to do. +### 4.2 Unnecessary Client-Side Scripts -### 4.5 Dependency Management +Avoid ` +``` -### 4.6 Environment Variables +✅ GOOD (Explicitly inline or part of an island) +```astro + +``` -- **Store Secrets Securely:** Store secrets like API keys and database passwords in environment variables. Do not hardcode secrets in your code. -- **Avoid Committing `.env`:** Never commit your `.env` file to version control. Use a `.gitignore` file to exclude it. +## 5. State Management -## 5. Testing Approaches +Keep state management simple and localized. Astro is not an SPA framework; most "state" should be server-rendered or localized to islands. -### 5.1 Unit Testing +### 5.1 Local Island State -- **Test Individual Components:** Write unit tests to test individual components in isolation. Use a testing framework like Jest or Mocha. -- **Mock Dependencies:** Mock dependencies to isolate components during testing. +For interactivity within an island, use the UI framework's native state management (e.g., React `useState`, Svelte stores). -### 5.2 Integration Testing +```tsx +// src/components/react/ThemeToggle.tsx +import { useState } from 'react'; -- **Test Component Interactions:** Write integration tests to test how components interact with each other. Use a testing framework like Cypress or Playwright. +export default function ThemeToggle() { + const [theme, setTheme] = useState('light'); + const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light'); -### 5.3 End-to-End Testing + return ( + + ); +} +``` -- **Test User Flows:** Write end-to-end tests to test complete user flows. Use a testing framework like Cypress or Playwright. +### 5.2 Global State (Minimal) -### 5.4 Accessibility Testing +For truly global, cross-island state (e.g., user authentication status), consider: +1. **Server-side data:** Fetch global data in the Astro component frontmatter and pass it down as props. This is the preferred method. +2. **Lightweight context/store within a shared island:** If client-side global state is unavoidable, use a minimal library like Zustand or Jotai within a single, shared UI framework component that wraps other islands. -- **Automated Accessibility Testing:** Use automated accessibility testing tools to identify accessibility issues. Use a tool like axe-core. -- **Manual Accessibility Testing:** Perform manual accessibility testing to ensure that your website is accessible to users with disabilities. Use a screen reader to test your website. +❌ BAD (Heavy global state management for a content site) +```tsx +// src/components/react/MyApp.tsx (large, complex context provider) + +
+ +