diff --git a/rules-mdc/ai_ml/cloud_inference/modal.mdc b/rules-mdc/ai_ml/cloud_inference/modal.mdc new file mode 100644 index 0000000..fbf976f --- /dev/null +++ b/rules-mdc/ai_ml/cloud_inference/modal.mdc @@ -0,0 +1,174 @@ +--- +description: This rule provides comprehensive best practices for developing with the modal library, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers towards writing maintainable, efficient, and secure modal applications. +globs: **/*.py +--- +- **Purpose and Clarity:** Ensure the modal's title clearly states its purpose and use concise headers. Use power words to grab attention (e.g., 'New,' 'Exclusive,' 'You'). +- **User Control:** Modals should only be used for critical information and should not disrupt the user experience. Provide visible options for users to close the modal easily. Use a dark overlay to guide attention. +- **Accessibility:** Test modals with assistive technologies to ensure they are accessible to all users. Limit the use of system-initiated modals to avoid user frustration. Adhere to WAI-ARIA guidelines for modal implementation. + +## 1. Code Organization and Structure + +- **Directory Structure:** + - `modal.py`: Core module containing the `modal` class and related functions. + - `modal/`: A directory containing submodules: + - `modal/config.py`: Configuration settings for modal deployment and runtime. + - `modal/stub.py`: Definition and handling of modal stubs for local development. + - `modal/secret.py`: Secure handling of secrets required by modal applications. + - `modal/image.py`: Image definition and building processes. + - `modal/volume.py`: Management of persistent volumes for data storage. +- **File Naming Conventions:** Use descriptive names (e.g., `modal_api.py`, `modal_utils.py`). Follow PEP 8 guidelines for Python file names. +- **Module Organization:** Group related functionality into modules (e.g., `modal.network`, `modal.security`). +- **Component Architecture:** + - Decouple components for reusability and testability. + - Use dependency injection to manage dependencies between components. +- **Code Splitting Strategies:** Break down large files into smaller, more manageable modules. Consider lazy-loading modules that are not immediately needed. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Singleton:** Use sparingly, typically for global configuration objects. + - **Factory:** For creating modal objects with complex initialization logic. + - **Observer:** For handling events triggered by modal state changes. +- **Recommended Approaches:** + - Use context managers (`with` statement) for resource management. + - Employ decorators for adding functionality (e.g., caching, logging). +- **Anti-patterns:** + - Avoid global state, as it can lead to unpredictable behavior. + - Avoid deeply nested code, which is hard to read and maintain. + - Avoid hardcoding configuration values. +- **State Management:** + - Use immutable data structures for state to prevent unintended modifications. + - Implement clear state transition logic. + - Consider using a state management library like `modal.aio_libs.AioState` for complex scenarios. +- **Error Handling:** + - Use try-except blocks to handle potential exceptions. + - Log errors with sufficient context for debugging. + - Raise custom exceptions for specific error conditions. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - Use caching to avoid redundant computations. + - Profile code to identify performance bottlenecks. + - Optimize database queries. +- **Memory Management:** + - Use generators to process large datasets in chunks. + - Explicitly release resources when they are no longer needed. + - Be mindful of memory leaks. +- **Rendering Optimization:** (If applicable for UI elements within modal). + - Minimize DOM manipulations. + - Use efficient rendering algorithms. +- **Bundle Size Optimization:** + - Remove unused code. + - Use code minification and compression. + - Leverage tree shaking to eliminate dead code. +- **Lazy Loading:** Defer loading non-critical resources until they are needed. + +## 4. Security Best Practices + +- **Common Vulnerabilities:** + - Input validation vulnerabilities (e.g., SQL injection, cross-site scripting). + - Authentication and authorization vulnerabilities. + - Data breaches due to insecure storage. +- **Input Validation:** + - Validate all user inputs before processing them. + - Use input sanitization techniques to prevent injection attacks. +- **Authentication and Authorization:** + - Use strong authentication mechanisms (e.g., multi-factor authentication). + - Implement role-based access control. + - Securely store and manage user credentials using `modal.Secret`. +- **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use secure communication protocols (e.g., HTTPS). + - Comply with relevant data privacy regulations (e.g., GDPR, CCPA). +- **Secure API Communication:** + - Use API keys or tokens for authentication. + - Rate limit API requests to prevent abuse. + - Implement proper error handling to avoid leaking sensitive information. + +## 5. Testing Approaches + +- **Unit Testing:** + - Test individual functions and classes in isolation. + - Use mocking to isolate dependencies. + - Write test cases for different scenarios, including edge cases. +- **Integration Testing:** + - Test the interaction between different components. + - Verify that data flows correctly between modules. +- **End-to-end Testing:** + - Test the entire application workflow. + - Simulate user interactions to verify functionality. +- **Test Organization:** + - Organize tests into separate directories based on the module being tested. + - Use descriptive test names. +- **Mocking and Stubbing:** + - Use mocking to replace external dependencies with controlled substitutes. + - Use stubs to provide predefined responses for external calls. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes:** + - Incorrectly handling asynchronous operations. + - Not properly closing resources (e.g., files, network connections). + - Ignoring error conditions. +- **Edge Cases:** + - Handling empty or invalid input data. + - Dealing with network timeouts and failures. + - Ensuring compatibility with different operating systems and environments. +- **Version-Specific Issues:** + - Be aware of breaking changes in newer versions of the library. + - Check the release notes for known issues and workarounds. +- **Compatibility Concerns:** + - Ensure compatibility with different Python versions. + - Consider cross-platform compatibility. +- **Debugging Strategies:** + - Use debuggers to step through code and inspect variables. + - Use logging to track program execution and identify errors. + - Use assertions to verify expected conditions. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - IDE: VS Code, PyCharm. + - Debugger: pdb, ipdb. + - Profiler: cProfile. +- **Build Configuration:** + - Use a build system like `setuptools` or `poetry` to manage dependencies and create distributable packages. +- **Linting and Formatting:** + - Use linters (e.g., pylint, flake8) to enforce coding style guidelines. + - Use formatters (e.g., black, autopep8) to automatically format code. +- **Deployment Best Practices:** + - Use containerization (e.g., Docker) to create consistent and reproducible environments. + - Use infrastructure-as-code (e.g., Terraform, CloudFormation) to automate infrastructure provisioning. +- **CI/CD Integration:** + - Use CI/CD pipelines to automatically build, test, and deploy code changes. + - Integrate linters and formatters into the CI/CD pipeline. + +## 8. modal Specific Best Practices + +- **Efficient Use of Images:** + - Use pre-built base images whenever possible to reduce build times. + - Leverage caching mechanisms in `modal.Image` to avoid rebuilding unchanged images. +- **Data Serialization:** + - Be aware of the data serialization overhead when passing data between modal functions. + - Use efficient serialization formats like `pickle` or `protobuf` for large datasets. +- **Secret Management:** + - Use `modal.Secret` to securely manage sensitive information like API keys and passwords. + - Avoid hardcoding secrets in your code. +- **Concurrency and Parallelism:** + - Utilize `modal.method.call` and `modal.Queue` for concurrent and parallel processing. + - Understand the limitations of Python's Global Interpreter Lock (GIL) when writing multi-threaded code. +- **Resource Limits:** + - Be aware of resource limits (CPU, memory, disk space) imposed by the modal platform. + - Optimize your code to stay within these limits. +- **Monitoring and Logging:** + - Implement monitoring and logging to track the performance of your modal applications. + - Use tools like Prometheus and Grafana for visualization. +- **Cold Starts:** + - Be aware of cold start times when invoking modal functions for the first time. + - Optimize your code to reduce cold start times. +- **Version Control and Rollbacks:** + - Always use version control (e.g., Git) to track changes to your code. + - Implement rollback mechanisms to quickly revert to previous versions in case of errors. + +By following these best practices, developers can build robust, scalable, and secure modal applications. \ No newline at end of file diff --git a/rules-mdc/ai_ml/gpu_computing/cuda.mdc b/rules-mdc/ai_ml/gpu_computing/cuda.mdc new file mode 100644 index 0000000..6f41bb3 --- /dev/null +++ b/rules-mdc/ai_ml/gpu_computing/cuda.mdc @@ -0,0 +1,165 @@ +--- +description: Enforces CUDA coding standards, performance optimizations, and best practices to ensure efficient and maintainable GPU-accelerated code. This rule provides guidance on code organization, memory management, error handling, and more. +globs: **/*.cu +--- +- # CUDA Best Practices Guide + This document outlines best practices for CUDA development, focusing on code organization, performance optimization, and common pitfalls. It is based on NVIDIA's CUDA C++ Best Practices Guide and expands on it with more detailed recommendations. + +- ## 1. Code Organization and Structure + + - ### 1.1 Directory Structure + - Organize your CUDA project with a clear directory structure. A common structure includes: + + project_root/ + ├── src/ + │ ├── kernels/ # CUDA kernel source files (.cu) + │ ├── host/ # Host-side code (.cpp, .h) + │ ├── common/ # Shared utility code (.h, .cpp) + │ └── include/ # Header files + ├── build/ # Build output directory + ├── data/ # Input and output data + ├── tests/ # Unit and integration tests + └── CMakeLists.txt # CMake build configuration + + + - ### 1.2 File Naming Conventions + - Use descriptive file names that clearly indicate the purpose of the file. + - Kernel files: `kernel_name.cu` (e.g., `matrix_multiply.cu`) + - Host files: `module_name.cpp`, `module_name.h` (e.g., `data_loader.cpp`, `data_loader.h`) + - Common files: `utility.h`, `error_handling.cpp` + + - ### 1.3 Module Organization + - Divide your code into logical modules based on functionality. + - Use namespaces to avoid naming conflicts and improve code organization. + - Encapsulate CUDA kernel launches within well-defined functions or classes. + + - ### 1.4 Component Architecture + - Design your application with a modular component architecture to facilitate code reuse and maintainability. + - Decouple host-side code from CUDA kernels as much as possible. + - Use abstraction layers to hide CUDA-specific details from higher-level components. + + - ### 1.5 Code Splitting Strategies + - Split large CUDA kernels into smaller, more manageable functions. + - Use separate files for different kernels or related functionalities. + - Consider using template metaprogramming to generate specialized kernels at compile time. + +- ## 2. Common Patterns and Anti-patterns + + - ### 2.1 Design Patterns Specific to CUDA + - **CUDA Stream Pattern:** Use CUDA streams to overlap data transfers and kernel execution. + - **Memory Pooling Pattern:** Implement memory pools to reduce the overhead of frequent memory allocations and deallocations. + - **Tiling Pattern:** Divide large data structures into smaller tiles to improve data locality and cache utilization. + - **Reduction Pattern:** Use parallel reduction algorithms to efficiently compute aggregate values. + + - ### 2.2 Recommended Approaches for Common Tasks + - **Error Handling:** Use the CUDA error handling API to check for errors after each CUDA function call. + - **Memory Allocation:** Use `cudaMalloc`, `cudaFree`, and related functions for memory allocation on the device. + - **Data Transfer:** Use `cudaMemcpy` to transfer data between host and device memory. + - **Kernel Launch:** Use the `<<>>` syntax to launch CUDA kernels. + + - ### 2.3 Anti-patterns and Code Smells to Avoid + - **Synchronous Memory Transfers:** Avoid blocking memory transfers that stall the GPU. + - **Excessive Global Memory Access:** Minimize global memory access by using shared memory and registers. + - **Thread Divergence:** Avoid conditional branches that cause threads within a warp to execute different code paths. + - **Uncoalesced Memory Access:** Ensure that threads access memory in a coalesced manner to maximize memory bandwidth. + - **CPU-GPU Synchronization Bottlenecks:** Minimize the number of synchronization points between the CPU and GPU. + + - ### 2.4 State Management Best Practices + - Encapsulate CUDA context and device management within a dedicated class or module. + - Avoid global state variables that can lead to unexpected behavior and concurrency issues. + - Use RAII (Resource Acquisition Is Initialization) to ensure that CUDA resources are properly released. + + - ### 2.5 Error Handling Patterns + - Check the return value of every CUDA function call and handle errors appropriately. + - Use `cudaGetLastError` to retrieve the last error that occurred on the device. + - Implement custom error handling routines for specific error conditions. + - Log error messages with file name, line number, and a descriptive error message. + +- ## 3. Performance Considerations + + - ### 3.1 Optimization Techniques + - **Kernel Fusion:** Combine multiple kernels into a single kernel to reduce kernel launch overhead and data transfers. + - **Loop Unrolling:** Unroll loops to improve instruction-level parallelism. + - **Instruction Scheduling:** Optimize instruction scheduling to reduce pipeline stalls. + - **Constant Memory Usage:** Store frequently accessed read-only data in constant memory. + - **Texture Memory Usage:** Utilize texture memory for spatially coherent data access patterns. + + - ### 3.2 Memory Management + - **Minimize Data Transfers:** Reduce the amount of data transferred between host and device. + - **Asynchronous Data Transfers:** Use asynchronous memory transfers with CUDA streams to overlap computation and communication. + - **Zero-Copy Memory:** Use zero-copy memory to directly access host memory from the GPU (use with caution due to performance implications). + - **Pinned Memory (Page-Locked Memory):** Use pinned memory for efficient asynchronous data transfers. + + - ### 3.3 CUDA Profiler + - Use the NVIDIA Nsight Systems and Nsight Compute profilers to identify performance bottlenecks. + +- ## 4. Security Best Practices + + - ### 4.1 Common Vulnerabilities and How to Prevent Them + - **Buffer Overflows:** Carefully validate input sizes to prevent buffer overflows in CUDA kernels. + - **Integer Overflows:** Check for potential integer overflows in calculations involving data sizes and indices. + - **Race Conditions:** Protect shared data with appropriate synchronization mechanisms (e.g., atomic operations, mutexes) to prevent race conditions. + - **Injection Attacks:** Sanitize input data to prevent injection attacks that could execute arbitrary code on the GPU. + + - ### 4.2 Input Validation + - Validate all input data received by CUDA kernels to ensure that it is within the expected range and format. + - Check for invalid or malicious input that could lead to security vulnerabilities. + + - ### 4.3 Data Protection Strategies + - Encrypt sensitive data stored on the GPU to protect it from unauthorized access. + - Use secure communication channels to transfer data between host and device. + +- ## 5. Testing Approaches + + - ### 5.1 Unit Testing Strategies + - Write unit tests to verify the correctness of individual CUDA kernels and host-side functions. + - Use a testing framework like Google Test or Catch2 to automate the testing process. + - Mock CUDA runtime functions to isolate kernels during testing. + - Use a separate compilation approach to test individual kernel functions. + + - ### 5.2 Integration Testing + - Perform integration tests to verify the interaction between different components of the CUDA application. + - Test data transfers between host and device, kernel launches, and error handling. + + - ### 5.3 Test Organization + - Organize your tests into a logical directory structure. + - Use descriptive test names that clearly indicate the purpose of each test. + - Group related tests together into test suites. + + - ### 5.4 Mocking and Stubbing + - Use mocking and stubbing techniques to isolate components during testing and simulate different scenarios. + - Mock CUDA runtime functions to control the behavior of the GPU during testing. + +- ## 6. Common Pitfalls and Gotchas + + - ### 6.1 Frequent Mistakes Developers Make + - **Ignoring CUDA Error Codes:** Always check the return values of CUDA functions to ensure that they succeed. + - **Incorrect Grid and Block Dimensions:** Choose appropriate grid and block dimensions for your kernels. + - **Shared Memory Bank Conflicts:** Avoid shared memory bank conflicts to maximize memory bandwidth. + - **Thread Divergence:** Minimize thread divergence within warps to improve performance. + - **Uncoalesced Memory Access:** Ensure that threads access memory in a coalesced manner. + + - ### 6.2 Version-Specific Issues + - Be aware of compatibility issues between different CUDA versions. + - Use conditional compilation to handle version-specific code. + + - ### 6.3 Debugging Strategies + - Use the NVIDIA Nsight Systems and Nsight Compute debuggers to debug CUDA code. + - Insert print statements to track the execution flow and variable values. + - Use the `cudaDeviceSynchronize` function to force the GPU to complete all operations before proceeding. + +- ## 7. Tooling and Environment + + - ### 7.1 Recommended Development Tools + - **CUDA Toolkit:** Install the latest version of the CUDA Toolkit from NVIDIA's website. + - **NVIDIA Nsight Systems and Nsight Compute:** Use the Nsight profilers to analyze and optimize CUDA code. + - **CMake:** Use CMake to manage the build process. + - **Integrated Development Environment (IDE):** Use an IDE such as Visual Studio or Eclipse with CUDA support. + + - ### 7.2 Build Configuration + - Use CMake to generate build files for your target platform. + - Configure the CUDA compiler (nvcc) with appropriate optimization flags. + + - ### 7.3 Linting and Formatting + - Use a linter such as clang-tidy to enforce coding standards and identify potential errors. + - Use a code formatter such as clang-format to ensure consistent code formatting. \ No newline at end of file diff --git a/rules-mdc/ai_ml/llm_tools/huggingface.mdc b/rules-mdc/ai_ml/llm_tools/huggingface.mdc new file mode 100644 index 0000000..6e1f418 --- /dev/null +++ b/rules-mdc/ai_ml/llm_tools/huggingface.mdc @@ -0,0 +1,342 @@ +--- +description: This rule provides guidelines for best practices when working with the Hugging Face Transformers library, covering code organization, performance, testing, security, and common pitfalls. It emphasizes community standards and maintainability. +globs: **/*.py +--- +# Hugging Face Transformers Library Best Practices + +This document outlines best practices and coding standards for using the Hugging Face Transformers library. It covers various aspects, including code organization, performance, testing, security, and common pitfalls. + +## Philosophy: Embrace the Single Model File Policy + +- **Single Model File Policy:** Prioritize having all the code for a model's forward pass within a single file. While it might seem to contradict the DRY (Don't Repeat Yourself) principle, this improves readability and accessibility, especially for newcomers. This makes it easier to understand the entire model architecture without navigating through multiple files. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +While the Transformers library promotes the single model file policy, good project-level organization is still crucial. A typical project structure might look like this: + + +my_project/ +├── data/ +│ ├── raw/ +│ ├── processed/ +│ └── ... +├── models/ +│ ├── modeling_bert.py # Example: BERT model definition +│ ├── ... +├── scripts/ +│ ├── train.py +│ ├── evaluate.py +│ ├── preprocess.py +│ └── ... +├── utils/ +│ ├── data_utils.py +│ ├── model_utils.py +│ └── ... +├── tests/ +│ ├── test_models.py +│ ├── test_data_utils.py +│ └── ... +├── notebooks/ # optional +│ ├── exploration.ipynb +│ └── ... +├── requirements.txt +├── pyproject.toml +└── README.md + + +- **`data/`:** Stores raw and processed datasets. +- **`models/`:** Contains model definitions (adhering to the single model file policy). +- **`scripts/`:** Holds training, evaluation, and preprocessing scripts. +- **`utils/`:** Includes utility functions for data handling, model management, etc. +- **`tests/`:** Contains unit, integration, and end-to-end tests. +- **`notebooks/`:** (Optional) Jupyter notebooks for experimentation. + +### 1.2 File Naming Conventions + +- Use descriptive and consistent file names. +- For model files, follow the naming convention `modeling_.py` (e.g., `modeling_bert.py`). +- For utility files, use `*_utils.py` (e.g., `data_utils.py`). +- Use lowercase letters and underscores for file names (snake_case). + +### 1.3 Module Organization + +- Keep modules focused and avoid creating overly large modules. Each module should have a clear responsibility. +- Import necessary modules within functions or classes to improve readability and avoid unnecessary dependencies at the module level. +- Use relative imports within the project structure (e.g., `from . import data_utils`) to avoid conflicts and improve portability. + +### 1.4 Component Architecture + +- Design models as modular components. While adhering to the single model file policy, the internal structure of the model can be highly modular. Use classes to encapsulate different parts of the model (e.g., embedding layer, attention mechanism, feedforward network). +- Each component should have a well-defined interface. +- Leverage inheritance when appropriate to share common functionality between similar components. + +### 1.5 Code Splitting Strategies + +- For extremely large models, consider splitting the model definition into multiple files, but maintain a clear entry point that encapsulates the entire model. A primary file should import and orchestrate the other components. +- Consider splitting preprocessing and postprocessing logic into separate modules to improve readability and maintainability. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to Hugging Face + +- **Configuration-Driven Design:** Use `PretrainedConfig` objects to define model parameters. This allows for easy configuration and sharing of model architectures. +- **Tokenizers and Pipelines:** Leverage the built-in tokenizers and pipelines for efficient text processing. Understand how to customize them for specific tasks. +- **Model Cards:** Create comprehensive model cards that document the model's architecture, training data, evaluation metrics, and intended use cases. This is crucial for reproducibility and transparency. + +### 2.2 Recommended Approaches for Common Tasks + +- **Loading Pre-trained Models:** Use `AutoModel` and `AutoTokenizer` classes to automatically load the appropriate model and tokenizer based on the model name. + + python + from transformers import AutoModelForSequenceClassification, AutoTokenizer + + model_name = "bert-base-uncased" + model = AutoModelForSequenceClassification.from_pretrained(model_name) + tokenizer = AutoTokenizer.from_pretrained(model_name) + + +- **Fine-tuning Models:** Use the `Trainer` class for efficient fine-tuning. Customize the training loop when necessary for advanced control. + + python + from transformers import Trainer, TrainingArguments + + training_args = TrainingArguments( + output_dir="./results", + evaluation_strategy="epoch", + num_train_epochs=3 + ) + + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset + ) + + trainer.train() + + +- **Inference:** Use pipelines for simple inference tasks or write custom inference loops for more control. + + python + from transformers import pipeline + + classifier = pipeline("sentiment-analysis") + result = classifier("This is a great movie!") + + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **Ignoring `model_max_length`:** When initializing tokenizers and models, be mindful of the `model_max_length` parameter. Ensure that input sequences are properly truncated or padded to avoid errors or performance issues. +- **Hardcoding Paths:** Avoid hardcoding file paths. Use relative paths or environment variables to make the code more portable. +- **Lack of Documentation:** Write clear and concise documentation for all functions, classes, and modules. This is especially important given the single model file policy, as comprehensive inline documentation becomes critical. +- **Over-Complicating Model Definitions:** Keep model definitions as simple as possible while still meeting the requirements. Avoid unnecessary complexity. +- **Ignoring Warnings:** Pay attention to warnings raised by the Transformers library. They often indicate potential issues. + +### 2.4 State Management Best Practices + +- Avoid global variables. Encapsulate state within classes or functions. +- Use immutable data structures when possible to prevent accidental modifications. +- Manage model weights carefully. Load and save weights using the `state_dict` method. + + python + # Save model weights + torch.save(model.state_dict(), "model.pth") + + # Load model weights + model.load_state_dict(torch.load("model.pth")) + + +### 2.5 Error Handling Patterns + +- Use `try...except` blocks to handle potential exceptions, such as file not found errors or invalid input data. +- Provide informative error messages to help users understand the cause of the error. +- Use logging to record errors and debug information. + + python + import logging + + logging.basicConfig(level=logging.INFO) + + try: + model = AutoModelForSequenceClassification.from_pretrained("invalid-model") + except OSError as e: + logging.error(f"Failed to load model: {e}") + + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Mixed Precision Training:** Use mixed precision training (e.g., using `torch.cuda.amp` in PyTorch) to reduce memory usage and improve training speed. +- **Gradient Accumulation:** Use gradient accumulation to simulate larger batch sizes when memory is limited. +- **Quantization:** Quantize models to reduce their size and improve inference speed. +- **ONNX Runtime:** Convert models to ONNX format and use the ONNX Runtime for faster inference. + +### 3.2 Memory Management + +- Delete unused variables and tensors to free up memory. +- Use `torch.no_grad()` during inference to disable gradient calculations and reduce memory usage. +- Consider using techniques like gradient checkpointing to reduce memory usage during training, especially for very large models. + +### 3.3 Rendering Optimization (If Applicable) + +- If the application involves rendering model outputs (e.g., text generation), optimize the rendering process to minimize latency and improve user experience. +- Use efficient text rendering libraries. +- Cache rendered outputs when possible. + +### 3.4 Bundle Size Optimization (If Applicable) + +- If the application is deployed as a web application or mobile app, optimize the bundle size to reduce download times. +- Use code splitting to load only the necessary code for each feature. +- Use minification and compression to reduce the size of JavaScript and CSS files. + +### 3.5 Lazy Loading Strategies + +- Load models and data lazily to reduce startup time and memory usage. +- Use generators to process large datasets in chunks. +- Only load the parts of the model that are needed for the current task. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **Prompt Injection:** Be aware of prompt injection attacks, where malicious users craft inputs that can manipulate the model's behavior. Implement input validation and sanitization techniques to mitigate this risk. +- **Data Poisoning:** Protect against data poisoning attacks by carefully vetting training data sources. +- **Model Stealing:** Implement measures to protect model weights from being stolen. Consider using encryption or access controls. + +### 4.2 Input Validation + +- Validate all inputs to ensure that they are within the expected range and format. +- Sanitize inputs to remove potentially harmful characters or code. +- Use regular expressions to enforce input constraints. + +### 4.3 Authentication and Authorization Patterns + +- Implement authentication to verify the identity of users. +- Use authorization to control access to resources based on user roles. +- Store credentials securely using encryption and hashing. + +### 4.4 Data Protection Strategies + +- Encrypt sensitive data at rest and in transit. +- Use access controls to restrict access to data. +- Anonymize or pseudonymize data to protect user privacy. + +### 4.5 Secure API Communication + +- Use HTTPS to encrypt communication between the client and the server. +- Use API keys or tokens to authenticate requests. +- Implement rate limiting to prevent abuse. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- Write unit tests for all individual functions, classes, and modules. +- Use a testing framework like `pytest` or `unittest`. +- Test edge cases and boundary conditions. + +### 5.2 Integration Testing + +- Write integration tests to verify the interaction between different components of the system. +- Test the flow of data through the system. +- Use mocks and stubs to isolate components during testing. + +### 5.3 End-to-end Testing + +- Write end-to-end tests to verify the entire system from end to end. +- Simulate user interactions to test the system's functionality. +- Use a testing framework like `Selenium` or `Cypress` for web applications. + +### 5.4 Test Organization + +- Organize tests into separate files or directories based on the component being tested. +- Use descriptive names for test functions and classes. +- Keep tests concise and focused. + +### 5.5 Mocking and Stubbing + +- Use mocks and stubs to isolate components during testing. +- Mock external dependencies, such as API calls or database connections. +- Use a mocking library like `unittest.mock` or `pytest-mock`. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Incorrect Tokenization:** Using the wrong tokenizer or not properly handling special tokens can lead to inaccurate results. +- **Oversized Inputs:** Forgetting to truncate or pad input sequences to the model's maximum length can cause errors or performance issues. +- **Incorrect Device Placement:** Running models on the CPU when a GPU is available can significantly slow down training and inference. +- **Ignoring Data Preprocessing:** Failing to properly preprocess data (e.g., cleaning, normalizing) can negatively impact model performance. + +### 6.2 Edge Cases to be Aware Of + +- **Rare Words:** Handle rare or out-of-vocabulary words gracefully. +- **Long Sequences:** Models may struggle with extremely long sequences. +- **Adversarial Examples:** Models can be fooled by adversarial examples. + +### 6.3 Version-Specific Issues + +- Be aware of breaking changes in new versions of the Transformers library. +- Check the release notes for details on any changes that may affect your code. +- Use version pinning in `requirements.txt` or `pyproject.toml` to ensure that your code runs with the correct version of the library. + +### 6.4 Compatibility Concerns + +- Ensure that your code is compatible with the target hardware and software environment. +- Test your code on different platforms and configurations. +- Use conditional imports to handle different dependencies. + +### 6.5 Debugging Strategies + +- Use logging to track the flow of execution and identify errors. +- Use a debugger to step through the code and inspect variables. +- Use print statements to output intermediate values. +- Use a profiler to identify performance bottlenecks. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **IDE:** Visual Studio Code, PyCharm +- **Version Control:** Git +- **Package Manager:** pip, conda, uv +- **Testing Framework:** pytest +- **Linting:** pylint, flake8 +- **Formatting:** black, autopep8 + +### 7.2 Build Configuration + +- Use `requirements.txt` or `pyproject.toml` to manage dependencies. +- Use a build system like `Make` or `Poetry` to automate the build process. +- Create a virtual environment for each project to isolate dependencies. + +### 7.3 Linting and Formatting + +- Use a linter to enforce code style guidelines. +- Use a formatter to automatically format code. +- Configure the linter and formatter to run automatically on save. + +### 7.4 Deployment Best Practices + +- Containerize your application using Docker. +- Use a cloud platform like AWS, Azure, or GCP to deploy your application. +- Use a deployment tool like Kubernetes to manage your application. + +### 7.5 CI/CD Integration + +- Use a CI/CD pipeline to automate the testing and deployment process. +- Use a CI/CD tool like Jenkins, GitHub Actions, or GitLab CI. +- Run tests automatically on every commit. +- Deploy the application automatically when tests pass. + +## Additional Recommendations + +- **Utilize NVIDIA RTX GPUs:** Leverage RTX GPUs for enhanced performance due to their high-speed VRAM and dedicated AI accelerators. This is especially important for larger models and higher batch sizes. +- **Token Management:** Understand how to manage tokens effectively to optimize performance, as performance is often measured in tokens per second. +- **Batch API:** Consider using the OpenAI Batch API for cost efficiency and higher rate limits, especially when immediate responses are not required. + +By following these best practices, you can write more maintainable, efficient, and secure code when working with the Hugging Face Transformers library. \ No newline at end of file diff --git a/rules-mdc/ai_ml/llm_tools/langchain.mdc b/rules-mdc/ai_ml/llm_tools/langchain.mdc new file mode 100644 index 0000000..94b3d02 --- /dev/null +++ b/rules-mdc/ai_ml/llm_tools/langchain.mdc @@ -0,0 +1,310 @@ +--- +description: This rule provides best practices for developing LangChain applications, covering code organization, performance, security, testing, and common pitfalls. It aims to improve code quality, maintainability, and overall project success. +globs: **/*.py +--- +# LangChain Development Best Practices + +This document outlines the best practices for developing LangChain applications to ensure code quality, maintainability, performance, security, and overall project success. These guidelines cover various aspects of development, from code organization to testing and deployment. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure Best Practices + +Adopt a clear and consistent directory structure to improve code discoverability and maintainability. A recommended structure is: + + +project_root/ +├── data/ # Raw data, processed data, and datasets +├── src/ # Source code directory +│ ├── components/ # Reusable LangChain components (e.g., custom chains, tools) +│ ├── chains/ # Definitions of LangChain chains +│ ├── agents/ # Agent implementations +│ ├── memory/ # Memory implementations +│ ├── utils/ # Utility functions and modules +│ ├── models/ # Custom model definitions or wrappers +│ ├── callbacks/ # Custom callback handlers +│ ├── vectorstores/ # Vectorstore configurations and connections +│ ├── document_loaders/ # Custom document loaders +│ ├── prompts/ # Prompt templates and management +│ ├── config/ # Configuration files +│ └── main.py # Entry point of the application +├── tests/ # Unit and integration tests +├── notebooks/ # Jupyter notebooks for experimentation and documentation +├── docs/ # Project documentation +├── requirements.txt # Project dependencies +├── pyproject.toml # Project metadata and build configuration +└── README.md # Project README file + + +### 1.2 File Naming Conventions + +Use descriptive and consistent file names: + +- `module_name.py`: For general modules. +- `component_name.py`: For LangChain components (e.g., `custom_chain.py`). +- `test_module_name.py`: For test files. +- Use lowercase and underscores for file names (snake_case). + +### 1.3 Module Organization + +Organize code into logical modules based on functionality. Each module should have a clear purpose and minimal dependencies. + +- **Cohesion**: Modules should have high cohesion, meaning their elements are closely related. +- **Coupling**: Modules should have low coupling, meaning they are independent of each other as much as possible. + +### 1.4 Component Architecture + +Design LangChain applications using a component-based architecture. Components should be reusable, testable, and well-defined. + +- **Chains**: Define chains as reusable components that encapsulate specific workflows. +- **Agents**: Implement agents as modular entities that interact with the environment using tools. +- **Memory**: Manage conversation history and state using memory components. +- **Tools**: Create tools as independent units that perform specific actions. +- **Callbacks**: Utilize callbacks for logging, monitoring, and custom event handling. + +### 1.5 Code Splitting Strategies + +Split large files into smaller, manageable chunks to improve readability and maintainability. + +- **Function-level splitting**: Break down large functions into smaller, single-purpose functions. +- **Class-level splitting**: Divide large classes into smaller, more focused classes. +- **Module-level splitting**: Separate modules based on functionality to reduce complexity. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to LangChain + +- **Chain of Responsibility**: Implement chains of operations where each component handles a specific task, passing the result to the next component. +- **Strategy Pattern**: Use strategy patterns to encapsulate different algorithms or behaviors within interchangeable strategy objects. +- **Template Method**: Define the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the algorithm's structure. +- **Factory Pattern**: Use factory patterns to create instances of LangChain components dynamically, based on configuration or runtime conditions. + +### 2.2 Recommended Approaches for Common Tasks + +- **Prompt Engineering**: Use prompt templates to manage and reuse prompts. Optimize prompts for clarity, context, and desired output. +- **Data Loading**: Implement custom data loaders to handle various data sources and formats. Use text splitters to chunk large documents into smaller pieces for retrieval. +- **Vector Storage**: Use vector stores to store and retrieve embeddings efficiently. Choose the appropriate vector store based on performance, scalability, and cost. +- **Agent Design**: Design agents with clear objectives, tools, and decision-making logic. Use observation logs to track agent actions and outcomes. +- **Memory Management**: Implement memory components to maintain conversation history and context. Use sliding window or summarization techniques to manage long conversations. + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **God Classes**: Avoid creating large classes that handle too many responsibilities. +- **Long Methods**: Avoid creating long methods that are difficult to understand and maintain. +- **Duplicated Code**: Avoid duplicating code across multiple modules. Extract common code into reusable functions or components. +- **Magic Numbers**: Avoid using magic numbers or hardcoded values. Define constants or configuration variables instead. +- **Tight Coupling**: Avoid creating tight coupling between modules. Use interfaces and dependency injection to promote loose coupling. + +### 2.4 State Management Best Practices + +- **Stateless Components**: Design components to be stateless whenever possible. This improves testability and scalability. +- **Centralized State**: Manage application state in a centralized location (e.g., a state management class or library). +- **Immutable State**: Use immutable data structures to prevent unintended side effects and improve predictability. +- **Explicit State Transitions**: Define explicit state transitions to make state changes clear and traceable. + +### 2.5 Error Handling Patterns + +- **Try-Except Blocks**: Use try-except blocks to handle exceptions and prevent application crashes. +- **Logging**: Log errors and exceptions to facilitate debugging and monitoring. +- **Custom Exceptions**: Define custom exceptions to represent specific error conditions. +- **Retry Logic**: Implement retry logic for transient errors (e.g., network timeouts). +- **Fallback Strategies**: Implement fallback strategies for critical operations to ensure application resilience. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Caching**: Implement caching mechanisms to store frequently accessed data and results. +- **Batch Processing**: Process data in batches to reduce overhead and improve throughput. +- **Asynchronous Operations**: Use asynchronous operations to perform non-blocking I/O and improve responsiveness. +- **Connection Pooling**: Use connection pooling to reuse database connections and reduce latency. +- **Data Compression**: Compress data to reduce storage space and network bandwidth. +- **Vectorstore Optimization**: Use efficient vectorstore implementations (e.g., FAISS, Annoy) and optimize indexing parameters for fast retrieval. + +### 3.2 Memory Management + +- **Object Pooling**: Use object pooling to reuse objects and reduce memory allocation overhead. +- **Garbage Collection**: Monitor garbage collection performance and tune parameters to minimize pauses. +- **Memory Profiling**: Use memory profiling tools to identify memory leaks and optimize memory usage. +- **Lazy Loading**: Load data on demand to reduce initial memory footprint. +- **Chunking Large Documents**: Process large documents in smaller chunks to avoid memory overflow. + +### 3.3 Rendering Optimization (if applicable for UI components) + +- **Virtualization**: Use virtualization techniques to render large lists efficiently. +- **Debouncing and Throttling**: Use debouncing and throttling to reduce the frequency of UI updates. +- **Memoization**: Use memoization to cache expensive rendering calculations. + +### 3.4 Bundle Size Optimization (if applicable for web apps) + +- **Code Splitting**: Split code into smaller chunks to reduce initial load time. +- **Tree Shaking**: Use tree shaking to remove unused code from bundles. +- **Minification and Compression**: Minify and compress code to reduce bundle size. +- **Lazy Loading**: Load components and modules on demand. + +### 3.5 Lazy Loading Strategies + +- **On-Demand Loading**: Load data or components only when they are needed. +- **Intersection Observer**: Use the Intersection Observer API to load components when they become visible in the viewport. +- **Dynamic Imports**: Use dynamic imports to load modules asynchronously. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **Prompt Injection**: Prevent prompt injection by validating and sanitizing user inputs. Use prompt templates and parameterized queries to avoid direct injection of malicious code. +- **Data Exfiltration**: Prevent data exfiltration by restricting access to sensitive data and implementing data masking techniques. +- **Code Execution**: Prevent arbitrary code execution by avoiding the use of `eval()` or similar functions. Use safe alternatives for dynamic code generation. +- **Denial of Service (DoS)**: Prevent DoS attacks by implementing rate limiting, input validation, and resource quotas. + +### 4.2 Input Validation + +- **Whitelisting**: Validate inputs against a whitelist of allowed values or patterns. +- **Sanitization**: Sanitize inputs to remove or escape potentially harmful characters or code. +- **Type Checking**: Enforce type checking to ensure that inputs conform to expected data types. +- **Length Limits**: Enforce length limits to prevent buffer overflows or excessive memory usage. + +### 4.3 Authentication and Authorization Patterns + +- **Authentication**: Use strong authentication mechanisms (e.g., multi-factor authentication) to verify user identities. +- **Authorization**: Implement role-based access control (RBAC) to restrict access to resources based on user roles. +- **Least Privilege**: Grant users the minimum necessary privileges to perform their tasks. +- **Secure Storage**: Store sensitive credentials (e.g., API keys) securely using encryption or secret management tools. + +### 4.4 Data Protection Strategies + +- **Encryption**: Encrypt sensitive data at rest and in transit. +- **Data Masking**: Mask sensitive data to protect it from unauthorized access. +- **Data Anonymization**: Anonymize data to remove personally identifiable information (PII). +- **Access Logging**: Log all data access events to track and monitor usage. +- **Data Retention**: Define and enforce data retention policies to minimize the risk of data breaches. + +### 4.5 Secure API Communication + +- **HTTPS**: Use HTTPS to encrypt communication between clients and servers. +- **API Keys**: Protect API keys and other sensitive credentials. +- **Rate Limiting**: Implement rate limiting to prevent abuse and DoS attacks. +- **Input Validation**: Validate all API inputs to prevent injection attacks. +- **Output Encoding**: Encode API outputs to prevent cross-site scripting (XSS) attacks. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- **Test-Driven Development (TDD)**: Write unit tests before writing the code to be tested. +- **Mocking**: Use mocking to isolate components and test them independently. +- **Assertion**: Use assertions to verify that the code behaves as expected. +- **Coverage**: Aim for high code coverage to ensure that all code paths are tested. +- **Parameterized Tests**: Use parameterized tests to test multiple scenarios with different inputs. + +### 5.2 Integration Testing + +- **Component Integration**: Test the integration between components to ensure that they work together correctly. +- **API Integration**: Test the integration with external APIs to ensure that data is exchanged correctly. +- **Database Integration**: Test the integration with databases to ensure that data is stored and retrieved correctly. +- **End-to-End Flows**: Test end-to-end flows to ensure that the application works as a whole. + +### 5.3 End-to-End Testing + +- **UI Testing**: Test the user interface to ensure that it is functional and user-friendly. +- **Functional Testing**: Test the functional requirements of the application to ensure that it meets the specifications. +- **Performance Testing**: Test the performance of the application to ensure that it is responsive and scalable. +- **Security Testing**: Test the security of the application to identify and mitigate vulnerabilities. +- **Accessibility Testing**: Test the accessibility of the application to ensure that it is usable by people with disabilities. + +### 5.4 Test Organization + +- **Test Suites**: Organize tests into test suites based on functionality or component. +- **Test Naming**: Use descriptive test names to make it clear what each test is testing. +- **Test Data**: Use realistic test data to simulate real-world scenarios. +- **Test Environment**: Set up a dedicated test environment to isolate tests from production data. + +### 5.5 Mocking and Stubbing + +- **Mocking**: Use mocking to replace external dependencies with controlled substitutes. +- **Stubbing**: Use stubbing to provide predefined responses to external dependencies. +- **Dependency Injection**: Use dependency injection to make it easier to mock and stub dependencies. +- **Mocking Frameworks**: Use mocking frameworks (e.g., `unittest.mock`) to simplify the mocking process. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Hardcoding API Keys**: Storing API keys directly in the code instead of using environment variables. +- **Ignoring Rate Limits**: Failing to handle API rate limits, leading to errors and service disruptions. +- **Lack of Input Validation**: Not validating user inputs, making the application vulnerable to prompt injection attacks. +- **Insufficient Error Handling**: Not handling errors properly, leading to application crashes and data loss. +- **Over-Reliance on Default Settings**: Using default settings without considering their impact on performance and security. + +### 6.2 Edge Cases to Be Aware Of + +- **Empty Inputs**: Handling empty inputs gracefully to prevent errors. +- **Long Inputs**: Handling long inputs efficiently to avoid performance issues. +- **Special Characters**: Handling special characters correctly to prevent injection attacks. +- **Unicode Support**: Ensuring proper Unicode support to handle different languages and character sets. +- **Network Errors**: Handling network errors gracefully to ensure application resilience. + +### 6.3 Version-Specific Issues + +- **API Changes**: Being aware of API changes in different LangChain versions and updating code accordingly. +- **Compatibility**: Ensuring compatibility between different LangChain components and versions. +- **Deprecated Features**: Avoiding the use of deprecated features and migrating to their replacements. + +### 6.4 Compatibility Concerns + +- **Python Versions**: Ensuring compatibility with different Python versions. +- **Operating Systems**: Ensuring compatibility with different operating systems (e.g., Windows, macOS, Linux). +- **Dependency Conflicts**: Resolving dependency conflicts between different libraries. + +### 6.5 Debugging Strategies + +- **Logging**: Use logging to track the execution flow and identify errors. +- **Debugging Tools**: Use debugging tools (e.g., `pdb`) to step through code and inspect variables. +- **Print Statements**: Use print statements strategically to output debugging information. +- **Error Messages**: Pay attention to error messages and stack traces to understand the root cause of errors. +- **Remote Debugging**: Use remote debugging to debug applications running on remote servers. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **IDE**: Use a powerful IDE (e.g., VS Code, PyCharm) with support for Python and LangChain. +- **Linters**: Use linters (e.g., `flake8`, `pylint`) to enforce code style and identify potential errors. +- **Formatters**: Use formatters (e.g., `black`, `autopep8`) to automatically format code according to PEP 8 standards. +- **Debuggers**: Use debuggers (e.g., `pdb`, `ipdb`) to step through code and inspect variables. +- **Version Control**: Use Git for version control and collaboration. + +### 7.2 Build Configuration + +- **`pyproject.toml`**: Use `pyproject.toml` file to manage project metadata, dependencies, and build configuration. +- **`requirements.txt`**: Generate and update the `requirements.txt` file to specify project dependencies. +- **Virtual Environments**: Use virtual environments (`venv`, `conda`) to isolate project dependencies. + +### 7.3 Linting and Formatting + +- **Linting**: Configure linters to enforce code style and identify potential errors automatically. +- **Formatting**: Configure formatters to automatically format code according to PEP 8 standards. +- **Pre-commit Hooks**: Use pre-commit hooks to run linters and formatters before committing code. + +### 7.4 Deployment Best Practices + +- **Containerization**: Use containerization (e.g., Docker) to package the application and its dependencies. +- **Orchestration**: Use orchestration tools (e.g., Kubernetes) to manage and scale the application. +- **Infrastructure as Code (IaC)**: Use IaC tools (e.g., Terraform, CloudFormation) to provision and manage infrastructure. +- **Monitoring**: Implement monitoring and logging to track application performance and identify issues. +- **Continuous Deployment**: Implement continuous deployment to automate the deployment process. + +### 7.5 CI/CD Integration + +- **Continuous Integration (CI)**: Use CI tools (e.g., GitHub Actions, GitLab CI, Jenkins) to automatically build, test, and analyze code. +- **Continuous Delivery (CD)**: Use CD tools to automatically deploy code to staging or production environments. +- **Automated Testing**: Integrate automated testing into the CI/CD pipeline to ensure code quality. +- **Rollback Strategies**: Implement rollback strategies to quickly revert to previous versions in case of deployment failures. + +By following these best practices, developers can build robust, scalable, and maintainable LangChain applications that meet the needs of their users and stakeholders. + +This comprehensive guide is designed to help developers create high-quality LangChain applications by adhering to industry-standard coding practices and principles. + + +@file best_practices_python.mdc +@file best_practices_langchain_specific.mdc \ No newline at end of file diff --git a/rules-mdc/ai_ml/llm_tools/vllm.mdc b/rules-mdc/ai_ml/llm_tools/vllm.mdc new file mode 100644 index 0000000..d3a786b --- /dev/null +++ b/rules-mdc/ai_ml/llm_tools/vllm.mdc @@ -0,0 +1,140 @@ +--- +description: This rule outlines the best practices and coding standards for developing with the vllm library, ensuring code quality, performance, and maintainability. It covers code organization, performance considerations, security, testing, and common pitfalls. +globs: **/*.py +--- +- ## General + - Adhere to the Google Python Style Guide: vllm projects should strictly follow the Google Python Style Guide for consistency and readability. + - Adhere to the Google C++ Style Guide (where applicable, especially for backend components). + - Pass all linter checks: Ensure code passes all configured linter checks (e.g., pylint, flake8) before committing. + - Always use UV when installing dependencies. + - Always use Python 3.12 or higher. + - Prefer classes over bare functions for better code organization and state management (where appropriate). + +- ## Code Organization and Structure: + - **Directory Structure Best Practices:** + - `vllm/` (Root directory): + - `api/`: Contains API endpoints and related logic. + - `core/`: Core functionalities and algorithms. + - `layers/`: Custom layers for the models. + - `models/`: Model definitions and configurations. + - `sampling/`: Sampling algorithms. + - `sequence/`: Sequence management and data structures. + - `utils/`: Utility functions and helper modules. + - `tests/`: Unit and integration tests. + - `examples/`: Example usage and demonstrations. + - `docs/`: Documentation. + - Maintain clear separation of concerns. + - **File Naming Conventions:** + - Use descriptive and meaningful names for files and modules (e.g., `attention_layer.py`, `model_loader.py`). + - Follow snake_case for Python files and variables. + - **Module Organization:** + - Group related functionalities into modules. + - Use `__init__.py` files to define packages and control module imports. + - **Component Architecture:** + - Design components with clear interfaces and responsibilities. + - Favor composition over inheritance to promote flexibility and reusability. + - **Code Splitting Strategies:** + - Break down large modules into smaller, more manageable files. + - Utilize lazy loading or dynamic imports to reduce startup time. + +- ## Common Patterns and Anti-patterns: + - **Design Patterns Specific to vllm:** + - **Model Abstraction:** Decouple the model implementation from the core engine. + - **Sequence Manager:** Centralized management of sequences and their states. + - **Asynchronous Execution:** Use asyncio to handle concurrent requests and I/O operations. + - **Recommended Approaches for Common Tasks:** + - **Model Loading:** Implement a robust model loading mechanism with caching and error handling. + - **Tokenization:** Use a dedicated tokenizer class to handle tokenization and detokenization. + - **Inference:** Design an efficient inference pipeline with batching and optimized tensor operations. + - **Anti-patterns and Code Smells to Avoid:** + - **God Classes:** Avoid creating large classes with too many responsibilities. + - **Code Duplication:** Refactor duplicated code into reusable functions or classes. + - **Magic Numbers:** Use named constants for configuration values. + - **State Management Best Practices:** + - Use immutable data structures to avoid unintended side effects. + - Manage state within dedicated classes or modules. + - Avoid global state where possible. + - **Error Handling Patterns:** + - Use exceptions to handle errors and unexpected conditions. + - Provide informative error messages. + - Implement retry mechanisms for transient errors. + +- ## Performance Considerations: + - **Optimization Techniques:** + - **Tensor Optimization:** Use optimized tensor operations and data layouts (e.g., `torch.compile`). + - **Kernel Fusion:** Fuse multiple operations into a single kernel to reduce overhead. + - **Quantization:** Use quantization techniques to reduce model size and memory footprint. + - **Memory Management:** + - Minimize memory allocations and deallocations. + - Use memory pooling to reuse memory buffers. + - Profile memory usage to identify bottlenecks. + - **Bundle Size Optimization:** + - Remove unused dependencies. + - **Lazy Loading Strategies:** + - Use lazy loading for large modules or resources. + - Implement asynchronous loading for non-critical components. + +- ## Security Best Practices: + - **Common Vulnerabilities and How to Prevent Them:** + - **Injection Attacks:** Sanitize user inputs to prevent injection attacks. + - **Denial of Service (DoS):** Implement rate limiting and resource management to protect against DoS attacks. + - **Data Breaches:** Protect sensitive data with encryption and access controls. + - **Input Validation:** + - Validate all user inputs before processing. + - Use regular expressions or schema validation to enforce input constraints. + - **Authentication and Authorization Patterns:** + - Implement authentication to verify user identities. + - Use authorization to control access to resources. + - **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use secure storage mechanisms. + - **Secure API Communication:** + - Use HTTPS for API communication. + - Implement API authentication and authorization. + +- ## Testing Approaches: + - **Unit Testing Strategies:** + - Write unit tests for individual functions and classes. + - Use mocking and stubbing to isolate units of code. + - **Integration Testing:** + - Test the interaction between different modules and components. + - **End-to-End Testing:** + - Test the entire system from end to end. + - **Test Organization:** + - Organize tests into separate directories. + - Use descriptive names for test files and functions. + - **Mocking and Stubbing:** + - Use mocking to replace external dependencies with controlled substitutes. + - Use stubbing to provide predefined responses for function calls. + +- ## Common Pitfalls and Gotchas: + - **Frequent Mistakes Developers Make:** + - **Incorrect Tensor Shapes:** Ensure tensor shapes are compatible for operations. + - **Memory Leaks:** Properly release allocated memory to prevent memory leaks. + - **Synchronization Issues:** Avoid race conditions and deadlocks in concurrent code. + - **Edge Cases to be Aware Of:** + - **Handling Empty Sequences:** Handle empty sequences gracefully. + - **Dealing with Unknown Tokens:** Implement a mechanism to handle unknown tokens. + - **Version-Specific Issues:** + - Keep dependencies up-to-date and be aware of breaking changes when upgrading. + - **Compatibility Concerns:** + - Ensure compatibility with different hardware platforms (CPU, GPU). + - Consider different versions of Python and PyTorch. + - **Debugging Strategies:** + - Use logging to track program execution. + - Use a debugger to step through code and inspect variables. + - Profile performance to identify bottlenecks. + +- ## Tooling and Environment: + - **Recommended Development Tools:** + - **VS Code:** A popular code editor with Python and C++ support. + - **PyCharm:** An IDE specifically designed for Python development. + - **Build Configuration:** + - Use `setup.py` or `pyproject.toml` to define project dependencies and build configurations. + - **Linting and Formatting:** + - Use pylint, flake8, and black to enforce code style. + - **Deployment Best Practices:** + - Use Docker to containerize the application. + - Deploy to a cloud platform such as AWS, Google Cloud, or Azure. + - **CI/CD Integration:** + - Use a CI/CD pipeline to automate testing and deployment. \ No newline at end of file diff --git a/rules-mdc/ai_ml/machine_learning/pandas.mdc b/rules-mdc/ai_ml/machine_learning/pandas.mdc new file mode 100644 index 0000000..599f747 --- /dev/null +++ b/rules-mdc/ai_ml/machine_learning/pandas.mdc @@ -0,0 +1,175 @@ +--- +description: This rule outlines best practices for using the pandas library in Python, covering code style, performance, data handling, and testing. It aims to promote maintainable, efficient, and robust data analysis workflows. +globs: **/*.py +--- +# Pandas Best Practices + +This document provides guidelines for writing high-quality pandas code, covering various aspects from code style to performance optimization. + +## 1. Code Organization and Structure + +- **Directory Structure:** + - Organize your project with a clear directory structure. + - Use separate directories for data, scripts, modules, tests, and documentation. + - Example: + + project_root/ + ├── data/ + │ ├── raw/ + │ └── processed/ + ├── src/ + │ ├── modules/ + │ │ ├── data_cleaning.py + │ │ ├── feature_engineering.py + │ │ └── ... + │ ├── main.py + ├── tests/ + │ ├── unit/ + │ ├── integration/ + │ └── ... + ├── docs/ + ├── notebooks/ + ├── requirements.txt + └── ... + + +- **File Naming Conventions:** + - Use descriptive and consistent file names. + - Use snake_case for Python files and variables. + - Example: `data_processing.py`, `load_data.py` + +- **Module Organization:** + - Break down your code into reusable modules. + - Each module should focus on a specific task or functionality. + - Use clear and concise function and class names within modules. + - Follow the Single Responsibility Principle (SRP). + +- **Component Architecture:** + - Design your pandas-based applications with a clear component architecture. + - Separate data loading, preprocessing, analysis, and visualization into distinct components. + - Use classes to encapsulate related functionality and data. + +- **Code Splitting Strategies:** + - Split large pandas operations into smaller, more manageable steps. + - Use functions or methods to encapsulate these steps. + - This improves readability and makes debugging easier. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns Specific to Pandas:** + - **Chain of Responsibility:** Use method chaining to perform a sequence of operations on a DataFrame. + - **Strategy Pattern:** Implement different data processing strategies based on input parameters. + - **Factory Pattern:** Use factory functions to create DataFrames or Series from various sources. + +- **Recommended Approaches for Common Tasks:** + - **Data Loading:** Use `pd.read_csv()`, `pd.read_excel()`, `pd.read_sql()` to load data from different sources. + - **Data Cleaning:** Use `dropna()`, `fillna()`, `replace()` to clean missing or incorrect data. + - **Data Transformation:** Use `apply()`, `map()`, `groupby()`, `pivot_table()` to transform data. + - **Data Aggregation:** Use `groupby()`, `agg()`, `transform()` to aggregate data. + - **Data Visualization:** Use `matplotlib`, `seaborn`, or `plotly` to visualize data. + +- **Anti-patterns and Code Smells to Avoid:** + - **Iterating over DataFrames with `iterrows()` or `itertuples()`:** These are slow; prefer vectorized operations. + - **Chained Indexing:** Avoid using chained indexing (e.g., `df['A']['B']`) as it can lead to unexpected behavior. Use `.loc` or `.iloc` instead. + - **Ignoring Data Types:** Always be aware of your data types and convert them appropriately using `astype()`. + - **Writing loops to filter/process the data:** Vectorize these operations to avoid performance issues. + - **Modifying DataFrame inplace:** Creating copies is a safer approach. + +- **State Management Best Practices:** + - Avoid modifying DataFrames in place unless absolutely necessary. + - Make copies of DataFrames using `.copy()` to avoid unintended side effects. + - Use functional programming principles where possible to minimize state changes. + +- **Error Handling Patterns:** + - Use `try-except` blocks to handle potential errors during data loading, processing, or analysis. + - Log errors and warnings using the `logging` module. + - Raise exceptions when necessary to signal errors to the calling code. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - **Vectorization:** Use vectorized operations instead of loops whenever possible. Pandas is optimized for vectorized operations. + - **Cython:** Consider using Cython to optimize performance-critical parts of your code. + - **Numba:** Use Numba to JIT-compile NumPy and pandas code for improved performance. + - **Dask:** Use Dask for parallel processing of large datasets that don't fit in memory. + - **Parquet or Feather:** Use Parquet or Feather file formats for efficient data storage and retrieval. + - **Categorical Data:** Use categorical data types for columns with a limited number of unique values. + +- **Memory Management:** + - **Data Types:** Choose appropriate data types to minimize memory usage (e.g., `int8`, `float32` instead of `int64`, `float64`). + - **Chunking:** Load large datasets in chunks to avoid memory errors. + - **Garbage Collection:** Use `gc.collect()` to explicitly release memory. + - **Sparse Data:** Use sparse data structures for data with many missing values. + +## 4. Security Best Practices + +- **Common Vulnerabilities and How to Prevent Them:** + - **SQL Injection:** When reading data from SQL databases, use parameterized queries or ORM frameworks to prevent SQL injection attacks. + - **CSV Injection:** Be cautious when loading CSV files from untrusted sources, as they may contain malicious formulas that can execute arbitrary code. + - **Arbitrary Code Execution:** Avoid using `eval()` or `exec()` on data loaded from untrusted sources, as this can lead to arbitrary code execution. + +- **Input Validation:** + - Validate user inputs to prevent malicious data from entering your pandas workflows. + - Use regular expressions or custom validation functions to check the format and content of inputs. + +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use access control mechanisms to restrict access to sensitive data. + - Anonymize or pseudonymize data when possible to protect privacy. + +## 5. Testing Approaches + +- **Unit Testing Strategies:** + - Write unit tests for individual functions and classes. + - Use `pytest` or `unittest` for writing and running tests. + - Test edge cases and boundary conditions. + - Use assert statements to verify the correctness of your code. + +- **Integration Testing:** + - Write integration tests to verify the interaction between different modules or components. + - Test the end-to-end functionality of your pandas-based applications. + +- **Test Organization:** + - Organize your tests in a separate `tests` directory. + - Use a clear naming convention for your test files and functions. + - Example: `test_data_cleaning.py`, `test_load_data()` + +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate units of code during testing. + - Use the `unittest.mock` module or third-party libraries like `pytest-mock`. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes Developers Make:** + - **Forgetting to set the index properly:** This can lead to performance issues when joining or merging DataFrames. + - **Incorrectly handling missing data:** Be aware of how missing data is represented in your DataFrames and handle it appropriately. + - **Not understanding the difference between `.loc` and `.iloc`:** These methods are used for different types of indexing and can lead to unexpected results if used incorrectly. + +- **Edge Cases to Be Aware Of:** + - **Empty DataFrames:** Handle the case where a DataFrame is empty. + - **DataFrames with duplicate indices:** Be aware of how pandas handles DataFrames with duplicate indices. + +- **Debugging Strategies:** + - Use the `print()` function or the `logging` module to debug your code. + - Use a debugger to step through your code and inspect variables. + - Use the `pdb` module for interactive debugging. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - **Jupyter Notebook/Lab:** For interactive data exploration and analysis. + - **VS Code with Python extension:** For code editing, debugging, and testing. + - **PyCharm:** A full-featured IDE for Python development. + +- **Linting and Formatting:** + - Use `flake8` to lint your code and identify potential issues. + - Use `black` to automatically format your code according to PEP 8. + - Use `isort` to automatically sort your imports. + - Integrate these tools into your pre-commit hooks to ensure consistent code style. + +- **CI/CD Integration:** + - Use CI/CD pipelines to automate the testing and deployment of your pandas-based applications. + - Integrate your CI/CD pipelines with your version control system (e.g., GitHub, GitLab, Bitbucket). + - Use Docker to containerize your applications for consistent deployment. + +This comprehensive guide covers the key aspects of pandas best practices and coding standards. By following these guidelines, you can write more maintainable, efficient, and robust pandas code. \ No newline at end of file diff --git a/rules-mdc/ai_ml/machine_learning/pytorch.mdc b/rules-mdc/ai_ml/machine_learning/pytorch.mdc new file mode 100644 index 0000000..48c742f --- /dev/null +++ b/rules-mdc/ai_ml/machine_learning/pytorch.mdc @@ -0,0 +1,381 @@ +--- +description: This rule provides comprehensive guidelines for PyTorch development, covering code organization, performance optimization, security, testing, and common pitfalls. It aims to ensure readable, maintainable, and efficient PyTorch code. +globs: **/*.py +--- +# PyTorch Best Practices and Coding Standards + +This document provides comprehensive guidelines for developing PyTorch projects, encompassing code organization, performance optimization, security, testing methodologies, and common pitfalls. Adhering to these best practices will result in more readable, maintainable, and efficient PyTorch code. + +**Library Information:** +- Name: PyTorch +- Category: ai_ml +- Subcategory: machine_learning + +## 1. Code Organization and Structure + +### 1.1 Directory Structure Best Practices + +A well-organized directory structure enhances code maintainability and collaboration. Here's a recommended structure for PyTorch projects: + + +project_root/ +├── data/ +│ ├── raw/ +│ ├── processed/ +│ └── ... +├── models/ +│ ├── layers.py +│ ├── networks.py +│ ├── losses.py +│ ├── ops.py +│ └── model_name.py +├── src/ +│ ├── data/ +│ │ ├── datasets.py +│ │ ├── dataloaders.py +│ │ └── transforms.py +│ ├── models/ +│ │ └── ... (model-related code) +│ ├── utils/ +│ │ └── ... (utility functions) +│ └── visualization/ +│ └── ... +├── notebooks/ +│ └── ... (Jupyter notebooks for experimentation) +├── tests/ +│ ├── unit/ +│ ├── integration/ +│ └── ... +├── scripts/ +│ └── train.py +│ └── eval.py +├── configs/ +│ └── ... (Configuration files, e.g., YAML) +├── README.md +├── requirements.txt +├── .gitignore +└── ... + + +- `data/`: Stores raw and processed datasets. +- `models/`: Contains PyTorch model definitions, layers, and custom loss functions. Separate network architectures, individual layers/blocks, and operations into different files. +- `src/`: Holds the main source code, including data loading, model definitions, utility functions, and visualization tools. It's common to split the `src/` folder further based on responsibilities. +- `notebooks/`: Jupyter notebooks for experimentation and exploration. Use notebooks for initial exploration and prototyping but transition finalized code to Python scripts. +- `tests/`: Unit, integration, and end-to-end tests. +- `scripts/`: Training, evaluation, and deployment scripts. The main training script should import model definitions. +- `configs/`: Configuration files for hyperparameter settings and other parameters. + +### 1.2 File Naming Conventions + +- Use descriptive and consistent file names. +- Python files: `lower_with_under.py` (e.g., `data_loader.py`, `model_utils.py`). +- Model files: `model_name.py` (e.g., `resnet.py`, `transformer.py`). +- Configuration files: `config_name.yaml` (e.g., `train_config.yaml`). + +### 1.3 Module Organization + +- Group related functions and classes into modules. +- Use clear and concise module names. +- Include a docstring at the beginning of each module to describe its purpose. +- Follow a consistent import style: + python + # Standard library imports + import os + import sys + + # Third-party library imports + import numpy as np + import torch + import torchvision + + # Local application/library imports + from src.data import data_loader + from src.models import resnet + from src.utils import helper_functions + + +### 1.4 Component Architecture + +- **`nn.Module`:** The fundamental building block for creating neural networks in PyTorch. Always subclass `nn.Module` for defining models, layers, and custom operations. +- **`forward()` method:** Implement the forward pass of your module within the `forward()` method. PyTorch uses the `__call__` method, which executes `forward()`, to pass data through the model. +- **Separation of Concerns:** Design models as compositions of smaller, reusable modules. This promotes modularity and simplifies debugging. + +Example: + +python +import torch.nn as nn + +class ConvBlock(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding) + self.relu = nn.ReLU() + self.bn = nn.BatchNorm2d(out_channels) + + def forward(self, x): + x = self.conv(x) + x = self.relu(x) + x = self.bn(x) + return x + +class SimpleCNN(nn.Module): + def __init__(self, num_classes=10): + super().__init__() + self.conv1 = ConvBlock(3, 32) + self.conv2 = ConvBlock(32, 64) + self.pool = nn.MaxPool2d(2, 2) + self.fc = nn.Linear(64 * 8 * 8, num_classes) + + def forward(self, x): + x = self.conv1(x) + x = self.pool(x) + x = self.conv2(x) + x = self.pool(x) + x = x.view(x.size(0), -1) + x = self.fc(x) + return x + + +### 1.5 Code Splitting Strategies + +- **Vertical Splitting (Feature-based):** Divide code based on features or functionalities (e.g., data loading, model definition, training loop). This approach aligns well with module organization. +- **Horizontal Splitting (Layer-based):** Split code based on layers or components of a neural network. This is suitable for complex models with distinct layers (e.g., encoder, decoder). The `models/` directory structure supports this. +- **Microservices (for large projects):** For very large and complex machine learning deployments, consider breaking the workload into microservices - one for training, one for inference, another for data preprocessing, etc. This can improve scalability and fault tolerance. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to PyTorch + +- **`nn.Sequential`:** A container for chaining layers in a sequential manner. Suitable for simple, linear models. +- **Custom `nn.Module`:** Create custom modules for encapsulating reusable blocks of layers or operations. This promotes modularity and code reuse. +- **Hooks:** Utilize forward and backward hooks for inspecting and modifying activations and gradients during training. Useful for debugging and research. +- **DataParallel/DistributedDataParallel:** Wrap models with `DataParallel` or `DistributedDataParallel` to leverage multiple GPUs for training. `DistributedDataParallel` is generally preferred for multi-node training and offers better performance. +- **Transfer Learning:** Reuse pretrained models from `torchvision.models` as a starting point for new tasks. Fine-tune the pretrained weights or add custom layers. + +### 2.2 Recommended Approaches for Common Tasks + +- **Data Loading:** Use `torch.utils.data.Dataset` and `torch.utils.data.DataLoader` for efficient data loading and batching. Use custom Datasets to control data transformation. +- **Model Definition:** Define models as classes that inherit from `nn.Module`. Use the layers defined in `torch.nn` to build the model. +- **Training Loop:** Implement a structured training loop that iterates over epochs and batches. Include forward pass, loss calculation, backward pass, and optimization steps. +- **Validation:** Evaluate model performance on a validation set during training to monitor overfitting and tune hyperparameters. +- **Checkpointing:** Save model weights and optimizer state during training to resume training or load the best model. + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **Hardcoding shapes:** Avoid hardcoding input or output shapes. Use dynamic shapes or calculate shapes based on input data. +- **Global Variables:** Minimize the use of global variables. Pass data and configurations as function arguments. +- **Magic Numbers:** Avoid using magic numbers without explanation. Define constants with descriptive names. +- **Deeply Nested Loops:** Optimize performance-critical sections of code. Consider using vectorized operations or optimized data structures to avoid nested loops where possible. +- **Ignoring Warnings:** Address all warnings. They often indicate potential problems or inefficiencies in your code. Use a debugger and logging to diagnose runtime behavior. +- **Over-commenting:** Avoid redundant comments that simply reiterate the code. Focus on explaining the *why* rather than the *what*. +- **Not using GPU when Available:** Always check if cuda is available and moves tensors and models to cuda for faster training and inference. + +### 2.4 State Management Best Practices + +- **Model Parameters:** Model parameters are automatically managed by PyTorch. Use `nn.Parameter` to register tensors as model parameters. +- **Buffers:** Use `nn.Buffer` to store non-trainable tensors that are part of the model state (e.g., running statistics in BatchNorm). +- **Optimizer State:** The optimizer maintains its own state, such as learning rate and momentum. Access and modify optimizer state through the `optimizer.state_dict()` and `optimizer.load_state_dict()` methods. +- **Random Seeds:** Set random seeds for reproducibility: + + python + import numpy as np + import torch + + def set_seed(seed): + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) # if using multiple GPUs + torch.backends.cudnn.deterministic = True #Ensures that CUDA uses deterministic algorithms. + torch.backends.cudnn.benchmark = False #Prevents CUDA from benchmarking multiple convolution algorithms. + + +### 2.5 Error Handling Patterns + +- **Specific Exception Handling:** Catch specific exceptions rather than using bare `except` clauses. This allows you to handle different error scenarios appropriately. +- **Logging:** Use the `logging` module to log errors and warnings. Include relevant information, such as timestamps, file names, and line numbers. +- **Assertion Statements:** Use `assert` statements to check for unexpected conditions. This can help catch errors early in development. +- **Custom Exceptions:** Define custom exception classes for specific error conditions in your application. This improves code readability and maintainability. +- **Graceful Degradation:** Implement mechanisms to handle errors gracefully, such as providing default values or skipping problematic data points. Avoid crashing the application. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **GPU Utilization:** Use a GPU for training and inference. Move models and tensors to the GPU using `.to('cuda')`. +- **Batch Size:** Tune the batch size to maximize GPU utilization without running out of memory. Larger batch sizes generally lead to better performance. +- **Data Loading:** Optimize data loading by using multiple workers in the `DataLoader`. Consider using asynchronous data loading techniques. +- **Mixed Precision Training:** Use mixed precision training (`torch.cuda.amp`) to reduce memory usage and accelerate training on NVIDIA GPUs with Tensor Cores. +- **Gradient Accumulation:** Accumulate gradients over multiple batches to simulate a larger batch size when memory is limited. +- **Operator Fusion:** Utilize PyTorch's JIT compiler (`torch.jit.script` or `torch.jit.trace`) to fuse multiple operations into a single kernel, reducing overhead and improving performance. +- **Memory Usage:** When using `DataParallel`, ensure that the input data is evenly distributed across the available GPUs. Uneven data distribution can result in memory imbalances and slow down training. + +### 3.2 Memory Management + +- **Tensor Deletion:** Delete unnecessary tensors using `del` to free up memory. +- **`torch.no_grad()`:** Use `torch.no_grad()` during inference to disable gradient calculation and reduce memory usage. +- **In-place Operations:** Use in-place operations (e.g., `x.add_(1)`) to modify tensors directly without creating new tensors. Be cautious with in-place operations as they can sometimes cause issues with autograd. +- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage. +- **Garbage Collection:** Explicitly call `gc.collect()` to force garbage collection. This can be useful in situations where memory is not being released promptly. + +### 3.3 Rendering Optimization (if applicable) + +- This section applies if PyTorch is used for rendering tasks (e.g., neural rendering). +- **Optimize Mesh Data Structures:** Use efficient mesh data structures to reduce memory usage and improve rendering performance. +- **Level of Detail (LOD):** Implement LOD techniques to reduce the complexity of rendered objects at a distance. +- **Caching:** Cache frequently accessed data to reduce rendering time. + +### 3.4 Bundle Size Optimization (if applicable) + +- This section applies if PyTorch models are deployed in web applications or other size-sensitive environments. +- **Model Quantization:** Quantize models to reduce their size. Use `torch.quantization` to quantize models to 8-bit integers. +- **Model Pruning:** Prune unimportant weights from models to reduce their size. Use `torch.nn.utils.prune` to prune models. +- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms. + +### 3.5 Lazy Loading Strategies + +- **Lazy Initialization:** Defer the initialization of expensive resources until they are needed. +- **Data Streaming:** Load data in smaller chunks instead of loading the entire dataset into memory at once. +- **Just-In-Time (JIT) Compilation:** Use `torch.jit.script` or `torch.jit.trace` to compile models just before they are used. This can improve performance and reduce memory usage. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Implement techniques like adversarial training and input sanitization. +- **Data Poisoning:** Protect against data poisoning attacks by validating input data and using robust training techniques. +- **Model Extraction:** Prevent model extraction by limiting access to model weights and predictions. +- **Integer Overflow:** Be aware of integer overflow issues in user-provided data. + +### 4.2 Input Validation + +- **Data Type Validation:** Ensure that input data has the correct data type. +- **Range Validation:** Check that input values are within a valid range. +- **Format Validation:** Validate the format of input strings (e.g., URLs, email addresses). +- **Sanitization:** Sanitize input data to remove potentially malicious characters or code. + +### 4.3 Authentication and Authorization Patterns + +- **API Keys:** Use API keys to authenticate clients accessing your models. +- **OAuth 2.0:** Implement OAuth 2.0 for secure authorization of user access. +- **Role-Based Access Control (RBAC):** Use RBAC to restrict access to specific models or functionalities based on user roles. + +### 4.4 Data Protection Strategies + +- **Encryption:** Encrypt sensitive data at rest and in transit. +- **Anonymization:** Anonymize data to protect user privacy. +- **Differential Privacy:** Use differential privacy techniques to protect the privacy of training data. +- **Access Control:** Implement strict access control policies to limit access to sensitive data. + +### 4.5 Secure API Communication + +- **HTTPS:** Use HTTPS to encrypt communication between clients and your API. +- **TLS/SSL:** Use TLS/SSL certificates to secure your API endpoints. +- **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks. +- **Input Validation:** Always validate and sanitize input data to prevent injection attacks. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- **Test Individual Modules:** Write unit tests for individual modules to ensure they function correctly. +- **Test Edge Cases:** Test edge cases and boundary conditions to identify potential errors. +- **Use Assertions:** Use assertions to verify expected outcomes. +- **Test Model Outputs:** Verify that model outputs have the correct shape and data type. + +### 5.2 Integration Testing + +- **Test Interactions Between Modules:** Write integration tests to ensure that different modules work together correctly. +- **Test Data Pipelines:** Test the entire data pipeline, from data loading to model output. +- **Test End-to-End Functionality:** Test the entire application to ensure that it meets the requirements. + +### 5.3 End-to-End Testing + +- **Simulate User Interactions:** Write end-to-end tests that simulate user interactions with the application. +- **Test the Entire System:** Test the entire system, including the user interface, API, and database. +- **Verify Expected Outcomes:** Verify that the application produces the expected outcomes. + +### 5.4 Test Organization + +- **Separate Test Files:** Create separate test files for each module or component. +- **Use a Test Runner:** Use a test runner (e.g., `pytest`, `unittest`) to discover and run tests. +- **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions. + +### 5.5 Mocking and Stubbing + +- **Use Mocks to Isolate Units:** Use mocks to isolate units of code from their dependencies. +- **Use Stubs to Provide Test Data:** Use stubs to provide test data to units of code. +- **Verify Interactions with Dependencies:** Verify that units of code interact with their dependencies as expected. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Incorrect Tensor Shapes:** Pay close attention to tensor shapes when performing operations. Use `torch.Size()` to check tensor shapes. +- **Gradient Issues:** Be mindful of gradient flow. Ensure that gradients are properly calculated and propagated through the network. Use `torch.autograd.set_detect_anomaly(True)` for debugging autograd issues. +- **Memory Leaks:** Be careful to deallocate tensors when they are no longer needed. Use memory profiling tools to identify memory leaks. +- **Data Type Mismatches:** Ensure that tensors have the correct data type (e.g., `torch.float32`, `torch.int64`). +- **Device Mismatches:** Ensure that tensors and models are on the same device (CPU or GPU). + +### 6.2 Edge Cases to Be Aware Of + +- **Empty Datasets:** Handle cases where datasets are empty or contain missing data. +- **Out-of-Memory Errors:** Handle out-of-memory errors gracefully by reducing batch size or using gradient accumulation. +- **Numerical Instability:** Be aware of numerical instability issues, such as vanishing or exploding gradients. Use techniques like gradient clipping and batch normalization. + +### 6.3 Version-Specific Issues + +- **Compatibility with Libraries:** Be aware of compatibility issues between different versions of PyTorch and other libraries. +- **API Changes:** Track API changes in PyTorch releases and update your code accordingly. + +### 6.4 Compatibility Concerns + +- **Hardware Compatibility:** Ensure that your code is compatible with different hardware configurations (e.g., different GPUs). +- **Operating System Compatibility:** Ensure that your code is compatible with different operating systems (e.g., Linux, Windows, macOS). + +### 6.5 Debugging Strategies + +- **Print Statements:** Use print statements to inspect the values of tensors and variables. +- **Debuggers:** Use a debugger (e.g., `pdb`) to step through your code and inspect the state of your application. +- **TensorBoard:** Use TensorBoard to visualize model training progress, including loss curves, metrics, and model architecture. +- **`torch.autograd.set_detect_anomaly(True)`:** A powerful tool for debugging autograd issues. It will raise an error when a NaN gradient is detected, helping you pinpoint the source of the problem. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **IDEs:** Visual Studio Code (with Python extension), PyCharm. +- **Virtual Environments:** `venv`, `conda`. +- **Debugging Tools:** `pdb`, `ipdb`. +- **Profiling Tools:** `torch.profiler`, `memory_profiler`. + +### 7.2 Build Configuration + +- **`requirements.txt`:** Specify project dependencies in a `requirements.txt` file. Use `pip freeze > requirements.txt` to generate the file. + + Example `requirements.txt`: + + torch==1.13.1 +torchvision==0.14.1 +numpy==1.24.1 + +- **`setup.py` (for libraries):** Use `setup.py` to define your library's metadata and dependencies. + +### 7.3 Linting and Formatting + +- **Linters:** `flake8`, `pylint`. +- **Formatters:** `black`, `autopep8`. +- **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code. + +### 7.4 Deployment Best Practices + +- **Model Serialization:** Use `torch.save` to serialize models for deployment. Use `torch.load` to load models. +- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms. +- **Serving Frameworks:** Use serving frameworks like TorchServe, FastAPI, or Flask to deploy PyTorch models as REST APIs. + +### 7.5 CI/CD Integration + +- **Continuous Integration (CI):** Use CI tools like Jenkins, GitHub Actions, or GitLab CI to automatically build and test your code. +- **Continuous Deployment (CD):** Use CD tools to automatically deploy your code to production environments. +- **Automated Testing:** Integrate automated testing into your CI/CD pipeline to ensure code quality and prevent regressions. Run unit, integration, and end-to-end tests. \ No newline at end of file diff --git a/rules-mdc/ai_ml/machine_learning/scikit-learn.mdc b/rules-mdc/ai_ml/machine_learning/scikit-learn.mdc new file mode 100644 index 0000000..8541b46 --- /dev/null +++ b/rules-mdc/ai_ml/machine_learning/scikit-learn.mdc @@ -0,0 +1,193 @@ +--- +description: Enforces best practices and coding standards for scikit-learn projects, promoting maintainability, performance, and security. This rule provides guidelines on code organization, common patterns, performance optimization, testing, and common pitfalls. +globs: **/*.py +--- +# Scikit-learn Best Practices and Coding Standards + +This document outlines best practices and coding standards for developing with scikit-learn, aiming to improve code quality, maintainability, performance, and security. + +## 1. Code Organization and Structure + +- **Directory Structure:** + - Organize your project into logical modules or components. A typical structure might include: + - `src/`: Source code for your project. + - `models/`: Contains the implementation of machine learning models. + - `features/`: Feature engineering and processing logic. + - `utils/`: Utility functions and helper modules. + - `data/`: Datasets used for training and testing. + - `raw/`: Original, unprocessed data. + - `processed/`: Cleaned and preprocessed data. + - `notebooks/`: Jupyter notebooks for experimentation and analysis. + - `tests/`: Unit and integration tests. + - `scripts/`: Scripts for training, evaluation, and deployment. + - `config/`: Configuration files (e.g., YAML, JSON). + - Example: + + + project_root/ + ├── src/ + │ ├── models/ + │ │ ├── __init__.py + │ │ ├── model_1.py + │ │ └── model_2.py + │ ├── features/ + │ │ ├── __init__.py + │ │ ├── feature_engineering.py + │ │ └── feature_selection.py + │ ├── utils/ + │ │ ├── __init__.py + │ │ └── helpers.py + │ ├── __init__.py + │ └── main.py + ├── data/ + │ ├── raw/ + │ │ └── data.csv + │ └── processed/ + │ └── processed_data.csv + ├── notebooks/ + │ └── exploratory_data_analysis.ipynb + ├── tests/ + │ ├── __init__.py + │ ├── test_models.py + │ └── test_features.py + ├── scripts/ + │ ├── train.py + │ └── evaluate.py + ├── config/ + │ └── config.yaml + ├── README.md + └── requirements.txt + + +- **File Naming Conventions:** + - Use descriptive and consistent names for files and modules. + - Prefer snake_case for Python files and variables (e.g., `model_training.py`, `n_samples`). + +- **Module Organization:** + - Each module should have a clear and specific purpose. + - Use `__init__.py` files to define packages and modules within directories. + - Minimize dependencies between modules to improve maintainability. + +- **Component Architecture:** + - Design your application with loosely coupled components. + - Implement interfaces or abstract classes to define contracts between components. + - Use dependency injection to manage dependencies and promote testability. + +- **Code Splitting Strategies:** + - Split large files into smaller, more manageable modules. + - Group related functions and classes into modules based on functionality. + - Consider splitting code based on layers (e.g., data access, business logic, presentation). + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Pipeline:** Use scikit-learn's `Pipeline` class to chain together multiple data preprocessing and modeling steps. This helps prevent data leakage and ensures consistent data transformations. + - **Model Selection:** Employ techniques like cross-validation and grid search to select the best model and hyperparameters for your data. Use `GridSearchCV` or `RandomizedSearchCV`. + - **Ensemble Methods:** Leverage ensemble methods like Random Forests, Gradient Boosting, and Voting Classifiers to improve model accuracy and robustness. + - **Custom Transformers:** Create custom transformers using `BaseEstimator` and `TransformerMixin` to encapsulate complex feature engineering logic. + +- **Recommended Approaches:** + - **Data Preprocessing:** Always split your data into training and testing sets *before* any preprocessing steps. + - **Feature Scaling:** Apply appropriate feature scaling techniques (e.g., StandardScaler, MinMaxScaler) to numerical features before training models. + - **Categorical Encoding:** Use one-hot encoding or ordinal encoding for categorical features. + - **Missing Value Imputation:** Handle missing values using imputation techniques like mean, median, or k-NN imputation. + - **Model Persistence:** Save trained models to disk using `joblib` or `pickle` for later use. + +- **Anti-patterns and Code Smells:** + - **Data Leakage:** Avoid data leakage by preprocessing the entire dataset before splitting into training and testing sets. + - **Overfitting:** Be cautious of overfitting by using regularization techniques and cross-validation. + - **Ignoring Data Distributions:** Always visualize and understand data distributions before applying transformations or choosing models. + - **Hardcoding Parameters:** Avoid hardcoding parameters directly in the code. Use configuration files or command-line arguments instead. + - **Ignoring Warnings:** Pay attention to scikit-learn warnings, as they often indicate potential problems with your code or data. + +- **State Management:** + - Use classes to encapsulate state and behavior related to models or data processing steps. + - Avoid global variables and mutable state whenever possible. + - Use immutable data structures where appropriate to prevent unintended side effects. + +- **Error Handling:** + - Use try-except blocks to handle exceptions and prevent your application from crashing. + - Log errors and warnings to a file or logging service. + - Provide informative error messages to users. + - Implement retry mechanisms for transient errors. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - **Vectorization:** Utilize NumPy's vectorized operations to perform calculations on entire arrays instead of looping through individual elements. Use `.values` from pandas DataFrames when passing to scikit-learn. + - **Memory Optimization:** Minimize memory usage by using appropriate data types (e.g., `int8`, `float32`) and avoiding unnecessary copies of data. + - **Algorithm Selection:** Choose efficient algorithms that are well-suited for your data and task. For example, use `MiniBatchKMeans` for large datasets. + - **Parallelization:** Use scikit-learn's built-in support for parallel processing to speed up training and prediction. + +- **Memory Management:** + - Use memory profiling tools to identify memory leaks and optimize memory usage. + - Release unused memory by deleting variables or using the `gc` module. + - Use data streaming techniques for large datasets that don't fit into memory. + +- **Lazy Loading Strategies:** + - Load data and models only when they are needed. + - Use generators or iterators to process large datasets in chunks. + +## 4. Security Best Practices + +- **Common Vulnerabilities:** + - **Model Poisoning:** Protect against model poisoning attacks by validating input data and sanitizing user-provided data. + - **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Consider using techniques like adversarial training to improve model robustness. + +- **Input Validation:** + - Validate all input data to ensure it conforms to the expected format and range. + - Sanitize user-provided data to prevent injection attacks. + +- **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use access control mechanisms to restrict access to data and models. + +## 5. Testing Approaches + +- **Unit Testing:** + - Write unit tests for individual functions and classes. + - Use mocking to isolate components and test them in isolation. + - Assert that your code produces the expected output for different inputs. + +- **Integration Testing:** + - Write integration tests to verify that different components work together correctly. + - Test the interaction between your code and external dependencies. + +- **Test Organization:** + - Organize your tests into a separate directory (e.g., `tests`). + - Use descriptive names for your test files and functions. + +- **Mocking and Stubbing:** + - Use mocking libraries like `unittest.mock` or `pytest-mock` to create mock objects for testing. + - Use stubs to replace complex dependencies with simpler implementations. + +## 6. Common Pitfalls and Gotchas + +- **Data Type Mismatches:** Ensure that the data types of your input features are compatible with the model you are using. +- **Feature Scaling Issues:** Use the correct scaling method for your features, understanding how each scaler behaves. +- **Improper Cross-Validation:** Make sure the cross-validation strategy you choose is appropriate for your dataset and model. +- **Version Compatibility:** Be aware of compatibility issues between different versions of scikit-learn and its dependencies. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - **IDE:** Use an IDE like VS Code, PyCharm, or JupyterLab. + - **Version Control:** Use Git for version control. + - **Package Manager:** Use pip or Conda for managing dependencies. + - **Virtual Environments:** Create virtual environments for each project to isolate dependencies. + +- **Linting and Formatting:** + - Use linters like pylint or flake8 to enforce code style and identify potential errors. + - Use formatters like black or autopep8 to automatically format your code. + +- **CI/CD Integration:** + - Integrate your code with a CI/CD system like Jenkins, Travis CI, or CircleCI. + - Automatically run tests and linters on every commit. + - Deploy your application to a production environment automatically. + +## General Coding Style +- Use underscores to separate words in non-class names: `n_samples` rather than `nsamples`. +- Avoid multiple statements on one line. +- Use relative imports for references inside scikit-learn (except for unit tests, which should use absolute imports). + +By following these best practices, you can write cleaner, more maintainable, and more efficient scikit-learn code. \ No newline at end of file diff --git a/rules-mdc/ai_ml/machine_learning/tensorflow.mdc b/rules-mdc/ai_ml/machine_learning/tensorflow.mdc new file mode 100644 index 0000000..0e797f4 --- /dev/null +++ b/rules-mdc/ai_ml/machine_learning/tensorflow.mdc @@ -0,0 +1,185 @@ +--- +description: Comprehensive guide to TensorFlow best practices, covering code organization, performance, testing, and security for robust and maintainable machine learning projects. +globs: **/*.{py,tf,keras} +--- +- **Code Organization and Structure:** + - **Directory Structure:** + - Structure your project into logical directories. For example: + + project_root/ + ├── data/ + │ ├── raw/ + │ └── processed/ + ├── models/ + │ ├── training/ + │ └── saved_models/ + ├── src/ + │ ├── utils/ + │ ├── layers/ + │ ├── models/ + │ ├── training/ + │ └── evaluation/ + ├── notebooks/ #Jupyter notebooks for experimentation + ├── tests/ + ├── configs/ + └── README.md + + + - **File Naming Conventions:** + - Use descriptive and consistent names. For example: + - `model_name.py` + - `data_processing.py` + - `train.py` + - `evaluate.py` + - `layer_name.py` + + - **Module Organization:** + - Break down code into reusable modules and functions. + - Use `tf.Module` and Keras layers to manage variables. This enables encapsulation and avoids global variable pollution. + - Import modules using explicit relative or absolute paths, such as `from src.models import MyModel`. + - Group related functionality into modules/packages. + + - **Component Architecture:** + - Employ modular design principles. + - Keras `Layers` and `Models` promote a component-based architecture. Custom layers should inherit from `tf.keras.layers.Layer`. Custom models inherit from `tf.keras.Model`. + - Use dependency injection to decouple components and facilitate testing. + + - **Code Splitting Strategies:** + - Refactor code into smaller, manageable modules. + - Separate data loading, preprocessing, model definition, training, and evaluation into distinct modules. + - Implement generator functions or `tf.data.Dataset` pipelines for large datasets to avoid loading all data into memory at once. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Strategy Pattern:** Use different strategies for optimization or regularization. + - **Factory Pattern:** Create model architectures dynamically based on configuration. + - **Observer Pattern:** Monitor training progress and trigger actions based on metrics. + + - **Recommended Approaches:** + - Use Keras layers and models to manage variables. Keras handles the underlying TensorFlow operations. + - Leverage `tf.data.Dataset` for efficient data loading and preprocessing. + - Use `tf.function` to compile Python functions into TensorFlow graphs for improved performance. + + - **Anti-patterns and Code Smells:** + - **God Classes:** Avoid monolithic classes that perform too many tasks. Break them into smaller, more focused classes or functions. + - **Copy-Pasted Code:** Refactor duplicated code into reusable functions or modules. + - **Magic Numbers:** Use named constants instead of hardcoded values. + - **Global Variables:** Minimize the use of global variables, especially for model parameters. + + - **State Management:** + - Use Keras layers and models for managing model state (weights, biases). + - Use `tf.Variable` objects for persistent state that needs to be tracked during training. + - When creating a model subclass, define trainable weights as tf.Variable objects within the `build()` method. + - Consider using `tf.saved_model` to save and load the entire model state, including the computation graph and variable values. + + - **Error Handling:** + - Use `tf.debugging.assert_*` functions to check tensor values during development and debugging. + - Implement try-except blocks to handle potential exceptions, such as `tf.errors.InvalidArgumentError` or `tf.errors.OutOfRangeError`. + - Log errors and warnings using `tf.compat.v1.logging` or the standard `logging` module. + - Ensure error messages are informative and actionable. + +- **Performance Considerations:** + - **Optimization Techniques:** + - Use `tf.function` to compile Python functions into TensorFlow graphs for improved performance. Use autograph (automatic graph construction). + - Optimize data input pipelines using `tf.data.Dataset.prefetch` and `tf.data.Dataset.cache`. + - Experiment with different optimizers (e.g., Adam, SGD) and learning rates. + - Adjust the default learning rate for some `tf.keras.*` optimizers. + - Use mixed precision training with `tf.keras.mixed_precision.Policy` to reduce memory usage and improve performance on GPUs. + + - **Memory Management:** + - Use `tf.data.Dataset` to stream data from disk instead of loading it all into memory. + - Release unnecessary tensors using `del` to free up memory. + - Use `tf.GradientTape` to compute gradients efficiently, and avoid keeping unnecessary tensors alive within the tape. + + - **GPU Utilization:** + - Ensure that TensorFlow is using the GPU by checking `tf.config.list_physical_devices('GPU')`. + - Use larger batch sizes to maximize GPU utilization. + - Profile your code using TensorFlow Profiler to identify bottlenecks and optimize GPU usage. + +- **Security Best Practices:** + - **Common Vulnerabilities:** + - **Untrusted Input:** Validate all user-provided input to prevent malicious code injection or data poisoning attacks. + - **Model Poisoning:** Protect against adversarial attacks that can manipulate the training data and degrade model performance. + - **Model Inversion:** Implement techniques to protect sensitive data from being extracted from the model. + + - **Input Validation:** + - Sanitize and validate all input data to prevent SQL injection, cross-site scripting (XSS), and other security vulnerabilities. + - Use `tf.io.decode_image` to decode images safely and prevent potential vulnerabilities related to malformed image files. + - Input validation for image and text data is critical. + + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use differential privacy techniques to protect the privacy of training data. + - Regularly audit your code and infrastructure for security vulnerabilities. + + - **Secure API Communication:** + - Use HTTPS to encrypt communication between the client and the server. + - Implement authentication and authorization mechanisms to restrict access to sensitive data and functionality. + +- **Testing Approaches:** + - **Unit Testing:** + - Write unit tests for individual functions and classes using `unittest` or `pytest`. + - Use `tf.test.TestCase` for testing TensorFlow-specific code. + - Mock external dependencies to isolate the code being tested. + + - **Integration Testing:** + - Test the integration of different modules and components. + - Verify that the data pipeline is working correctly. + - Ensure that the model is producing accurate predictions on real-world data. + + - **End-to-End Testing:** + - Test the entire workflow from data loading to model deployment. + - Use tools like Selenium or Cypress to automate end-to-end tests. + - Test for performance and scalability. + + - **Test Organization:** + - Organize tests into logical directories and modules. + - Use clear and descriptive test names. + - Follow the Arrange-Act-Assert pattern for writing tests. + + - **Mocking and Stubbing:** + - Use mocking frameworks like `unittest.mock` or `pytest-mock` to replace external dependencies with mock objects. + - Use stubs to provide controlled responses from external dependencies. + +- **Common Pitfalls and Gotchas:** + - **Version Compatibility:** + - Be aware of version-specific issues and compatibility concerns when upgrading TensorFlow versions. + - Use `tf.compat.v1` or `tf.compat.v2` to maintain compatibility with older versions of TensorFlow. + + - **Eager Execution:** + - Understand the differences between eager execution and graph execution. + - Use `tf.function` to compile functions into graphs for improved performance in production. + + - **Tensor Shapes and Data Types:** + - Pay attention to tensor shapes and data types to avoid errors. + - Use `tf.debugging.assert_shapes` and `tf.debugging.assert_type` to check tensor shapes and data types during development. + + - **Variable Scope:** + - Be aware of variable scope when using `tf.Variable` objects. + - Use `tf.compat.v1.get_variable` to create or reuse variables within a specific scope. + +- **Tooling and Environment:** + - **Recommended Development Tools:** + - Jupyter Notebooks or Google Colab for interactive development and experimentation. + - TensorBoard for visualizing training progress and model graphs. + - TensorFlow Profiler for identifying performance bottlenecks. + - Debuggers such as the Python Debugger (pdb) for stepping through code and inspecting variables. + + - **Linting and Formatting:** + - Use linters like pylint or flake8 to enforce code style guidelines. + - Use formatters like black or autopep8 to automatically format your code. + + - **Deployment Best Practices:** + - Use TensorFlow Serving to deploy models in production. + - Use Docker to containerize your application and ensure consistent deployments. + - Use a platform like Vertex AI for scalable model training and deployment. + + - **CI/CD Integration:** + - Integrate your code with a continuous integration/continuous delivery (CI/CD) pipeline. + - Use tools like Jenkins, Travis CI, or CircleCI to automate testing and deployment. + +- **References:** + - [TensorFlow Core](https://www.tensorflow.org/guide/effective_tf2) + - [TensorFlow testing best practices](https://www.tensorflow.org/community/contribute/tests) + - [Medium - 10 tips to improve your machine learning models with tensorflow](https://medium.com/decathlondigital/10-tips-to-improve-your-machine-learning-models-with-tensorflow-ba7c724761e2) + - [Quora - What are the best practices with TensorFlow](https://www.quora.com/What-are-the-best-practices-with-TensorFlow) \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/go/fiber.mdc b/rules-mdc/backend_frameworks/go/fiber.mdc new file mode 100644 index 0000000..0124d77 --- /dev/null +++ b/rules-mdc/backend_frameworks/go/fiber.mdc @@ -0,0 +1,4 @@ +--- +description: This rule provides comprehensive best practices for developing robust, maintainable, and scalable applications using the Fiber web framework in Go. It covers code organization, performance, security, testing, and common pitfalls. +globs: **/*.go +--- diff --git a/rules-mdc/backend_frameworks/go/servemux.mdc b/rules-mdc/backend_frameworks/go/servemux.mdc new file mode 100644 index 0000000..48537a7 --- /dev/null +++ b/rules-mdc/backend_frameworks/go/servemux.mdc @@ -0,0 +1,406 @@ +--- +description: This rule enforces best practices for using the `net/http` ServeMux in Go, promoting clean, maintainable, and efficient code. It covers routing, handler design, and error handling specifics to help developers leverage ServeMux effectively. +globs: **/*.go +--- +--- +# servemux Best Practices and Coding Standards + +This document provides comprehensive guidelines for using the `net/http` ServeMux in Go, promoting best practices, coding standards, and efficient development. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure Best Practices + +- **Modular Design:** Organize your code into logical modules, each responsible for a specific set of functionalities. +- **Handler Grouping:** Group related handlers within the same directory or package. For instance, all user-related handlers could reside in a `users` package. +- **Middleware Directory:** Create a dedicated `middleware` directory for reusable middleware functions. +- **Internal vs. External:** Utilize the `internal` directory to encapsulate code that should not be exposed outside your module. This enhances encapsulation and reduces the API surface. + + +project-root/ +├── cmd/ +│ └── my-app/ +│ └── main.go +├── internal/ +│ ├── handlers/ +│ │ ├── users.go +│ │ └── products.go +│ └── middleware/ +│ ├── auth.go +│ └── logging.go +├── pkg/ +│ └── utils/ +│ └── utils.go +└── go.mod + + +### 1.2 File Naming Conventions + +- **Descriptive Names:** Use clear and descriptive file names that reflect the functionality they contain. For example, `users.go` for user-related handlers, and `auth.go` for authentication middleware. +- **Handler Specifics:** If a file contains a specific handler, name it accordingly. For example, `get_user_handler.go` or `create_product_handler.go`. +- **Lowercase:** Use lowercase for all file names. + +### 1.3 Module Organization + +- **`go.mod`:** Ensure your project has a `go.mod` file to manage dependencies. Run `go mod init ` to create one. +- **Semantic Versioning:** Follow semantic versioning for your modules. Use tags (e.g., `v1.0.0`) to mark releases. +- **Vendor Dependencies:** Consider vendoring dependencies using `go mod vendor` to ensure reproducibility. + +### 1.4 Component Architecture + +- **Separation of Concerns:** Design your components to have a single responsibility. Separate handler logic from business logic and data access. +- **Interfaces:** Use interfaces to define contracts between components, promoting loose coupling and testability. For example: + + go +type UserStore interface { + GetUser(id int) (*User, error) + CreateUser(user *User) error +} + +type UserHandler struct { + store UserStore +} + + +### 1.5 Code Splitting Strategies + +- **Package-Based Splitting:** Divide your application into packages based on functionality. Each package should be cohesive and have a clear purpose. +- **Feature-Based Splitting:** Organize code based on features. Each feature gets its own directory or package containing all relevant components. +- **Layered Architecture:** Implement a layered architecture (e.g., presentation, business logic, data access) and split the code accordingly. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to servemux + +- **Middleware Chaining:** Implement middleware as a chain of functions that decorate the handler. This allows for modular and reusable logic. Example: + + go +func LoggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Printf("Request: %s %s", r.Method, r.URL.Path) + next.ServeHTTP(w, r) + }) +} + +// Usage: +mux := http.NewServeMux() +mux.Handle("/", LoggingMiddleware(http.HandlerFunc(myHandler))) + + +- **Context-Aware Handlers:** Utilize the `context.Context` to pass request-scoped values to handlers. This facilitates tracing, request cancellation, and data sharing. + + go +func MyHandler(w http.ResponseWriter, r *http.Request) { + userID := r.Context().Value("userID").(int) + // ... +} + +// Setting context value in middleware: +ctx := context.WithValue(r.Context(), "userID", 123) +r = r.WithContext(ctx) + + +- **Route Grouping (with custom muxes):** Use separate ServeMux instances for different route groups (e.g., API v1, API v2, admin routes). This improves organization and maintainability. + + go +v1Mux := http.NewServeMux() +v1Mux.HandleFunc("/users", v1UsersHandler) +v1Mux.HandleFunc("/products", v1ProductsHandler) + +v2Mux := http.NewServeMux() +v2Mux.HandleFunc("/users", v2UsersHandler) +v2Mux.HandleFunc("/products", v2ProductsHandler) + +http.Handle("/api/v1/", v1Mux) +http.Handle("/api/v2/", v2Mux) + + +### 2.2 Recommended Approaches for Common Tasks + +- **Creating a New ServeMux:** Always use `http.NewServeMux()` to create a new ServeMux instance. Avoid using the default `http.DefaultServeMux` to prevent global state issues. Example: + + go +mux := http.NewServeMux() +mux.HandleFunc("/", myHandler) +http.ListenAndServe(":8080", mux) + + +- **Registering Handlers:** Use `mux.HandleFunc()` or `mux.Handle()` to register handlers with the ServeMux. + + go +mux.HandleFunc("/users", usersHandler) +mux.Handle("/products", productHandler{}) + + +- **Serving Static Files:** Use `http.FileServer()` to serve static files. + + go +fs := http.FileServer(http.Dir("./static")) +mux.Handle("/static/", http.StripPrefix("/static/", fs)) + + +- **Handling HTTP Methods:** Use `http.MethodGet`, `http.MethodPost`, etc., constants to check the HTTP method. With Go 1.22+, specify methods in the pattern itself for `HandleFunc`. + + go +mux.HandleFunc("GET /users/{id}", getUserHandler) +mux.HandleFunc("POST /users", createUserHandler) + + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **Global State:** Avoid using global variables or the default `http.DefaultServeMux` for request handling, as it can lead to race conditions and difficult debugging. +- **Overlapping Routes:** Be mindful of overlapping routes. Go 1.22+ will panic if conflicting patterns are registered. Ensure that your routes are distinct and do not cause conflicts. Properly consider precedence rules. +- **Ignoring Errors:** Always handle errors returned by functions. Log errors and return appropriate HTTP status codes to the client. +- **Long Handler Functions:** Keep handler functions short and focused. Delegate complex logic to other functions or services. +- **Hardcoding Values:** Avoid hardcoding configuration values. Use environment variables or configuration files. +- **Lack of Input Validation:** Always validate user input to prevent security vulnerabilities. + +### 2.4 State Management Best Practices + +- **Stateless Handlers:** Design handlers to be stateless whenever possible. If state is required, store it in the request context or an external data store. +- **Request-Scoped Values:** Use the `context.Context` to store request-scoped values. Avoid using global variables to store state related to a specific request. +- **Sessions:** Use secure session management techniques to maintain user sessions. + +### 2.5 Error Handling Patterns + +- **Centralized Error Handling:** Implement a centralized error handling middleware to catch and log errors. Return appropriate HTTP status codes and error messages to the client. + + go +func ErrorHandlingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + log.Printf("Panic: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + }() + next.ServeHTTP(w, r) + }) +} + + +- **Custom Error Types:** Define custom error types to provide more context about the error. + + go +type ValidationError struct { + Field string + Message string +} + +func (e *ValidationError) Error() string { + return fmt.Sprintf("Validation error: %s - %s", e.Field, e.Message) +} + + +- **Logging Errors:** Log errors with sufficient detail for debugging. +- **Returning Appropriate Status Codes:** Return appropriate HTTP status codes based on the error. Use descriptive error messages in the response body. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Connection Pooling:** Use connection pooling for database connections to reduce overhead. +- **Caching:** Implement caching for frequently accessed data to reduce database load. +- **Gzip Compression:** Enable Gzip compression for responses to reduce bandwidth usage. + + go +func GzipMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + gz, err := gzip.NewWriterLevel(w, gzip.BestSpeed) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer gz.Close() + w.Header().Set("Content-Encoding", "gzip") + next.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r) + } else { + next.ServeHTTP(w, r) + } + }) +} + +type gzipResponseWriter struct { + io.Writer + http.ResponseWriter +} + +func (w gzipResponseWriter) Write(b []byte) (int, error) { + return w.Writer.Write(b) +} + + +- **Keep-Alive Connections:** Enable keep-alive connections to reduce connection establishment overhead. +- **Efficient Data Structures:** Use efficient data structures and algorithms for data processing. + +### 3.2 Memory Management + +- **Avoid Memory Leaks:** Be aware of potential memory leaks, especially when using goroutines. Ensure that all goroutines are properly terminated. +- **Object Pooling:** Consider using object pooling for frequently allocated objects. +- **String Conversions:** Minimize unnecessary string conversions, as they can be expensive. +- **Defer Statements:** Use `defer` statements carefully. While convenient, they can add overhead if overused in performance-critical sections. + +### 3.3 Rendering Optimization + +- **Template Caching:** Cache templates to reduce parsing overhead. +- **Efficient Template Rendering:** Use efficient template rendering techniques. Consider using pre-compiled templates. +- **Minimize DOM Updates:** Minimize DOM updates in the client-side JavaScript code. + +### 3.4 Bundle Size Optimization + +- **Code Minification:** Minify JavaScript and CSS code to reduce bundle size. +- **Tree Shaking:** Use tree shaking to remove unused code from the bundle. +- **Image Optimization:** Optimize images to reduce file size. + +### 3.5 Lazy Loading Strategies + +- **Lazy Loading Images:** Lazy load images that are not immediately visible. +- **Code Splitting:** Split the code into smaller chunks that can be loaded on demand. +- **Dynamic Imports:** Use dynamic imports to load modules only when they are needed. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **SQL Injection:** Prevent SQL injection by using parameterized queries or ORMs. +- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input before rendering it in HTML. +- **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens. +- **Authentication Bypass:** Implement robust authentication and authorization mechanisms to prevent authentication bypass. +- **Denial-of-Service (DoS):** Implement rate limiting and request validation to prevent DoS attacks. + +### 4.2 Input Validation + +- **Validate All Inputs:** Validate all user inputs to ensure that they conform to the expected format and values. Use libraries like `ozzo-validation` for complex validation rules. +- **Sanitize Inputs:** Sanitize inputs to remove potentially malicious characters. +- **Whitelist Inputs:** Use a whitelist approach to only allow specific characters or patterns. + +### 4.3 Authentication and Authorization Patterns + +- **Authentication Middleware:** Implement authentication middleware to verify user credentials. +- **Authorization Middleware:** Implement authorization middleware to check user permissions. +- **JWT (JSON Web Tokens):** Use JWT for stateless authentication. +- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. +- **Role-Based Access Control (RBAC):** Implement RBAC to manage user permissions. + +### 4.4 Data Protection Strategies + +- **Encryption:** Encrypt sensitive data at rest and in transit. +- **Hashing:** Hash passwords with a strong hashing algorithm like bcrypt. +- **Salting:** Use salts to prevent rainbow table attacks. +- **Data Masking:** Mask sensitive data in logs and error messages. + +### 4.5 Secure API Communication + +- **HTTPS:** Use HTTPS to encrypt communication between the client and the server. +- **TLS (Transport Layer Security):** Use TLS 1.3 or higher for secure communication. +- **Certificate Pinning:** Consider using certificate pinning to prevent man-in-the-middle attacks. +- **Rate Limiting:** Implement rate limiting to prevent abuse. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- **Test Individual Units:** Unit test individual functions and methods in isolation. +- **Mock Dependencies:** Use mocks to isolate the unit under test from its dependencies. Use libraries like `gomock` or `testify/mock`. +- **Test Boundary Conditions:** Test boundary conditions and edge cases. +- **Table-Driven Tests:** Use table-driven tests to test multiple scenarios with different inputs and outputs. + +### 5.2 Integration Testing + +- **Test Interactions Between Components:** Integration test the interactions between different components of the application. +- **Test Database Interactions:** Test the interactions with the database. +- **Test API Endpoints:** Test the API endpoints. + +### 5.3 End-to-End Testing + +- **Test the Entire Application:** End-to-end test the entire application flow. +- **Use Automated Testing Tools:** Use automated testing tools like Selenium or Cypress. + +### 5.4 Test Organization + +- **Keep Tests Close to Code:** Keep test files in the same directory as the code they test. Use the `_test.go` suffix for test files. +- **Separate Test Packages:** Consider creating separate test packages for integration and end-to-end tests. +- **Descriptive Test Names:** Use descriptive test names that clearly indicate what is being tested. + +### 5.5 Mocking and Stubbing + +- **Use Interfaces:** Define interfaces for dependencies to facilitate mocking. +- **Use Mocking Libraries:** Use mocking libraries like `gomock` or `testify/mock` to generate mocks. +- **Create Stub Implementations:** Create stub implementations for dependencies that are difficult to mock. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Forgetting to Handle Errors:** Always check and handle errors returned by functions. +- **Ignoring Context Cancellation:** Respect context cancellation signals and terminate long-running operations. +- **Not Validating Inputs:** Always validate user inputs to prevent security vulnerabilities. +- **Using Global State:** Avoid using global variables for request handling, as it can lead to race conditions. +- **Overlapping Routes:** Failing to understand route precedence, especially in Go 1.22+ can lead to unexpected behavior or panics during server initialization. Thoroughly test route registrations. + +### 6.2 Edge Cases to Be Aware Of + +- **Trailing Slashes:** Be aware of how trailing slashes affect route matching. In Go 1.22+, use `{$}` to match only the path with the trailing slash. +- **Wildcard Matching:** Understand how wildcards match different segments of the path. Use `{pathname...}` to match all remaining segments. +- **Method Matching:** Ensure that the correct HTTP method is being used for each route. With Go 1.22+, be aware that `GET` also matches `HEAD` requests. + +### 6.3 Version-Specific Issues + +- **Go 1.22 Routing Enhancements:** Be aware of the new routing enhancements in Go 1.22, including method matching and wildcard support. Understand the new precedence rules. +- **Compatibility Issues:** Check for compatibility issues when upgrading to new versions of Go or third-party libraries. + +### 6.4 Compatibility Concerns + +- **Backwards Compatibility:** Ensure that changes do not break backwards compatibility. Use feature flags to gradually introduce new features. +- **API Versioning:** Use API versioning to manage changes to the API. +- **Client Compatibility:** Ensure that client applications are compatible with the API. + +### 6.5 Debugging Strategies + +- **Logging:** Use logging to track the execution flow and identify errors. +- **Debugging Tools:** Use debugging tools like `delve` to step through the code and inspect variables. +- **Profiling:** Use profiling tools to identify performance bottlenecks. +- **Tracing:** Use tracing tools to track requests across different services. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **GoLand:** A powerful IDE for Go development. +- **Visual Studio Code with Go Extension:** A lightweight and versatile code editor with excellent Go support. +- **Delve:** A Go debugger. +- **Profiling Tools:** `pprof` is the built-in Go profiler. + +### 7.2 Build Configuration + +- **Makefile:** Use a Makefile to automate common build tasks. +- **`go build`:** Use `go build` to compile the application. +- **`go test`:** Use `go test` to run tests. + +### 7.3 Linting and Formatting + +- **`go fmt`:** Use `go fmt` to format the code according to the Go style guidelines. +- **`go vet`:** Use `go vet` to identify potential errors in the code. +- **`golangci-lint`:** Use `golangci-lint` for more advanced linting. + +### 7.4 Deployment Best Practices + +- **Containerization:** Use containers (e.g., Docker) to package the application and its dependencies. +- **Orchestration:** Use orchestration tools (e.g., Kubernetes) to manage and scale the application. +- **Immutable Infrastructure:** Deploy immutable infrastructure to ensure consistency and reproducibility. + +### 7.5 CI/CD Integration + +- **Continuous Integration:** Integrate with a CI/CD pipeline to automate the build, test, and deployment process. +- **Automated Testing:** Run automated tests as part of the CI/CD pipeline. +- **Automated Deployment:** Automate the deployment process using tools like Jenkins, CircleCI, or GitHub Actions. + +## Additional Best Practices + +- **Meaningful Handler Names:** Use meaningful, concise names for handlers, avoiding repetition of context in function names (as per the Google Style Guide). +- **Document Code:** Write clear and concise documentation for all functions, methods, and types. +- **Code Reviews:** Conduct regular code reviews to ensure code quality and identify potential issues. +- **Stay Updated:** Stay up-to-date with the latest Go best practices and security vulnerabilities. + +By following these best practices and coding standards, you can develop robust, maintainable, and efficient applications using the `net/http` ServeMux in Go. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/java/springboot.mdc b/rules-mdc/backend_frameworks/java/springboot.mdc new file mode 100644 index 0000000..23c5c0a --- /dev/null +++ b/rules-mdc/backend_frameworks/java/springboot.mdc @@ -0,0 +1,339 @@ +--- +description: This rule provides comprehensive best practices and coding standards for developing robust, maintainable, and performant Spring Boot applications, covering code structure, performance, security, testing, and common pitfalls. +globs: **/*.java +--- +# Spring Boot Best Practices and Coding Standards + +This document outlines best practices and coding standards for developing applications with Spring Boot. Following these guidelines will help ensure that your applications are robust, maintainable, performant, and secure. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +Adopt a layered architecture to separate concerns and improve maintainability. A recommended directory structure is: + + +src/ + ├── main/ + │ ├── java/ + │ │ └── com/example/app/ + │ │ ├── Application.java (Main entry point) + │ │ ├── config/ (Configuration classes) + │ │ ├── controller/ (REST controllers) + │ │ ├── service/ (Business logic services) + │ │ ├── repository/ (Data access repositories) + │ │ ├── model/ (Data transfer objects (DTOs), entities) + │ │ ├── exception/ (Custom exceptions) + │ │ ├── util/ (Utility classes) + │ │ └── security/ (Security-related classes) + │ └── resources/ + │ ├── application.properties/application.yml (Application configuration) + │ ├── static/ (Static resources like HTML, CSS, JavaScript) + │ └── templates/ (View templates, e.g., Thymeleaf) + └── test/ + ├── java/ + │ └── com/example/app/ + │ ├── controller/ (Controller tests) + │ ├── service/ (Service tests) + │ └── repository/ (Repository tests) + └── resources/ + ├── application.properties/application.yml (Test-specific configuration) + + +* **Root Package:** Choose a meaningful root package name (e.g., `com.yourcompany.appname`). +* **Modularization:** For larger applications, consider breaking down the application into modules (e.g., using Maven or Gradle modules) based on business domains or features. + +### 1.2 File Naming Conventions + +* **Classes:** Use PascalCase (e.g., `UserController`, `ProductService`). +* **Interfaces:** Use PascalCase, often prefixed with `I` (e.g., `ProductRepository`, `IOrderService`). Consider omitting the `I` prefix if it doesn't add value. +* **Methods:** Use camelCase (e.g., `getUserById`, `calculateTotal`). +* **Variables:** Use camelCase (e.g., `userName`, `productPrice`). +* **Constants:** Use UPPER_SNAKE_CASE (e.g., `MAX_RETRIES`, `DEFAULT_TIMEOUT`). +* **Configuration Files:** Use lowercase with hyphens (e.g., `application.properties`, `bootstrap.yml`). + +### 1.3 Module Organization + +For larger projects, break down the application into modules. Each module should represent a distinct business domain or feature. + +* **Maven/Gradle Modules:** Use Maven or Gradle to manage module dependencies and build processes. +* **Clear Boundaries:** Define clear interfaces between modules to promote loose coupling. +* **Independent Deployments:** Design modules to be independently deployable, if possible. + +### 1.4 Component Architecture + +* **Controllers:** Handle incoming requests and delegate to services. Keep controllers thin. +* **Services:** Implement business logic. Services should be transactional. +* **Repositories:** Provide data access abstraction. Use Spring Data JPA or other data access technologies. +* **Models:** Represent data structures. Use DTOs for transferring data between layers and entities for persistence. + +### 1.5 Code Splitting Strategies + +* **Feature-Based Splitting:** Group code related to a specific feature into its own package or module. +* **Layer-Based Splitting:** Separate code based on layers (e.g., presentation, business logic, data access). +* **Horizontal vs. Vertical Slicing:** Consider horizontal slicing (grouping similar functionalities across features) or vertical slicing (grouping all functionalities for a specific feature) based on project needs. + +## 2. Common Patterns and Anti-Patterns + +### 2.1 Design Patterns Specific to Spring Boot + +* **Dependency Injection (DI):** Use constructor injection for required dependencies and setter injection for optional dependencies. +* **Inversion of Control (IoC):** Let the Spring container manage the lifecycle and dependencies of your beans. +* **Aspect-Oriented Programming (AOP):** Use AOP for cross-cutting concerns like logging, security, and transaction management. +* **Repository Pattern:** Use Spring Data repositories for simplified data access. +* **Service Layer Pattern:** Decouple controllers from business logic by introducing a service layer. +* **Template Method Pattern:** Use `JdbcTemplate` or `RestTemplate` for consistent data access or external API calls. +* **Factory Pattern:** Use `@Configuration` classes and `@Bean` methods to define and configure beans. + +### 2.2 Recommended Approaches for Common Tasks + +* **Configuration:** Use `application.properties` or `application.yml` for externalized configuration. Use `@ConfigurationProperties` to bind configuration properties to a class. +* **Logging:** Use SLF4J for logging abstraction and a suitable logging implementation (e.g., Logback or Log4j2). +* **Exception Handling:** Use `@ControllerAdvice` to handle exceptions globally. Create custom exception classes for specific error scenarios. +* **Validation:** Use JSR-303 Bean Validation for validating request parameters and request bodies. Use `@Validated` annotation with appropriate groups. +* **Data Transfer:** Use DTOs to transfer data between layers to avoid exposing internal data structures. +* **Asynchronous Operations:** Use `@Async` annotation and `TaskExecutor` to perform asynchronous operations. +* **Caching:** Use Spring's caching abstraction with implementations like Ehcache, Caffeine, or Redis. +* **Scheduling:** Use `@Scheduled` annotation to schedule tasks. +* **Transaction Management:** Use `@Transactional` annotation for managing transactions. + +### 2.3 Anti-Patterns and Code Smells to Avoid + +* **God Class:** A class that does too much. Break it down into smaller, more focused classes. +* **Long Method:** A method that is too long and complex. Extract smaller methods. +* **Feature Envy:** A method that accesses data from another object more than its own. Move the method to the other object. +* **Data Clumps:** Groups of data that frequently appear together. Create a new class to encapsulate the data clump. +* **Primitive Obsession:** Using primitive data types instead of creating meaningful domain objects. +* **Shotgun Surgery:** Making small changes in many different places. Refactor the code to centralize the changes. +* **Spaghetti Code:** Code that is difficult to understand and maintain due to its tangled structure. +* **Copy-Paste Programming:** Duplicating code instead of reusing existing code. Create reusable components or methods. +* **Field Injection:** Use constructor injection instead for required dependencies. +* **Tight Coupling:** Classes that are highly dependent on each other. Decouple the classes using interfaces or abstract classes. +* **Ignoring Exceptions:** Catching exceptions but not handling them properly. Log the exception and take appropriate action. +* **Over-Engineering:** Making the code too complex for the problem it solves. Keep it simple and only add complexity when needed. + +### 2.4 State Management Best Practices + +* **Stateless Services:** Design services to be stateless whenever possible. This improves scalability and testability. +* **Session Management:** Use Spring Session to manage user sessions in a distributed environment. Store session data in a persistent store like Redis or a database. +* **Caching:** Use caching to store frequently accessed data. Choose a suitable caching strategy (e.g., LRU, FIFO). +* **Database:** Use a relational database or a NoSQL database to persist data. +* **Distributed Transactions:** Use distributed transaction management techniques like two-phase commit (2PC) or Saga pattern for transactions spanning multiple services. + +### 2.5 Error Handling Patterns + +* **Global Exception Handling:** Use `@ControllerAdvice` and `@ExceptionHandler` to handle exceptions globally. +* **Custom Exceptions:** Create custom exception classes for specific error scenarios. +* **Logging:** Log exceptions with sufficient context information (e.g., request parameters, user ID). +* **Error Responses:** Return meaningful error responses with appropriate HTTP status codes and error messages. +* **Retry Mechanism:** Implement a retry mechanism for transient errors. +* **Circuit Breaker:** Use a circuit breaker pattern to prevent cascading failures. +* **Dead Letter Queue:** Use a dead letter queue to handle messages that cannot be processed. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +* **Database Query Optimization:** Use indexes, optimize queries, and avoid N+1 queries. +* **Caching:** Use caching to reduce database load and improve response times. +* **Connection Pooling:** Use connection pooling to reuse database connections. +* **Asynchronous Operations:** Use asynchronous operations to offload long-running tasks from the main thread. +* **Load Balancing:** Use load balancing to distribute traffic across multiple instances. +* **Gzip Compression:** Use Gzip compression to reduce the size of HTTP responses. +* **Code Profiling:** Use profiling tools to identify performance bottlenecks. + +### 3.2 Memory Management + +* **Object Pooling:** Use object pooling to reuse objects and reduce object creation overhead. +* **Avoid Memory Leaks:** Ensure that objects are properly garbage collected. +* **Use Appropriate Data Structures:** Choose data structures that are efficient for the operations you perform. +* **Optimize Collections:** Use appropriate collection types (e.g., `ArrayList` vs. `LinkedList`) based on usage patterns. +* **Lazy Loading:** Use lazy loading to load data only when it is needed. + +### 3.3 Rendering Optimization + +* **Template Caching:** Cache frequently used templates to reduce rendering time. +* **Minimize DOM Manipulations:** Minimize DOM manipulations in the view layer. +* **Use CDN:** Use a Content Delivery Network (CDN) to serve static resources. + +### 3.4 Bundle Size Optimization + +* **Code Splitting:** Split the code into smaller bundles to reduce the initial load time. +* **Tree Shaking:** Remove unused code from the bundles. +* **Minification:** Minify the code to reduce the bundle size. +* **Compression:** Compress the bundles to reduce the transfer size. + +### 3.5 Lazy Loading Strategies + +* **Lazy Initialization:** Initialize objects only when they are first accessed. +* **Virtual Proxy:** Use a virtual proxy to delay the loading of an object until it is needed. +* **Database Lazy Loading:** Use lazy loading features provided by JPA or other data access technologies. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +* **SQL Injection:** Use parameterized queries or ORM frameworks to prevent SQL injection attacks. +* **Cross-Site Scripting (XSS):** Sanitize user input and use output encoding to prevent XSS attacks. +* **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to prevent CSRF attacks. +* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms. +* **Session Management:** Secure session management to prevent session hijacking. +* **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks. +* **Insecure Direct Object References (IDOR):** Implement access control checks to prevent unauthorized access to objects. +* **Security Misconfiguration:** Properly configure security settings to prevent misconfigurations. +* **Using Components with Known Vulnerabilities:** Keep dependencies up-to-date to address known vulnerabilities. +* **Insufficient Logging and Monitoring:** Implement sufficient logging and monitoring to detect and respond to security incidents. + +### 4.2 Input Validation + +* **Whitelisting:** Validate input against a whitelist of allowed values. +* **Regular Expressions:** Use regular expressions to validate input format. +* **Data Type Validation:** Validate that input is of the expected data type. +* **Length Validation:** Validate that input is within the allowed length limits. +* **Encoding Validation:** Validate that input is properly encoded. + +### 4.3 Authentication and Authorization Patterns + +* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. +* **JWT (JSON Web Token):** Use JWT for stateless authentication. +* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles. +* **Attribute-Based Access Control (ABAC):** Implement ABAC for fine-grained access control based on attributes. +* **Spring Security:** Leverage Spring Security for authentication and authorization. + +### 4.4 Data Protection Strategies + +* **Encryption:** Encrypt sensitive data at rest and in transit. +* **Hashing:** Hash passwords and other sensitive data using strong hashing algorithms. +* **Salting:** Use salting to protect against rainbow table attacks. +* **Data Masking:** Mask sensitive data when it is displayed or used for non-production purposes. +* **Tokenization:** Tokenize sensitive data to replace it with non-sensitive tokens. + +### 4.5 Secure API Communication + +* **HTTPS:** Use HTTPS for secure communication. +* **TLS/SSL:** Use TLS/SSL to encrypt data in transit. +* **API Keys:** Use API keys to authenticate API clients. +* **Rate Limiting:** Implement rate limiting to prevent abuse. +* **Input Validation:** Validate all input to prevent injection attacks. +* **Output Encoding:** Encode output to prevent XSS attacks. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +* **Test-Driven Development (TDD):** Write tests before writing the code. +* **Mocking:** Use mocking frameworks (e.g., Mockito) to isolate the unit under test. +* **Assertion Libraries:** Use assertion libraries (e.g., AssertJ) for expressive assertions. +* **Code Coverage:** Aim for high code coverage. +* **Test Naming:** Use clear and descriptive test names. +* **Arrange-Act-Assert:** Structure tests using the Arrange-Act-Assert pattern. + +### 5.2 Integration Testing + +* **Test Slices:** Use Spring Boot's test slices (e.g., `@WebMvcTest`, `@DataJpaTest`) to test specific parts of the application. +* **TestContainers:** Use Testcontainers to run integration tests with real dependencies (e.g., databases, message queues). +* **Spring Test:** Use Spring's testing support for integration tests. +* **Database Testing:** Use an in-memory database or a test database for database integration tests. + +### 5.3 End-to-End Testing + +* **Selenium:** Use Selenium to automate browser-based end-to-end tests. +* **REST Assured:** Use REST Assured to test REST APIs. +* **Headless Browser:** Use a headless browser for faster end-to-end tests. + +### 5.4 Test Organization + +* **Test Packages:** Create separate packages for unit tests, integration tests, and end-to-end tests. +* **Test Classes:** Create test classes that correspond to the classes under test. +* **Test Suites:** Use test suites to group related tests. + +### 5.5 Mocking and Stubbing + +* **Mockito:** Use Mockito for mocking dependencies. +* **Spring MockMvc:** Use Spring MockMvc for testing controllers. +* **WireMock:** Use WireMock for stubbing external services. +* **Avoid Over-Mocking:** Mock only the dependencies that are necessary to isolate the unit under test. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +* **Not Understanding Spring Boot Concepts:** Jumping into Spring Boot without a solid understanding of Spring and Dependency Injection. +* **Overusing `@Autowired`:** Using `@Autowired` for field injection instead of constructor injection. +* **Not Using Spring Boot Starters:** Manually adding dependencies instead of using Spring Boot Starters. +* **Not Externalizing Configuration:** Hardcoding configuration values instead of using `application.properties` or `application.yml`. +* **Not Handling Exceptions Properly:** Ignoring exceptions or not providing meaningful error responses. +* **Not Writing Tests:** Neglecting to write unit tests and integration tests. +* **Using `System.out.println` for Logging:** Using `System.out.println` instead of a proper logging framework. +* **Not Securing the Application:** Failing to implement proper security measures. +* **Not Monitoring the Application:** Not setting up proper monitoring and alerting. + +### 6.2 Edge Cases to Be Aware Of + +* **Null Values:** Handle null values gracefully. +* **Empty Collections:** Handle empty collections properly. +* **Large Datasets:** Optimize performance for large datasets. +* **Concurrency Issues:** Handle concurrency issues properly. +* **Network Errors:** Handle network errors gracefully. + +### 6.3 Version-Specific Issues + +* **Spring Boot Version Compatibility:** Ensure that dependencies are compatible with the Spring Boot version. +* **Java Version Compatibility:** Ensure that the Java version is compatible with the Spring Boot version. +* **Third-Party Library Compatibility:** Ensure that third-party libraries are compatible with the Spring Boot version. + +### 6.4 Compatibility Concerns + +* **Browser Compatibility:** Ensure that the application is compatible with different browsers. +* **Operating System Compatibility:** Ensure that the application is compatible with different operating systems. +* **Device Compatibility:** Ensure that the application is compatible with different devices. + +### 6.5 Debugging Strategies + +* **Logging:** Use logging to trace the execution flow and identify errors. +* **Debuggers:** Use debuggers to step through the code and inspect variables. +* **Profiling Tools:** Use profiling tools to identify performance bottlenecks. +* **Remote Debugging:** Use remote debugging to debug applications running on remote servers. +* **Heap Dumps:** Use heap dumps to analyze memory usage. +* **Thread Dumps:** Use thread dumps to analyze thread activity. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +* **IDE:** IntelliJ IDEA, Eclipse, or Visual Studio Code. +* **Build Tool:** Maven or Gradle. +* **Version Control:** Git. +* **Database Client:** DBeaver or SQL Developer. +* **API Testing Tool:** Postman or Insomnia. + +### 7.2 Build Configuration + +* **Maven:** Use `pom.xml` to define dependencies and build configuration. +* **Gradle:** Use `build.gradle` to define dependencies and build configuration. +* **Spring Boot Maven Plugin:** Use the Spring Boot Maven Plugin for packaging and running the application. +* **Spring Boot Gradle Plugin:** Use the Spring Boot Gradle Plugin for packaging and running the application. + +### 7.3 Linting and Formatting + +* **Checkstyle:** Use Checkstyle to enforce coding style guidelines. +* **PMD:** Use PMD to find potential code defects. +* **FindBugs/SpotBugs:** Use FindBugs/SpotBugs to find potential bugs. +* **EditorConfig:** Use EditorConfig to maintain consistent coding styles across different editors. +* **IntelliJ IDEA Code Style:** Configure IntelliJ IDEA's code style settings to match the project's coding style. + +### 7.4 Deployment Best Practices + +* **Containerization:** Use Docker to containerize the application. +* **Orchestration:** Use Kubernetes or Docker Swarm to orchestrate containers. +* **Cloud Deployment:** Deploy the application to a cloud platform (e.g., AWS, Azure, Google Cloud). +* **Configuration Management:** Use configuration management tools (e.g., Spring Cloud Config) to manage configuration in a distributed environment. +* **Monitoring:** Set up monitoring to track application performance and health. +* **Logging:** Aggregate logs to a central location for analysis. + +### 7.5 CI/CD Integration + +* **Continuous Integration (CI):** Use a CI server (e.g., Jenkins, Travis CI, CircleCI) to automatically build and test the application. +* **Continuous Delivery (CD):** Use a CD pipeline to automatically deploy the application to production. +* **Automated Testing:** Automate unit tests, integration tests, and end-to-end tests. +* **Code Quality Checks:** Integrate code quality checks (e.g., Checkstyle, PMD, FindBugs/SpotBugs) into the CI pipeline. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/nodejs/bun.mdc b/rules-mdc/backend_frameworks/nodejs/bun.mdc new file mode 100644 index 0000000..134aa56 --- /dev/null +++ b/rules-mdc/backend_frameworks/nodejs/bun.mdc @@ -0,0 +1,310 @@ +--- +description: This rule provides comprehensive guidance on Bun library coding standards, best practices, and common patterns. It includes performance optimization, security considerations, and testing strategies. +globs: **/*.{js,ts,jsx,tsx,bun} +--- +# Bun Library Best Practices + +This document outlines the recommended coding standards, best practices, and patterns for developing applications using the Bun library. Following these guidelines ensures maintainability, performance, security, and overall code quality. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure + +A well-defined directory structure is crucial for maintainability. Consider the following structure as a starting point: + + +project-root/ +├── src/ # Source code +│ ├── components/ # Reusable UI components (if applicable) +│ ├── services/ # Business logic and API interactions +│ ├── utils/ # Utility functions +│ ├── types/ # TypeScript type definitions +│ ├── routes/ # API route handlers +│ ├── middleware/ # Middleware functions +│ ├── models/ # Data models +│ ├── config/ # Configuration files +│ ├── index.ts # Entry point for the application +├── tests/ # Unit and integration tests +├── public/ # Static assets (e.g., images, CSS) +├── .env # Environment variables +├── bun.lockb # Lockfile for dependencies +├── package.json # Project metadata and dependencies +├── tsconfig.json # TypeScript configuration +├── README.md # Project documentation + + +* **src/**: Contains the main source code of the application. +* **components/**: Houses reusable UI components (if building a web application). +* **services/**: Encapsulates business logic and interactions with external APIs. +* **utils/**: Contains utility functions used throughout the application. +* **types/**: Stores TypeScript type definitions. +* **routes/**: Defines API route handlers using Bun's built-in HTTP server. +* **middleware/**: Includes middleware functions for request processing. +* **models/**: Defines data models used in the application. +* **config/**: Contains configuration files for different environments. +* **tests/**: Holds unit and integration tests. +* **public/**: Stores static assets like images and CSS files. +* **.env**: Stores environment variables. +* **bun.lockb**: Lockfile ensuring consistent dependency versions. +* **package.json**: Defines project metadata and dependencies. +* **tsconfig.json**: Configures TypeScript compiler options. +* **README.md**: Provides project documentation and instructions. + +### 1.2. File Naming Conventions + +* Use descriptive and consistent file names. +* Prefer camelCase for JavaScript/TypeScript files (e.g., `userService.ts`, `apiHelper.js`). +* Use kebab-case for component directories (e.g., `user-profile`). +* For React components, use PascalCase for the filename (e.g., `UserProfile.tsx`). + +### 1.3. Module Organization + +* Group related functionality into modules. +* Use clear and concise module names. +* Export only the necessary functions and classes from each module. +* Favor explicit imports over global variables. + +### 1.4. Component Architecture (if applicable) + +* If building a web application, adopt a component-based architecture (e.g., using React, SolidJS). +* Divide the UI into small, reusable components. +* Follow the Single Responsibility Principle (SRP) for each component. +* Use a consistent component structure (e.g., a folder for each component containing the component file, styles, and tests). + +### 1.5. Code Splitting Strategies + +* Use dynamic imports (`import()`) to split code into smaller chunks. +* Load only the necessary code for each route or component. +* Consider using a library like `esbuild` (Bun's underlying bundler) or `parcel` to automate code splitting. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns + +* **Singleton**: Use for managing global resources (e.g., database connections, configuration). +* **Factory**: Use for creating objects without specifying their concrete classes. +* **Observer**: Use for implementing event-driven systems. +* **Middleware**: Use to handle requests and responses in a centralized manner. +* **Dependency Injection**: Use to decouple components and improve testability. + +### 2.2. Recommended Approaches for Common Tasks + +* **API Request Handling**: Utilize `fetch` API provided by Bun for making HTTP requests. +* **File System Operations**: Use `Bun.file()` and other built-in functions for reading and writing files. +* **Process Management**: Leverage `Bun.spawn()` or `Bun.serve()` to manage child processes and servers. +* **Environment Variable Access**: Use `Bun.env` or `process.env` to access environment variables. +* **Logging**: Implement logging using `console.log` or a dedicated logging library like `pino`. + +### 2.3. Anti-patterns and Code Smells + +* **Global State**: Avoid using global variables for application state. Use state management solutions instead. +* **Long Functions**: Break down long functions into smaller, more manageable functions. +* **Duplicated Code**: Extract common logic into reusable functions or modules. +* **Magic Numbers**: Use named constants instead of hardcoded values. +* **Ignoring Errors**: Always handle errors properly using try-catch blocks or error handling middleware. + +### 2.4. State Management Best Practices + +* If your application requires complex state management, consider using a library like Zustand, Valtio, or Jotai. +* Choose a state management solution that fits the complexity of your application. +* Keep state updates predictable and consistent. +* Avoid mutating state directly. + +### 2.5. Error Handling Patterns + +* Use try-catch blocks to handle synchronous errors. +* Use `async/await` with try-catch blocks for asynchronous errors. +* Implement error handling middleware to catch unhandled exceptions. +* Log errors with relevant information (e.g., stack trace, request details). +* Provide informative error messages to the user. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Minimize Dependencies**: Reduce the number of dependencies to decrease bundle size and install time. +* **Code Splitting**: Split code into smaller chunks that can be loaded on demand. +* **Tree Shaking**: Remove unused code during the build process. +* **Caching**: Cache frequently accessed data to reduce latency. +* **Compression**: Compress responses using gzip or Brotli to reduce network traffic. +* **Efficient Algorithms**: Choose the most efficient algorithms for your tasks. + +### 3.2. Memory Management + +* Avoid memory leaks by properly releasing resources. +* Use weak references to avoid circular dependencies. +* Monitor memory usage using tools like `bun --inspect`. +* Be mindful of large data structures and use streams when appropriate. + +### 3.3. Rendering Optimization (if applicable) + +* Use virtualization for large lists or tables. +* Optimize images and other assets. +* Use memoization to avoid unnecessary re-renders. +* Profile rendering performance using browser developer tools. + +### 3.4. Bundle Size Optimization + +* Use a bundler like `esbuild` to minimize bundle size. +* Remove unused code and dependencies. +* Use code splitting to load only the necessary code. +* Consider using a smaller alternative to large libraries. + +### 3.5. Lazy Loading Strategies + +* Use dynamic imports (`import()`) to load modules on demand. +* Implement lazy loading for images and other assets. +* Use a library like `react-lazyload` (if using React) to simplify lazy loading. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +* **Cross-Site Scripting (XSS)**: Sanitize user input to prevent malicious scripts from being injected into the page. +* **Cross-Site Request Forgery (CSRF)**: Use CSRF tokens to prevent attackers from forging requests on behalf of authenticated users. +* **SQL Injection**: Use parameterized queries or an ORM to prevent attackers from injecting malicious SQL code. +* **Authentication and Authorization**: Implement robust authentication and authorization mechanisms to protect sensitive data. +* **Denial of Service (DoS)**: Implement rate limiting and other measures to prevent attackers from overwhelming the server. + +### 4.2. Input Validation + +* Validate all user input on both the client and server sides. +* Use a validation library like `zod` or `yup` to define validation schemas. +* Sanitize user input to remove potentially harmful characters. +* Escape user input when displaying it on the page. + +### 4.3. Authentication and Authorization Patterns + +* Use a secure authentication protocol like OAuth 2.0 or OpenID Connect. +* Store passwords securely using a hashing algorithm like bcrypt or Argon2. +* Implement role-based access control (RBAC) to restrict access to sensitive resources. +* Use JSON Web Tokens (JWT) for authentication and authorization. + +### 4.4. Data Protection Strategies + +* Encrypt sensitive data at rest and in transit. +* Use HTTPS to encrypt communication between the client and server. +* Store encryption keys securely using a key management system. +* Regularly back up data to prevent data loss. + +### 4.5. Secure API Communication + +* Use HTTPS for all API communication. +* Implement API authentication using API keys or JWTs. +* Rate limit API requests to prevent abuse. +* Validate API requests and responses. +* Use a firewall to protect the API from unauthorized access. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +* Write unit tests for individual functions and classes. +* Use a testing framework like Jest or Bun's built-in test runner. +* Aim for high code coverage. +* Use mocks and stubs to isolate units of code. +* Test edge cases and error conditions. + +### 5.2. Integration Testing + +* Write integration tests to verify the interaction between different modules. +* Test the integration of the application with external APIs. +* Use a testing framework like Jest or Mocha. +* Use a testing database or mock API to isolate the tests. + +### 5.3. End-to-End Testing + +* Write end-to-end tests to verify the entire application flow. +* Use a testing framework like Playwright or Cypress. +* Run tests in a browser environment. +* Test the application from the user's perspective. + +### 5.4. Test Organization + +* Create a separate `tests` directory for test files. +* Organize test files in a way that mirrors the source code structure. +* Use descriptive test names. +* Follow a consistent testing style. + +### 5.5. Mocking and Stubbing + +* Use mocks and stubs to isolate units of code during testing. +* Use a mocking library like `jest.mock()` or `sinon`. +* Mock external dependencies to avoid relying on external services. +* Stub functions to control their behavior during testing. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +* **Not Using Strict Mode**: Always use strict mode (`'use strict'`) to catch common coding errors. +* **Ignoring Error Handling**: Always handle errors properly using try-catch blocks or error handling middleware. +* **Leaking Global Variables**: Avoid creating global variables by using `let` or `const` to declare variables. +* **Not Understanding Asynchronous JavaScript**: Understand how asynchronous JavaScript works to avoid common pitfalls like callback hell. +* **Over-Engineering**: Keep the code simple and avoid unnecessary complexity. + +### 6.2. Edge Cases to Be Aware Of + +* **Handling Null and Undefined Values**: Check for null and undefined values before using them to avoid errors. +* **Integer Overflow**: Be aware of integer overflow and underflow when performing arithmetic operations. +* **Unicode Support**: Properly handle Unicode characters to avoid encoding issues. +* **Time Zone Handling**: Handle time zones correctly to avoid date and time discrepancies. + +### 6.3. Version-Specific Issues + +* Be aware of breaking changes in new versions of Bun. +* Test the application with different versions of Bun to ensure compatibility. +* Use a version manager like `bunx` to manage different Bun versions. + +### 6.4. Compatibility Concerns + +* Ensure the application is compatible with different operating systems and browsers. +* Use polyfills to support older browsers. +* Test the application on different devices to ensure responsiveness. + +### 6.5. Debugging Strategies + +* Use the `bun --inspect` flag to debug the application using Chrome DevTools. +* Use `console.log` statements to print debugging information. +* Use a debugger like VS Code's built-in debugger. +* Use a logging library to log errors and other important events. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +* **VS Code**: A popular code editor with excellent TypeScript support. +* **ESLint**: A linter for identifying and fixing code style issues. +* **Prettier**: A code formatter for automatically formatting code. +* **Jest**: A testing framework for unit and integration testing. +* **Playwright/Cypress**: A testing framework for end-to-end testing. +* **Postman/Insomnia**: API client for testing API endpoints. + +### 7.2. Build Configuration + +* Use a build tool like `esbuild` or `webpack` to bundle the application. +* Configure the build tool to optimize the bundle size and performance. +* Use environment variables to configure the build process for different environments. + +### 7.3. Linting and Formatting + +* Use ESLint to enforce consistent coding style. +* Use Prettier to automatically format code. +* Integrate ESLint and Prettier into the development workflow using VS Code extensions or command-line tools. +* Configure ESLint and Prettier to follow the project's coding style guidelines. + +### 7.4. Deployment Best Practices + +* Use a process manager like `pm2` or `systemd` to manage the application in production. +* Deploy the application to a cloud platform like DigitalOcean, Vercel, or Render. +* Use a CI/CD pipeline to automate the deployment process. +* Monitor the application's performance and health using monitoring tools. + +### 7.5. CI/CD Integration + +* Use a CI/CD platform like GitHub Actions, GitLab CI, or CircleCI to automate the build, test, and deployment process. +* Configure the CI/CD pipeline to run tests, lint code, and build the application on every commit. +* Use environment variables to configure the CI/CD pipeline for different environments. +* Deploy the application to a staging environment before deploying it to production. + +By following these best practices, developers can build high-quality, performant, and secure applications using the Bun library. Remember to adapt these guidelines to the specific needs of your project. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/nodejs/express.mdc b/rules-mdc/backend_frameworks/nodejs/express.mdc new file mode 100644 index 0000000..4aa2c7b --- /dev/null +++ b/rules-mdc/backend_frameworks/nodejs/express.mdc @@ -0,0 +1,297 @@ +--- +description: This rule provides comprehensive guidance on best practices for developing robust, maintainable, and performant Express.js applications, covering aspects from code organization and security to testing and deployment. +globs: **/*.js +--- +- # Express.js Best Practices + + This document outlines best practices for developing Express.js applications to ensure code quality, maintainability, performance, and security. + + ## 1. Code Organization and Structure + + - ### Directory Structure Best Practices + + - **Modular Structure:** Organize your application into logical modules based on functionality (e.g., `controllers`, `models`, `routes`, `middleware`, `services`). + - **Configuration:** Separate configuration files for different environments (development, production, testing). + - **Public Assets:** Keep static assets (CSS, JavaScript, images) in a dedicated `public` directory. + - **Views:** Store template files in a `views` directory. Use a template engine like EJS or Pug. + - **Example Structure:** + + + my-express-app/ + ├── controllers/ + │ ├── userController.js + │ └── productController.js + ├── models/ + │ ├── user.js + │ └── product.js + ├── routes/ + │ ├── userRoutes.js + │ └── productRoutes.js + ├── middleware/ + │ ├── authMiddleware.js + │ └── errorMiddleware.js + ├── services/ + │ ├── userService.js + │ └── productService.js + ├── config/ + │ ├── config.js + │ └── db.js + ├── views/ + │ ├── index.ejs + │ └── user.ejs + ├── public/ + │ ├── css/ + │ │ └── style.css + │ ├── js/ + │ │ └── script.js + │ └── images/ + ├── app.js # Main application file + ├── package.json + └── .env # Environment variables + + + - ### File Naming Conventions + + - **Descriptive Names:** Use clear and descriptive names for files and directories. + - **Case Convention:** Use camelCase for JavaScript files and directories. For components consider PascalCase. + - **Route Files:** Name route files according to the resource they handle (e.g., `userRoutes.js`, `productRoutes.js`). + - **Controller Files:** Name controller files according to the resource they handle (e.g., `userController.js`, `productController.js`). + - **Model Files:** Name model files after the data model they represent (e.g., `user.js`, `product.js`). + + - ### Module Organization + + - **ES Modules:** Use ES modules (`import`/`export`) for modularity. + - **Single Responsibility Principle:** Each module should have a single, well-defined responsibility. + - **Loose Coupling:** Minimize dependencies between modules to improve reusability and testability. + + - ### Component Architecture + + - **Reusable Components:** Break down the application into reusable components (e.g., UI components, service components). + - **Separation of Concerns:** Separate presentation logic (views) from business logic (controllers/services). + - **Component Composition:** Compose complex components from simpler ones. + + - ### Code Splitting Strategies + - **Route-Based Splitting:** Split code based on application routes to reduce initial load time. Use dynamic imports (`import()`) to load modules on demand. + - **Component-Based Splitting:** Split code based on components, loading components only when they are needed. + + ## 2. Common Patterns and Anti-patterns + + - ### Design Patterns Specific to Express + + - **Middleware Pattern:** Use middleware functions to handle request processing, authentication, logging, etc. + - **MVC Pattern:** Implement the Model-View-Controller (MVC) pattern to separate concerns and improve code organization. + - **Observer Pattern:** Implement the observer pattern when you need to notify multiple objects about state changes. + + - ### Recommended Approaches for Common Tasks + + - **Route Handling:** Use Express Router to define routes in separate modules. + - **Error Handling:** Use custom error handling middleware to catch and handle errors gracefully. See section 6 for more details. + - **Data Validation:** Use middleware for validating request data before processing it. + - **Asynchronous Operations:** Use `async/await` or Promises to handle asynchronous operations. + + - ### Anti-patterns and Code Smells to Avoid + + - **God Object:** Avoid creating a single, massive object that handles too many responsibilities. + - **Callback Hell:** Avoid deeply nested callbacks; use Promises or `async/await` instead. + - **Ignoring Errors:** Always handle errors properly instead of ignoring them. + - **Global Variables:** Minimize the use of global variables to avoid naming conflicts and unexpected behavior. + - **Hardcoding Secrets:** Never hardcode sensitive information (API keys, passwords) in your code. Use environment variables instead. + + - ### State Management Best Practices + + - **Stateless Controllers:** Keep controllers stateless to improve scalability and testability. + - **Session Management:** Use session management middleware (e.g., `express-session`) to manage user sessions. + - **Caching:** Implement caching strategies (e.g., Redis, Memcached) to improve performance. + + - ### Error Handling Patterns + + - **Centralized Error Handling:** Create a custom error handling middleware to catch and handle errors from different parts of the application. + - **Error Logging:** Log errors to a file or a monitoring service for debugging and analysis. + - **Custom Error Objects:** Create custom error objects with specific error codes and messages. + - **Graceful Error Messages:** Return user-friendly error messages instead of exposing internal errors. + - **Example Error Handler Middleware:** + + javascript + // middleware/errorMiddleware.js + const errorHandler = (err, req, res, next) => { + console.error(err.stack); + const statusCode = res.statusCode === 200 ? 500 : res.statusCode; + res.status(statusCode); + res.json({ + message: err.message, + stack: process.env.NODE_ENV === 'production' ? null : err.stack, + }); + }; + + module.exports = errorHandler; + + + ## 3. Performance Considerations + + - ### Optimization Techniques + + - **Gzip Compression:** Use Gzip compression to reduce the size of responses. + - **Caching:** Implement caching at different levels (e.g., browser caching, server-side caching) to reduce server load. + - **Connection Pooling:** Use connection pooling for database connections to improve performance. + - **Load Balancing:** Distribute traffic across multiple servers using a load balancer. + + - ### Memory Management + + - **Avoid Memory Leaks:** Be mindful of memory leaks, especially when working with large datasets or long-running processes. Use tools like `memwatch` to profile. + - **Garbage Collection:** Understand how garbage collection works in Node.js and optimize your code accordingly. + - **Streams:** Use streams for handling large files or data streams to avoid loading the entire data into memory. + + - ### Rendering Optimization + + - **Template Caching:** Enable template caching in your template engine to improve rendering performance. + - **Minify Assets:** Minify CSS and JavaScript files to reduce their size. + - **Lazy Loading Images:** Lazy load images to improve initial page load time. + + - ### Bundle Size Optimization + + - **Tree Shaking:** Use tree shaking to remove unused code from your bundles. + - **Code Splitting:** Split your code into smaller chunks to reduce the size of initial bundles. + - **Dependency Analysis:** Analyze your dependencies to identify and remove unnecessary packages. + + - ### Lazy Loading Strategies + + - **Lazy Load Modules:** Load modules only when they are needed using dynamic imports (`import()`). + - **Lazy Load Images and Other Assets:** Use lazy loading for images and other assets that are not immediately visible on the page. + + ## 4. Security Best Practices + + - ### Common Vulnerabilities and How to Prevent Them + + - **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and encoding output. + - **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using CSRF tokens. + - **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks. + - **NoSQL Injection:** Sanitize user input and avoid constructing queries from strings to prevent NoSQL injection attacks. + - **Command Injection:** Avoid executing shell commands based on user input. If necessary, sanitize the input and use appropriate escaping. + - **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks. + - **Man-in-the-Middle (MitM):** Use HTTPS to encrypt communication between the client and server and protect against MitM attacks. + - **HTTP Parameter Pollution (HPP):** Avoid using the same parameter multiple times in a request to prevent HPP attacks. + + - ### Input Validation + + - **Server-Side Validation:** Always validate user input on the server-side, even if you have client-side validation. + - **Data Sanitization:** Sanitize user input to remove potentially harmful characters or code. + - **Schema Validation:** Use schema validation libraries (e.g., Joi, express-validator) to validate request data against a predefined schema. + + - ### Authentication and Authorization Patterns + + - **Authentication:** Use a secure authentication mechanism (e.g., JWT, OAuth) to verify user identities. + - **Authorization:** Implement role-based access control (RBAC) or attribute-based access control (ABAC) to control access to resources. + - **Secure Password Storage:** Use a strong hashing algorithm (e.g., bcrypt) to store user passwords securely. + - **Multi-Factor Authentication (MFA):** Implement MFA to add an extra layer of security. + + - ### Data Protection Strategies + + - **Encryption:** Encrypt sensitive data at rest and in transit. + - **Data Masking:** Mask sensitive data in logs and other outputs. + - **Access Control:** Restrict access to sensitive data to authorized users and processes. + + - ### Secure API Communication + + - **HTTPS:** Use HTTPS for all API communication. + - **API Keys:** Use API keys to authenticate clients. + - **Rate Limiting:** Implement rate limiting to prevent abuse and DoS attacks. + - **Input Validation:** Validate all input data to prevent injection attacks. + - **Output Encoding:** Encode all output data to prevent XSS attacks. + + ## 5. Testing Approaches + + - ### Unit Testing Strategies + + - **Test-Driven Development (TDD):** Write unit tests before writing the actual code. + - **Test Individual Modules:** Test individual modules in isolation to ensure they work correctly. + - **Mock Dependencies:** Mock external dependencies (e.g., databases, APIs) to isolate the module being tested. + + - ### Integration Testing + + - **Test Interactions Between Modules:** Test the interactions between different modules to ensure they work together correctly. + - **Test API Endpoints:** Test API endpoints to ensure they return the expected results. + + - ### End-to-End Testing + + - **Test the Entire Application Flow:** Test the entire application flow from start to finish. + - **Simulate User Interactions:** Simulate user interactions to ensure the application behaves as expected. + + - ### Test Organization + + - **Separate Test Files:** Create separate test files for each module or component. + - **Descriptive Test Names:** Use clear and descriptive names for test cases. + - **Arrange-Act-Assert Pattern:** Follow the Arrange-Act-Assert pattern in your tests. + + - ### Mocking and Stubbing + + - **Use Mocking Libraries:** Use mocking libraries (e.g., Jest, Sinon) to create mocks and stubs. + - **Mock External Dependencies:** Mock external dependencies to isolate the module being tested. + - **Stub Function Calls:** Stub function calls to control the behavior of dependencies. + + ## 6. Common Pitfalls and Gotchas + + - ### Frequent Mistakes Developers Make + + - **Not Handling Errors Properly:** Always handle errors properly to prevent unexpected behavior. + - **Ignoring Security Vulnerabilities:** Be aware of common security vulnerabilities and take steps to prevent them. + - **Not Using Middleware Wisely:** Use middleware wisely to handle common tasks such as authentication, logging, and error handling. + - **Over-Engineering:** Avoid over-engineering your code by keeping it simple and focused. + + - ### Edge Cases to Be Aware Of + + - **Handling Large File Uploads:** Use streams or middleware libraries for handling large file uploads to prevent memory issues. + - **Dealing with Timezones:** Be aware of timezone issues when working with dates and times. + - **Handling Unicode Characters:** Properly handle Unicode characters to prevent encoding issues. + - **Dealing with Concurrent Requests:** Implement concurrency control mechanisms to handle concurrent requests safely. + + - ### Version-Specific Issues + + - **Deprecated Features:** Be aware of deprecated features and use the recommended alternatives. + - **Breaking Changes:** Be aware of breaking changes when upgrading to a new version of Express.js. + + - ### Compatibility Concerns + + - **Browser Compatibility:** Test your application in different browsers to ensure it works correctly. + - **Operating System Compatibility:** Test your application on different operating systems to ensure it works correctly. + - **Node.js Version Compatibility:** Ensure your application is compatible with the supported versions of Node.js. + + - ### Debugging Strategies + + - **Use Debugging Tools:** Use debugging tools (e.g., Node.js Inspector, Chrome DevTools) to debug your code. + - **Log Statements:** Use log statements to track the flow of execution and identify issues. + - **Error Messages:** Read error messages carefully to understand the cause of the error. + + ## 7. Tooling and Environment + + - ### Recommended Development Tools + + - **IDE:** Use a good IDE such as VS Code, WebStorm, or Sublime Text. + - **Debugger:** Use a debugger to step through your code and identify issues. + - **Linter:** Use a linter (e.g., ESLint) to enforce coding standards. + - **Formatter:** Use a formatter (e.g., Prettier) to format your code automatically. + + - ### Build Configuration + + - **Use a Build Tool:** Use a build tool (e.g., Webpack, Parcel) to bundle and optimize your code. + - **Configure Build Scripts:** Configure build scripts in your `package.json` file to automate the build process. + - **Use Environment Variables:** Use environment variables to configure your application for different environments. + + - ### Linting and Formatting + + - **Use ESLint:** Use ESLint to enforce coding standards and identify potential issues. + - **Use Prettier:** Use Prettier to format your code automatically. + - **Configure Editor Integration:** Configure your editor to automatically run ESLint and Prettier on save. + + - ### Deployment Best Practices + + - **Use a Process Manager:** Use a process manager (e.g., PM2, Forever) to keep your application running in production. + - **Use a Reverse Proxy:** Use a reverse proxy (e.g., Nginx, Apache) to handle incoming requests and forward them to your application. + - **Use a Load Balancer:** Use a load balancer to distribute traffic across multiple servers. + - **Use HTTPS:** Use HTTPS to encrypt communication between the client and server. + - **Monitor Your Application:** Monitor your application to identify and resolve issues. + + - ### CI/CD Integration + + - **Use a CI/CD Pipeline:** Use a CI/CD pipeline (e.g., Jenkins, Travis CI, CircleCI, GitHub Actions) to automate the build, test, and deployment process. + - **Run Tests Automatically:** Configure your CI/CD pipeline to run tests automatically on every commit. + - **Automate Deployment:** Automate the deployment process to reduce the risk of errors. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/nodejs/nestjs.mdc b/rules-mdc/backend_frameworks/nodejs/nestjs.mdc new file mode 100644 index 0000000..78bba87 --- /dev/null +++ b/rules-mdc/backend_frameworks/nodejs/nestjs.mdc @@ -0,0 +1,178 @@ +--- +description: This rule provides comprehensive guidance on NestJS best practices, coding standards, and architectural patterns. It aims to help developers build scalable, maintainable, and performant NestJS applications by covering code organization, security, testing, and other essential aspects. +globs: **/*.ts +--- +- **Code Organization and Structure:** + - **Directory Structure:** + - Adopt a modular structure that reflects the application's domain or features. A common approach includes organizing code into modules, services, controllers, DTOs, and entities, each in their own directory. + - Example: + + src/ + ├── app.module.ts + ├── auth/ + │ ├── auth.module.ts + │ ├── auth.controller.ts + │ ├── auth.service.ts + │ ├── strategies/ + │ │ └── jwt.strategy.ts + │ ├── dtos/ + │ │ └── create-user.dto.ts + │ └── entities/ + │ └── user.entity.ts + ├── users/ + │ ├── users.module.ts + │ ├── users.controller.ts + │ ├── users.service.ts + │ └── ... + ├── core/ + │ ├── filters/ + │ │ └── http-exception.filter.ts + │ ├── interceptors/ + │ │ └── logging.interceptor.ts + │ └── ... + └── main.ts + + - **File Naming Conventions:** + - Use descriptive and consistent naming conventions. Prefix files based on their role (e.g., `user.controller.ts`, `auth.service.ts`, `create-user.dto.ts`). + - Use PascalCase for classes and interfaces (e.g., `UserService`, `CreateUserDto`). + - Use camelCase for instances and variables (e.g., `userService`, `createUserDto`). + - **Module Organization:** + - Encapsulate features within modules. Each module should represent a distinct part of the application and handle related functionality. + - Modules should import necessary dependencies and export components that other modules need. + - Use the `forRoot` and `forFeature` methods for configuration and feature modules, respectively, especially when dealing with database connections or other shared resources. + - **Component Architecture:** + - Follow the SOLID principles for designing components. Each component (controller, service, etc.) should have a single responsibility. + - Use dependency injection to manage dependencies between components, making them more testable and maintainable. + - Controllers should handle request routing and validation, services should implement business logic, and entities should represent data models. + - **Code Splitting Strategies:** + - For large applications, consider splitting modules into smaller, more manageable chunks using feature modules or lazy-loaded modules. + - Use dynamic imports and lazy loading to improve initial load times and reduce bundle size. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Dependency Injection:** Use NestJS's built-in dependency injection container to manage dependencies and promote loose coupling. + - **Repository Pattern:** Abstract data access logic into repositories to decouple services from specific database implementations. + - **Unit of Work:** Use a Unit of Work pattern for managing transactions across multiple repositories. + - **CQRS (Command Query Responsibility Segregation):** For complex applications, consider using CQRS to separate read and write operations, improving performance and scalability. + - **Recommended Approaches:** + - Use DTOs (Data Transfer Objects) for data validation and transformation between layers. + - Implement global exception filters to handle errors consistently across the application. + - Use interceptors for logging, caching, and other cross-cutting concerns. + - Utilize pipes for request validation and data transformation. + - Use asynchronous operations (`async/await`) for non-blocking I/O operations. + - **Anti-patterns:** + - **Tight Coupling:** Avoid creating tightly coupled components that are difficult to test and maintain. Use dependency injection and interfaces to promote loose coupling. + - **God Classes:** Avoid creating classes with too many responsibilities. Break down large classes into smaller, more manageable components. + - **Ignoring Errors:** Always handle errors properly using try-catch blocks, exception filters, and logging. Never ignore errors or swallow exceptions. + - **Hardcoding Configuration:** Avoid hardcoding configuration values directly in the code. Use environment variables or configuration files to manage settings. + - **State Management:** + - For simple applications, use services to manage application state. + - For more complex applications, consider using a state management library like Redux or NgRx (although this is less common on the backend). + - Avoid storing sensitive data in the client-side state. Store it securely on the server. + - **Error Handling:** + - Implement a global exception filter to catch unhandled exceptions and return appropriate error responses to the client. + - Use custom exceptions to represent specific error conditions in the application. + - Log errors with sufficient detail to facilitate debugging. + - Return consistent error responses with appropriate HTTP status codes. + +- **Performance Considerations:** + - **Optimization Techniques:** + - Use caching to reduce database load and improve response times. NestJS provides built-in support for caching using interceptors. + - Optimize database queries by using indexes, avoiding N+1 queries, and using efficient data retrieval methods. + - Use connection pooling to reduce the overhead of establishing database connections. + - Profile the application to identify performance bottlenecks and optimize accordingly. + - **Memory Management:** + - Avoid memory leaks by properly managing resources and releasing unused objects. + - Use streams for handling large files or data streams. + - Use object pooling to reuse frequently created objects. + - **Rendering Optimization (Server-Side Rendering):** + - Not directly applicable to NestJS, as it's primarily a backend framework. However, if using SSR, optimize rendering performance by caching rendered pages and using efficient templating engines. + - **Bundle Size Optimization:** + - Use tree shaking to remove unused code from the bundle. + - Minify and compress code to reduce bundle size. + - Use code splitting to load only the necessary code for each route or module. + - **Lazy Loading:** + - Use lazy loading to load modules or features on demand, improving initial load times. + - Implement code splitting to create smaller bundles that can be loaded independently. + +- **Security Best Practices:** + - **Common Vulnerabilities:** + - **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM that automatically escapes user inputs. + - **Cross-Site Scripting (XSS):** Protect against XSS by sanitizing user inputs and encoding outputs. + - **Cross-Site Request Forgery (CSRF):** Implement CSRF protection using tokens or other mechanisms. + - **Authentication and Authorization Flaws:** Secure authentication and authorization by using strong passwords, multi-factor authentication, and role-based access control. + - **Insecure Direct Object References (IDOR):** Prevent IDOR by validating user access to resources before granting access. + - **Input Validation:** + - Validate all user inputs to prevent malicious data from entering the system. Use DTOs and validation pipes to enforce input constraints. + - Sanitize user inputs to remove or escape potentially harmful characters. + - Validate file uploads to prevent malicious files from being uploaded. + - **Authentication and Authorization:** + - Use JWT (JSON Web Tokens) for authentication and authorization. + - Implement role-based access control (RBAC) to restrict access to resources based on user roles. + - Use secure password hashing algorithms (e.g., bcrypt) to store passwords securely. + - Implement rate limiting to prevent brute-force attacks. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to encrypt communication between the client and server. + - Store secrets securely using environment variables or a secrets management system. + - **Secure API Communication:** + - Use API keys or OAuth 2.0 for API authentication and authorization. + - Implement request validation and rate limiting to protect APIs from abuse. + - Use a secure API gateway to manage API traffic and enforce security policies. + +- **Testing Approaches:** + - **Unit Testing:** + - Write unit tests for individual components (services, controllers, etc.) to verify their functionality in isolation. + - Use mocking and stubbing to isolate components from their dependencies. + - Follow the Arrange-Act-Assert pattern for writing clear and concise unit tests. + - **Integration Testing:** + - Write integration tests to verify the interaction between multiple components or modules. + - Test the integration between the application and external systems (e.g., databases, APIs). + - **End-to-End Testing:** + - Write end-to-end tests to verify the application's functionality from a user's perspective. + - Use tools like Puppeteer or Cypress to automate end-to-end tests. + - **Test Organization:** + - Organize tests into separate directories that mirror the application's directory structure. + - Use descriptive names for test files and test cases. + - **Mocking and Stubbing:** + - Use mocking frameworks (e.g., Jest, Sinon.js) to create mock objects and stub methods. + - Use dependency injection to make components easily testable. + +- **Common Pitfalls and Gotchas:** + - **Frequent Mistakes:** + - **Not using DTOs for validation:** Always use DTOs and validation pipes to ensure data integrity. + - **Ignoring environment variables:** Use environment variables for configuration to avoid hardcoding values. + - **Not handling exceptions properly:** Implement global exception filters to catch unhandled exceptions and return appropriate error responses. + - **Overlooking security vulnerabilities:** Be aware of common security vulnerabilities and take steps to mitigate them. + - **Edge Cases:** + - **Handling large file uploads:** Use streams and appropriate buffering techniques to handle large file uploads efficiently. + - **Dealing with concurrent requests:** Use appropriate locking mechanisms or transaction management to handle concurrent requests safely. + - **Version-Specific Issues:** + - Be aware of breaking changes between NestJS versions and update code accordingly. + - Consult the NestJS documentation for migration guides and compatibility information. + - **Compatibility Concerns:** + - Ensure compatibility with different Node.js versions and operating systems. + - Test the application on different browsers and devices to ensure cross-platform compatibility. + - **Debugging Strategies:** + - Use the NestJS debugger to step through code and inspect variables. + - Use logging to track the flow of execution and identify errors. + - Use profiling tools to identify performance bottlenecks. + +- **Tooling and Environment:** + - **Recommended Development Tools:** + - **IDE:** Visual Studio Code with NestJS extensions. + - **CLI:** Nest CLI for generating and managing NestJS projects. + - **Database:** PostgreSQL, MySQL, MongoDB, or other compatible database. + - **Testing:** Jest, Supertest. + - **Build Configuration:** + - Use `tsconfig.json` to configure the TypeScript compiler. + - Use Webpack or Parcel to bundle and optimize the application. + - **Linting and Formatting:** + - Use ESLint and Prettier to enforce code style and formatting rules. + - Configure pre-commit hooks to automatically lint and format code before committing. + - **Deployment:** + - Deploy to platforms like Heroku, AWS, Google Cloud, or Azure. + - Use Docker to containerize the application and simplify deployment. + - **CI/CD Integration:** + - Integrate with CI/CD pipelines (e.g., Jenkins, Travis CI, GitHub Actions) to automate testing and deployment. + - Use environment-specific configuration files for different environments (development, staging, production). \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/php/laravel.mdc b/rules-mdc/backend_frameworks/php/laravel.mdc new file mode 100644 index 0000000..7a99379 --- /dev/null +++ b/rules-mdc/backend_frameworks/php/laravel.mdc @@ -0,0 +1,216 @@ +--- +description: This rule outlines comprehensive best practices for Laravel development, covering coding standards, security, performance, and testing to ensure maintainable, efficient, and secure applications. It provides guidelines for code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling. +globs: **/*.php +--- +- Adhere to PSR coding standards (PSR-1, PSR-2, PSR-12). +- Use meaningful and descriptive variable, function, and class names. +- Organize routes effectively, leveraging resource controllers and route groups. +- Use Eloquent ORM for database interactions; avoid raw SQL queries where possible (unless necessary for performance). +- Implement caching strategies using Laravel's caching system for frequently accessed data. +- Maintain a clear and consistent project structure following Laravel's conventions (app, config, database, public, resources, routes, storage). +- Ensure code simplicity and readability to enhance maintainability. Follow the single responsibility principle. +- Keep Laravel and its packages up-to-date to mitigate security vulnerabilities and leverage new features. + +### 1. Code Organization and Structure: + + - **Directory Structure Best Practices:** + - Follow Laravel's default directory structure: `app` (core application logic), `config` (configuration files), `database` (migrations and seeds), `public` (static assets), `resources` (views and assets), `routes` (route definitions), `storage` (file storage). + - Organize `app` directory using subdirectories like `Models`, `Controllers`, `Services`, `Repositories`, `Exceptions`, `Policies`, `Providers`, and `Http/Middleware`. + - Consider using modules for larger applications to encapsulate features. + + - **File Naming Conventions:** + - Use PascalCase for class names (e.g., `UserController`). + - Use camelCase for variable and function names (e.g., `$userName`, `getUserName()`). + - Use snake_case for database table names and column names (e.g., `users`, `user_id`). + - Use kebab-case for route names (e.g., `user.profile`). + - Use descriptive names that clearly indicate the purpose of the file or class. + + - **Module Organization:** + - For larger applications, use packages or modules to organize code into reusable components. + - Implement module-specific service providers, routes, and configurations. + - Isolate module dependencies to prevent conflicts. + + - **Component Architecture:** + - Use Blade components for reusable UI elements. + - Create custom components for complex logic and rendering. + - Pass data to components using attributes and slots. + - Encapsulate component logic in dedicated classes. + + - **Code Splitting Strategies:** + - Use lazy loading for non-critical features. + - Split large controllers into smaller, more manageable classes. + - Extract complex logic into service classes or repositories. + +### 2. Common Patterns and Anti-patterns: + + - **Design Patterns Specific to Laravel:** + - **Repository Pattern:** Abstract data access logic from controllers. + - **Service Pattern:** Encapsulate business logic into reusable classes. + - **Observer Pattern:** Implement event-driven behavior for model changes. + - **Factory Pattern:** Create test data and seed databases. + - **Strategy Pattern:** Define a family of algorithms and make them interchangeable. + + - **Recommended Approaches for Common Tasks:** + - Use Eloquent ORM for database interactions, including relationships and aggregations. + - Use Laravel's validation system for request data validation. + - Use middleware for authentication, authorization, and request modification. + - Use queues for background processing and asynchronous tasks. + - Use events and listeners for decoupling components. + + - **Anti-patterns and Code Smells to Avoid:** + - **God Classes:** Avoid creating large classes with too many responsibilities. + - **Spaghetti Code:** Avoid complex and unstructured code that is difficult to understand and maintain. + - **Copy-Paste Programming:** Avoid duplicating code; instead, create reusable components or functions. + - **Ignoring Exceptions:** Always handle exceptions properly to prevent unexpected behavior. + - **Over-Engineering:** Don't overcomplicate solutions with unnecessary complexity. + - **Mass Assignment Vulnerability:** Use guarded or fillable attributes to protect against mass assignment vulnerabilities. + + - **State Management Best Practices:** + - Use sessions for storing user-specific data. + - Use cookies for storing client-side data. + - Use the cache for storing frequently accessed data. + - Use databases for persistent data storage. + - Consider using Laravel's broadcasting feature for real-time updates. + + - **Error Handling Patterns:** + - Use try-catch blocks to handle exceptions gracefully. + - Use Laravel's exception handler to log and report errors. + - Implement custom exception classes for specific error scenarios. + - Provide informative error messages to users. + +### 3. Performance Considerations: + + - **Optimization Techniques:** + - Use caching to reduce database queries and improve response times. + - Use eager loading to reduce N+1 query problems. + - Use queues for background processing. + - Optimize database queries with indexes and query optimization techniques. + - Minimize the use of loops and conditional statements in performance-critical code. + + - **Memory Management:** + - Avoid storing large amounts of data in memory. + - Use garbage collection to free up memory. + - Use streams for processing large files. + + - **Rendering Optimization:** + - Use Blade's caching features to cache rendered views. + - Use CSS and JavaScript minification to reduce file sizes. + - Use image optimization techniques to reduce image sizes. + + - **Bundle Size Optimization:** + - Use Laravel Mix to bundle and minify assets. + - Remove unused CSS and JavaScript code. + - Use code splitting to load only the necessary code for each page. + + - **Lazy Loading Strategies:** + - Use lazy loading for images and other non-critical assets. + - Use route model binding with eager loading to reduce database queries. + +### 4. Security Best Practices: + + - **Common Vulnerabilities and How to Prevent Them:** + - **SQL Injection:** Use Eloquent ORM and prepared statements to prevent SQL injection attacks. + - **Cross-Site Scripting (XSS):** Sanitize user input and escape output to prevent XSS attacks. + - **Cross-Site Request Forgery (CSRF):** Use CSRF protection tokens to prevent CSRF attacks. + - **Mass Assignment:** Use guarded or fillable attributes to protect against mass assignment vulnerabilities. + - **Authentication and Authorization:** Use Laravel's built-in authentication and authorization features. + + - **Input Validation:** + - Use Laravel's validation system to validate all user input. + - Sanitize user input to remove potentially harmful characters. + - Validate file uploads to prevent malicious files from being uploaded. + + - **Authentication and Authorization Patterns:** + - Use Laravel's built-in authentication system for user authentication. + - Use policies to define authorization rules. + - Use gates to authorize access to specific resources. + - Implement two-factor authentication for enhanced security. + + - **Data Protection Strategies:** + - Encrypt sensitive data using Laravel's encryption features. + - Store passwords using bcrypt hashing. + - Protect API keys and other sensitive configuration data. + + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Use API tokens for authentication. + - Implement rate limiting to prevent abuse. + - Validate API requests and responses. + +### 5. Testing Approaches: + + - **Unit Testing Strategies:** + - Test individual units of code in isolation. + - Use mock objects to isolate dependencies. + - Write tests for all critical code paths. + + - **Integration Testing:** + - Test the interaction between different components of the application. + - Test database interactions and external API calls. + + - **End-to-End Testing:** + - Test the entire application from end to end. + - Use browser automation tools to simulate user interactions. + + - **Test Organization:** + - Organize tests into logical groups. + - Use descriptive test names. + - Follow the arrange-act-assert pattern. + + - **Mocking and Stubbing:** + - Use mock objects to isolate dependencies. + - Use stubbing to replace complex dependencies with simpler implementations. + +### 6. Common Pitfalls and Gotchas: + + - **Frequent Mistakes Developers Make:** + - Not using dependency injection properly. + - Writing complex logic in views. + - Not using caching effectively. + - Ignoring security vulnerabilities. + - Not writing tests. + + - **Edge Cases to Be Aware Of:** + - Handling large file uploads. + - Dealing with concurrent requests. + - Handling database connection errors. + - Handling time zone conversions. + + - **Version-Specific Issues:** + - Be aware of breaking changes between Laravel versions. + - Consult the Laravel upgrade guide when upgrading to a new version. + + - **Compatibility Concerns:** + - Ensure compatibility with different PHP versions and extensions. + - Ensure compatibility with different database systems. + + - **Debugging Strategies:** + - Use Laravel's debugging tools (e.g., debugbar, telescope). + - Use logging to track application behavior. + - Use Xdebug for step-by-step debugging. + +### 7. Tooling and Environment: + + - **Recommended Development Tools:** + - PHPStorm or VS Code with PHP extensions. + - Composer for dependency management. + - MySQL or PostgreSQL for database management. + - Docker for containerization. + + - **Build Configuration:** + - Use Laravel Mix to compile assets. + - Use environment variables to configure the application. + - Use a build script to automate the build process. + + - **Linting and Formatting:** + - Use PHP CS Fixer to enforce coding standards. + - Use ESLint and Prettier for JavaScript and CSS linting and formatting. + + - **Deployment Best Practices:** + - Use a deployment tool like Envoyer or Deployer. + - Use zero-downtime deployment strategies. + - Use a CDN for static assets. + + - **CI/CD Integration:** + - Use a CI/CD pipeline to automate testing and deployment. + - Use tools like Jenkins, GitLab CI, or GitHub Actions. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/python/django.mdc b/rules-mdc/backend_frameworks/python/django.mdc new file mode 100644 index 0000000..41c83ad --- /dev/null +++ b/rules-mdc/backend_frameworks/python/django.mdc @@ -0,0 +1,202 @@ +--- +description: Comprehensive guide to Django best practices covering code organization, performance, security, testing, and common pitfalls. This rule ensures adherence to community standards for maintainable and efficient Django applications. +globs: **/*.py +--- +# Django Best Practices and Coding Standards + +This guide outlines best practices for developing Django applications to ensure code quality, maintainability, performance, and security. + +## 1. Code Organization and Structure + +- **Directory Structure:** + - **Project Root:** Manage.py, settings, urls, wsgi. + - **Apps:** Each app should reside in its own directory. + - **Static Files:** Separate directory for static files (CSS, JavaScript, images). + - **Templates:** Dedicated directory for HTML templates. + - **Media:** For user-uploaded files. + - **Tests:** Tests for each app in a separate tests/ directory. + +- **File Naming Conventions:** + - Use lowercase letters with underscores (snake_case) for Python files and variables (e.g., `models.py`, `user_profile`). + - Classes should use CamelCase (e.g., `UserProfile`). + - Function names should use snake_case (e.g., `get_user_profile`). + +- **Module Organization:** + - Each app should be a self-contained module. + - Group related functionalities into submodules within the app. + - Use `__init__.py` files to define packages. + +- **Component Architecture:** + - Follow the Model-View-Template (MVT) architecture. + - Keep models lean and focused on data representation. + - Use views for request handling and business logic. + - Templates should focus on presentation. + +- **Code Splitting Strategies:** + - Break down large views into smaller, reusable functions or class-based views. + - Use mixins to share functionality across multiple views. + - Implement custom template tags and filters for reusable template logic. + - Consider using Celery for asynchronous task processing. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Model-View-Template (MVT):** Django's core architectural pattern. + - **Form Objects:** Use Django's forms for handling user input and validation. + - **Signals:** Implement signals for decoupled event handling. + - **Managers:** Use custom model managers to encapsulate query logic. + - **DRY (Don't Repeat Yourself):** Avoid redundant code by extracting reusable components. + +- **Recommended Approaches:** + - **Database Interactions:** Use Django's ORM for database interactions. Avoid raw SQL queries unless necessary. + - **Form Handling:** Leverage Django's form classes for data validation and rendering forms. + - **URL Routing:** Use named URL patterns for reverse URL lookup. + - **Template Inheritance:** Utilize template inheritance to create a consistent look and feel. + +- **Anti-patterns and Code Smells:** + - **Fat Models:** Avoid putting too much business logic in models. Use services or utility functions instead. + - **Complex Templates:** Keep templates simple and focused on presentation. Move complex logic to views or custom template tags. + - **Hardcoded Values:** Avoid hardcoding values in code. Use settings or environment variables. + - **Ignoring Security:** Neglecting security best practices can lead to vulnerabilities. + +- **State Management:** + - Use Django's session framework for managing user sessions. + - Avoid storing sensitive data in sessions. + - Consider using a dedicated caching system (e.g., Redis, Memcached) for storing frequently accessed data. + +- **Error Handling:** + - Implement proper error handling using `try...except` blocks. + - Use Django's logging framework to log errors and warnings. + - Display user-friendly error messages. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - **Database Optimization:** Use indexes on frequently queried fields. + - **Caching:** Implement caching at various levels (e.g., template caching, view caching, database caching). + - **Query Optimization:** Use `select_related` and `prefetch_related` to reduce the number of database queries. + - **Gzip Compression:** Enable Gzip compression for static files and responses. + +- **Memory Management:** + - Avoid loading large datasets into memory. Use iterators or generators. + - Close database connections and file handles properly. + - Be mindful of memory leaks. + +- **Rendering Optimization:** + - Minimize the use of complex template logic. + - Use template caching to cache rendered templates. + - Optimize images and other static assets. + +- **Lazy Loading Strategies:** + - Implement lazy loading for images and other resources that are not immediately visible. + - Use pagination to display large datasets in smaller chunks. + +## 4. Security Best Practices + +- **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates and using Django's `escape` filter. + - **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using Django's CSRF protection. + - **SQL Injection:** Use Django's ORM to prevent SQL injection attacks. Avoid raw SQL queries. + - **Authentication and Authorization Issues:** Implement proper authentication and authorization mechanisms. + +- **Input Validation:** + - Validate all user input on both the client-side and server-side. + - Use Django's form validation to validate data. + - Sanitize user input to remove potentially harmful characters. + +- **Authentication and Authorization:** + - Use Django's built-in authentication system for user authentication. + - Implement proper authorization checks to restrict access to sensitive resources. + - Use Django's permission system to manage user permissions. + +- **Data Protection:** + - Store sensitive data securely using encryption. + - Use HTTPS to encrypt communication between the client and server. + - Protect against data breaches by implementing proper access controls and monitoring. + +- **Secure API Communication:** + - Use authentication tokens or API keys to authenticate API requests. + - Implement rate limiting to prevent abuse. + - Validate all API input. + +## 5. Testing Approaches + +- **Unit Testing:** + - Write unit tests for individual functions and classes. + - Use Django's testing framework to write and run tests. + - Mock external dependencies to isolate units of code. + +- **Integration Testing:** + - Write integration tests to test the interaction between different components. + - Test database interactions, form handling, and view rendering. + +- **End-to-End Testing:** + - Write end-to-end tests to test the entire application flow. + - Use tools like Selenium or Cypress to automate browser testing. + +- **Test Organization:** + - Organize tests into separate test suites for each app or component. + - Use meaningful test names to describe what each test does. + - Keep tests concise and focused. + +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate units of code during testing. + - Avoid mocking external dependencies unless necessary. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes:** + - **Incorrect Database Configuration:** Ensure that the database settings are configured correctly. + - **Improper Static File Handling:** Configure static file serving properly in production. + - **Not Using Django's Built-in Features:** Leverage Django's built-in features instead of reinventing the wheel. + - **Ignoring Security Warnings:** Address any security warnings or vulnerabilities reported by Django's security checks. + +- **Edge Cases:** + - **Handling Time Zones:** Be mindful of time zones and use Django's time zone support. + - **Dealing with Unicode:** Handle Unicode characters correctly. + - **Managing File Uploads:** Implement proper file upload handling to prevent security vulnerabilities. + +- **Version-Specific Issues:** + - Be aware of compatibility issues between different Django versions. + - Consult the Django release notes for information about breaking changes. + +- **Compatibility Concerns:** + - Ensure that your code is compatible with different browsers and devices. + - Test your application on different platforms. + +- **Debugging Strategies:** + - Use Django's debugging tools to identify and fix errors. + - Use logging to track the execution flow of your application. + - Consult the Django documentation and community forums for help. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - **IDE:** PyCharm, VS Code, Sublime Text + - **Package Manager:** pip, uv + - **Database Client:** pgAdmin, MySQL Workbench + +- **Build Configuration:** + - Use a `requirements.txt` file to manage dependencies. + - Use a virtual environment to isolate project dependencies. + +- **Linting and Formatting:** + - Use Black to format code automatically. + - Use flake8 to lint code and identify potential errors. + +- **Deployment Best Practices:** + - Use a production-ready web server (e.g., Gunicorn, uWSGI). + - Configure a reverse proxy (e.g., Nginx, Apache). + - Use a database server (e.g., PostgreSQL, MySQL). + +- **CI/CD Integration:** + - Integrate your project with a CI/CD pipeline to automate testing and deployment. + - Use tools like Jenkins, Travis CI, or GitLab CI. + +## Additional Notes + +- Always follow PEP 8 guidelines for Python code. +- Write clear and concise comments. +- Keep your code DRY (Don't Repeat Yourself). +- Regularly update your dependencies. +- Monitor your application for performance and security issues. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/python/fastapi.mdc b/rules-mdc/backend_frameworks/python/fastapi.mdc new file mode 100644 index 0000000..465be69 --- /dev/null +++ b/rules-mdc/backend_frameworks/python/fastapi.mdc @@ -0,0 +1,336 @@ +--- +description: Comprehensive guidelines for developing robust, scalable, and maintainable FastAPI applications. Covers code structure, performance, security, testing, and common pitfalls. +globs: **/*.py +--- +# FastAPI Best Practices: A Comprehensive Guide + +This document provides a comprehensive set of best practices and coding standards for developing FastAPI applications. These guidelines cover various aspects of development, including project structure, common patterns, performance considerations, security, testing, and tooling. + +## 1. Code Organization and Structure + +A well-structured codebase is crucial for maintainability, scalability, and collaboration. Adopting a consistent and predictable project structure makes it easier for developers to navigate and understand the application. + +### 1.1 Directory Structure Best Practices + +Inspired by projects like Netflix's Dispatch, a feature-based directory structure is recommended, especially for larger applications: + + +fastapi-project/ +├── alembic/ # Database migrations +├── src/ # Source code +│ ├── auth/ # Authentication module +│ │ ├── router.py # API endpoints for authentication +│ │ ├── schemas.py # Pydantic models for request/response +│ │ ├── models.py # Database models +│ │ ├── dependencies.py# Dependency injection definitions +│ │ ├── config.py # Local configurations +│ │ ├── constants.py # Constants and error codes +│ │ ├── exceptions.py # Custom exceptions +│ │ ├── service.py # Business logic +│ │ └── utils.py # Utility functions +│ ├── aws/ # AWS integration module (example) +│ │ ├── ... +│ ├── posts/ # Posts module +│ │ ├── ... +│ ├── config.py # Global configurations +│ ├── models.py # Global models +│ ├── exceptions.py # Global exceptions +│ ├── pagination.py # Pagination logic +│ ├── database.py # Database connection and ORM setup +│ └── main.py # Main application entry point +├── tests/ # Tests +│ ├── auth/ +│ ├── aws/ +│ └── posts/ +├── templates/ # Jinja2 Templates +│ └── index.html +├── requirements/ +│ ├── base.txt # Base dependencies +│ ├── dev.txt # Development dependencies +│ └── prod.txt # Production dependencies +├── .env # Environment variables +├── .gitignore # Git ignore file +├── logging.ini # Logging configuration +└── alembic.ini # Alembic configuration + + +Key aspects of this structure: + +* `src/`: The root directory containing all application code. +* Module-based organization: Features are grouped into modules (e.g., `auth`, `posts`). Each module contains its own set of `router.py`, `schemas.py`, `models.py`, etc. This promotes loose coupling and high cohesion. +* `main.py`: The entry point of the FastAPI application. +* `config.py`: Stores global configurations. +* `database.py`: Handles database connection and ORM setup (e.g., SQLAlchemy). +* `requirements/`: Separate dependency files for different environments. + +### 1.2 File Naming Conventions + +* Python files: Use lowercase with underscores (e.g., `user_service.py`). +* Pydantic schemas: Use PascalCase with the suffix "Schema" or "Model" (e.g., `UserSchema`, `PostModel`). +* Database models: Use PascalCase (e.g., `User`, `Post`). +* Routers: Typically named `router.py` within each module. +* Configuration files: `config.py` +* Tests: `test_.py` or `test_.py` + +### 1.3 Module Organization + +* **Routers**: Contain API endpoint definitions. +* **Schemas**: Define data structures using Pydantic models for request and response validation and serialization. +* **Models**: Represent database entities (if using an ORM). +* **Services**: Implement business logic, interacting with the database or other services. +* **Dependencies**: Define dependency injection functions used in route handlers. +* **Constants**: Store module-specific constants and error codes. +* **Configuration**: Store module-specific environment variables and settings. +* **Exceptions**: Define custom exceptions for specific modules. +* **Utils**: Contains general-purpose utility functions. + +### 1.4 Component Architecture + +* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access). This improves maintainability and testability. +* **Loose Coupling:** Design components to be independent and minimize dependencies between them. This allows for easier modification and replacement of components. +* **High Cohesion:** Ensure that each component has a single, well-defined responsibility. +* **Dependency Injection:** Use FastAPI's built-in dependency injection system to manage dependencies between components. This promotes testability and reusability. Favor interface-based dependency injection for added flexibility. + +### 1.5 Code Splitting Strategies + +* **Feature-Based Splitting:** Divide the codebase into modules based on application features (e.g., user management, product catalog, order processing). This makes it easier to understand and maintain the code. +* **Vertical Slicing:** Group related components (e.g., routers, schemas, models, services) into slices that represent specific use cases or functionalities. +* **Horizontal Splitting:** Separate components based on technical layers (e.g., presentation, business logic, data access). This is useful for enforcing separation of concerns but can lead to more complex dependencies if not managed carefully. + +## 2. Common Patterns and Anti-patterns + +Employ established design patterns and avoid common anti-patterns to write clean, efficient, and maintainable FastAPI code. + +### 2.1 Design Patterns Specific to FastAPI + +* **Repository Pattern:** Abstract data access logic behind a repository interface. This allows you to switch data sources easily (e.g., from a database to a mock for testing) and centralizes data access concerns. +* **Service Layer Pattern:** Encapsulate business logic in service classes. Routers then call the service layer. Promotes testability and keeps routes thin and focused on request/response handling. +* **Dependency Injection:** Utilize FastAPI's dependency injection system extensively for request validation, authentication, authorization, and accessing shared resources like database connections. +* **Asynchronous Operations:** Favor `async` functions for I/O-bound tasks to improve performance and concurrency. +* **Pydantic Models for Validation:** Use Pydantic models for request and response data validation. Enforce data types, constraints, and custom validation logic. + +### 2.2 Recommended Approaches for Common Tasks + +* **Configuration Management:** Use Pydantic's `BaseSettings` to manage environment variables and application settings. +* **Database Interactions:** Use an ORM like SQLAlchemy for interacting with databases. Define database models and use them for data access. +* **Authentication and Authorization:** Implement authentication and authorization using strategies like JWT (JSON Web Tokens) or OAuth 2.0. Use FastAPI's security utilities. +* **Error Handling:** Use `HTTPException` for returning meaningful error responses to the client. Define custom exception classes for specific error conditions. +* **Logging:** Configure logging using Python's `logging` module. Log important events and errors for debugging and monitoring. + +### 2.3 Anti-patterns and Code Smells to Avoid + +* **Fat Route Handlers:** Avoid putting too much logic directly inside route handlers. Delegate complex tasks to service classes or utility functions. +* **Tight Coupling:** Minimize dependencies between components to improve maintainability and testability. +* **Ignoring Asynchronous Operations:** Blocking I/O in async routes can negate the benefits of concurrency. Ensure all I/O operations in async routes are non-blocking. +* **Lack of Data Validation:** Failing to validate input data can lead to security vulnerabilities and unexpected behavior. Always use Pydantic models for data validation. +* **Hardcoding Values:** Avoid hardcoding values in the code. Use configuration files or environment variables instead. +* **Returning Pydantic objects directly from routes.** FastAPI makes an extra conversion. Return a dict. + +### 2.4 State Management Best Practices + +* **Stateless Applications:** FastAPI applications are typically stateless, meaning they don't store any persistent data within the application itself. This makes them easier to scale and deploy. +* **External Data Stores:** Store application state in external data stores like databases, caches, or message queues. +* **Dependency Injection for State:** Use dependency injection to provide access to shared resources or stateful objects to route handlers. + +### 2.5 Error Handling Patterns + +* **Centralized Exception Handling:** Implement a global exception handler to catch unhandled exceptions and return appropriate error responses. +* **Custom Exception Classes:** Define custom exception classes for specific error conditions. This makes it easier to identify and handle different types of errors. +* **Logging Errors:** Log all errors for debugging and monitoring. +* **Meaningful Error Messages:** Return meaningful error messages to the client to help them understand what went wrong. + +## 3. Performance Considerations + +FastAPI is known for its performance, but optimizations are still crucial for high-load applications. + +### 3.1 Optimization Techniques + +* **Asynchronous Operations:** Utilize `async` and `await` for I/O-bound operations to prevent blocking the event loop. +* **Database Connection Pooling:** Use a database connection pool to reuse database connections and reduce connection overhead. +* **Caching:** Implement caching for frequently accessed data to reduce database load and improve response times. Use tools like Redis or Memcached. +* **Gzip Compression:** Enable gzip compression for API responses to reduce the size of the data transmitted over the network. +* **Load Balancing:** Distribute traffic across multiple instances of the application to improve scalability and availability. +* **Profiling:** Use profiling tools to identify performance bottlenecks in the code. + +### 3.2 Memory Management + +* **Resource Management:** Properly manage resources like database connections, file handles, and network sockets. Close resources when they are no longer needed. +* **Data Structures:** Use efficient data structures like sets and dictionaries for fast lookups. +* **Generators:** Use generators for processing large datasets to avoid loading the entire dataset into memory at once. +* **Object Reuse:** Reuse objects whenever possible to reduce memory allocation overhead. Consider using object pools for frequently used objects. + +### 3.3 Rendering Optimization + +* **Template Caching:** Enable template caching for Jinja2 templates to reduce rendering overhead. +* **Minimize Template Logic:** Keep template logic simple and avoid complex computations in templates. +* **Content Delivery Network (CDN):** Use a CDN to serve static assets like images, CSS, and JavaScript files. + +### 3.4 Bundle Size Optimization (for Frontend Integration) + +* **Code Splitting:** Split the frontend code into smaller bundles that can be loaded on demand. +* **Tree Shaking:** Remove unused code from the frontend bundles using tree shaking techniques. +* **Minification:** Minify the frontend code to reduce its size. +* **Image Optimization:** Optimize images for the web by compressing them and using appropriate image formats. + +### 3.5 Lazy Loading Strategies + +* **Lazy Loading of Modules:** Use lazy loading to load modules only when they are needed. +* **Lazy Loading of Data:** Load data on demand instead of loading it all at once. +* **Asynchronous Loading:** Use asynchronous loading to load data in the background without blocking the main thread. + +## 4. Security Best Practices + +Security is paramount. Protect your FastAPI application from common web vulnerabilities. + +### 4.1 Common Vulnerabilities and How to Prevent Them + +* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM with proper escaping. +* **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and escaping output data. +* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens. +* **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms to protect sensitive data and resources. +* **Insecure Direct Object References (IDOR):** Prevent IDOR by verifying that users have access to the objects they are requesting. +* **Denial of Service (DoS):** Prevent DoS attacks by implementing rate limiting and input validation. + +### 4.2 Input Validation + +* **Pydantic Models:** Use Pydantic models to define data types, constraints, and validation rules for request bodies and query parameters. +* **Custom Validation Logic:** Implement custom validation logic for complex validation scenarios. +* **Sanitization:** Sanitize user input to remove potentially harmful characters or code. + +### 4.3 Authentication and Authorization Patterns + +* **JWT (JSON Web Tokens):** Use JWT for stateless authentication. Generate a JWT when a user logs in and verify the JWT on subsequent requests. +* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. Allow users to grant third-party applications access to their data without sharing their credentials. +* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles. +* **Attribute-Based Access Control (ABAC):** Implement ABAC to control access to resources based on user attributes and resource attributes. +* **CORS (Cross-Origin Resource Sharing):** Configure CORS middleware properly to allow requests only from trusted origins. + +### 4.4 Data Protection Strategies + +* **Encryption:** Encrypt sensitive data at rest and in transit. +* **Hashing:** Hash passwords and other sensitive data using a strong hashing algorithm like bcrypt or Argon2. +* **Data Masking:** Mask sensitive data in logs and other output. +* **Data Anonymization:** Anonymize data to protect user privacy. + +### 4.5 Secure API Communication + +* **HTTPS:** Always use HTTPS to encrypt communication between the client and the server. +* **TLS/SSL Certificates:** Use valid TLS/SSL certificates to establish secure connections. +* **Strict Transport Security (HSTS):** Enable HSTS to force browsers to use HTTPS for all requests to the application. +* **Content Security Policy (CSP):** Configure CSP to prevent XSS attacks by controlling the sources from which the browser is allowed to load resources. + +## 5. Testing Approaches + +Write comprehensive tests to ensure the quality and reliability of your FastAPI application. + +### 5.1 Unit Testing Strategies + +* **Test Individual Components:** Write unit tests to test individual components like functions, classes, and modules in isolation. +* **Mock Dependencies:** Use mocking frameworks like `unittest.mock` or `pytest-mock` to mock external dependencies and isolate the component being tested. +* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that the component handles unexpected input correctly. + +### 5.2 Integration Testing + +* **Test Interactions Between Components:** Write integration tests to test the interactions between different components of the application. +* **Use a Test Database:** Use a separate test database for integration tests to avoid affecting the production database. +* **Test API Endpoints:** Write integration tests to test the API endpoints of the application. + +### 5.3 End-to-End Testing + +* **Test the Entire Application Flow:** Write end-to-end tests to test the entire application flow, from the client to the database. +* **Use a Testing Framework:** Use a testing framework like Selenium or Cypress to automate end-to-end tests. +* **Test User Interface (UI):** Test the user interface of the application to ensure that it is working correctly. + +### 5.4 Test Organization + +* **Organize Tests by Module:** Organize tests into separate directories or files based on the module or component being tested. +* **Use Descriptive Test Names:** Use descriptive test names that clearly indicate what the test is verifying. +* **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions. +* **Keep Tests Concise:** Keep tests concise and focused on a single aspect of the component being tested. + +### 5.5 Mocking and Stubbing + +* **Use Mocking Frameworks:** Use mocking frameworks like `unittest.mock` or `pytest-mock` to create mock objects and stub out external dependencies. +* **Mock External APIs:** Mock external APIs to isolate the component being tested and avoid making actual API calls during testing. +* **Stub Database Interactions:** Stub database interactions to avoid affecting the database during testing. +* **Verify Interactions:** Verify that the component being tested interacts with the mock objects as expected. + +## 6. Common Pitfalls and Gotchas + +Be aware of common pitfalls and gotchas that can arise when developing FastAPI applications. + +### 6.1 Frequent Mistakes Developers Make + +* **Incorrectly Using `Depends`:** Ensure `Depends` is used properly to inject dependencies into route handlers. +* **Blocking I/O in Async Routes:** Avoid blocking I/O operations in async routes. +* **Not Handling Exceptions:** Implement proper exception handling to prevent unhandled exceptions from crashing the application. +* **Ignoring Security Best Practices:** Follow security best practices to protect the application from vulnerabilities. +* **Not Writing Tests:** Write comprehensive tests to ensure the quality and reliability of the application. + +### 6.2 Edge Cases to Be Aware Of + +* **Unicode Handling:** Be aware of unicode handling issues when processing user input. +* **Time Zones:** Handle time zones correctly when working with dates and times. +* **Large File Uploads:** Handle large file uploads efficiently to prevent memory exhaustion. +* **Concurrency Issues:** Be aware of concurrency issues when working with shared resources in a multi-threaded or multi-process environment. + +### 6.3 Version-Specific Issues + +* **Check Changelogs:** Review the changelogs for FastAPI and its dependencies to be aware of any breaking changes or new features. +* **Test Compatibility:** Test the application with different versions of FastAPI and its dependencies to ensure compatibility. + +### 6.4 Compatibility Concerns + +* **Python Version:** Ensure that the application is compatible with the target Python version. +* **Operating System:** Test the application on different operating systems to ensure compatibility. +* **Database Compatibility:** Ensure that the application is compatible with the target database. + +### 6.5 Debugging Strategies + +* **Use a Debugger:** Use a debugger like `pdb` or `ipdb` to step through the code and inspect variables. +* **Logging:** Use logging to track the execution flow and identify errors. +* **Profiling:** Use profiling tools to identify performance bottlenecks. +* **Remote Debugging:** Use remote debugging to debug applications running on remote servers. + +## 7. Tooling and Environment + +Utilize the right tools and environment for efficient FastAPI development. + +### 7.1 Recommended Development Tools + +* **IDE:** VS Code, PyCharm, or other IDE with Python support. +* **Virtual Environment Manager:** `venv`, `conda`, or `poetry` for managing project dependencies. +* **Package Manager:** `pip` or `poetry` for installing and managing Python packages. +* **Debugger:** `pdb` or `ipdb` for debugging Python code. +* **Profiler:** `cProfile` or `py-spy` for profiling Python code. + +### 7.2 Build Configuration + +* **`requirements.txt`:** Use `requirements.txt` to specify project dependencies. Generate it using `pip freeze > requirements.txt`. +* **`pyproject.toml`:** Consider using `pyproject.toml` (with Poetry or similar tools) for more advanced dependency management and build configuration. + +### 7.3 Linting and Formatting + +* **Linters:** Use linters like `flake8`, `pylint`, or `ruff` to enforce code style and identify potential errors. +* **Formatters:** Use code formatters like `black` or `autopep8` to automatically format the code according to PEP 8 standards. +* **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code. + +### 7.4 Deployment Best Practices + +* **Containerization:** Use Docker to containerize the application for easy deployment and scaling. +* **Reverse Proxy:** Use a reverse proxy like Nginx or Apache to handle incoming requests and forward them to the application. +* **Process Manager:** Use a process manager like Supervisor or systemd to manage the application process. +* **Load Balancing:** Use a load balancer to distribute traffic across multiple instances of the application. +* **Monitoring:** Monitor the application using tools like Prometheus or Grafana. + +### 7.5 CI/CD Integration + +* **Continuous Integration (CI):** Set up a CI pipeline to automatically build, test, and lint the code on every commit. +* **Continuous Delivery (CD):** Set up a CD pipeline to automatically deploy the application to the production environment after the CI pipeline has passed. +* **Version Control:** Use a version control system like Git to manage the code and track changes. +* **Automated Testing:** Integrate automated tests into the CI/CD pipeline to ensure that the application is working correctly before deployment. +* **Automated Rollbacks:** Implement automated rollbacks to revert to a previous version of the application if a deployment fails. + +## Conclusion + +By adhering to these best practices, you can develop robust, scalable, and maintainable FastAPI applications that are secure, performant, and easy to test. This guide provides a foundation for building high-quality APIs with FastAPI. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/python/flask.mdc b/rules-mdc/backend_frameworks/python/flask.mdc new file mode 100644 index 0000000..b03e117 --- /dev/null +++ b/rules-mdc/backend_frameworks/python/flask.mdc @@ -0,0 +1,199 @@ +--- +description: This rule provides comprehensive best practices for developing Flask applications, covering code structure, security, performance, and testing. +globs: **/*.py +--- +- ## Code Organization and Structure: + - **Directory Structure Best Practices:** + - Follow a modular and organized project structure. A common structure is: + + project_root/ + ├── app/ + │ ├── __init__.py + │ ├── models.py + │ ├── views.py # Or controllers.py + │ ├── forms.py + │ ├── utils.py # Helper functions + │ ├── api/ + │ │ ├── __init__.py + │ │ ├── routes.py + │ ├── templates/ + │ │ └── ... + │ ├── static/ + │ │ └── ... + ├── tests/ + │ ├── __init__.py + │ ├── conftest.py # Fixtures for tests + │ ├── test_models.py + │ ├── test_views.py + ├── migrations/ + │ └── ... # Alembic migrations + ├── venv/ # Virtual environment + ├── .env # Environment variables (use with caution, not for sensitive data in production) + ├── config.py # Application configuration + ├── requirements.txt or pyproject.toml # Dependencies + ├── run.py # Application entry point + + - Use Blueprints to organize routes and views into logical modules. Blueprints promote reusability and maintainability. + - **File Naming Conventions:** + - Use descriptive and consistent file names. + - Examples: `models.py`, `views.py`, `forms.py`, `utils.py`, `routes.py`, `test_*.py`. + - Maintain consistency throughout the project. + - **Module Organization:** + - Group related functionality into modules. For instance, database models in `models.py`, user authentication logic in `auth.py`, and utility functions in `utils.py`. + - Use `__init__.py` files to make directories packages, allowing you to import modules within the directory using relative paths. + - **Component Architecture:** + - Design components with clear responsibilities and interfaces. + - Consider using a layered architecture (e.g., presentation, business logic, data access) to separate concerns. + - Use dependency injection to decouple components. + - **Code Splitting Strategies:** + - Decompose large modules into smaller, more manageable files. + - Extract reusable code into separate modules or packages. + - Employ lazy loading for modules that are not immediately needed. + +- ## Common Patterns and Anti-patterns: + - **Design Patterns Specific to Flask:** + - **Application Factory:** Use the application factory pattern to create Flask application instances. This allows for different configurations for different environments (development, testing, production). + python + def create_app(config_name): + app = Flask(__name__) + app.config.from_object(config[config_name]) + config[config_name].init_app(app) + + # Initialize extensions (e.g., db, mail) here + db.init_app(app) + mail.init_app(app) + + # Register blueprints + from .main import main as main_blueprint + app.register_blueprint(main_blueprint) + + return app + + - **Blueprints:** Organize application functionality into reusable blueprints. + python + from flask import Blueprint + + bp = Blueprint('my_blueprint', __name__, url_prefix='/my_blueprint') + + @bp.route('/route') + def my_route(): + return 'Hello from my_blueprint' + + - **Recommended Approaches for Common Tasks:** + - **Database Interactions:** Use Flask-SQLAlchemy or another ORM for database interactions. Define models to represent database tables. + - **Form Handling:** Use Flask-WTF for form handling. This provides CSRF protection and simplifies form validation. + - **Authentication:** Use Flask-Login for user authentication. It provides utilities for managing user sessions and protecting routes. + - **API Development:** Use Flask-RESTful or Flask-API for building RESTful APIs. Consider using Marshmallow for serializing and deserializing data. + - **Anti-patterns and Code Smells to Avoid:** + - **Global State:** Avoid using global variables to store application state. Use the `g` object or session variables instead. + - **Tight Coupling:** Design components with loose coupling to improve maintainability and testability. + - **Fat Models/Views:** Keep models and views focused on their primary responsibilities. Move complex business logic to separate modules. + - **Hardcoding Configuration:** Avoid hardcoding configuration values. Use environment variables or a configuration file. + - **State Management Best Practices:** + - Use the Flask `session` object to store user-specific data across requests. + - For application-wide state, consider using a database or a caching mechanism. + - Avoid storing sensitive data in the session without proper encryption. + - **Error Handling Patterns:** + - Use `try...except` blocks to handle exceptions gracefully. + - Implement custom error handlers for specific exceptions. Return appropriate HTTP status codes and error messages. + - Use logging to record errors and warnings. + - Use Flask's `abort()` function to raise HTTP exceptions. + +- ## Performance Considerations: + - **Optimization Techniques:** + - **Caching:** Implement caching to reduce database queries and improve response times. Use Flask-Caching or Redis. + - **Database Optimization:** Optimize database queries and use indexes to improve performance. + - **Profiling:** Use a profiler to identify performance bottlenecks in your code. + - **Memory Management:** + - Avoid memory leaks by properly closing database connections and releasing resources. + - Use generators to process large datasets efficiently. + - **Rendering Optimization:** + - Minimize the number of database queries in templates. + - Use template caching to reduce rendering time. + - **Bundle Size Optimization:** + - For larger front-end applications, use a bundler like Webpack or Parcel to optimize JavaScript and CSS files. Minify and compress assets. + - **Lazy Loading Strategies:** + - Implement lazy loading for images and other assets to improve initial page load time. + - Use code splitting to load only the necessary JavaScript code for each page. + +- ## Security Best Practices: + - **Common Vulnerabilities and How to Prevent Them:** + - **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates. Use Jinja2's autoescaping feature. + - **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM. + - **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using Flask-WTF, which provides CSRF protection. + - **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms. Use strong passwords and protect user credentials. + - **Input Validation:** + - Validate all user input to prevent malicious data from entering your application. + - Use Flask-WTF for form validation. + - **Authentication and Authorization Patterns:** + - Use Flask-Login for user authentication. + - Implement role-based access control (RBAC) to restrict access to certain resources. + - Use JWT (JSON Web Tokens) for API authentication. + - **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between the client and the server. + - Store passwords securely using a strong hashing algorithm (e.g., bcrypt). + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Implement authentication and authorization for API endpoints. + - Validate API requests and responses. + - Use rate limiting to prevent abuse. + +- ## Testing Approaches: + - **Unit Testing Strategies:** + - Write unit tests to verify the functionality of individual components. + - Use pytest or unittest for writing and running tests. + - Mock external dependencies to isolate components during testing. + - **Integration Testing:** + - Write integration tests to verify the interaction between different components. + - Test the integration between the application and the database. + - **End-to-End Testing:** + - Write end-to-end tests to simulate user interactions with the application. + - Use Selenium or Cypress for end-to-end testing. + - **Test Organization:** + - Organize tests into separate directories based on functionality. + - Use descriptive test names. + - Follow the Arrange-Act-Assert pattern in your tests. + - **Mocking and Stubbing:** + - Use mocking and stubbing to isolate components during testing. + - Use the `unittest.mock` module or a third-party mocking library like `mock`. + +- ## Common Pitfalls and Gotchas: + - **Frequent Mistakes Developers Make:** + - **Not using a virtual environment:** Always use a virtual environment to isolate project dependencies. + - **Not handling exceptions properly:** Handle exceptions gracefully to prevent application crashes. + - **Exposing sensitive data:** Avoid exposing sensitive data in logs or error messages. + - **Edge Cases to Be Aware Of:** + - **Handling Unicode correctly:** Be aware of Unicode encoding issues when working with text data. + - **Dealing with time zones:** Use a consistent time zone throughout the application. + - **Version-Specific Issues:** + - Be aware of compatibility issues when upgrading Flask or its dependencies. + - Consult the Flask documentation for version-specific information. + - **Compatibility Concerns:** + - Ensure that your application is compatible with different browsers and operating systems. + - Test your application on different devices. + - **Debugging Strategies:** + - Use the Flask debugger to identify and fix errors. + - Use logging to record errors and warnings. + - Use a profiler to identify performance bottlenecks. + +- ## Tooling and Environment: + - **Recommended Development Tools:** + - **Virtual Environment Manager:** `virtualenv`, `venv`, or `conda` + - **Package Manager:** `pip` or `pipenv` or `poetry` + - **IDE/Text Editor:** VS Code, PyCharm, Sublime Text + - **Debugger:** `pdb` or `ipdb` + - **Profiler:** `cProfile` + - **Build Configuration:** + - Use a `requirements.txt` or `pyproject.toml` file to specify project dependencies. + - Use a build system like `setuptools` or `poetry` to package your application. + - **Linting and Formatting:** + - Use a linter like `flake8` or `pylint` to enforce code style guidelines. + - Use a formatter like `black` or `autopep8` to automatically format your code. + - **Deployment Best Practices:** + - Use a production-ready WSGI server like Gunicorn or uWSGI. + - Use a reverse proxy like Nginx or Apache to serve static files and handle SSL termination. + - Deploy your application to a cloud platform like AWS, Google Cloud, or Azure. + - **CI/CD Integration:** + - Use a CI/CD pipeline to automate testing, building, and deployment. + - Use tools like Jenkins, Travis CI, or GitHub Actions. \ No newline at end of file diff --git a/rules-mdc/backend_frameworks/rust/actix-web.mdc b/rules-mdc/backend_frameworks/rust/actix-web.mdc new file mode 100644 index 0000000..78efeab --- /dev/null +++ b/rules-mdc/backend_frameworks/rust/actix-web.mdc @@ -0,0 +1,318 @@ +--- +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 +--- +# 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 diff --git a/rules-mdc/backend_frameworks/rust/rocket.mdc b/rules-mdc/backend_frameworks/rust/rocket.mdc new file mode 100644 index 0000000..cbcb964 --- /dev/null +++ b/rules-mdc/backend_frameworks/rust/rocket.mdc @@ -0,0 +1,113 @@ +--- +description: Comprehensive guidelines for developing robust and maintainable web applications with the Rocket web framework, covering code organization, security, performance, testing, and more. +globs: **/*.rs +--- +- **Code Organization and Structure:** + - **Directory Structure:** Organize your project with a clear and maintainable directory structure. A common pattern is: + - `src/`: Contains the main source code. + - `main.rs`: Entry point of the application. + - `lib.rs`: Defines library components. + - `routes/`: Contains route handlers. + - `mod.rs`: Defines and exports route modules. + - `resource_name.rs`: Individual route files. + - `models/`: Defines data structures and database interactions. + - `mod.rs`: Defines and exports model modules. + - `data_model.rs`: Individual model definitions. + - `utils/`: Utility functions and modules. + - `mod.rs`: Defines and exports utility modules. + - `helper_functions.rs`: Individual utility function files. + - `config/`: Configuration files and settings. + - `static/`: Static assets like CSS, JavaScript, and images. + - `templates/`: Templates for rendering dynamic content (using templating engines like Handlebars or Tera). + - `tests/`: Unit and integration tests. + - `migrations/`: Database migrations (if applicable). + - **File Naming Conventions:** Use descriptive and consistent file names. Follow Rust's conventions, such as `snake_case` for file and module names. For example, `user_routes.rs`, `database_connection.rs`. + - **Module Organization:** Break down your code into logical modules. Use `mod.rs` files to define and re-export modules within a directory. + - **Component Architecture:** Design your application using a component-based architecture. This promotes reusability and maintainability. Consider using traits to define interfaces between components. + - **Code Splitting Strategies:** For larger applications, split your code into smaller, manageable crates to improve compilation times and code organization. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Repository Pattern:** Abstract data access logic behind a repository interface. + - **Service Layer Pattern:** Decouple route handlers from business logic using a service layer. + - **State Pattern:** Manage complex state transitions within route handlers or components. + - **Recommended Approaches for Common Tasks:** + - **Database Interactions:** Use an ORM like Diesel or SeaORM to interact with databases. Use connection pooling to efficiently manage database connections. + - **Authentication and Authorization:** Implement authentication using JWT (JSON Web Tokens) or sessions. Use role-based access control (RBAC) for authorization. + - **Input Validation:** Thoroughly validate user input to prevent security vulnerabilities and data corruption. + - **Anti-patterns and Code Smells:** + - **Global Variables:** Avoid using global variables, as they can lead to unexpected side effects and make code harder to reason about. Use dependency injection instead. + - **Tight Coupling:** Minimize dependencies between components. Use interfaces and abstractions to decouple components. + - **Long Functions:** Break down long functions into smaller, more manageable functions. + - **State Management:** Use Rocket's managed state feature (`#[rocket::State]`) to manage application-level state. + - **Error Handling:** Use Rust's `Result` type for error handling. Provide informative error messages to the user. + +- **Performance Considerations:** + - **Optimization Techniques:** + - **Asynchronous Programming:** Use asynchronous programming (`async/await`) to handle concurrent requests efficiently. + - **Caching:** Implement caching to reduce database load and improve response times. + - **Connection Pooling:** Use connection pooling to reuse database connections. + - **Memory Management:** Be mindful of memory allocation and deallocation. Use Rust's ownership and borrowing system to prevent memory leaks and data races. + - **Rendering Optimization:** Optimize your templates to reduce rendering time. Use template caching. + - **Bundle Size Optimization:** Minimize the size of your application's binary. Use release mode compilation (`cargo build --release`). Strip debug symbols. + - **Lazy Loading Strategies:** Load resources on demand to improve initial page load time. + +- **Security Best Practices:** + - **Common Vulnerabilities:** + - **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM. + - **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. + - **Cross-Site Request Forgery (CSRF):** Implement CSRF protection using tokens. + - **Input Validation:** Validate all user input on both the client-side and server-side. + - **Authentication and Authorization:** + - Use strong password hashing algorithms (e.g., bcrypt or Argon2). + - Implement two-factor authentication (2FA). + - Use role-based access control (RBAC) to restrict access to resources. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between the client and server. + - Store passwords securely using a strong hashing algorithm. + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Implement rate limiting to prevent abuse. + - Use API keys or JWT for authentication. + +- **Testing Approaches:** + - **Unit Testing:** Write unit tests to verify the functionality of individual functions and modules. Use the `#[cfg(test)]` attribute to define test modules. + - **Integration Testing:** Write integration tests to verify the interaction between different parts of your application. Test routes and database interactions. + - **End-to-End Testing:** Write end-to-end tests to verify the complete functionality of your application. Use a testing framework like Selenium or Cypress. + - **Test Organization:** Organize your tests in a clear and maintainable way. Create separate test modules for each component or module. + - **Mocking and Stubbing:** Use mocking and stubbing to isolate units of code during testing. Use a mocking framework like Mockall. + +- **Common Pitfalls and Gotchas:** + - **Frequent Mistakes:** + - **Forgetting to handle errors:** Always handle errors properly using `Result` and provide informative error messages. + - **Not validating user input:** Always validate user input to prevent security vulnerabilities. + - **Using global state:** Avoid using global state, as it can lead to unexpected side effects. + - **Edge Cases:** + - **Handling concurrent requests:** Use asynchronous programming to handle concurrent requests efficiently. + - **Dealing with large files:** Use streaming to process large files without loading them into memory. + - **Handling database connection errors:** Implement retry logic to handle database connection errors. + - **Version-Specific Issues:** Be aware of version-specific issues and compatibility concerns. Consult the Rocket documentation and release notes. + - **Compatibility Concerns:** Ensure that your application is compatible with the target platform and browser versions. + - **Debugging Strategies:** + - Use the `println!` macro for debugging. + - Use a debugger like GDB or LLDB. + - Use logging to track the execution of your application. + +- **Tooling and Environment:** + - **Recommended Development Tools:** + - **Rust toolchain:** Install the Rust toolchain using `rustup`. + - **IDE:** Use an IDE like Visual Studio Code with the Rust Analyzer extension. + - **Database client:** Use a database client like DBeaver or pgAdmin. + - **Build Configuration:** Configure your build using `Cargo.toml`. Specify dependencies, build scripts, and other build settings. + - **Linting and Formatting:** + - Use `rustfmt` for code formatting. + - Use `clippy` for linting. + - Configure your IDE to automatically format and lint your code. + - **Deployment Best Practices:** + - Use a process manager like systemd or PM2 to manage your application. + - Use a reverse proxy like Nginx or Apache to handle incoming requests. + - Use a load balancer to distribute traffic across multiple instances of your application. + - **CI/CD Integration:** + - Use a CI/CD platform like GitHub Actions or GitLab CI to automate your build, test, and deployment process. + - Write tests to ensure that your application is working correctly before deploying. \ No newline at end of file diff --git a/rules-mdc/blockchain/ethereum/hardhat.mdc b/rules-mdc/blockchain/ethereum/hardhat.mdc new file mode 100644 index 0000000..659ecb4 --- /dev/null +++ b/rules-mdc/blockchain/ethereum/hardhat.mdc @@ -0,0 +1,278 @@ +--- +description: This rule outlines best practices for Hardhat development, covering code organization, security, testing, and performance. It aims to provide a comprehensive guide for developers working with the Hardhat Ethereum development environment. +globs: **/*.{js,ts,sol,json} +--- +# Hardhat Best Practices and Coding Standards + +This document provides a comprehensive guide to best practices for developing smart contracts and decentralized applications (dApps) using Hardhat. It covers code organization, security, testing, performance, and other essential aspects of Hardhat development. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure Best Practices + + +hardhat-project/ +├── contracts/ # Solidity smart contracts +│ ├── MyContract.sol +│ └── ... +├── scripts/ # Deployment and interaction scripts +│ ├── deploy.js +│ ├── interact.js +│ └── ... +├── test/ # Unit and integration tests +│ ├── MyContract.test.js +│ └── ... +├── hardhat.config.js # Hardhat configuration file +├── package.json # Node.js package file +├── README.md # Project documentation +└── .gitignore # Git ignore file + + +- **contracts/:** Store all Solidity smart contracts in this directory. Consider subdirectories for different modules or features. +- **scripts/:** Keep deployment, interaction, and other utility scripts in this directory. Organize scripts by function or deployment environment. +- **test/:** Place all unit and integration tests in this directory. Mirror the `contracts/` directory structure for test files. +- **hardhat.config.js:** Configure Hardhat settings in this file, including compiler versions, network configurations, and task definitions. Consider using TypeScript. +- **package.json:** Manage project dependencies and scripts using npm or yarn. +- **README.md:** Provide clear and concise documentation for your project. +- **.gitignore:** Exclude unnecessary files from source control (e.g., build artifacts, node_modules). + +### 1.2. File Naming Conventions + +- **Solidity Files:** Use PascalCase with the `.sol` extension for Solidity contract files (e.g., `MyContract.sol`). +- **JavaScript/TypeScript Files:** Use camelCase with the `.js` or `.ts` extension for JavaScript/TypeScript files (e.g., `deploy.js`, `myContract.test.ts`). +- **Test Files:** Use the `.test.js` or `.test.ts` suffix to identify test files (e.g., `MyContract.test.js`). + +### 1.3. Module Organization + +- **Separate Concerns:** Divide your contracts into logical modules or components based on their functionality. +- **Interfaces:** Use interfaces to define the public API of your contracts. +- **Libraries:** Create reusable libraries for common functionalities to avoid code duplication. +- **Abstract Contracts:** Use abstract contracts to define common logic and state variables for related contracts. + +### 1.4. Component Architecture + +- **Modular Design:** Design contracts as independent, reusable components. +- **Composition:** Combine smaller components to create more complex systems. +- **Minimal Dependencies:** Reduce dependencies between components to improve maintainability and testability. + +### 1.5. Code Splitting Strategies + +- **Separate Logic and Data:** Keep contract logic separate from data storage to improve readability and maintainability. +- **External Libraries:** Utilize external libraries (e.g., OpenZeppelin) for common functionalities to reduce code size and improve security. +- **Proxy Patterns:** Consider using proxy patterns to enable upgradeability and code splitting. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to Hardhat/Solidity + +- **Ownable:** Control access to privileged functions using the Ownable pattern (from OpenZeppelin). +- **Pausable:** Implement a Pausable contract to temporarily halt contract functionality in case of emergencies. +- **Pull over Push:** Favor pull-based payment mechanisms over push-based mechanisms to mitigate reentrancy attacks. +- **Proxy patterns (e.g., UUPS, Transparent Proxy):** For contract upgrades. + +### 2.2. Recommended Approaches for Common Tasks + +- **Deployment:** Use Hardhat's deployment scripts and network configurations to automate contract deployment. +- **Testing:** Employ Hardhat's testing framework and Chai matchers for comprehensive unit and integration testing. +- **Interaction:** Utilize Hardhat's console and Ethers.js for interacting with deployed contracts. +- **Verification:** Verify contract source code on Etherscan to enhance transparency and trust. + +### 2.3. Anti-patterns and Code Smells to Avoid + +- **Unchecked Arithmetic:** Use SafeMath or Solidity 0.8+ to prevent integer overflow/underflow. +- **Reentrancy:** Protect against reentrancy attacks by using the Checks-Effects-Interactions pattern or reentrancy guards (from OpenZeppelin). +- **Denial of Service (DoS):** Avoid patterns that can lead to DoS attacks, such as unbounded loops or expensive operations. +- **Timestamp Dependence:** Avoid relying on block timestamps for critical logic, as they can be manipulated by miners. +- **Insufficient Gas Limits:** Ensure functions have sufficient gas limits, especially for complex operations. +- **Hardcoding Addresses/Values:** Use configuration files or environment variables for addresses and other configurable values. + +### 2.4. State Management Best Practices + +- **Minimize State Variables:** Reduce the number of state variables to minimize storage costs and improve performance. +- **Use Appropriate Data Types:** Choose the most efficient data types for state variables (e.g., `uint256` instead of `uint`). +- **Immutability:** Use `immutable` variables when the value is assigned at construction and never changed after. +- **Constants:** Use `constant` variables for gas optimization when the value is known at compile time and never changed after. +- **Events:** Emit events to track state changes and enable off-chain monitoring. + +### 2.5. Error Handling Patterns + +- **Require Statements:** Use `require` statements to validate inputs and enforce preconditions. +- **Revert Statements:** Use `revert` statements to handle exceptional conditions and return informative error messages. +- **Custom Errors:** Use custom errors (Solidity 0.8.4+) for gas optimization and detailed error reporting. +- **Try/Catch (Solidity 0.8.16+):** Implement Try/Catch blocks when calling external contracts. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +- **Gas Optimization:** Minimize gas consumption to reduce transaction costs. +- **Data Packing:** Pack multiple small variables into a single storage slot to reduce storage costs. +- **Short Circuiting:** Use short-circuiting evaluation in logical expressions to avoid unnecessary computations. +- **Assembly Optimization:** Use inline assembly for performance-critical sections of code. +- **Caching:** Cache values that are frequently accessed. + +### 3.2. Memory Management + +- **Minimize Memory Usage:** Reduce memory usage to avoid out-of-gas errors. +- **Storage vs. Memory:** Use storage for persistent data and memory for temporary data. +- **Delete Unused Variables:** Delete variables in memory after use to free up space. + +### 3.3. Rendering Optimization (If applicable - for frontend DApps) + +- **Lazy Loading:** Load components and data only when they are needed. +- **Virtualization:** Use virtualization techniques to render large lists efficiently. +- **Memoization:** Memoize computationally expensive functions to avoid redundant calculations. + +### 3.4. Bundle Size Optimization (If applicable - for frontend DApps) + +- **Code Splitting:** Split the application code into smaller bundles to improve initial load time. +- **Tree Shaking:** Remove unused code from the bundle using tree shaking. +- **Minification:** Minify JavaScript and CSS files to reduce bundle size. + +### 3.5. Lazy Loading Strategies (If applicable - for frontend DApps) + +- **Dynamic Imports:** Use dynamic imports to load modules on demand. +- **Intersection Observer:** Use the Intersection Observer API to load resources when they become visible. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +- **Reentrancy:** Use Checks-Effects-Interactions pattern. Employ reentrancy guards (@openzeppelin/contracts/security/ReentrancyGuard.sol). +- **Integer Overflow/Underflow:** Use SafeMath or Solidity 0.8+. +- **Denial of Service (DoS):** Limit gas costs, avoid unbounded loops, and implement rate limiting. +- **Timestamp Dependence:** Avoid relying on block timestamps for critical logic. +- **Front Running:** Design contracts to be resilient to front-running attacks. +- **Signature Replay:** Prevent signature replay attacks by using nonces or other unique identifiers. +- **Cross-Site Scripting (XSS):** Sanitize user inputs in frontend DApps to prevent XSS attacks. +- **SQL Injection:** Use parameterized queries to prevent SQL injection attacks in backend systems. +- **Improper Access Control:** Enforce strict access control policies to protect sensitive data and functions. + +### 4.2. Input Validation + +- **Sanitize Inputs:** Sanitize and validate all user inputs to prevent malicious data from entering the system. +- **Check Data Types:** Verify that inputs are of the expected data types. +- **Limit Input Length:** Restrict the length of input strings to prevent buffer overflows. +- **Regular Expressions:** Use regular expressions to validate complex input patterns. + +### 4.3. Authentication and Authorization Patterns + +- **Role-Based Access Control (RBAC):** Implement RBAC to manage user permissions. +- **Attribute-Based Access Control (ABAC):** Use ABAC for more fine-grained access control. +- **Multi-Factor Authentication (MFA):** Implement MFA to enhance security. +- **OAuth:** Use OAuth for secure delegation of access to third-party applications. + +### 4.4. Data Protection Strategies + +- **Encryption:** Encrypt sensitive data at rest and in transit. +- **Hashing:** Use hashing to store passwords securely. +- **Salting:** Salt passwords to prevent rainbow table attacks. +- **Key Management:** Implement secure key management practices. + +### 4.5. Secure API Communication (If applicable - for backend systems) + +- **HTTPS:** Use HTTPS for all API communication. +- **API Keys:** Use API keys to authenticate API requests. +- **Rate Limiting:** Implement rate limiting to prevent abuse. +- **Input Validation:** Validate and sanitize all API inputs. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +- **Test Driven Development (TDD):** Write tests before writing code. +- **Black Box Testing:** Test the functionality of the contract without knowledge of the internal implementation. +- **White Box Testing:** Test the internal implementation of the contract, including branches and loops. +- **Coverage Analysis:** Use coverage analysis tools to ensure that all code is covered by tests. + +### 5.2. Integration Testing + +- **Test Contract Interactions:** Test the interactions between multiple contracts. +- **Test External Dependencies:** Test the integration with external dependencies, such as oracles or other smart contracts. + +### 5.3. End-to-End Testing (If applicable - for frontend DApps) + +- **Simulate User Flows:** Simulate real-world user flows to test the entire application stack. +- **Automated Testing:** Use automated testing tools to run end-to-end tests regularly. + +### 5.4. Test Organization + +- **Arrange-Act-Assert:** Organize tests using the Arrange-Act-Assert pattern. +- **Descriptive Test Names:** Use descriptive names for tests to clearly indicate their purpose. +- **Test Suites:** Group related tests into test suites. + +### 5.5. Mocking and Stubbing + +- **Mock External Dependencies:** Use mocking to isolate contracts from external dependencies during testing. +- **Stub Function Calls:** Use stubbing to replace function calls with predefined values or behaviors. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +- **Incorrectly handling gas costs** +- **Failing to validate inputs** +- **Ignoring security best practices** +- **Not writing enough tests** +- **Misunderstanding Ethereum's execution model** +- **Not using the latest compiler version** + +### 6.2. Edge Cases to Be Aware Of + +- **Integer overflow/underflow** +- **Reentrancy attacks** +- **Denial-of-service attacks** +- **Front-running attacks** +- **Signature replay attacks** + +### 6.3. Version-Specific Issues + +- **Solidity compiler bugs:** Be aware of known bugs in the Solidity compiler and use appropriate workarounds. +- **Hardhat version compatibility:** Ensure that Hardhat and its plugins are compatible with each other. + +### 6.4. Compatibility Concerns + +- **EVM version compatibility:** Consider the target EVM version when developing contracts. +- **Web3.js/Ethers.js compatibility:** Ensure compatibility with the chosen JavaScript library for interacting with the blockchain. + +### 6.5. Debugging Strategies + +- **Console.log:** Use `console.log` statements to debug code. +- **Hardhat console:** Use the Hardhat console for interactive debugging. +- **Truffle debugger:** Use the Truffle debugger for more advanced debugging. +- **Remix IDE:** Use Remix IDE for online debugging. +- **Solidity stack traces:** Use Solidity stack traces to identify the source of errors. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +- **Hardhat:** Ethereum development environment. +- **Visual Studio Code:** Code editor with Solidity support. +- **Remix IDE:** Online Solidity IDE. +- **Etherscan:** Blockchain explorer. +- **Ganache:** Local Ethereum blockchain. +- **OpenZeppelin:** Secure smart contract libraries. + +### 7.2. Build Configuration + +- **Hardhat configuration file:** Configure Hardhat settings in the `hardhat.config.js` file. +- **Compiler version:** Specify the Solidity compiler version in the Hardhat configuration file. +- **Optimization settings:** Configure optimization settings in the Hardhat configuration file. + +### 7.3. Linting and Formatting + +- **Solhint:** Solidity linter. +- **Prettier:** Code formatter. +- **ESLint:** JavaScript/TypeScript linter. + +### 7.4. Deployment Best Practices + +- **Automated deployments:** Use Hardhat's deployment scripts to automate contract deployment. +- **Network configurations:** Configure network settings in the Hardhat configuration file. +- **Gas price estimation:** Estimate gas prices before deploying contracts. +- **Contract verification:** Verify contract source code on Etherscan after deployment. + +### 7.5. CI/CD Integration + +- **Continuous integration:** Integrate Hardhat with CI/CD systems (e.g., GitHub Actions, Jenkins) to automate testing and deployment. \ No newline at end of file diff --git a/rules-mdc/blockchain/ethereum/solidity.mdc b/rules-mdc/blockchain/ethereum/solidity.mdc new file mode 100644 index 0000000..4c6c930 --- /dev/null +++ b/rules-mdc/blockchain/ethereum/solidity.mdc @@ -0,0 +1,308 @@ +--- +description: This rule provides best practices and coding standards for Solidity smart contract development, covering code organization, security, performance, and testing. +globs: **/*.sol +--- +# Solidity Smart Contract Best Practices and Coding Standards + +This guide provides comprehensive best practices and coding standards for writing secure, efficient, and maintainable Solidity smart contracts. It covers various aspects of smart contract development, from code organization to security considerations. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure + +* **contracts/:** Contains Solidity contract files (.sol). +* **interfaces/:** Contains interface definitions (.sol). +* **libraries/:** Contains reusable libraries (.sol). +* **test/:** Contains test scripts (e.g., using Hardhat, Foundry, or Truffle). +* **scripts/:** Contains deployment and utility scripts. +* **deployments/:** Stores contract deployment information (addresses, ABIs, etc.). +* **artifacts/:** (Typically generated) Contains compiled contract ABIs and bytecode. +* **node_modules/:** (Typically generated) Contains installed npm packages. + +Example: + + +my-project/ +├── contracts/ +│ ├── MyContract.sol +│ └── ERC20.sol +├── interfaces/ +│ └── IMyContract.sol +├── libraries/ +│ └── SafeMath.sol +├── test/ +│ ├── MyContract.test.js +│ └── ERC20.test.js +├── scripts/ +│ ├── deploy.js +│ └── utils.js +├── deployments/ +│ └── rinkeby/ +│ └── MyContract.json +├── artifacts/ +│ └── contracts/ +│ ├── MyContract.json +│ └── ERC20.json +├── node_modules/ +├── hardhat.config.js +├── package.json +└── README.md + + +### 1.2. File Naming Conventions + +* Use PascalCase for contract names (e.g., `MyContract.sol`). +* Use PascalCase starting with I for interface names (e.g., `IMyContract.sol`). +* Use PascalCase for library names (e.g., `SafeMath.sol`). +* Filenames should match the contract name defined within the file. + +### 1.3. Module Organization + +* Keep contracts small and focused on a single responsibility (Single Responsibility Principle). +* Use libraries for reusable code blocks and mathematical operations. +* Use interfaces to define the functionality of contracts without implementation. +* Group related contracts into modules or subdirectories. + +### 1.4. Component Architecture + +* **Modular Design:** Break down complex systems into smaller, manageable, and reusable components. +* **Layered Architecture:** Separate concerns into different layers (e.g., data access, business logic, presentation). +* **Dependency Injection:** Decouple components by injecting dependencies instead of hardcoding them. + +### 1.5. Code Splitting Strategies + +* Use libraries for common functionality to reduce contract size and gas costs. +* Consider using the delegatecall pattern for complex logic, but be aware of the security implications. +* Split large contracts into smaller, more manageable contracts using inheritance or composition. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns + +* **Ownable:** Restricts access to certain functions to the contract owner. +* **Pausable:** Allows pausing contract functionality in case of emergency. +* **Pull over Push:** Favors withdrawing funds over automatically sending them. +* **Proxy Pattern:** Allows upgrading contract logic without changing the contract address (e.g., using UUPS or transparent proxies). +* **Factory Pattern:** Used to create new contract instances. +* **State Machine:** Manages different states of a contract. +* **Circuit Breaker:** Prevents a function from being called if it has repeatedly failed. + +### 2.2. Recommended Approaches + +* Use SafeMath library for arithmetic operations to prevent overflows and underflows (or use Solidity >= 0.8.0, which includes built-in overflow/underflow protection). +* Use events to log important state changes. +* Use modifiers to enforce access control and preconditions. +* Follow the Checks-Effects-Interactions pattern to prevent reentrancy attacks. + +### 2.3. Anti-patterns and Code Smells + +* **Unchecked Arithmetic:** Not using SafeMath or built-in overflow/underflow protection. +* **Reentrancy:** Vulnerable to reentrancy attacks. +* **Timestamp Dependence:** Relying on block timestamps for critical logic. +* **Integer Overflow/Underflow:** Not handling potential overflows and underflows. +* **Gas Limit Issues:** Causing transactions to run out of gas. +* **Centralization:** Over-reliance on a single administrator or owner. +* **Magic Numbers:** Using hardcoded values without explanation. +* **Tight Coupling:** Components are highly dependent on each other, making it difficult to modify or reuse them. + +### 2.4. State Management Best Practices + +* Minimize state variables to reduce gas costs. +* Use appropriate data types for state variables. +* Initialize state variables correctly. +* Consider using immutables for constants. +* Use structs and mappings to organize related data. + +### 2.5. Error Handling Patterns + +* Use `require()` to validate inputs and preconditions. +* Use `revert()` to handle errors and return informative error messages. +* Use custom errors to provide more context about errors (Solidity >= 0.8.4). +* Avoid using `assert()` in production code (it consumes all remaining gas). +* Consider using try/catch blocks for external calls. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Gas Optimization:** Aim to reduce gas consumption by using efficient data structures, minimizing storage writes, and optimizing control flow. +* **Storage Optimization:** Minimize storage usage by using appropriate data types and packing variables. +* **Function Optimization:** Optimize functions by reducing the number of operations and minimizing gas costs. +* **Loop Optimization:** Avoid unnecessary loops and optimize loop conditions. +* **Use Calldata:** Pass function arguments as calldata instead of memory when possible. +* **Short Circuiting:** Leverage short circuiting in conditional statements. + +### 3.2. Memory Management + +* Minimize memory usage by using calldata for function arguments when possible. +* Avoid creating large arrays in memory. +* Use memory efficiently in loops. +* Consider using assembly for memory-intensive operations. + +### 3.3. Rendering Optimization (Applicable for front-ends interacting with contracts) + +* This section refers to optimization of the front-end, typically written in Javascript, used to display data from the blockchain. Data retrieved from the blockchain should be displayed in an efficient manner. This is more applicable to traditional software engineering, and less applicable to Solidity itself. For the sake of completeness, it's added here. +* Use virtualization or pagination for large datasets. +* Optimize rendering logic to minimize DOM updates. +* Use caching to avoid unnecessary re-renders. + +### 3.4. Bundle Size Optimization (Applicable for front-ends interacting with contracts) +* This section refers to optimization of the front-end, typically written in Javascript, used to display data from the blockchain. The bundle size of the front end app should be as minimal as possible, to provide a performant user experience. This is more applicable to traditional software engineering, and less applicable to Solidity itself. For the sake of completeness, it's added here. +* Remove unused code and dependencies. +* Use code splitting to load only necessary code. +* Compress assets (images, JavaScript, CSS). + +### 3.5. Lazy Loading Strategies (Applicable for front-ends interacting with contracts) +* This section refers to optimization of the front-end, typically written in Javascript, used to display data from the blockchain. Lazy loading can be used to improve the performance of a front-end that interacts with a blockchain. This is more applicable to traditional software engineering, and less applicable to Solidity itself. For the sake of completeness, it's added here. +* Load images and other resources only when they are needed. +* Use lazy loading for off-screen components. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and Prevention + +* **Reentrancy:** Prevent reentrancy attacks by following the Checks-Effects-Interactions pattern, using reentrancy guards, or using `transfer()`/`send()` to limit gas available for callbacks. +* **Integer Overflow/Underflow:** Use SafeMath or built-in overflow/underflow protection (Solidity >= 0.8.0). +* **Denial of Service (DoS):** Protect against DoS attacks by limiting gas consumption, avoiding unbounded loops, and using pull-over-push pattern. +* **Timestamp Dependence:** Avoid relying on block timestamps for critical logic, as they can be manipulated by miners. +* **Front Running:** Protect against front running by using commit-reveal schemes or off-chain order matching. +* **Gas Limit Issues:** Ensure that functions do not consume excessive gas, which can lead to transactions running out of gas. +* **Delegatecall:** Be extremely careful when using `delegatecall`, as the called contract can modify the caller's storage. +* **Uninitialized Storage Pointers:** Ensure all storage pointers are initialized before use. +* **Access Control:** Implement robust access control mechanisms to restrict access to sensitive functions and data. +* **Signature Replay:** Use nonces or other mechanisms to prevent signature replay attacks. + +### 4.2. Input Validation + +* Validate all inputs to ensure they are within expected ranges. +* Check for zero addresses and invalid values. +* Sanitize inputs to prevent injection attacks. +* Use appropriate data types for inputs. + +### 4.3. Authentication and Authorization Patterns + +* **Ownable:** Use the Ownable pattern to restrict access to certain functions to the contract owner. +* **Role-Based Access Control (RBAC):** Implement RBAC to assign different roles to users and grant them specific permissions. +* **Multi-Signature Wallets:** Use multi-signature wallets for critical operations that require multiple approvals. +* **Access Control Lists (ACLs):** Use ACLs to define fine-grained access control rules. + +### 4.4. Data Protection Strategies + +* Use encryption to protect sensitive data. +* Store sensitive data off-chain. +* Use access control to restrict access to sensitive data. +* Consider using zero-knowledge proofs for privacy. + +### 4.5. Secure API Communication + +* Use HTTPS for secure communication. +* Validate all data received from external sources. +* Implement rate limiting to prevent abuse. +* Use authentication and authorization to protect APIs. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +* Write unit tests for all functions. +* Test all possible scenarios and edge cases. +* Use assertions to verify expected behavior. +* Use code coverage tools to ensure that all code is tested. +* Test state transitions and event emissions. + +### 5.2. Integration Testing + +* Test interactions between multiple contracts. +* Test integration with external systems. +* Test deployment and upgrade processes. + +### 5.3. End-to-End Testing + +* Test the entire system from end to end. +* Simulate real-world scenarios. +* Test user interactions and workflows. + +### 5.4. Test Organization + +* Organize tests into separate files or directories. +* Use descriptive test names. +* Group tests by functionality or module. + +### 5.5. Mocking and Stubbing + +* Use mocking to isolate contracts and simulate dependencies. +* Use stubbing to replace external calls with predefined responses. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes + +* **Unchecked Arithmetic:** Not using SafeMath or built-in overflow/underflow protection. +* **Reentrancy:** Not protecting against reentrancy attacks. +* **Timestamp Dependence:** Relying on block timestamps for critical logic. +* **Gas Limit Issues:** Causing transactions to run out of gas. +* **Ignoring Event Emissions:** Failing to emit events for important state changes, making off-chain monitoring and indexing difficult. + +### 6.2. Edge Cases + +* **Zero Values:** Handling cases where input values are zero. +* **Large Numbers:** Handling cases where input values are very large. +* **Empty Strings:** Handling cases where input strings are empty. +* **Extreme Conditions:** Testing the contract under extreme network conditions, such as high gas prices or network congestion. + +### 6.3. Version-Specific Issues + +* Be aware of breaking changes between Solidity versions. +* Test your contracts with the target Solidity version. +* Use the latest compiler version to leverage improvements and security patches. + +### 6.4. Compatibility Concerns + +* Ensure compatibility with different Ethereum clients and networks. +* Test your contracts on different testnets before deploying to mainnet. +* Consider compatibility with different wallets and browsers. + +### 6.5. Debugging Strategies + +* Use debugging tools like Remix, Hardhat, or Truffle. +* Use console.log statements for debugging. +* Use event logs to track state changes. +* Use revert reasons to understand why transactions failed. +* Use fuzzing to find unexpected behavior and vulnerabilities. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +* **Remix:** Online IDE for writing, compiling, and deploying Solidity contracts. +* **Hardhat:** Development environment for Ethereum smart contracts. +* **Truffle:** Development framework for Ethereum with testing and deployment capabilities. +* **Foundry:** Blazing-fast, portable and modular toolkit for Ethereum application development +* **VS Code:** Code editor with Solidity extensions for syntax highlighting, linting, and debugging. + +### 7.2. Build Configuration + +* Use a build tool like Hardhat or Truffle to manage the build process. +* Configure the compiler version and optimization settings. +* Generate contract ABIs and bytecode. + +### 7.3. Linting and Formatting + +* Use a linter like Solhint to enforce code style and best practices. +* Use a formatter like Prettier to format code consistently. +* Configure linting and formatting rules to match your project's standards. + +### 7.4. Deployment Best Practices + +* Deploy contracts to a testnet before deploying to mainnet. +* Verify contract code on Etherscan. +* Use a deployment script to automate the deployment process. +* Store contract deployment information (addresses, ABIs, etc.). + +### 7.5. CI/CD Integration + +* Integrate testing and deployment into your CI/CD pipeline. +* Run tests automatically on every commit. +* Automate the deployment process to reduce errors. + +By following these best practices, you can write more secure, efficient, and maintainable Solidity smart contracts. \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/deployment/cloudflare.mdc b/rules-mdc/cloud_platforms/deployment/cloudflare.mdc new file mode 100644 index 0000000..72161ef --- /dev/null +++ b/rules-mdc/cloud_platforms/deployment/cloudflare.mdc @@ -0,0 +1,292 @@ +--- +description: This rule provides a comprehensive set of best practices and coding standards for developing with the Cloudflare library, specifically focusing on Terraform configurations. It aims to guide developers in creating efficient, secure, and maintainable infrastructure code. +globs: **/*.tf +--- +# Cloudflare Terraform Best Practices + +This document outlines the recommended best practices and coding standards for working with Cloudflare resources using Terraform. Following these guidelines will help you create robust, scalable, and maintainable infrastructure code. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +* **Account-Based Segregation:** Organize your Terraform projects by Cloudflare accounts. This allows for clear separation of resources and access control. +* **Zone-Based Grouping:** Within each account, further group resources by zones. This makes it easier to manage resources associated with specific domains. +* **Product/Feature-Based Organization:** Within each zone, create subdirectories for individual Cloudflare products or features (e.g., `dns`, `page_rules`, `rulesets`, `waf`). This promotes modularity and maintainability. +* **Environment Separation:** While not strictly enforced within a single repository, using separate Cloudflare accounts for different environments (development, staging, production) is *strongly* recommended for complete isolation. + +Example: + + +example-tf/ +├── demo_account_a # Per account segregation of resources +│ ├── users # Top level directory for account members as they are "zoneless" +│ │ ├── provider.tf # `provider.tf` is for configuring the providers +│ │ ├── users.tf # `.tf` (users.tf) is for managing the individual resources +│ │ └── vars.tf # Manage all variables for this component +│ ├── zone_a # Group all zone based features together +│ │ ├── dns # Individual (or grouped, your choice) of products or features to manage together +│ │ │ ├── dns.tf # `.tf` (dns.tf) is for managing the individual resources +│ │ │ ├── provider.tf # `provider.tf` is for configuring the providers +│ │ │ └── vars.tf # Manage all variables for this component +│ │ └── page_rules # ... same as above but for Page Rules (legacy) +│ │ ├── page_rules.tf +│ │ ├── provider.tf +│ │ └── vars.tf +│ ├── zone_b +│ │ ├── dns +│ │ │ ├── dns.tf +│ │ │ ├── provider.tf +│ │ │ └── vars.tf +│ │ └── page_rules +│ │ ├── page_rules.tf +│ │ ├── provider.tf +│ │ └── vars.tf +│ └── zone_c +│ ├── dns +│ │ ├── dns.tf +│ │ ├── provider.tf +│ │ └── vars.tf +│ └── page_rules +│ ├── page_rules.tf +│ ├── provider.tf +│ └── vars.tf +└── demo_account_b + ├── users + │ ├── provider.tf + │ ├── users.tf + │ └── vars.tf + ├── zone_a + │ ├── dns + │ │ ├── dns.tf + │ │ ├── provider.tf + │ │ └── vars.tf + │ └── page_rules + │ ├── page_rules.tf + │ ├── provider.tf + │ └── vars.tf + ├── zone_b + │ ├── dns + │ │ ├── dns.tf + │ │ ├── provider.tf + │ │ └── vars.tf + │ └── page_rules + │ ├── page_rules.tf + │ ├── provider.tf + │ └── vars.tf + └── zone_c + ├── dns + │ ├── dns.tf + │ ├── provider.tf + │ └── vars.tf + └── page_rules + ├── page_rules.tf + ├── provider.tf + └── vars.tf + + +### 1.2 File Naming Conventions + +* `provider.tf`: Contains provider configuration (e.g., Cloudflare provider settings). +* `variables.tf`: Defines input variables for the module/component. +* `outputs.tf`: Declares output values that can be used by other modules/components. +* `.tf`: Contains resource definitions for a specific Cloudflare resource type (e.g., `dns_records.tf`, `page_rules.tf`, `waf_rules.tf`). +* `data.tf`: Contains Terraform data sources. +* `main.tf`: If `provider.tf` and `outputs.tf` are not required, `main.tf` should contain your main resource and data source definitions. + +### 1.3 Module Organization + +* **Avoid Modules (or Use Sparingly):** While modules can provide abstraction, they can also introduce complexity and make debugging more difficult. Carefully consider whether a module is truly necessary before creating one. If you do use modules, keep them small and well-defined. +* **Module Structure:** If using modules, follow a consistent internal structure, including `variables.tf`, `outputs.tf`, and `main.tf`. +* **Versioning:** If you share Terraform modules (internal or public), ensure you practice module versioning best practices. A well-defined versioning strategy, such as semantic versioning is recommended. + +### 1.4 Component Architecture + +* **Small, Focused Components:** Design your Terraform code as a collection of small, focused components, each responsible for a specific aspect of your Cloudflare configuration. +* **Loose Coupling:** Minimize dependencies between components to improve reusability and reduce the impact of changes. +* **Well-Defined Interfaces:** Clearly define the input variables and output values for each component to create well-defined interfaces. + +### 1.5 Code Splitting Strategies + +* **Resource Type:** Split code based on resource type (e.g., DNS records, Page Rules). +* **Functionality:** Split code based on logical functionality (e.g., WAF rules for specific types of attacks). +* **Environment:** While *strongly* recommending separate Cloudflare accounts for environments, you can also use Terraform workspaces to manage different environments within the same codebase, though this is generally discouraged due to potential blast radius of changes. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to Cloudflare + +* **Data Source-Driven Configuration:** Use data sources to dynamically fetch information about existing Cloudflare resources (e.g., zone ID, account ID) rather than hardcoding them. +* **Looping with `for_each` and `count`:** Use `for_each` or `count` to create multiple similar resources (e.g., multiple DNS records) based on variables or data sources. Favor `for_each` over `count` when possible, as it provides more explicit resource naming and updating behaviors. +* **Dynamic Blocks:** Leverage dynamic blocks to conditionally create resource attributes based on variables or data sources. This allows for more flexible and reusable code. + +### 2.2 Recommended Approaches for Common Tasks + +* **Creating DNS Records:** Use `cloudflare_record` resource to manage DNS records. Utilize `for_each` to create multiple records based on a variable containing a list of record definitions. +* **Managing Page Rules:** Use the `cloudflare_page_rule` resource to create and manage page rules. Consider using a module to encapsulate common page rule configurations. +* **Configuring WAF Rules:** Use the `cloudflare_ruleset` and related resources to create and manage WAF rulesets. Organize rulesets into logical groups based on functionality. +* **Setting up Load Balancers:** Use `cloudflare_load_balancer`, `cloudflare_load_balancer_pool`, and `cloudflare_load_balancer_monitor` resources to create and manage load balancers. +* **Worker Deployment**: Use `cloudflare_worker` to manage Cloudflare Workers. + +### 2.3 Anti-patterns and Code Smells to Avoid + +* **Hardcoding Values:** Avoid hardcoding values such as API keys, account IDs, and zone IDs in your code. Use variables and data sources instead. +* **Managing Resources Outside of Terraform:** Terraform works best when it manages all changes to and the lifecycle of a resource. Avoid making manual changes to Cloudflare resources outside of Terraform, as this can lead to inconsistencies and drift. If external changes are unavoidable, plan to re-import the resources or reconcile the differences. +* **Overly Complex Modules:** Avoid creating overly complex modules that perform too many tasks. Break down complex configurations into smaller, more manageable components. +* **Ignoring `terraform fmt` and `terraform validate`:** Always run `terraform fmt` to format your code and `terraform validate` to check for syntax errors and other issues before committing changes. +* **Storing Secrets in Code:** Never store API tokens or other secrets directly in your Terraform code or version control. Use a secure secret management solution like Vault or environment variables. + +### 2.4 State Management Best Practices + +* **Remote State:** Always use remote state management (e.g., Terraform Cloud, AWS S3, Azure Blob Storage) to store your Terraform state file. This ensures that your state is stored securely and is accessible to all members of your team. +* **State Locking:** Enable state locking to prevent concurrent modifications to your state file. +* **Encryption:** Encrypt your state file at rest to protect sensitive information. +* **Backup:** Regularly back up your state file to prevent data loss. +* **Consider Terraform Cloud:** For teams, consider using Terraform Cloud for state management, collaboration, and automation. It offers features like remote state storage, state locking, plan previews, and automated runs. + +### 2.5 Error Handling Patterns + +* **Use `try` and `catch` in Expressions:** Use `try` and `catch` to handle errors in Terraform expressions gracefully. +* **Validate Input Variables:** Validate input variables to ensure that they are in the correct format and within the expected range. +* **Use `depends_on` Sparingly:** Use `depends_on` only when necessary to explicitly define dependencies between resources. Overuse of `depends_on` can lead to performance issues and deadlocks. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +* **Minimize Resource Dependencies:** Reduce the number of dependencies between resources to improve plan and apply times. +* **Use Data Sources Effectively:** Use data sources to retrieve information about existing resources rather than creating new resources when possible. +* **Targeted Applies:** Use targeted applies (`terraform apply -target=resource`) to apply changes to specific resources rather than applying the entire configuration. + +### 3.2 Memory Management + +* **Large State Files:** Be mindful of large state files. Break down large configurations into smaller, more manageable components to reduce state file size. Review state files periodically and consider refactoring if they become unwieldy. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +* **Exposed API Keys:** Never expose your Cloudflare API keys in your code or version control. Use environment variables or a secure secret management solution instead. +* **Insufficient Input Validation:** Validate all input variables to prevent injection attacks and other security vulnerabilities. +* **Overly Permissive Permissions:** Grant only the necessary permissions to your Cloudflare API keys and Terraform service accounts. + +### 4.2 Input Validation + +* **Variable Validation:** Use the `validation` block in variable definitions to enforce constraints on input values. This is crucial for preventing unexpected behavior and security vulnerabilities. +* **Regular Expressions:** Use regular expressions to validate input strings. +* **Type Checking:** Use Terraform's type system to ensure that variables are of the correct type. + +### 4.3 Authentication and Authorization Patterns + +* **API Tokens vs. Global API Key:** Prefer using API tokens with specific permissions over the global API key, as API tokens can be scoped to specific resources and actions. +* **Least Privilege Principle:** Grant only the necessary permissions to your Terraform service accounts. +* **Secure Storage:** Store API tokens and other secrets securely using a secret management solution. + +### 4.4 Data Protection Strategies + +* **Encryption:** Encrypt sensitive data at rest and in transit. +* **Data Masking:** Mask sensitive data in logs and error messages. +* **Access Control:** Implement strict access control policies to protect sensitive data. + +### 4.5 Secure API Communication + +* **HTTPS:** Always use HTTPS to communicate with the Cloudflare API. +* **TLS:** Use TLS 1.2 or higher. +* **Certificate Validation:** Validate the Cloudflare API certificate. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +* **Validate Resource Attributes:** Write unit tests to validate the attributes of individual resources. +* **Check for Expected Errors:** Write unit tests to check for expected errors. +* **Use `terraform show`:** Use `terraform show` to inspect the generated Terraform configuration and verify that it is correct. + +### 5.2 Integration Testing + +* **Deploy to a Test Environment:** Deploy your Terraform code to a test environment and verify that it works as expected. +* **Automated Testing:** Automate your integration tests using a CI/CD pipeline. +* **Check Cloudflare Resources:** After applying a Terraform configuration in a test environment, use the Cloudflare API or UI to verify that the resources have been created and configured correctly. + +### 5.3 End-to-End Testing + +* **Simulate Real-World Traffic:** Simulate real-world traffic to your Cloudflare resources to verify that they are functioning correctly. +* **Monitor Performance:** Monitor the performance of your Cloudflare resources to identify any bottlenecks or issues. + +### 5.4 Test Organization + +* **Separate Test Directory:** Create a separate directory for your Terraform tests. +* **Test Naming Conventions:** Follow consistent naming conventions for your tests. + +### 5.5 Mocking and Stubbing + +* **Mock Data Sources:** Mock data sources to isolate your tests from external dependencies. +* **Stub API Calls:** Stub API calls to control the behavior of the Cloudflare API during testing. + +## 6. Common Pitfalls and Gotchas + +* **Rate Limiting:** Be aware of Cloudflare's API rate limits. Implement retry logic to handle rate limit errors. +* **Resource Dependencies:** Understand the dependencies between Cloudflare resources. Create resources in the correct order to avoid errors. +* **State Drift:** Regularly check for state drift and reconcile any differences between your Terraform state and your Cloudflare resources. +* **Idempotency:** Ensure that your Terraform code is idempotent. Applying the same configuration multiple times should have the same result. +* **Cloudflare Provider Version:** Lock the Cloudflare provider version in your `terraform` block in `main.tf`. Upgrading the provider can sometimes introduce breaking changes, so testing the upgrade in a non-production environment is suggested first. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +* **Terraform CLI:** The official Terraform command-line interface. +* **Terraform Language Server:** Provides code completion, syntax highlighting, and other features for Terraform code in your IDE. +* **IDE Extensions:** Use IDE extensions for Terraform to improve your development experience (e.g., VS Code Terraform extension). +* **cf-terraforming:** Use `cf-terraforming` tool to import existing Cloudflare resources into Terraform state. + +### 7.2 Build Configuration + +* **Terraform Block:** Configure the required providers and Terraform version in the `terraform` block in `main.tf`. +* **Provider Configuration:** Configure the Cloudflare provider with your API key and account ID. + +### 7.3 Linting and Formatting + +* **`terraform fmt`:** Use `terraform fmt` to automatically format your Terraform code. +* **`terraform validate`:** Use `terraform validate` to check for syntax errors and other issues. +* **`tflint`:** Consider using `tflint` or other linting tools to enforce coding standards and best practices. + +### 7.4 Deployment Best Practices + +* **CI/CD Pipeline:** Automate your Terraform deployments using a CI/CD pipeline. +* **Plan Previews:** Always review the Terraform plan before applying changes. +* **Apply with Auto-Approve (Carefully):** Use the `-auto-approve` flag with caution. Only use it in automated environments where you have a high degree of confidence in your code. +* **Blue/Green Deployments:** Consider using blue/green deployments to minimize downtime during deployments. + +### 7.5 CI/CD Integration + +* **Terraform Cloud/Enterprise:** Use Terraform Cloud or Enterprise to manage your Terraform workflows and collaborate with your team. +* **GitHub Actions:** Use GitHub Actions to automate your Terraform deployments. +* **GitLab CI:** Use GitLab CI to automate your Terraform deployments. +* **Jenkins:** Use Jenkins to automate your Terraform deployments. + +## 8. Angle Brackets, Square Brackets, and Curly Braces + +* **Angle Brackets (`<` and `>`):** Use angle brackets as placeholders for variables that the user must enter, except in URLs, where you should use curly braces. + * Example: `https://.cloudflare.com` +* **Square Brackets (`[` and `]`):** Use square brackets to enclose optional items. + * Example: `tag=dns query [search tag=malware]` +* **Curly Braces (`{` and `}`):** Use curly braces in code samples or string literals, such as placeholders in URLs. + * Example: `https://api.cloudflare.com/client/v4/organizations/{organization_identifier}/invites` + +## 9. Cloudflare's Convention Symbols + +* The `>` symbol leads you through nested menu items and dialog box options to a final action. + * Example: `Options > Settings > General` directs you to pull down the Options menu, select the Settings item, and select General from the last dialog box. Do not use bold formatting for the `>` symbol. +* Tip icon: This icon denotes a tip, which alerts you to advisory information. +* Note icon: This icon denotes a note, which alerts you to important information. +* Info icon: This icon denotes info, which alerts you to important information. +* Notice icon: This icon denotes a notice, which alerts you to take precautions to avoid data loss, loss of signal integrity, or degradation of performance. +* Caution icon: This icon denotes a caution, which advises you to take precautions to avoid injury. +* Blue text: Text in this color indicates a link. +* Bold: Use bold when referring to a clickable action or to highlight a title or name in the UI. Bold text denotes items that you must select or click in the software, identifiers in the UI, or parameter names. Do not use bold for programs. In nested menus, use bold for the word not the symbol. + * Example: `Dashboard > This > That` +* Italics: Use italics when referring to an option that customers can select from, like in dropdown menus. Do not use italics when referring to the state of a toggle - for example, enabled/disabled should not be italicized. +* Monospace: Text in this font denotes text or characters that you should enter from the keyboard, sections of code, programming examples, and syntax examples. This font is also used for the proper names of drives, paths, directories, programs, subprograms, devices, functions, operations, variables, files, API commands, and extensions. + +By adhering to these best practices, you can create more efficient, secure, and maintainable Terraform code for managing your Cloudflare infrastructure. \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/deployment/modal.mdc b/rules-mdc/cloud_platforms/deployment/modal.mdc new file mode 100644 index 0000000..4d51523 --- /dev/null +++ b/rules-mdc/cloud_platforms/deployment/modal.mdc @@ -0,0 +1,227 @@ +--- +description: This rule outlines best practices for developing and maintaining the Modal library, covering code organization, performance, security, and testing. It aims to ensure high-quality, maintainable, and scalable cloud deployment solutions. +globs: **/*.py +--- +# Modal Library Best Practices + +This document outlines the best practices for developing and maintaining the Modal library. These guidelines cover various aspects of the library, including code organization, performance, security, testing, and deployment. Following these guidelines will ensure the Modal library remains a high-quality, maintainable, and scalable cloud deployment solution. + +## 1. Code Organization and Structure + +- **Directory Structure Best Practices:** + - Adopt a modular directory structure based on functionality or component type. + - Use clear and descriptive directory names. + - Example: + + modal/ + ├── api/ + │ ├── __init__.py + │ ├── routes.py + │ └── models.py + ├── config/ + │ ├── __init__.py + │ └── settings.py + ├── deployment/ + │ ├── __init__.py + │ ├── deploy.py + │ └── utils.py + ├── exceptions/ + │ ├── __init__.py + │ └── custom_exceptions.py + ├── security/ + │ ├── __init__.py + │ ├── auth.py + │ └── permissions.py + ├── testing/ + │ ├── __init__.py + │ ├── unit/ + │ └── integration/ + ├── utils/ + │ ├── __init__.py + │ └── helpers.py + ├── __init__.py + └── core.py + + +- **File Naming Conventions:** + - Use descriptive and consistent file names. + - Follow a consistent naming convention (e.g., `snake_case` for Python). + - Example: `user_authentication.py`, `database_connection.py` + +- **Module Organization:** + - Group related functions, classes, and data into modules. + - Use `__init__.py` files to define package structure. + - Ensure clear separation of concerns between modules. + - Each module should have a clearly defined purpose. + +- **Component Architecture:** + - Design the library using a component-based architecture. + - Each component should be self-contained and reusable. + - Components should have well-defined interfaces. + - Use dependency injection to manage component dependencies. + +- **Code Splitting Strategies:** + - Divide large modules into smaller, more manageable files. + - Split code based on functionality or feature. + - Consider using lazy loading for infrequently used modules. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns Specific to Modal:** + - **Singleton:** For managing global resources (e.g., configuration). + - **Factory:** For creating Modal clients with different configurations. + - **Observer:** For notifying subscribers of Modal state changes. + - **Strategy:** For different deployment strategies (e.g., different cloud providers). + +- **Recommended Approaches for Common Tasks:** + - **Configuration Management:** Use a dedicated configuration module to manage settings. + - **Logging:** Implement a robust logging system for debugging and monitoring. + - **Error Handling:** Use exception handling to gracefully handle errors. + - **Asynchronous Operations:** Use `asyncio` or similar libraries for handling asynchronous tasks. + - **Resource Management:** Use context managers (`with` statement) to ensure proper resource cleanup. + +- **Anti-patterns and Code Smells to Avoid:** + - **God Classes:** Avoid creating classes that are too large and complex. + - **Spaghetti Code:** Maintain a clear and well-structured codebase. + - **Magic Numbers:** Use constants instead of hardcoded values. + - **Duplicated Code:** Refactor duplicated code into reusable functions or classes. + - **Ignoring Errors:** Always handle exceptions appropriately. + +- **State Management Best Practices:** + - Prefer immutable data structures to avoid unintended side effects. + - Use a centralized state management system (if needed) for complex state. + - Consider using libraries like `attrs` or `dataclasses` for managing data objects. + +- **Error Handling Patterns:** + - Use try-except blocks to handle potential exceptions. + - Define custom exception classes for specific error conditions. + - Log exceptions with relevant information for debugging. + - Implement retry mechanisms for transient errors. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - Profile code to identify performance bottlenecks. + - Optimize database queries and data access patterns. + - Use caching to reduce the load on external services. + - Avoid unnecessary computations and memory allocations. + +- **Memory Management:** + - Use generators and iterators to process large datasets efficiently. + - Avoid creating large objects in memory unnecessarily. + - Use memory profiling tools to identify memory leaks. + +- **Rendering Optimization (if applicable):** + - N/A (Modal library is primarily backend-focused). + +- **Bundle Size Optimization (if applicable):** + - N/A (Modal library is primarily backend-focused). + +- **Lazy Loading Strategies:** + - Use lazy loading to load modules and resources only when they are needed. + - This can reduce startup time and memory usage. + +## 4. Security Best Practices + +- **Common Vulnerabilities and How to Prevent Them:** + - **Injection Attacks:** Sanitize user inputs to prevent SQL injection, command injection, etc. + - **Cross-Site Scripting (XSS):** N/A (Modal library is primarily backend-focused). + - **Cross-Site Request Forgery (CSRF):** N/A (Modal library is primarily backend-focused). + - **Authentication and Authorization Flaws:** Implement secure authentication and authorization mechanisms. + - **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit. + +- **Input Validation:** + - Validate all user inputs to prevent malicious data from entering the system. + - Use data validation libraries (e.g., `marshmallow`, `pydantic`) to enforce data types and constraints. + +- **Authentication and Authorization Patterns:** + - Use a strong authentication mechanism (e.g., OAuth 2.0, JWT). + - Implement role-based access control (RBAC) to restrict access to sensitive resources. + - Avoid storing passwords in plain text; use password hashing algorithms (e.g., bcrypt, Argon2). + +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between clients and servers. + - Implement data masking and anonymization techniques to protect sensitive data. + +- **Secure API Communication:** + - Use API keys or tokens to authenticate API requests. + - Implement rate limiting to prevent abuse. + - Use input validation to prevent malicious data from entering the system. + +## 5. Testing Approaches + +- **Unit Testing Strategies:** + - Write unit tests for all critical functions and classes. + - Use mocking and stubbing to isolate units of code. + - Aim for high test coverage. + +- **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 system functionality. + - Simulate real-world scenarios. + +- **Test Organization:** + - Organize tests into separate directories based on functionality or component. + - Use a consistent naming convention for test files and functions. + +- **Mocking and Stubbing:** + - Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to isolate units of code. + - Create stubs for external dependencies. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes Developers Make:** + - Improper error handling. + - Lack of input validation. + - Security vulnerabilities. + - Performance bottlenecks. + - Inadequate testing. + +- **Edge Cases to Be Aware Of:** + - Handling of large datasets. + - Concurrent access to shared resources. + - Network failures and timeouts. + - Unexpected input values. + +- **Version-Specific Issues:** + - Be aware of compatibility issues between different versions of the library and its dependencies. + - Test the library with different versions of Python and other dependencies. + +- **Compatibility Concerns:** + - Ensure the library is compatible with different operating systems and environments. + +- **Debugging Strategies:** + - Use logging to trace the execution flow and identify errors. + - Use debuggers to step through the code and inspect variables. + - Use profiling tools to identify performance bottlenecks. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - IDE: VS Code, PyCharm + - Debugger: pdb, ipdb + - Profiler: cProfile, line_profiler + - Testing Framework: pytest, unittest + - Mocking Library: unittest.mock, pytest-mock + - Linting and Formatting: pylint, flake8, black + +- **Build Configuration:** + - Use a build system (e.g., `setuptools`, `poetry`) to manage dependencies and build the library. + - Define a clear build process. + +- **Linting and Formatting:** + - Use linters (e.g., `pylint`, `flake8`) to enforce code style and identify potential errors. + - Use formatters (e.g., `black`) to automatically format the code. + +- **Deployment Best Practices:** + - Use a deployment automation tool (e.g., Ansible, Terraform) to automate the deployment process. + - Use infrastructure-as-code (IaC) to manage infrastructure. + - Monitor the deployment process for errors. + +- **CI/CD Integration:** + - Integrate the library with a CI/CD pipeline to automate testing and deployment. + - Use tools like Jenkins, GitLab CI, or GitHub Actions. \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/deployment/vercel.mdc b/rules-mdc/cloud_platforms/deployment/vercel.mdc new file mode 100644 index 0000000..8fc342f --- /dev/null +++ b/rules-mdc/cloud_platforms/deployment/vercel.mdc @@ -0,0 +1,161 @@ +--- +description: Enforces Vercel's recommended coding style, optimization strategies, and security best practices. This guide helps developers build performant, secure, and maintainable applications on the Vercel platform. +globs: **/*.{js,jsx,ts,tsx,md,mdx,json,yml,yaml,html,css,scss,sass} +--- +- Adhere to Vercel's Style Guide: Utilize linting and styling tools configured according to the Vercel Style Guide for consistent code formatting and style. Use `@file vercel_style_guide.mdc` to include style guide details. +- Enforce Consistent Coding Style: Integrate ESLint, Prettier, and TypeScript to automatically enforce coding style and prevent stylistic inconsistencies. Refer to [Vercel's documentation](https://vercel.com/docs) for setup instructions. +- Optimize Codebase Performance: Focus on optimizing the codebase for faster loading times and improved user experience. Includes optimizing cache, assets, and serverless functions. +- Implement Conformance Checks: Utilize Vercel's Conformance tools to automatically check for performance, security, and code health issues. + +## 1. Code Organization and Structure: + +- **Directory Structure:** + - Adopt a clear and consistent directory structure (e.g., `components`, `pages`, `lib`, `api`, `styles`, `public`). Group related files logically to improve maintainability. + - Use a `src` directory to encapsulate all source code, separating it from configuration files and other project assets. +- **File Naming Conventions:** + - Use descriptive and consistent file names (e.g., `Button.tsx`, `useUser.ts`, `api/products.js`). + - Prefer camelCase for JavaScript/TypeScript files and kebab-case for CSS/SCSS files. +- **Module Organization:** + - Organize code into reusable modules or components. Favor small, focused modules with well-defined interfaces. + - Use ES modules (`import`/`export`) for modularity and dependency management. +- **Component Architecture:** + - Employ a component-based architecture (e.g., using React, Vue, or Svelte) to build reusable UI elements. + - Follow the principles of separation of concerns and single responsibility. + - Consider using a design system or component library to maintain consistency across the application. +- **Code Splitting Strategies:** + - Implement code splitting to reduce the initial bundle size and improve loading times. Use dynamic imports for route-based or component-based splitting. + - Analyze bundle size using tools like `webpack-bundle-analyzer` to identify large dependencies. + +## 2. Common Patterns and Anti-patterns: + +- **Design Patterns Specific to Vercel:** + - Serverless Functions: Use serverless functions for API endpoints and background tasks. Optimize function size and execution time to minimize cold starts. + - Edge Functions: Use edge functions to perform operations closer to the user, reducing latency for geographically distributed users. + - Incremental Static Regeneration (ISR): Use ISR to combine the benefits of static generation and server-side rendering. +- **Recommended Approaches for Common Tasks:** + - Data Fetching: Use `getStaticProps` or `getServerSideProps` in Next.js for data fetching in pages. + - API Routes: Create API routes in the `pages/api` directory of a Next.js project for handling API requests. + - Environment Variables: Use environment variables to store sensitive information and configuration settings. +- **Anti-patterns and Code Smells to Avoid:** + - Large components: Break down large components into smaller, more manageable pieces. + - Deeply nested components: Avoid excessive nesting of components, which can make code harder to read and maintain. + - Over-fetching data: Fetch only the data that is needed by a component. + - Mutating state directly: Avoid mutating state directly, which can lead to unexpected behavior. +- **State Management Best Practices:** + - Choose a state management solution (e.g., Redux, Zustand, Recoil, React Context) that is appropriate for the application's complexity. + - Follow recommended patterns for managing state (e.g., reducers, actions, selectors). + - Avoid storing too much data in the global state. +- **Error Handling Patterns:** + - Implement comprehensive error handling throughout the application. + - Use try-catch blocks to catch exceptions. + - Log errors to a monitoring service. + - Display user-friendly error messages. + +## 3. Performance Considerations: + +- **Optimization Techniques:** + - Minimize bundle size by removing unused code and dependencies (tree shaking). + - Compress images and other assets. + - Use a content delivery network (CDN) to serve static assets. + - Optimize database queries. + - Cache frequently accessed data. +- **Memory Management:** + - Avoid memory leaks by properly releasing resources. + - Use garbage collection to reclaim unused memory. + - Profile application memory usage to identify potential issues. +- **Rendering Optimization:** + - Use memoization techniques (e.g., `React.memo`, `useMemo`) to prevent unnecessary re-renders. + - Virtualize long lists to improve rendering performance. + - Use code splitting to reduce the initial bundle size. +- **Bundle Size Optimization:** + - Analyze bundle size with tools like `webpack-bundle-analyzer` or `source-map-explorer`. + - Remove unused dependencies. + - Minify code. + - Compress code with gzip or Brotli. +- **Lazy Loading Strategies:** + - Implement lazy loading for images, components, and routes. + - Use the `IntersectionObserver` API to detect when an element is visible in the viewport. + +## 4. Security Best Practices: + +- **Common Vulnerabilities and How to Prevent Them:** + - Cross-site scripting (XSS): Sanitize user input to prevent XSS attacks. Use a library like DOMPurify. + - Cross-site request forgery (CSRF): Use CSRF tokens to protect against CSRF attacks. + - SQL injection: Use parameterized queries or an ORM to prevent SQL injection attacks. + - Authentication and authorization vulnerabilities: Implement strong authentication and authorization mechanisms. +- **Input Validation:** + - Validate all user input on both the client and server sides. + - Use a validation library to simplify the validation process. +- **Authentication and Authorization Patterns:** + - Use a secure authentication protocol (e.g., OAuth 2.0, JWT). + - Implement role-based access control (RBAC) to restrict access to sensitive resources. +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between the client and server. + - Protect against data breaches by implementing appropriate security measures. +- **Secure API Communication:** + - Use HTTPS to encrypt API traffic. + - Authenticate and authorize API requests. + - Limit API rate to prevent abuse. + +## 5. Testing Approaches: + +- **Unit Testing Strategies:** + - Write unit tests for individual components, functions, and modules. + - Use a unit testing framework (e.g., Jest, Mocha, Jasmine). + - Mock external dependencies. +- **Integration Testing:** + - Write integration tests to verify that different parts of the application work together correctly. + - Test interactions between components, modules, and APIs. +- **End-to-End Testing:** + - Write end-to-end tests to simulate user interactions and verify that the application works as expected. + - Use an end-to-end testing framework (e.g., Cypress, Playwright). +- **Test Organization:** + - Organize tests into separate directories based on the type of test (e.g., unit, integration, e2e). + - Use descriptive test names. +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate components and functions during testing. + - Mock external dependencies to avoid making real API calls. + +## 6. Common Pitfalls and Gotchas: + +- **Frequent Mistakes Developers Make:** + - Over-reliance on client-side rendering. + - Neglecting performance optimization. + - Ignoring security vulnerabilities. + - Not writing enough tests. +- **Edge Cases to Be Aware Of:** + - Handling errors gracefully. + - Supporting different browsers and devices. + - Dealing with slow network connections. +- **Version-Specific Issues:** + - Be aware of breaking changes in Vercel and its dependencies. + - Test application thoroughly after upgrading Vercel or any dependencies. +- **Compatibility Concerns:** + - Ensure that the application is compatible with different browsers, devices, and operating systems. +- **Debugging Strategies:** + - Use browser developer tools to debug client-side code. + - Use server-side logging to debug server-side code. + - Use a debugger to step through code and inspect variables. + +## 7. Tooling and Environment: + +- **Recommended Development Tools:** + - VS Code with extensions for ESLint, Prettier, and TypeScript. + - Chrome DevTools for debugging. + - Vercel CLI for deploying and managing applications. +- **Build Configuration:** + - Configure build scripts to optimize code and assets. + - Use environment variables to configure the build process. +- **Linting and Formatting:** + - Use ESLint and Prettier to enforce consistent code style. + - Configure linting and formatting rules to match the Vercel Style Guide. +- **Deployment Best Practices:** + - Deploy application to Vercel using the Vercel CLI or Git integration. + - Configure environment variables for production. + - Monitor application performance and logs. +- **CI/CD Integration:** + - Integrate with a CI/CD pipeline (e.g., GitHub Actions, CircleCI) to automate the build, test, and deployment process. + - Run tests and linters as part of the CI/CD pipeline. + +@file vercel_style_guide.mdc \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/major_platforms/aws.mdc b/rules-mdc/cloud_platforms/major_platforms/aws.mdc new file mode 100644 index 0000000..6a17dd1 --- /dev/null +++ b/rules-mdc/cloud_platforms/major_platforms/aws.mdc @@ -0,0 +1,344 @@ +--- +description: Comprehensive rules and best practices for AWS development using Terraform, covering code organization, security, performance, and testing. Adherence to these guidelines ensures maintainable, secure, and efficient infrastructure code. +globs: **/*.tf +--- +# AWS Development Best Practices using Terraform + +This document outlines best practices for developing and maintaining AWS infrastructure using Terraform. Following these guidelines will help ensure your code is maintainable, secure, and efficient. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +- **Root Module**: The primary entry point for your infrastructure definition. Contains `main.tf`, `variables.tf`, `outputs.tf`, `providers.tf`, `versions.tf` and `locals.tf`. +- **Modules Directory**: Reusable components of your infrastructure. Each module should have its own directory under `modules/`. +- **Examples Directory**: Demonstrates how to use the modules. Each example should be a self-contained Terraform configuration. +- **Scripts Directory**: Custom scripts used by Terraform. +- **Templates Directory**: Templates for files that are read using the `templatefile` function, using the extension `.tftpl`. +- **Files Directory**: Contains static files referenced by Terraform (e.g., startup scripts). +- **Helpers Directory**: Contains utility scripts that are *not* directly called by Terraform. +- **.tfvars files**: Files containing variable definitions. Use `terraform.tfvars` for common values and create environment specific files in the `envs/` directory (e.g., `envs/dev/terraform.tfvars`, `envs/prod/terraform.tfvars`). +- **.gitignore**: Specifies intentionally untracked files that Git should ignore. +- **docs/**: Place any supplemental documentation in a `docs/` subdirectory. +- **CODEOWNERS**: File to document who is responsible for the module. Before any merge request is merged, an owner should approve it. + +Example: + + +├── .terraform/ # Terraform working directory +├── modules/ +│ ├── ec2/ +│ │ ├── main.tf +│ │ ├── variables.tf +│ │ ├── outputs.tf +│ │ └── README.md +│ ├── s3/ +│ │ ├── main.tf +│ │ ├── variables.tf +│ │ ├── outputs.tf +│ │ └── README.md +├── examples/ +│ ├── ec2/ +│ │ ├── main.tf +│ │ ├── variables.tf +│ │ ├── outputs.tf +│ │ └── README.md +│ ├── s3/ +│ │ ├── main.tf +│ │ ├── variables.tf +│ │ ├── outputs.tf +│ │ └── README.md +├── scripts/ +│ ├── configure_instance.sh +├── templates/ +│ ├── user_data.tftpl +├── files/ +│ ├── application.conf +├── helpers/ +│ ├── backup_database.sh +├── terraform.tfvars +├── envs/ +│ ├── dev/ +│ │ ├── terraform.tfvars +│ ├── prod/ +│ │ ├── terraform.tfvars +├── main.tf +├── variables.tf +├── outputs.tf +├── providers.tf +├── versions.tf +├── locals.tf +└── .gitignore + + +### 1.2 File Naming Conventions + +- `main.tf`: Primary entry point for resource definitions. +- `variables.tf`: Variable declarations. +- `outputs.tf`: Output declarations. +- `providers.tf`: Provider configuration. +- `versions.tf`: Terraform and provider version constraints. +- `locals.tf`: Local variable definitions. +- `*.tfvars`: Variable value files. Use `terraform.tfvars` for default values and `env/.tfvars` for environment-specific values. + +### 1.3 Module Organization + +- **Reusable Modules**: Create modules for common infrastructure components (e.g., EC2 instances, S3 buckets, VPCs). +- **Module Composition**: Compose complex infrastructure by combining smaller, reusable modules. +- **Module Versioning**: Use version control (e.g., Git tags) to manage module versions. +- **Module Naming**: Module repositories must use the format `terraform--`. For example: `terraform-aws-ec2` +- **Module sources**: When referencing another module on a public registry, pin the Git commit hash by pointing directly to the underlying Git repo URL. Example: + + terraform + module "lambda" { + source = "github.com/terraform-aws-modules/terraform-aws-lambda.git?ref=e78cdf1f82944897ca6e30d6489f43cf24539374" # --> v4.18.0 + } + + +### 1.4 Component Architecture + +- **Layered Architecture**: Separate infrastructure into logical layers (e.g., network, compute, data). +- **Loose Coupling**: Design components to be loosely coupled, minimizing dependencies between them. +- **Clear Abstractions**: Use modules to create clear abstractions for complex infrastructure components. + +### 1.5 Code Splitting Strategies + +- **Functional Decomposition**: Split code into smaller, manageable functions. +- **Resource Grouping**: Group related resources into separate files or modules. +- **Environment Separation**: Use separate files or modules for environment-specific configurations. +- **Service-Based Separation**: Separate resources by service (e.g., `iam.tf`, `ec2.tf`, `s3.tf`) only if they exceed 150 lines in `main.tf`. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to AWS + +- **Immutable Infrastructure**: Deploy new infrastructure components instead of modifying existing ones. +- **Infrastructure as Code (IaC)**: Manage infrastructure through code, using tools like Terraform. +- **Blue/Green Deployments**: Deploy new versions of applications alongside existing ones, then switch traffic. +- **Canary Deployments**: Deploy new versions of applications to a small subset of users before rolling them out to everyone. + +### 2.2 Recommended Approaches for Common Tasks + +- **Creating VPCs**: Use the `terraform-aws-modules/vpc/aws` module for creating VPCs. +- **Creating EC2 Instances**: Use the `terraform-aws-modules/ec2-instance/aws` module for creating EC2 instances. +- **Creating S3 Buckets**: Use the `terraform-aws-modules/s3-bucket/aws` module for creating S3 buckets. +- **Managing IAM Roles**: Use the `aws_iam_role` and `aws_iam_policy` resources to manage IAM roles and policies. +- **Using Data Sources**: Utilize data sources (e.g., `aws_ami`, `aws_vpc`) to fetch information about existing AWS resources. +- **Resource Tagging**: Tag all AWS resources for cost allocation, automation, and identification. +- **State File Storage**: Use a remote backend (e.g., S3 with DynamoDB locking) for storing Terraform state. + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **Hardcoding Values**: Avoid hardcoding values in your code. Use variables instead. +- **Storing Secrets in Code**: Never store secrets (e.g., passwords, API keys) in your code. Use AWS Secrets Manager or other secret management solutions. +- **Overly Complex Modules**: Avoid creating modules that are too complex and difficult to understand. +- **Ignoring Errors**: Always handle errors gracefully. +- **Manual Infrastructure Changes**: Avoid making manual changes to infrastructure outside of Terraform. +- **Using embedded resource attributes**: avoid using these embedded resource attributes and instead you should use the unique resource to attach that pseudo-resource. These resource relationships can cause chicken/egg issues that are unique per resource. + +### 2.4 State Management Best Practices + +- **Remote Backend**: Use a remote backend (e.g., S3 with DynamoDB locking) for storing Terraform state. This allows for collaboration and prevents data loss. +- **State Locking**: Enable state locking to prevent concurrent modifications to the state file. +- **State Encryption**: Encrypt the state file at rest and in transit. +- **Workspace Management**: Use Terraform workspaces to manage multiple environments (e.g., development, staging, production). +- **Secure State Access**: Restrict access to the state file to authorized users and systems only. Consider implementing least privilege principles. +- **Versioning**: Implement a mechanism for versioning your state files, which could include frequent backups and using version control systems. +- **Avoid local state**: Never store Terraform state locally. + +### 2.5 Error Handling Patterns + +- **Validation Rules**: Use validation rules within variable definitions to check input values. +- **Error Propagation**: Propagate errors up the call stack to be handled at a higher level. +- **Retry Logic**: Implement retry logic for transient errors (e.g., network errors, API throttling). +- **Logging**: Log errors and warnings to aid in debugging. +- **Custom Error Messages**: Provide clear and informative error messages to users. +- **Panic Handling**: Avoid using `panic()` function that stops the execution, implement error handling. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Efficient Resource Usage**: Use the appropriate instance types and storage classes for your workloads. +- **Caching**: Implement caching to reduce latency and improve performance. +- **Load Balancing**: Use load balancing to distribute traffic across multiple instances. +- **Content Delivery Networks (CDNs)**: Use CDNs to deliver static content closer to users. +- **Database Optimization**: Optimize database queries and indexing for faster performance. +- **Parallelization**: Use `for_each` and `count` to parallelize resource creation and modification. + +### 3.2 Memory Management + +- **Resource Limits**: Set resource limits on EC2 instances and other AWS resources. +- **Memory Profiling**: Use memory profiling tools to identify memory leaks and optimize memory usage. +- **Garbage Collection**: Configure garbage collection settings for your applications. + +### 3.3 Rendering Optimization + +- **Minimize Rendering**: Minimize the amount of data that needs to be rendered. +- **Efficient Templates**: Use efficient templates to generate configuration files. + +### 3.4 Bundle Size Optimization + +- **Code Splitting**: Split code into smaller bundles that can be loaded on demand. +- **Tree Shaking**: Remove unused code from your bundles. +- **Minification**: Minify your code to reduce bundle sizes. +- **Compression**: Compress your bundles to reduce download times. + +### 3.5 Lazy Loading Strategies + +- **Lazy Loading of Resources**: Load resources only when they are needed. +- **Virtualization**: Use virtualization to reduce the number of resources that need to be loaded. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **IAM Misconfiguration**: Prevent IAM misconfiguration by following the principle of least privilege. +- **Unsecured S3 Buckets**: Secure S3 buckets by enabling encryption, access logging, and versioning. +- **Security Group Misconfiguration**: Configure security groups to allow only necessary traffic. +- **SQL Injection**: Prevent SQL injection by using parameterized queries and input validation. +- **Cross-Site Scripting (XSS)**: Prevent XSS by sanitizing user input and output. +- **Cross-Site Request Forgery (CSRF)**: Prevent CSRF by using anti-CSRF tokens. +- **Exposed Secrets**: Avoid exposing secrets by using AWS Secrets Manager and IAM roles. + +### 4.2 Input Validation + +- **Validate User Input**: Validate user input to prevent malicious code from being injected into your application. +- **Use Data Types**: Use appropriate data types for your variables to prevent type-related errors. +- **Regular Expressions**: Use regular expressions to validate complex input patterns. + +### 4.3 Authentication and Authorization Patterns + +- **IAM Roles**: Use IAM roles to grant permissions to AWS resources. +- **Multi-Factor Authentication (MFA)**: Enable MFA for all user accounts. +- **Principle of Least Privilege**: Grant users only the permissions they need to perform their tasks. +- **AWS Cognito**: Use AWS Cognito to manage user authentication and authorization. +- **API Gateway Authorization**: Implement authorization at the API Gateway level to control access to your APIs. + +### 4.4 Data Protection Strategies + +- **Encryption at Rest**: Encrypt data at rest using AWS KMS, S3 encryption, or other encryption solutions. +- **Encryption in Transit**: Encrypt data in transit using HTTPS, TLS, or other encryption protocols. +- **Data Masking**: Mask sensitive data to prevent unauthorized access. +- **Data Redaction**: Redact sensitive data from logs and other output. + +### 4.5 Secure API Communication + +- **HTTPS**: Use HTTPS for all API communication. +- **API Keys**: Use API keys to authenticate API requests. +- **OAuth 2.0**: Use OAuth 2.0 for authorization. +- **Rate Limiting**: Implement rate limiting to prevent abuse. +- **Web Application Firewall (WAF)**: Use a WAF to protect your APIs from common web attacks. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- **Test Individual Modules**: Unit test individual Terraform modules to ensure they are working correctly. +- **Mock AWS Resources**: Mock AWS resources to isolate your modules from external dependencies. +- **Test Variable Validation**: Verify variable validation rules work as expected. +- **Test Output Values**: Check that module outputs are correct. + +### 5.2 Integration Testing + +- **Test Module Integration**: Test how modules interact with each other. +- **Deploy to Test Environment**: Deploy your infrastructure to a test environment and verify that it is working correctly. +- **Automated Tests**: Write automated tests to verify that your infrastructure is working correctly. + +### 5.3 End-to-End Testing + +- **Test Full Infrastructure**: Test the entire infrastructure from end to end. +- **Simulate User Behavior**: Simulate user behavior to verify that your infrastructure is working correctly. +- **Monitor Performance**: Monitor performance to identify any performance bottlenecks. + +### 5.4 Test Organization + +- **Separate Test Directory**: Create a separate directory for your tests. +- **Test Naming Conventions**: Use clear naming conventions for your tests. +- **Test Documentation**: Document your tests to explain what they are testing. + +### 5.5 Mocking and Stubbing + +- **Use Mock Objects**: Use mock objects to isolate your code from external dependencies. +- **Use Stub Objects**: Use stub objects to provide canned responses to external dependencies. +- **Terratest**: Utilize Terratest for creating test environments and performing infrastructure tests. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Forgetting to Enable State Locking**: Enabling state locking is crucial for preventing corruption and ensuring integrity when multiple users work on the same Terraform project. +- **Overlooking IAM Permissions**: Ensuring the Terraform service account has the necessary IAM permissions to create, modify, and delete resources is vital. +- **Incorrect Resource Dependencies**: Managing resource dependencies correctly to prevent errors during creation or deletion. +- **Handling Sensitive Data Insecurely**: Implementing robust measures for managing sensitive data, such as API keys and passwords, by using AWS Secrets Manager or other appropriate services. +- **Neglecting to Monitor Infrastructure**: Setting up comprehensive monitoring and alerting to detect and respond to infrastructure issues promptly. +- **Using hardcoded values**: Always use variables + +### 6.2 Edge Cases to be Aware Of + +- **Resource Limits**: Be aware of AWS resource limits and plan accordingly. +- **Availability Zones**: Understand the implications of availability zones and design your infrastructure to be resilient to AZ failures. +- **Data Consistency**: Understand the consistency models of different AWS services and design your applications accordingly. +- **API Throttling**: Be aware of API throttling limits and implement retry logic. + +### 6.3 Version-Specific Issues + +- **Terraform Version Compatibility**: Ensure that your Terraform code is compatible with the version of Terraform you are using. +- **Provider Version Compatibility**: Ensure that your Terraform providers are compatible with the version of Terraform you are using. +- **AWS API Version Compatibility**: Be aware of changes to the AWS API and update your code accordingly. + +### 6.4 Compatibility Concerns + +- **Backwards Compatibility**: Ensure that your changes are backwards compatible. +- **Cross-Region Compatibility**: Ensure that your infrastructure is compatible across different AWS regions. +- **Cross-Account Compatibility**: Ensure that your infrastructure is compatible across different AWS accounts. + +### 6.5 Debugging Strategies + +- **Terraform Plan**: Use `terraform plan` to preview changes before applying them. +- **Terraform Show**: Use `terraform show` to inspect the current state of your infrastructure. +- **Terraform Graph**: Use `terraform graph` to visualize the dependencies between resources. +- **Terraform Console**: Use `terraform console` to evaluate Terraform expressions. +- **AWS CloudTrail**: Use AWS CloudTrail to audit API calls and identify errors. +- **CloudWatch Logs**: Use CloudWatch Logs to collect and analyze application logs. +- **Enable Debug Logging**: Enable debug logging to get more detailed information about what Terraform is doing. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **Terraform CLI**: The Terraform command-line interface. +- **IDE with Terraform Support**: Use an IDE with Terraform support (e.g., VS Code with the Terraform extension). +- **tfenv**: Use tfenv to manage multiple versions of Terraform. +- **AWS CLI**: The AWS command-line interface. +- **jq**: A command-line JSON processor. + +### 7.2 Build Configuration + +- **Makefile**: Use a Makefile to automate common build tasks (e.g., `terraform init`, `terraform plan`, `terraform apply`). +- **.terraformignore**: Create a `.terraformignore` to prevent files from being included in the Terraform package. + +### 7.3 Linting and Formatting + +- **terraform fmt**: Use `terraform fmt` to automatically format your Terraform code. +- **terraform validate**: Use `terraform validate` to validate your Terraform code. +- **tflint**: Use `tflint` to lint your Terraform code. +- **pre-commit hooks**: Enforce code quality standards using pre-commit hooks. + +### 7.4 Deployment Best Practices + +- **Automated Deployments**: Use automated deployments to reduce errors and improve consistency. +- **Infrastructure as Code (IaC)**: Manage infrastructure as code using tools like Terraform. +- **Immutable Infrastructure**: Deploy new infrastructure components instead of modifying existing ones. +- **Blue/Green Deployments**: Deploy new versions of applications alongside existing ones, then switch traffic. +- **Canary Deployments**: Deploy new versions of applications to a small subset of users before rolling them out to everyone. + +### 7.5 CI/CD Integration + +- **Integrate with CI/CD Pipeline**: Integrate Terraform with your CI/CD pipeline. +- **Automated Testing**: Run automated tests as part of your CI/CD pipeline. +- **Automated Deployments**: Automatically deploy your infrastructure as part of your CI/CD pipeline. +- **Version Control**: Store your Terraform code in version control. +- **Terraform Cloud/Enterprise**: Use Terraform Cloud/Enterprise for remote state management and collaboration. + +This document provides a comprehensive set of best practices for AWS development using Terraform. By following these guidelines, you can ensure your code is maintainable, secure, and efficient. \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/major_platforms/azure.mdc b/rules-mdc/cloud_platforms/major_platforms/azure.mdc new file mode 100644 index 0000000..625a574 --- /dev/null +++ b/rules-mdc/cloud_platforms/major_platforms/azure.mdc @@ -0,0 +1,347 @@ +--- +description: This rule provides comprehensive best practices for developing Azure applications, covering code organization, security, performance, testing, and common pitfalls. It aims to improve code quality, security posture, and overall efficiency when working with the Azure ecosystem. +globs: **/*.{az,tf,bicep,py,js,ts,json,yml,yaml,ps1,sh,cs,java} +--- +# Azure Library Best Practices and Coding Standards + +This document outlines the recommended best practices for developing applications and infrastructure using Azure services. It covers various aspects including code organization, security, performance, testing, and tooling to ensure robust, scalable, and secure solutions. + +## 1. Code Organization and Structure + +A well-organized codebase is crucial for maintainability, scalability, and collaboration. The following guidelines provide a structured approach to organizing your Azure projects. + +### Directory Structure Best Practices + +Adopt a modular and logical directory structure based on the application's architecture and components. + +* **`src/`**: Contains the source code of your application. + * **`modules/`**: Groups related functionalities into independent modules. + * **`components/`**: Contains reusable UI or logical components. + * **`services/`**: Encapsulates external service integrations (e.g., Azure Storage, Cosmos DB). + * **`models/`**: Defines data models and schemas. + * **`utils/`**: Contains utility functions and helper classes. +* **`infra/` or `terraform/` or `bicep/`**: Infrastructure-as-Code definitions (Terraform, Bicep, Azure Resource Manager templates). +* **`config/`**: Configuration files for different environments (development, staging, production). +* **`scripts/`**: Automation scripts for deployment, build processes, etc. +* **`tests/`**: Unit, integration, and end-to-end tests. +* **`docs/`**: Documentation for the project and its components. + +Example: + + +my-azure-project/ +├── src/ +│ ├── modules/ +│ │ ├── user-management/ +│ │ │ ├── ... +│ │ ├── data-processing/ +│ │ │ ├── ... +│ ├── components/ +│ │ ├── button/ +│ │ │ ├── ... +│ ├── services/ +│ │ ├── storage-service.js +│ │ ├── cosmosdb-service.js +│ ├── models/ +│ │ ├── user.js +│ ├── utils/ +│ │ ├── logger.js +├── infra/ +│ ├── main.tf +│ ├── variables.tf +│ ├── outputs.tf +├── config/ +│ ├── development.json +│ ├── production.json +├── scripts/ +│ ├── deploy.sh +│ ├── build.sh +├── tests/ +│ ├── unit/ +│ ├── integration/ +│ ├── e2e/ +├── docs/ +│ ├── README.md +├── .gitignore +├── package.json + + +### File Naming Conventions + +Maintain consistency in file naming to improve readability and searchability. + +* Use descriptive names that reflect the file's purpose. +* Use a consistent case (e.g., camelCase or kebab-case). +* Use appropriate file extensions (e.g., `.js`, `.ts`, `.py`, `.tf`, `.bicep`). +* For React components, use `ComponentName.jsx` or `ComponentName.tsx`. + +Example: + +* `user-service.js` (for a user service module) +* `UserProfile.jsx` (for a user profile component) +* `storage-account.tf` (for a Terraform file defining a storage account) + +### Module Organization + +Divide the application into independent and reusable modules based on functionality. + +* Each module should have a clear responsibility and a well-defined interface. +* Minimize dependencies between modules to promote loose coupling. +* Consider using a module bundler (e.g., Webpack, Parcel) to manage dependencies and optimize the build process. + +Example: + +A `user-management` module could contain components and services related to user authentication, authorization, and profile management. + +### Component Architecture + +For UI-based applications, adopt a component-based architecture (e.g., React, Angular, Vue.js). + +* Divide the UI into reusable components with clear inputs and outputs. +* Follow the principles of single responsibility and separation of concerns. +* Use a component library (e.g., Material UI, Ant Design) to accelerate development and maintain consistency. + +### Code Splitting Strategies + +Improve initial load time by splitting the application into smaller chunks that can be loaded on demand. + +* Use dynamic imports to load modules only when they are needed. +* Configure your module bundler to create separate chunks for different parts of the application. +* Consider using route-based code splitting for single-page applications. + +## 2. Common Patterns and Anti-patterns + +Understanding common patterns and anti-patterns is essential for building efficient, maintainable, and reliable Azure applications. + +### Design Patterns Specific to Azure + +* **Retry Pattern:** Implement retry logic to handle transient failures when interacting with Azure services. +* **Circuit Breaker Pattern:** Prevent cascading failures by temporarily blocking access to a service that is experiencing problems. +* **Queue-Based Load Leveling:** Use queues (e.g., Azure Queue Storage, Azure Service Bus) to decouple components and handle bursts of traffic. +* **Cache-Aside Pattern:** Use a cache (e.g., Azure Cache for Redis) to improve performance by storing frequently accessed data. +* **Gateway Aggregation Pattern:** Expose multiple backend services through a single API gateway (e.g., Azure API Management). + +### Recommended Approaches for Common Tasks + +* **Configuration Management:** Use Azure App Configuration to manage application settings and feature flags. +* **Secret Management:** Use Azure Key Vault to securely store and manage secrets, keys, and certificates. +* **Logging and Monitoring:** Use Azure Monitor to collect and analyze logs, metrics, and traces. +* **Identity and Access Management:** Use Azure Active Directory (Azure AD) for authentication and authorization. +* **Data Storage:** Choose the appropriate Azure storage service based on your data requirements (e.g., Azure Blob Storage for unstructured data, Azure Cosmos DB for NoSQL data, Azure SQL Database for relational data). + +### Anti-Patterns and Code Smells to Avoid + +* **Hardcoding Secrets:** Never hardcode secrets or API keys in your code. Use Azure Key Vault to manage them securely. +* **Ignoring Errors:** Always handle errors gracefully and log relevant information for debugging. +* **Over-Engineering:** Avoid unnecessary complexity and focus on delivering business value. +* **Long-Running Transactions:** Keep transactions short and avoid holding resources for extended periods. +* **Tight Coupling:** Design components and modules to be loosely coupled to improve maintainability and testability. +* **Monolithic Functions:** Avoid creating large, complex functions. Break them down into smaller, more manageable units. + +### State Management Best Practices + +* For serverless functions, design for statelessness whenever possible. Store state in external storage services like Azure Cosmos DB or Azure Storage. +* For web applications, use appropriate state management techniques (e.g., cookies, sessions, local storage, or dedicated state management libraries like Redux or Zustand). +* Consider using distributed caching (e.g., Azure Cache for Redis) to improve performance and scalability. + +### Error Handling Patterns + +* Use try-catch blocks to handle exceptions gracefully. +* Log errors with sufficient detail to aid in debugging. +* Implement a centralized error handling mechanism to catch and handle unhandled exceptions. +* Provide meaningful error messages to the user. +* Use Polly library for implementing resilience policies like retry, circuit breaker, and timeout. + +## 3. Performance Considerations + +Optimizing performance is crucial for delivering a responsive and scalable Azure application. + +### Optimization Techniques + +* **Caching:** Implement caching at various levels (e.g., browser, server, database) to reduce latency and improve performance. +* **Compression:** Enable compression (e.g., Gzip) to reduce the size of HTTP responses. +* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead. +* **Content Delivery Network (CDN):** Use Azure CDN to cache static assets closer to users. +* **Database Optimization:** Optimize database queries and indexes to improve query performance. +* **Asynchronous Operations:** Use asynchronous operations to avoid blocking the main thread. + +### Memory Management + +* **Dispose Resources:** Dispose of disposable resources (e.g., database connections, file streams) properly to avoid memory leaks. +* **Garbage Collection:** Be aware of garbage collection behavior and avoid creating unnecessary objects. +* **Large Object Heap (LOH):** Be mindful of the LOH and avoid allocating large objects frequently. + +### Rendering Optimization + +* **Virtualization:** Use virtualization techniques (e.g., React Virtualized, Angular CDK Virtual Scroll) to efficiently render large lists of data. +* **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of event handlers. +* **Lazy Loading:** Load images and other resources only when they are visible on the screen. + +### Bundle Size Optimization + +* **Tree Shaking:** Use tree shaking to remove unused code from your bundles. +* **Code Splitting:** Split your code into smaller chunks that can be loaded on demand. +* **Minification:** Minify your code to reduce its size. +* **Image Optimization:** Optimize images by compressing them and using appropriate formats. + +### Lazy Loading Strategies + +* **Component-Based Lazy Loading:** Load components only when they are needed. +* **Route-Based Lazy Loading:** Load modules associated with specific routes only when those routes are accessed. +* **Image Lazy Loading:** Load images only when they are scrolled into view. + +## 4. Security Best Practices + +Security should be a top priority when developing Azure applications. + +### Common Vulnerabilities and How to Prevent Them + +* **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks. +* **Cross-Site Scripting (XSS):** Sanitize user input and output to prevent XSS attacks. +* **Cross-Site Request Forgery (CSRF):** Use anti-CSRF tokens to prevent CSRF attacks. +* **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms. +* **Insecure Direct Object References (IDOR):** Validate that users have access to the resources they are requesting. +* **Security Misconfiguration:** Follow security best practices for configuring Azure services. +* **Sensitive Data Exposure:** Protect sensitive data by encrypting it at rest and in transit. + +### Input Validation + +* Validate all user input on both the client and server sides. +* Use a schema validation library (e.g., Joi, Yup) to define and enforce data validation rules. +* Sanitize user input to remove potentially malicious characters. + +### Authentication and Authorization Patterns + +* Use Azure Active Directory (Azure AD) for authentication and authorization. +* Implement role-based access control (RBAC) to restrict access to resources based on user roles. +* Use multi-factor authentication (MFA) to enhance security. +* Follow the principle of least privilege. +* Leverage Managed Identities for Azure resources to securely access other Azure services. + +### Data Protection Strategies + +* Encrypt sensitive data at rest using Azure Storage Service Encryption (SSE) or Azure Disk Encryption. +* Encrypt data in transit using TLS/SSL. +* Use Azure Key Vault to store and manage encryption keys. +* Implement data masking and tokenization to protect sensitive data. + +### Secure API Communication + +* Use HTTPS for all API communication. +* Implement API authentication using API keys, tokens, or OAuth 2.0. +* Use rate limiting to prevent abuse. +* Use Azure API Management to manage and secure your APIs. + +## 5. Testing Approaches + +Thorough testing is essential for ensuring the quality and reliability of your Azure applications. + +### Unit Testing Strategies + +* Write unit tests for individual components and functions. +* Use a unit testing framework (e.g., Jest, Mocha, JUnit, pytest). +* Aim for high code coverage. +* Follow the Arrange-Act-Assert pattern. +* Use mocks and stubs to isolate the code under test. + +### Integration Testing + +* Write integration tests to verify the interaction between different components and services. +* Test the integration with Azure services (e.g., Azure Storage, Cosmos DB). +* Use a testing environment that closely resembles the production environment. + +### End-to-End Testing + +* Write end-to-end tests to verify the entire application workflow. +* Use a testing framework (e.g., Cypress, Selenium, Playwright). +* Automate end-to-end tests as part of your CI/CD pipeline. + +### Test Organization + +* Organize tests into a clear directory structure. +* Use descriptive test names. +* Group related tests together. + +### Mocking and Stubbing + +* Use mocks to simulate the behavior of external dependencies. +* Use stubs to provide predefined responses for API calls. +* Use a mocking framework (e.g., Mockito, Jest Mocks). + +## 6. Common Pitfalls and Gotchas + +Be aware of common pitfalls and gotchas to avoid making mistakes when developing Azure applications. + +### Frequent Mistakes Developers Make + +* **Insufficient Resource Sizing:** Underestimating the required resources can lead to performance issues. +* **Ignoring Azure Service Limits:** Being unaware of Azure service limits can cause unexpected errors. +* **Improper Error Handling:** Inadequate error handling can make it difficult to diagnose and resolve issues. +* **Lack of Monitoring:** Failing to monitor the application's performance and health can lead to undetected problems. +* **Neglecting Security:** Overlooking security best practices can expose the application to vulnerabilities. + +### Edge Cases to Be Aware Of + +* **Network Latency:** Be aware of network latency when interacting with Azure services. +* **Transient Faults:** Implement retry logic to handle transient faults. +* **Resource Contention:** Be aware of resource contention and design the application to handle it gracefully. +* **Data Consistency:** Understand the data consistency models of Azure storage services. + +### Version-Specific Issues + +* Be aware of breaking changes in Azure SDKs and APIs. +* Keep your dependencies up to date. +* Test your application with different versions of Azure services. + +### Compatibility Concerns + +* Ensure that your application is compatible with the target Azure environment. +* Test your application on different browsers and devices. + +### Debugging Strategies + +* Use Azure Monitor to collect and analyze logs, metrics, and traces. +* Use remote debugging to debug your application running in Azure. +* Use logging to track the flow of execution and identify errors. +* Use breakpoints to pause execution and inspect variables. + +## 7. Tooling and Environment + +Choosing the right tools and environment can significantly improve your development experience. + +### Recommended Development Tools + +* **Visual Studio Code:** A popular code editor with excellent support for Azure development. +* **Azure CLI:** A command-line tool for managing Azure resources. +* **Azure PowerShell:** A PowerShell module for managing Azure resources. +* **Terraform:** An infrastructure-as-code tool for provisioning and managing Azure resources. +* **Bicep:** A declarative language for deploying Azure resources. +* **Azure SDKs:** Libraries for interacting with Azure services from various programming languages. + +### Build Configuration + +* Use a build automation tool (e.g., Azure DevOps, Jenkins, GitHub Actions) to automate the build process. +* Configure your build process to run tests, linters, and code formatters. +* Use environment variables to configure your application for different environments. + +### Linting and Formatting + +* Use a linter (e.g., ESLint, Pylint) to enforce code style guidelines. +* Use a code formatter (e.g., Prettier, Black) to automatically format your code. +* Configure your editor to automatically run the linter and formatter on save. + +### Deployment Best Practices + +* Use Infrastructure-as-Code (IaC) to automate the deployment of Azure resources. +* Use a deployment pipeline (e.g., Azure Pipelines, GitHub Actions) to automate the deployment process. +* Use blue-green deployments or canary deployments to minimize downtime. +* Implement rollback strategies to quickly revert to a previous version if necessary. + +### CI/CD Integration + +* Integrate your CI/CD pipeline with Azure DevOps, GitHub Actions, or other CI/CD tools. +* Automate the build, test, and deployment processes. +* Use environment variables to configure your application for different environments. +* Implement automated testing to catch errors early in the development cycle. + +By following these best practices, you can build robust, scalable, secure, and maintainable Azure applications. \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/major_platforms/gcp.mdc b/rules-mdc/cloud_platforms/major_platforms/gcp.mdc new file mode 100644 index 0000000..2f1a646 --- /dev/null +++ b/rules-mdc/cloud_platforms/major_platforms/gcp.mdc @@ -0,0 +1,196 @@ +--- +description: This rule provides best practices for developing and managing infrastructure and applications on Google Cloud Platform (GCP), encompassing code organization, security, performance, and deployment strategies. +globs: **/*.{tf,py,js,go,java,proto,sh,yaml,yml} +--- +--- +## GCP Library Best Practices + +This document outlines best practices for developing and managing applications and infrastructure on Google Cloud Platform (GCP). It covers various aspects, including code organization, common patterns, performance, security, testing, common pitfalls, and tooling. + +### 1. Code Organization and Structure + +- **Follow a Standard Module Structure (especially for Terraform)**: + - Start every module with a `main.tf` file. This file contains the primary resources defined in the module. + - Include a `README.md` file for module documentation. This should explain the module's purpose, usage, inputs, and outputs. + - Group related resources logically in separate files (e.g., `network.tf`, `compute.tf`, `storage.tf`). + - Use folders to logically group files. +- **Directory Structure Best Practices:** + - `modules/`: Contains reusable Terraform modules. Each module should encapsulate a specific set of resources or functionality. + - `environments/`: Contains environment-specific configurations (e.g., `dev/`, `staging/`, `prod/`). Each environment directory should contain its own `terraform.tfvars` and `backend.tf` (or equivalent). + - `scripts/`: Contains utility scripts (e.g., Python, Bash) for automation. + - `docs/`: Contains documentation for the project. + - `examples/`: Contains example configurations or usage scenarios. +- **File Naming Conventions:** + - Use descriptive names for Terraform files (e.g., `vpc.tf`, `firewall.tf`, `iam.tf`). + - Use underscores for resource names and avoid repeating resource types in names (e.g., `instance_web_server` instead of `web_server_instance`). + - Use consistent naming conventions for variables and outputs. +- **Module Organization:** + - Keep modules small and focused. Each module should have a single responsibility. + - Use input variables to parameterize modules. This makes them reusable and configurable. + - Define outputs for modules to expose important information. This allows other modules or configurations to consume the module's results. +- **Component Architecture (for application code):** + - Adopt a layered architecture (e.g., presentation, business logic, data access). + - Use dependency injection to decouple components and improve testability. + - Design components for reusability and maintainability. + - Use well-defined interfaces between components. +- **Code Splitting Strategies (especially for client-side code):** + - Split code into logical chunks based on functionality or features. + - Use lazy loading to load code only when it's needed. This can improve initial page load time. + - Consider using code splitting tools like Webpack or Parcel. + +### 2. Common Patterns and Anti-patterns + +- **Design Patterns Specific to GCP:** + - **Service Facade:** Abstract complex GCP service interactions behind a simple interface. + - **Pub/Sub Fanout:** Use Cloud Pub/Sub to distribute messages to multiple subscribers for parallel processing. + - **Cloud Functions Chaining:** Chain Cloud Functions together to create complex workflows. + - **Idempotent Operations:** Ensure operations can be safely retried without unintended side effects, especially crucial in distributed systems like GCP. +- **Recommended Approaches for Common Tasks:** + - **Configuration Management:** Use environment variables or Cloud KMS for storing sensitive configuration data. + - **Secret Management:** Use Cloud Secret Manager to securely store and manage secrets. + - **Data Storage:** Choose the appropriate storage solution based on the data type and access patterns (e.g., Cloud Storage for objects, Cloud SQL for relational data, Cloud Datastore for NoSQL data). + - **Logging:** Use Cloud Logging for centralized logging and monitoring. + - **Monitoring:** Utilize Cloud Monitoring and Cloud Trace for performance monitoring and troubleshooting. + - **Identity and Access Management (IAM):** Adopt the principle of least privilege. Grant users and service accounts only the necessary permissions. +- **Anti-patterns and Code Smells to Avoid:** + - **Hardcoding Credentials:** Never hardcode credentials in code or configuration files. Use environment variables, secret management, or IAM roles. + - **Overly Complex IAM Roles:** Avoid creating overly complex IAM roles with too many permissions. This can lead to security vulnerabilities. + - **Ignoring Error Handling:** Always handle errors gracefully and provide informative error messages. + - **Long-Running Processes in Cloud Functions:** Cloud Functions have time limits. Offload long-running processes to other services like Cloud Run or Compute Engine. + - **Lack of Monitoring:** Failing to monitor your application can lead to undetected performance issues and errors. + - **Ignoring Security Updates:** Regularly update your dependencies and software to address security vulnerabilities. +- **State Management Best Practices:** + - **Use Terraform State:** Store Terraform state remotely in Cloud Storage for collaboration and version control. + - **Stateless Applications:** Design applications to be stateless whenever possible. If state is required, store it in a persistent storage solution like Cloud SQL or Cloud Datastore. + - **Avoid Local Storage:** Do not rely on local storage for persistent data. Use Cloud Storage or other persistent storage solutions. +- **Error Handling Patterns:** + - **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions consistently. + - **Logging and Monitoring:** Log all errors to Cloud Logging and set up alerts for critical errors in Cloud Monitoring. + - **Retry Mechanisms:** Implement retry mechanisms for transient errors. + - **Circuit Breaker Pattern:** Use the circuit breaker pattern to prevent cascading failures in distributed systems. + +### 3. Performance Considerations + +- **Optimization Techniques:** + - **Caching:** Implement caching at various levels (e.g., browser, CDN, server-side) to reduce latency and improve performance. Consider using Cloud CDN or Memorystore. + - **Load Balancing:** Use Cloud Load Balancing to distribute traffic across multiple instances for high availability and scalability. + - **Database Optimization:** Optimize database queries and indexing to improve performance. Consider using Cloud SQL Insights for query analysis. + - **Asynchronous Operations:** Use asynchronous operations for long-running tasks to prevent blocking the main thread. +- **Memory Management (for application code):** + - **Efficient Data Structures:** Choose appropriate data structures to minimize memory usage. + - **Garbage Collection:** Understand how garbage collection works in your chosen language and optimize code to minimize memory leaks. + - **Resource Pooling:** Use resource pooling to reuse expensive resources like database connections. +- **Rendering Optimization (for web applications):** + - **Minimize DOM Manipulation:** Minimize DOM manipulation to improve rendering performance. + - **Use Virtual DOM:** Use a virtual DOM library like React or Vue.js to optimize rendering updates. + - **Optimize Images:** Optimize images for web use by compressing them and using appropriate formats (e.g., WebP). +- **Bundle Size Optimization (for web applications):** + - **Code Splitting:** Split code into smaller chunks to reduce initial bundle size. + - **Tree Shaking:** Use tree shaking to remove unused code from the bundle. + - **Minification:** Minify code to reduce bundle size. +- **Lazy Loading Strategies (for web applications):** + - **Lazy Load Images:** Lazy load images that are not initially visible on the page. + - **Lazy Load Modules:** Lazy load modules that are not immediately required. + - **Intersection Observer:** Use the Intersection Observer API to detect when elements are visible in the viewport. + +### 4. Security Best Practices + +- **Common Vulnerabilities and How to Prevent Them:** + - **SQL Injection:** Prevent SQL injection by using parameterized queries or object-relational mappers (ORMs). + - **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user inputs and encoding outputs. + - **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using anti-CSRF tokens. + - **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data. +- **Input Validation:** + - **Validate All Inputs:** Validate all user inputs on both the client-side and server-side. + - **Use Regular Expressions:** Use regular expressions to validate input formats. + - **Sanitize Inputs:** Sanitize inputs to remove potentially malicious characters. +- **Authentication and Authorization Patterns:** + - **Identity-Aware Proxy (IAP):** Use IAP to control access to applications running on Compute Engine, GKE, and App Engine. + - **Firebase Authentication:** Use Firebase Authentication to easily implement authentication in web and mobile applications. + - **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. + - **Service Accounts:** Use service accounts to authenticate applications running on GCP. +- **Data Protection Strategies:** + - **Encryption at Rest:** Encrypt data at rest using Cloud KMS or Cloud Storage encryption. + - **Encryption in Transit:** Encrypt data in transit using HTTPS (TLS). + - **Data Loss Prevention (DLP):** Use Cloud DLP to prevent sensitive data from being leaked. +- **Secure API Communication:** + - **HTTPS:** Always use HTTPS for API communication. + - **API Keys:** Use API keys to authenticate API clients. + - **JWTs:** Use JWTs for secure API authorization. + - **Rate Limiting:** Implement rate limiting to prevent abuse. + +### 5. Testing Approaches + +- **Unit Testing Strategies:** + - **Test Individual Units:** Test individual units of code (e.g., functions, classes) in isolation. + - **Use Mocking:** Use mocking to isolate units of code from dependencies. + - **Test Edge Cases:** Test edge cases and boundary conditions. +- **Integration Testing:** + - **Test Interactions:** Test the interactions between different units of code or components. + - **Test Database Interactions:** Test interactions with databases and other external systems. + - **Use Test Databases:** Use test databases to avoid affecting production data. +- **End-to-End Testing:** + - **Test Complete Workflows:** Test complete workflows from start to finish. + - **Simulate User Interactions:** Simulate user interactions to ensure the application behaves as expected. + - **Use Automated Testing Tools:** Use automated testing tools to automate end-to-end tests. +- **Test Organization:** + - **Organize Tests by Component:** Organize tests by component or module. + - **Use a Consistent Naming Convention:** Use a consistent naming convention for test files and test cases. + - **Keep Tests Separate from Code:** Keep tests separate from production code. +- **Mocking and Stubbing:** + - **Use Mocking Libraries:** Use mocking libraries to create mock objects and stubs. + - **Mock External Dependencies:** Mock external dependencies like APIs and databases. + - **Stub Responses:** Stub responses from external services to control test behavior. + +### 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes Developers Make:** + - **Incorrect IAM Permissions:** Assigning overly broad IAM permissions. + - **Misconfiguring Network Settings:** Misconfiguring firewall rules or VPC settings. + - **Ignoring Cost Optimization:** Failing to optimize resource usage and costs. + - **Not Using Managed Services:** Trying to manage infrastructure manually instead of using GCP managed services. + - **Lack of Automation:** Not automating deployments and infrastructure management. +- **Edge Cases to be Aware of:** + - **Network Latency:** Account for network latency in distributed systems. + - **Concurrency Issues:** Handle concurrency issues correctly in multi-threaded applications. + - **Data Consistency:** Ensure data consistency across distributed systems. +- **Version-Specific Issues:** + - **API Compatibility:** Be aware of API compatibility issues when upgrading GCP SDKs or services. + - **Deprecated Features:** Avoid using deprecated features. +- **Compatibility Concerns:** + - **Cross-Browser Compatibility:** Ensure web applications are compatible with different browsers. + - **Mobile Compatibility:** Ensure web applications are responsive and compatible with mobile devices. +- **Debugging Strategies:** + - **Use Cloud Debugger:** Use Cloud Debugger to debug applications running on GCP. + - **Use Logging:** Use Cloud Logging to log debug information. + - **Use Monitoring:** Use Cloud Monitoring to monitor application performance and identify issues. + - **Local Debugging:** Debug applications locally before deploying them to GCP. + +### 7. Tooling and Environment + +- **Recommended Development Tools:** + - **Google Cloud SDK (gcloud):** Command-line tool for interacting with GCP services. + - **Terraform:** Infrastructure as code tool for managing GCP resources. + - **IDE with GCP Support:** Use an IDE with GCP support (e.g., VS Code with the Google Cloud Code extension). + - **Docker:** Containerization platform for building and deploying applications. +- **Build Configuration:** + - **Use Build Automation Tools:** Use build automation tools like Maven, Gradle, or npm. + - **Define Build Steps:** Define clear build steps for compiling, testing, and packaging applications. + - **Manage Dependencies:** Manage dependencies using dependency management tools like Maven, Gradle, or npm. +- **Linting and Formatting:** + - **Use Linters:** Use linters to enforce code style and identify potential issues. + - **Use Formatters:** Use formatters to automatically format code. + - **Configure Linters and Formatters:** Configure linters and formatters to match project coding standards. +- **Deployment Best Practices:** + - **Automate Deployments:** Automate deployments using CI/CD pipelines. + - **Use Infrastructure as Code:** Use infrastructure as code (e.g., Terraform) to manage infrastructure. + - **Blue/Green Deployments:** Use blue/green deployments to minimize downtime. + - **Canary Deployments:** Use canary deployments to gradually roll out new features. + - **Rollback Strategy:** Have a rollback strategy in place to revert to a previous version if necessary. +- **CI/CD Integration:** + - **Use Cloud Build:** Use Cloud Build for CI/CD pipelines on GCP. + - **Integrate with Version Control:** Integrate CI/CD pipelines with version control systems (e.g., GitHub, GitLab, Cloud Source Repositories). + - **Automate Testing:** Automate testing as part of the CI/CD pipeline. + - **Automate Deployments:** Automate deployments as part of the CI/CD pipeline. + +By following these best practices, developers can build robust, secure, and scalable applications and infrastructure on Google Cloud Platform. \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/serverless/aws-lambda.mdc b/rules-mdc/cloud_platforms/serverless/aws-lambda.mdc new file mode 100644 index 0000000..9f3c2ed --- /dev/null +++ b/rules-mdc/cloud_platforms/serverless/aws-lambda.mdc @@ -0,0 +1,220 @@ +--- +description: Comprehensive guide for AWS Lambda development, covering best practices for code organization, performance, security, testing, and common pitfalls. Focuses on building robust, scalable, and secure serverless applications using AWS Lambda. +globs: **/*.{js,ts,jsx,tsx,py,java,go,c#,cs,ps1,sh} +--- +- **Use Documented APIs Only:** Rely solely on AWS Lambda's documented APIs to ensure compatibility and avoid unexpected behavior. Do not use undocumented or internal APIs. + +- **Single Responsibility Principle:** Design Lambda functions to perform a single, well-defined task. This promotes modularity, testability, and maintainability. + +- **Native AWS Integrations:** Prefer native AWS integrations (e.g., SQS, SNS, Kinesis) for passing data between services instead of custom code, which enhances scalability and reduces complexity. + +- **Local Dependencies:** Store and reference dependencies locally within the Lambda function package to minimize latency and improve cold start times. + +- **Limit Variable Re-initialization:** Initialize variables outside the function handler to leverage execution context reuse and reduce initialization overhead. + +- **Thorough Testing:** Implement a comprehensive testing strategy including unit, integration, and end-to-end tests to ensure function correctness and reliability. + +## 1. Code Organization and Structure: + + - **Directory Structure:** + - Organize code into logical directories based on functionality (e.g., `src`, `tests`, `utils`). + - Separate handler logic from core business logic. + - Example: + + my-lambda-function/ + ├── src/ + │ ├── handler.js # Lambda handler function + │ ├── business-logic.js # Core business logic + │ └── utils.js # Utility functions + ├── tests/ + │ ├── handler.test.js # Unit tests for handler.js + │ └── ... + ├── package.json # Dependencies and scripts + └── ... + + + - **File Naming Conventions:** + - Use descriptive and consistent file names. + - Follow a naming convention (e.g., `kebab-case`, `PascalCase`) consistently. + - Example: `user-service.js`, `UserService.java`. + + - **Module Organization:** + - Break down large functions into smaller, reusable modules. + - Use appropriate module systems (e.g., ES modules in JavaScript, packages in Python, modules in Go). + - Example (JavaScript): + javascript + // src/user-service.js + export function createUser(userData) { ... } + export function getUser(userId) { ... } + + + - **Component Architecture:** + - Design Lambda functions as part of a larger component-based architecture. + - Decouple functions from specific triggers (e.g., API Gateway, SQS) to increase reusability. + - Implement interfaces or contracts to define interactions between components. + + - **Code Splitting Strategies:** + - Use code splitting techniques to reduce Lambda function package size. + - Implement dynamic imports or lazy loading for infrequently used modules (where supported by the runtime). + - Leverage layers for shared dependencies across multiple functions. + +## 2. Common Patterns and Anti-patterns: + + - **Design Patterns:** + - **Event-Driven Architecture:** Design functions to respond to events from various AWS services. + - **Command Pattern:** Encapsulate requests as objects to decouple request processing from the handler. + - **Dependency Injection:** Inject dependencies into functions to improve testability and maintainability. + + - **Recommended Approaches:** + - **Configuration Management:** Use environment variables or AWS Systems Manager Parameter Store for configuration data. + - **Logging:** Implement structured logging with timestamps, request IDs, and relevant context. + - **Idempotency:** Ensure functions are idempotent to handle potential retry scenarios gracefully. + + - **Anti-patterns:** + - **Monolithic Functions:** Avoid creating large, complex functions that perform multiple unrelated tasks. + - **Hardcoding Secrets:** Never hardcode sensitive information (e.g., API keys, passwords) in code. Use AWS Secrets Manager or environment variables. + - **Excessive Dependencies:** Minimize the number of dependencies to reduce package size and improve cold start times. + + - **State Management:** + - Use external services (e.g., DynamoDB, Redis) for persistent state management. + - Leverage Lambda layers for caching frequently accessed data. + - Design functions to be stateless whenever possible. + + - **Error Handling:** + - Implement robust error handling mechanisms, including try-catch blocks and error logging. + - Use custom exceptions for specific error scenarios. + - Return meaningful error messages to the caller. + - Implement dead-letter queues (DLQs) for asynchronous invocations to handle failed events. + +## 3. Performance Considerations: + + - **Optimization Techniques:** + - **Minimize Package Size:** Reduce the size of the deployment package by removing unnecessary files and dependencies. + - **Optimize Dependencies:** Use lightweight dependencies and avoid importing entire libraries when only specific functions are needed. + - **Code Optimization:** Profile and optimize code for performance bottlenecks. + - **Connection Reuse:** Reuse database connections, HTTP clients, and other resources to minimize overhead. + + - **Memory Management:** + - Allocate sufficient memory to Lambda functions based on their needs. + - Monitor memory usage and adjust the memory allocation accordingly. + - Clean up resources (e.g., closing file streams, releasing memory) to avoid memory leaks. + + - **Cold Starts:** + - Minimize cold start times by reducing package size, optimizing dependencies, and using provisioned concurrency. + - Use initilization logic outside the handler to take advantage of container reuse + + - **Bundle Size Optimization:** + - Use tools like Webpack or esbuild to bundle and optimize code for production. + - Minify code and remove unused code (dead code elimination). + + - **Lazy Loading Strategies:** + - Implement lazy loading or dynamic imports for infrequently used modules to reduce initial load time. + +## 4. Security Best Practices: + + - **Common Vulnerabilities:** + - **Injection Attacks:** Prevent SQL injection, command injection, and other injection attacks by validating and sanitizing input. + - **Cross-Site Scripting (XSS):** Protect against XSS vulnerabilities by encoding output properly. + - **Insecure Deserialization:** Avoid deserializing untrusted data to prevent arbitrary code execution. + - **Broken Authentication:** Implement strong authentication and authorization mechanisms. + + - **Input Validation:** + - Validate all input data to prevent malicious or invalid data from being processed. + - Use schema validation libraries to enforce data types and formats. + - Sanitize input data to remove potentially harmful characters or code. + + - **Authentication and Authorization:** + - Use AWS Identity and Access Management (IAM) roles to grant Lambda functions the necessary permissions. + - Implement authentication and authorization mechanisms to protect sensitive resources. + - Use AWS Cognito for user authentication and authorization. + + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use AWS Key Management Service (KMS) to manage encryption keys. + - Mask or redact sensitive data in logs. + + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Implement API authentication and authorization using API keys, JWT tokens, or other secure mechanisms. + - Protect against common web application attacks (e.g., CSRF, DDoS). + +## 5. Testing Approaches: + + - **Unit Testing:** + - Write unit tests to verify the correctness of individual functions or modules. + - Use mocking or stubbing to isolate units of code from external dependencies. + - Use testing frameworks (e.g., Jest, Mocha, pytest) to automate unit testing. + + - **Integration Testing:** + - Write integration tests to verify the interactions between different components or services. + - Test the integration of Lambda functions with other AWS services (e.g., SQS, DynamoDB). + - Use tools like AWS SAM Local to run integration tests locally. + + - **End-to-End Testing:** + - Write end-to-end tests to verify the entire application flow from end to end. + - Simulate user interactions to test the application's functionality. + - Use tools like Selenium or Cypress to automate end-to-end testing. + + - **Test Organization:** + - Organize tests into separate directories based on the type of test (e.g., unit, integration, e2e). + - Use descriptive test names to clearly identify the purpose of each test. + - Follow a consistent testing strategy across all projects. + + - **Mocking and Stubbing:** + - Use mocking or stubbing to replace external dependencies with controlled test doubles. + - Mock AWS SDK calls to isolate Lambda functions from AWS services. + - Use mocking frameworks (e.g., Jest, Sinon.js) to simplify mocking and stubbing. + +## 6. Common Pitfalls and Gotchas: + + - **Frequent Mistakes:** + - **Incorrect IAM Permissions:** Ensure that Lambda functions have the necessary IAM permissions to access required AWS resources. + - **Timeout Errors:** Increase the Lambda function timeout if it takes longer than expected to complete. + - **Memory Exhaustion:** Allocate sufficient memory to Lambda functions to avoid memory exhaustion errors. + - **Unclosed Connections:** Close database connections, HTTP clients, and other resources properly to avoid resource leaks. + + - **Edge Cases:** + - **Concurrent Invocations:** Handle concurrent invocations gracefully to avoid race conditions or data corruption. + - **Throttling:** Implement retry mechanisms to handle throttling errors from AWS services. + - **Error Retries:** Design functions to be idempotent to handle potential retry scenarios gracefully. + + - **Version-Specific Issues:** + - Be aware of version-specific issues or compatibility concerns when upgrading Lambda function runtimes or dependencies. + - Test Lambda functions thoroughly after upgrading to ensure they still function correctly. + + - **Compatibility Concerns:** + - Ensure that Lambda functions are compatible with the supported runtime environment. + - Use compatible versions of dependencies to avoid compatibility issues. + + - **Debugging Strategies:** + - Use CloudWatch Logs to debug Lambda function execution. + - Use AWS X-Ray to trace and analyze Lambda function performance. + - Use local debugging tools (e.g., AWS SAM Local) to debug Lambda functions locally. + +## 7. Tooling and Environment: + + - **Recommended Tools:** + - **AWS SAM:** Use AWS SAM (Serverless Application Model) to define and deploy Lambda functions and other serverless resources. + - **AWS CLI:** Use the AWS CLI (Command Line Interface) to manage AWS resources from the command line. + - **Terraform/CloudFormation:** Use Infrastructure as Code (IaC) tools like Terraform or CloudFormation to provision and manage AWS infrastructure. + - **IDE:** Use an IDE with support for Lambda development (e.g., VS Code with the AWS Toolkit extension). + + - **Build Configuration:** + - Use build tools (e.g., npm, yarn, Maven, Gradle) to manage dependencies and build Lambda function packages. + - Configure build scripts to automate common tasks (e.g., linting, testing, bundling). + + - **Linting and Formatting:** + - Use linters (e.g., ESLint, Pylint) to enforce coding standards and identify potential code quality issues. + - Use formatters (e.g., Prettier, Black) to automatically format code consistently. + + - **Deployment:** + - Use AWS SAM CLI or other deployment tools to deploy Lambda functions to AWS. + - Implement blue/green deployments or canary deployments to minimize downtime during deployments. + - Automate deployments using CI/CD pipelines. + + - **CI/CD Integration:** + - Integrate Lambda function deployments with CI/CD pipelines to automate testing and deployment. + - Use CI/CD tools (e.g., Jenkins, CircleCI, GitHub Actions) to build, test, and deploy Lambda functions. + +@file aws-lambda-security.mdc +@file aws-lambda-performance.mdc \ No newline at end of file diff --git a/rules-mdc/cloud_platforms/serverless/modal.mdc b/rules-mdc/cloud_platforms/serverless/modal.mdc new file mode 100644 index 0000000..b0b821d --- /dev/null +++ b/rules-mdc/cloud_platforms/serverless/modal.mdc @@ -0,0 +1,210 @@ +--- +description: This rule outlines best practices for developing and maintaining modal libraries, covering aspects from code organization and performance to security and testing. It aims to guide developers in creating robust, efficient, and user-friendly modal components. +globs: **/*.{js,jsx,ts,tsx,mjs,cjs} +--- +- **Library Information:** + - Name: modal + - Category: cloud_platforms + - Subcategory: serverless + +- **General Principles:** + - **Clarity and Purpose:** Modals should have a clear and concise purpose, conveyed through a descriptive title. Content should be helpful and action-oriented. + - **User Control:** Prioritize user control by using modals sparingly and providing visible, intuitive close options (e.g., close button, overlay click). + - **Accessibility:** Ensure modals are accessible to all users by testing with assistive technologies and adhering to accessibility standards (e.g., ARIA attributes). + +- **Code Organization and Structure:** + - **Directory Structure:** + - `src/`: Contains the source code of the modal library. + - `components/`: Reusable modal components (e.g., `Modal.jsx`, `ModalHeader.jsx`, `ModalBody.jsx`, `ModalFooter.jsx`). + - `hooks/`: Custom hooks for managing modal state and logic (e.g., `useModal.js`). + - `utils/`: Utility functions (e.g., validation, formatting). + - `styles/`: CSS or styling components. + - `types/`: TypeScript type definitions. + - `examples/`: Example usage of the modal library. + - `tests/`: Unit and integration tests. + - `docs/`: Documentation for the library. + - **File Naming Conventions:** + - Use descriptive names for components (e.g., `ConfirmationModal.jsx`, `InputModal.jsx`). + - Follow a consistent naming convention (e.g., PascalCase for components, camelCase for variables and functions). + - **Module Organization:** + - Organize code into logical modules and submodules. Each module should have a specific responsibility. + - Use ES modules (import/export) for modularity and tree-shaking. + - **Component Architecture:** + - Favor a component-based architecture. Each modal element (header, body, footer) should be a reusable component. + - Use composition to create complex modals from smaller, reusable components. + - **Code Splitting Strategies:** + - Consider code splitting for large modal libraries to improve initial load time. + - Lazy load modal content or components that are not immediately needed. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Controlled Components:** Use controlled components for modal content to manage state effectively. + - **Render Props or Hooks:** Provide flexibility in rendering modal content using render props or custom hooks. + - **Provider Pattern:** Use a context provider to manage global modal state and configuration. + - **Recommended Approaches:** + - Use a state management library (e.g., Zustand, Jotai) for complex modal state. + - Implement a modal queue to manage multiple modals efficiently. + - Provide a consistent API for opening and closing modals. + - **Anti-patterns:** + - **Overusing Modals:** Avoid using modals for non-critical information or actions. + - **Deeply Nested Components:** Minimize deeply nested components within modals to improve performance. + - **Ignoring Accessibility:** Neglecting accessibility can make the modal unusable for some users. + - **State Management Best Practices:** + - Choose a state management solution that fits the complexity of the modal library. + - Keep state minimal and derive values when possible. + - Use immutable data structures to prevent unexpected side effects. + - **Error Handling Patterns:** + - Implement error boundaries to catch errors within modals. + - Provide informative error messages to the user. + - Log errors for debugging purposes. + +- **Performance Considerations:** + - **Optimization Techniques:** + - Memoize components to prevent unnecessary re-renders. + - Use virtualization for long lists of modal content. + - Debounce or throttle event handlers to improve responsiveness. + - **Memory Management:** + - Clean up event listeners and timers when the modal is closed. + - Avoid creating large data structures within modals. + - Release resources when the modal is unmounted. + - **Rendering Optimization:** + - Use CSS transforms for animations instead of modifying layout properties. + - Minimize the number of DOM updates. + - Use techniques like `requestAnimationFrame` for smoother animations. + - **Bundle Size Optimization:** + - Use tree-shaking to remove unused code from the bundle. + - Minify and compress the code. + - Use code splitting to reduce the initial bundle size. + - **Lazy Loading Strategies:** + - Lazy load modal content or components that are not immediately visible. + - Use dynamic imports to load modules on demand. + +- **Security Best Practices:** + - **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks. + - **Injection Attacks:** Protect against injection attacks by validating user inputs. + - **Input Validation:** + - Validate all user inputs within the modal. + - Use appropriate data types and formats. + - Sanitize inputs to remove malicious code. + - **Authentication and Authorization Patterns:** + - Implement authentication and authorization mechanisms to protect sensitive data. + - Use secure cookies or tokens to store user credentials. + - Enforce access control policies. + - **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use secure storage mechanisms to protect data. + - Implement data loss prevention measures. + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Validate API responses. + - Protect API keys and secrets. + +- **Testing Approaches:** + - **Unit Testing Strategies:** + - Test individual components and functions in isolation. + - Use mocking and stubbing to isolate dependencies. + - Test edge cases and error conditions. + - **Integration Testing:** + - Test the interaction between components and modules. + - Verify that the modal works correctly with other parts of the application. + - **End-to-End Testing:** + - Test the entire modal workflow from start to finish. + - Use automated testing tools to simulate user interactions. + - **Test Organization:** + - Organize tests into logical groups based on functionality. + - Use descriptive test names. + - Keep tests concise and focused. + - **Mocking and Stubbing:** + - Use mocking to simulate external dependencies. + - Use stubbing to replace complex functions with simpler versions. + - Avoid over-mocking, as it can lead to brittle tests. + +- **Common Pitfalls and Gotchas:** + - **Frequent Mistakes:** + - Forgetting to handle focus management when opening/closing modal + - Not properly managing the stacking context of modals. + - Ignoring keyboard navigation. + - **Edge Cases:** + - Handling modals within modals. + - Supporting different screen sizes and orientations. + - Handling modals in server-side rendered applications. + - **Version-Specific Issues:** + - Be aware of compatibility issues with different versions of dependencies. + - Test the modal library with different browsers and devices. + - **Compatibility Concerns:** + - Ensure the modal library is compatible with different JavaScript frameworks and libraries. + - Test with different browsers and devices. + - **Debugging Strategies:** + - Use browser developer tools to inspect the modal's HTML and CSS. + - Use logging to track the flow of execution. + - Use a debugger to step through the code. + +- **Tooling and Environment:** + - **Recommended Development Tools:** + - VS Code with extensions for React/TypeScript/ESLint. + - Chrome DevTools for debugging. + - **Build Configuration:** + - Use a build tool like webpack, Parcel, or Rollup. + - Configure the build tool to optimize the bundle size. + - **Linting and Formatting:** + - Use ESLint to enforce code style and detect potential errors. + - Use Prettier to automatically format the code. + - **Deployment Best Practices:** + - Deploy the modal library to a CDN for fast and reliable delivery. + - Use version control to track changes to the code. + - Automate the deployment process. + - **CI/CD Integration:** + - Integrate the modal library with a CI/CD pipeline for automated testing and deployment. + - Use a CI/CD tool like Jenkins, Travis CI, or CircleCI. + +- **Accessibility Considerations (WCAG Compliance):** + - **Keyboard Navigation:** Ensure all interactive elements within the modal are reachable and operable using the keyboard. Use tab index appropriately. + - **Focus Management:** Trap focus within the modal when it's open. Return focus to the previously focused element when the modal is closed. Prevent focus leaking to elements behind the modal. + - **ARIA Attributes:** + - Use `role="dialog"` or `role="alertdialog"` to indicate the modal's purpose. + - Use `aria-labelledby` to associate the modal's title with the modal element. + - Use `aria-describedby` to associate the modal's content with the modal element. + - Implement `aria-modal="true"` to signify the modal is blocking interaction with the rest of the page. + - **Color Contrast:** Ensure sufficient color contrast between text and background elements. + - **Screen Reader Compatibility:** Test the modal with screen readers to ensure content is read correctly and controls are accessible. + - **Visual Cues:** Provide clear visual cues to indicate the active element. + - **Alternative Text:** Ensure images have descriptive alternative text. + +- **UI/UX Best Practices:** + - **Modal Size and Positioning:** Ensure the modal is appropriately sized and positioned on the screen. Avoid modals that are too large or obstruct important content. + - **Animation and Transitions:** Use subtle animations and transitions to enhance the user experience. Avoid excessive or distracting animations. + - **Responsiveness:** Ensure the modal is responsive and adapts to different screen sizes and orientations. + - **Dark Overlay:** Use a dark overlay to dim the background and focus the user's attention on the modal. The overlay should be semi-transparent. + - **Clear Calls to Action:** Use clear and concise button labels for calls to action. Avoid ambiguous or confusing labels. + +- **Example Snippets (Illustrative):** + - **React Component:** + jsx + import React, { useState } from 'react'; + + const Modal = ({ isOpen, onClose, children }) => { + if (!isOpen) return null; + + return ( + + + {children} + + + + ); + }; + + export default Modal; + + - **TypeScript Type Definitions:** + typescript + interface ModalProps { + isOpen: boolean; + onClose: () => void; + children: React.ReactNode; + } + + +By adhering to these best practices, you can create robust, accessible, and user-friendly modal libraries that enhance the overall user experience of your applications. \ No newline at end of file diff --git a/rules-mdc/cross_platform/desktop/electron.mdc b/rules-mdc/cross_platform/desktop/electron.mdc new file mode 100644 index 0000000..d20637f --- /dev/null +++ b/rules-mdc/cross_platform/desktop/electron.mdc @@ -0,0 +1,150 @@ +--- +description: Enforces best practices, coding standards, and performance considerations for Electron development. Covers code structure, security, testing, and common pitfalls to ensure robust and maintainable applications. +globs: **/*.{js,jsx,ts,tsx,html,css,scss,mjs,cjs} +--- +- **General Practices** + - Adhere to the official Electron coding style guide. Run `npm run lint` to detect style issues using `cpplint` and `eslint`. + - Aim for line lengths between 80 and 100 characters for readability. + - Use `sh` instead of `cmd` in code blocks for cross-platform compatibility in documentation. + - Select the appropriate Electron version based on project needs and compatibility with dependencies. + - Always update electron to the latest stable version to receive security fixes and performance improvements. + +- **Code Organization and Structure** + - **Directory Structure:** + - Structure your project logically. Consider using a structure like: + + electron-app/ + ├── main.js # Main process entry point + ├── preload.js # Preload script (for specific renderers if needed) + ├── renderer/ + │ ├── index.html # Main HTML file + │ ├── script.js # Renderer process scripts + │ ├── style.css # Stylesheets + │ └── components/ # Reusable components (if applicable) + ├── assets/ # Static assets (images, fonts, etc.) + ├── package.json + └── electron-builder.yml # Electron Builder configuration + + - Organize your code into modules based on functionality (e.g., authentication, data handling, UI components). + - **File Naming Conventions:** + - Use descriptive and consistent naming conventions. + - JavaScript/TypeScript files: `camelCase` for variables and functions, `PascalCase` for classes and components. + - CSS/SCSS files: `kebab-case`. + - **Module Organization:** + - Split your application logic into separate modules for better maintainability and reusability. + - Use ES modules (`import`/`export`) or CommonJS (`require`/`module.exports`) for modularization. Be consistent throughout the project. + - **Component Architecture:** + - Design reusable UI components for the renderer process. + - Use a component-based framework (e.g., React, Vue, Angular) to manage UI complexity. + - **Code Splitting:** + - Implement code splitting to reduce the initial load time of your application. + - Use dynamic imports (`import()`) to load modules on demand. + - Consider using webpack or Parcel for bundling and code splitting. + +- **Common Patterns and Anti-patterns** + - **Design Patterns:** + - **Model-View-Controller (MVC):** Organize application logic into models, views, and controllers to separate concerns. + - **Observer Pattern:** Implement a publish-subscribe mechanism for communication between different parts of the application. + - **Singleton Pattern:** Use singletons sparingly. If used, implement carefully to avoid unexpected side effects. + - **Recommended Approaches:** + - **Inter-Process Communication (IPC):** Use `ipcRenderer` and `ipcMain` for communication between the main and renderer processes. Sanitize all data passed via IPC. + - **Native Modules:** Consider using native modules for performance-critical tasks or access to platform-specific APIs. + - **Remote Module:** Avoid using the remote module, as it can introduce security vulnerabilities and performance issues. Use IPC instead. + - **Anti-patterns:** + - **Tight Coupling:** Avoid tightly coupling components or modules to make the code more flexible and testable. + - **Global State:** Minimize the use of global state. Use state management libraries or techniques to manage application state effectively. + - **Long-Running Tasks in the Renderer Process:** Move long-running tasks to the main process or use worker threads to prevent blocking the UI. + - **State Management:** + - For simple applications, use basic state management techniques (e.g., component state, context API). + - For complex applications, consider using state management libraries like Redux, Zustand, or Vuex. + - **Error Handling:** + - Implement robust error handling mechanisms throughout your application. + - Use try-catch blocks to handle exceptions and prevent crashes. + - Log errors to a file or remote logging service for debugging. + +- **Performance Considerations** + - **Optimization Techniques:** + - **Reduce Load on the Renderer Process:** Minimize the amount of work performed in the renderer process. Offload heavy tasks to the main process or worker threads. + - **Hardware Acceleration:** Enable hardware acceleration to improve rendering performance. + - **Minimize DOM Manipulations:** Reduce the number of DOM manipulations to improve UI responsiveness. + - **Memory Management:** + - **Garbage Collection:** Be mindful of memory leaks and optimize code to reduce memory consumption. + - **Object Pools:** Use object pools to reuse objects and avoid unnecessary memory allocation. + - **Rendering Optimization:** + - **Virtual DOM:** Use a virtual DOM library (e.g., React, Vue) to optimize rendering performance. + - **CSS Sprites:** Use CSS sprites to reduce the number of HTTP requests for images. + - **Bundle Size Optimization:** + - **Code Minification:** Minify JavaScript and CSS code to reduce bundle size. + - **Tree Shaking:** Use tree shaking to remove unused code from the bundle. + - **Lazy Loading:** + - **Lazy Load Images:** Lazy load images to improve initial page load time. + - **Lazy Load Modules:** Lazy load modules on demand to reduce initial bundle size. + +- **Security Best Practices** + - **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and escaping output. + - **Remote Code Execution (RCE):** Avoid RCE vulnerabilities by validating input and preventing the execution of arbitrary code. + - **Insecure Deserialization:** Prevent insecure deserialization vulnerabilities by validating serialized data. + - **Input Validation:** + - Validate all user input to prevent malicious data from being processed. + - Use appropriate data types and formats to prevent type confusion attacks. + - **Authentication and Authorization:** + - Implement secure authentication and authorization mechanisms to protect sensitive data and resources. + - Use strong passwords and multi-factor authentication. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use secure storage mechanisms to protect sensitive data. + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Validate API responses to prevent data injection attacks. + - **Enable Context Isolation:** Enable context isolation for the renderer process to prevent access to the main process's JavaScript context. + - **Disable Node.js Integration:** Disable Node.js integration in the renderer process unless strictly necessary. If needed, only expose a limited API using contextBridge. + - **Handle `new-window` events:** Validate and sanitize all URLs before allowing a new window to be opened from a renderer process. + +- **Testing Approaches** + - **Unit Testing:** + - Write unit tests to verify the functionality of individual components or modules. + - Use a testing framework like Jest or Mocha. + - **Integration Testing:** + - Write integration tests to verify the interaction between different components or modules. + - Use a testing framework like Cypress or Puppeteer. + - **End-to-End Testing:** + - Write end-to-end tests to verify the overall functionality of the application. + - Use a testing framework like Cypress or Puppeteer. + - **Test Organization:** + - Organize tests into separate files or directories based on functionality. + - Use descriptive test names to clearly identify the purpose of each test. + - **Mocking and Stubbing:** + - Use mocking and stubbing to isolate components or modules during testing. + - Use a mocking library like Jest or Sinon. + +- **Common Pitfalls and Gotchas** + - **Frequent Mistakes:** + - **Not Sanitizing User Input:** Failing to sanitize user input can lead to XSS vulnerabilities. + - **Using the Remote Module:** The `remote` module provides direct access to main process functionality from the renderer, but bypassing IPC exposes security risks. Use `contextBridge` and IPC. + - **Blocking the Main Process:** Performing long-running tasks in the main process can block the UI and make the application unresponsive. + - **Edge Cases:** + - **Handling Different Screen Resolutions:** Test your application on different screen resolutions to ensure proper UI rendering. + - **Handling Different Operating Systems:** Test your application on different operating systems (Windows, macOS, Linux) to ensure compatibility. + - **Version-Specific Issues:** + - Be aware of version-specific issues and compatibility concerns when upgrading Electron or its dependencies. + - **Debugging Strategies:** + - Use the Chrome DevTools to debug the renderer process. + - Use the Electron DevTools to debug the main process. + +- **Tooling and Environment** + - **Recommended Development Tools:** + - **Visual Studio Code:** A popular code editor with excellent support for Electron development. + - **Electron Forge or Electron Builder:** Tools for packaging and distributing Electron applications. + - **Chrome DevTools:** A powerful debugging tool for the renderer process. + - **Build Configuration:** + - Use a build system like webpack or Parcel to bundle your application code. + - Configure the build system to optimize code for production. + - **Linting and Formatting:** + - Use a linter like ESLint to enforce code style and prevent errors. + - Use a formatter like Prettier to automatically format code. + - **Deployment Best Practices:** + - Sign your application code to prevent tampering. + - Distribute your application through a secure channel. + - **CI/CD Integration:** + - Integrate your application with a CI/CD system to automate the build, test, and deployment process. \ No newline at end of file diff --git a/rules-mdc/cross_platform/desktop/tauri.mdc b/rules-mdc/cross_platform/desktop/tauri.mdc new file mode 100644 index 0000000..c75423b --- /dev/null +++ b/rules-mdc/cross_platform/desktop/tauri.mdc @@ -0,0 +1,296 @@ +--- +description: This rule provides comprehensive guidelines for developing robust, secure, and performant Tauri applications. It covers code organization, security best practices, performance optimization, testing strategies, and common pitfalls to avoid. +globs: **/*.(rs|js|ts|html|css|json|toml|md) +--- +# Tauri Best Practices and Coding Standards + +This document outlines best practices and coding standards for developing Tauri applications. Following these guidelines will help you create maintainable, secure, and performant applications. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +Adopt a clear and consistent directory structure to improve maintainability and collaboration. + + +my-tauri-app/ +├── .cargo/ # Cargo configuration +├── .git/ # Git repository +├── .gitignore # Git ignore file +├── .rustfmt.toml # Rust code formatting configuration +├── src-tauri/ # Rust backend source code +│ ├── src/ # Rust source files +│ │ ├── main.rs # Main application entry point +│ │ ├── commands.rs # Custom commands +│ │ ├── models.rs # Data models +│ │ ├── utils.rs # Utility functions +│ │ └── state.rs # Application State management +│ ├── Cargo.toml # Rust project configuration +│ ├── tauri.conf.json # Tauri application configuration +│ └── icons/ # Application icons +├── src/ # Web frontend source code +│ ├── components/ # Reusable UI components +│ │ ├── MyComponent.jsx # Example React component +│ │ └── ... +│ ├── pages/ # Application pages/routes +│ │ ├── Home.jsx # Home page component +│ │ └── ... +│ ├── App.jsx # Main application component +│ ├── index.css # Global styles +│ ├── index.js # Entry point for web app +│ ├── assets/ # Static assets (images, fonts, etc.) +│ │ ├── logo.png # Application logo +│ │ └── ... +│ └── utils/ # Frontend utility functions +├── static/ # Static resources (images, fonts, etc.) served directly +├── README.md # Project documentation +├── LICENSE # License file +└── package.json # Node.js project configuration + + +### 1.2 File Naming Conventions + +- **Rust files:** Use snake_case for file names (e.g., `my_module.rs`). +- **JavaScript/TypeScript files:** Use PascalCase for component files (e.g., `MyComponent.jsx`) and camelCase for other files (e.g., `utils.js`). +- **CSS files:** Use kebab-case (e.g., `main-styles.css`). +- **HTML files:** Use kebab-case (e.g., `index.html`). + +### 1.3 Module Organization + +- Group related functionality into modules. +- Use the `mod` keyword in Rust to define modules. +- Create separate files for each module. +- Use `pub` keyword to export items from modules. + +rust +// src-tauri/src/commands.rs + +pub mod my_command { + use tauri::{{command, State}}; + + #[command] + pub fn greet(name: String) -> String { + format!("Hello, {{}}! You've been greeted from Rust!", name) + } +} + + + +### 1.4 Component Architecture + +- Adopt a component-based architecture for the frontend (e.g., using React, Vue, or Svelte). +- Break down the UI into reusable components. +- Follow a consistent component structure (e.g., separate files for component logic, styles, and tests). + +### 1.5 Code Splitting Strategies + +- Implement code splitting to reduce the initial bundle size. +- Use dynamic imports for lazy-loading modules and components. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to Tauri + +- **Command Pattern:** Use Tauri commands to expose Rust functions to the frontend. This allows you to perform complex operations in Rust and communicate the results to the frontend. +- **State Management:** Use a state management solution (e.g., Redux, Zustand, or React Context) to manage application state and ensure data consistency between the frontend and backend. Also use Tauri's `State` to manage state on the Rust side. +- **Event System:** Use Tauri's event system for inter-process communication (IPC). The backend can emit events that the frontend listens for, enabling real-time updates and notifications. + +### 2.2 Recommended Approaches for Common Tasks + +- **File System Access:** Use the Tauri API for file system access instead of directly using Node.js APIs. This ensures that your application respects the Tauri security model. +- **External API Calls:** Perform external API calls in the Rust backend to protect API keys and sensitive data. +- **Data Persistence:** Use a database or local storage for persistent data storage. Consider using an ORM like Diesel or SQLx for database access in Rust. + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **Over-reliance on JavaScript:** Offload complex logic to the Rust backend whenever possible to leverage Rust's performance and security features. +- **Ignoring Security Policies:** Always configure and enforce strict Content Security Policies (CSPs) to prevent XSS attacks. +- **Exposing Sensitive Data:** Avoid exposing sensitive data (e.g., API keys, database credentials) in the frontend code. +- **Blocking the Main Thread:** Avoid long-running tasks on the main thread, both in Rust and JavaScript, to prevent the UI from freezing. + +### 2.4 State Management Best Practices + +- Choose a state management solution that fits your application's complexity. +- Use immutable data structures to prevent accidental state mutations. +- Centralize state management logic to improve maintainability. +- Use Tauri's State management features to manage complex application states on the Rust side. + +### 2.5 Error Handling Patterns + +- Use Rust's `Result` type for error handling in the backend. +- Provide informative error messages to the frontend. +- Implement global error handling to catch unhandled exceptions. +- Use appropriate logging to track errors and debug issues. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Profiling:** Use profiling tools (e.g., Chrome DevTools, Rust's `perf` tool) to identify performance bottlenecks. +- **Code Optimization:** Optimize Rust code for performance by using efficient algorithms, data structures, and memory management techniques. +- **Webview Optimization:** Optimize frontend code for webview performance by reducing DOM manipulations, minimizing JavaScript execution time, and optimizing CSS styles. + +### 3.2 Memory Management + +- Use Rust's ownership and borrowing system to prevent memory leaks and data races. +- Avoid unnecessary allocations and deallocations. +- Use smart pointers (e.g., `Box`, `Rc`, `Arc`) to manage memory ownership. + +### 3.3 Rendering Optimization + +- Use virtual DOM techniques to minimize DOM updates. +- Optimize CSS selectors to improve rendering performance. +- Use hardware acceleration for animations and transitions. + +### 3.4 Bundle Size Optimization + +- Use code splitting to reduce the initial bundle size. +- Remove unused code and dependencies. +- Optimize images and other assets. +- Use a bundler (e.g., Webpack, Parcel, or Rollup) to optimize the bundle. + +### 3.5 Lazy Loading Strategies + +- Use dynamic imports to lazy-load modules and components. +- Load images and other assets only when they are visible. +- Use a virtualized list to render large lists of data. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **Cross-Site Scripting (XSS):** Prevent XSS attacks by enforcing strict Content Security Policies (CSPs) and sanitizing user inputs. +- **Remote Code Execution (RCE):** Prevent RCE attacks by avoiding the use of `eval()` and other unsafe JavaScript functions. Isolate the webview context. +- **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or an ORM. +- **Path Traversal:** Prevent path traversal attacks by validating user-provided file paths and using the Tauri API for file system access. +- **Dependency Vulnerabilities:** Regularly update dependencies and use tools like `cargo audit` and `npm audit` to identify and fix vulnerabilities. + +### 4.2 Input Validation + +- Validate all user inputs on both the frontend and backend. +- Use appropriate data types and formats. +- Sanitize inputs to remove potentially malicious characters. +- Implement rate limiting to prevent brute-force attacks. + +### 4.3 Authentication and Authorization Patterns + +- Use a secure authentication protocol (e.g., OAuth 2.0, JWT). +- Store passwords securely using a strong hashing algorithm (e.g., bcrypt). +- Implement authorization checks to ensure that users only have access to the resources they are authorized to access. + +### 4.4 Data Protection Strategies + +- Encrypt sensitive data at rest and in transit. +- Use HTTPS for all network communication. +- Store API keys and other secrets securely using environment variables or a dedicated secrets management solution. +- Avoid storing sensitive data in the frontend code or in local storage. + +### 4.5 Secure API Communication + +- Use the Tauri command pattern for secure communication between the frontend and backend. +- Validate all data exchanged between the frontend and backend. +- Implement rate limiting to prevent abuse. +- Use a secure communication protocol (e.g., TLS) for external API calls. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- Write unit tests for all critical functions and modules. +- Use a testing framework (e.g., `cargo test` for Rust, Jest or Mocha for JavaScript) to automate unit testing. +- Aim for high code coverage. +- Test edge cases and error conditions. + +### 5.2 Integration Testing + +- Write integration tests to verify the interaction between different modules and components. +- Use a testing framework to automate integration testing. +- Test the integration between the frontend and backend. + +### 5.3 End-to-End Testing + +- Write end-to-end tests to verify the entire application flow. +- Use a testing framework (e.g., Cypress, Playwright) to automate end-to-end testing. +- Test the application in a realistic environment. + +### 5.4 Test Organization + +- Organize tests into separate directories for unit tests, integration tests, and end-to-end tests. +- Follow a consistent naming convention for test files and functions. +- Use test suites to group related tests. + +### 5.5 Mocking and Stubbing + +- Use mocking and stubbing to isolate units of code during testing. +- Use a mocking framework (e.g., Mockall for Rust, Jest or Sinon.js for JavaScript) to create mocks and stubs. +- Mock external dependencies and APIs. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Incorrectly Configuring CSP:** Not setting a restrictive enough content security policy. +- **Misunderstanding Tauri's Security Model:** Assuming Node.js APIs are safe to use directly in the frontend. +- **Ignoring Error Handling:** Not handling errors properly, leading to unexpected application behavior. +- **Overcomplicating the Frontend:** Trying to do too much in the frontend, instead of leveraging the Rust backend. + +### 6.2 Edge Cases to Be Aware Of + +- **File System Permissions:** Handling file system permissions correctly on different operating systems. +- **Webview Compatibility:** Ensuring compatibility with different webview versions. +- **Application Update Process:** Handling application updates gracefully and securely. + +### 6.3 Version-Specific Issues + +- Be aware of breaking changes in Tauri releases. +- Consult the Tauri changelog for information about version-specific issues. + +### 6.4 Compatibility Concerns + +- Test your application on different operating systems (Windows, macOS, Linux). +- Test your application on different architectures (x86, x64, ARM). + +### 6.5 Debugging Strategies + +- Use the Tauri developer console for debugging frontend code. +- Use Rust's debugging tools for debugging backend code. +- Use logging to track application behavior. +- Use a debugger to step through code and inspect variables. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **Rust:** Use the latest stable version of Rust. +- **Node.js:** Use a recent version of Node.js. +- **IDE:** Use a powerful IDE (e.g., Visual Studio Code, IntelliJ IDEA) with Rust and JavaScript/TypeScript support. +- **Debugger:** Use a debugger (e.g., GDB, LLDB) for debugging Rust code. +- **Web Inspector:** Use the web inspector (e.g., Chrome DevTools, Firefox Developer Tools) for debugging frontend code. + +### 7.2 Build Configuration + +- Use the `tauri.conf.json` file to configure the build process. +- Configure the application name, version, and other metadata. +- Configure the build target and output directory. +- Configure the security policies and permissions. + +### 7.3 Linting and Formatting + +- Use a linter (e.g., Clippy for Rust, ESLint for JavaScript) to enforce code style and identify potential issues. +- Use a code formatter (e.g., Rustfmt for Rust, Prettier for JavaScript) to automatically format your code. +- Configure your IDE to automatically run the linter and formatter on save. + +### 7.4 Deployment Best Practices + +- Sign your application for the target platform. +- Use a code signing certificate to verify the authenticity of your application. +- Package your application for distribution using the appropriate tools (e.g., NSIS for Windows, DMG for macOS, DEB/RPM for Linux). + +### 7.5 CI/CD Integration + +- Use a CI/CD system (e.g., GitHub Actions, GitLab CI, Jenkins) to automate the build, test, and deployment process. +- Configure your CI/CD system to run the linter, formatter, and tests. +- Configure your CI/CD system to automatically build and package your application for different platforms. +- Automate the deployment process to reduce manual effort and errors. + +By adhering to these best practices, you can develop Tauri applications that are secure, performant, and maintainable. Remember to stay updated with the latest Tauri documentation and community recommendations for continuous improvement. \ No newline at end of file diff --git a/rules-mdc/cross_platform/mobile/expo.mdc b/rules-mdc/cross_platform/mobile/expo.mdc new file mode 100644 index 0000000..ec4275c --- /dev/null +++ b/rules-mdc/cross_platform/mobile/expo.mdc @@ -0,0 +1,200 @@ +--- +description: This rule provides comprehensive best practices and coding standards for Expo projects, covering code organization, performance, security, testing, and common pitfalls to ensure maintainable and high-quality applications. +globs: **/*.{js,jsx,ts,tsx} +--- +- **Code Organization and Structure** + - **Directory Structure:** + - Adopt a feature-based directory structure, grouping related files (components, hooks, styles, tests) within feature folders. + - Examples: + + src/ + ├── components/ + │ ├── Button/ + │ │ ├── Button.tsx + │ │ ├── Button.styles.ts + │ │ └── Button.test.tsx + │ └── ... + ├── screens/ + │ ├── Home/ + │ │ ├── HomeScreen.tsx + │ │ ├── HomeScreen.styles.ts + │ │ └── HomeScreen.test.tsx + │ └── ... + ├── navigation/ + │ ├── AppNavigator.tsx + │ └── ... + ├── services/ + │ ├── api.ts + │ └── ... + ├── utils/ + │ ├── helpers.ts + │ └── ... + ├── App.tsx + └── index.tsx + + - **File Naming Conventions:** + - Use descriptive and consistent names for files and directories. + - Component files: `ComponentName.tsx` or `ComponentName.js` + - Style files: `ComponentName.styles.ts` or `ComponentName.styles.js` + - Hook files: `useHookName.ts` or `useHookName.js` + - Test files: `ComponentName.test.tsx` or `ComponentName.test.js` + - **Module Organization:** + - Group related components, hooks, and utilities into modules. + - Use `index.ts` (or `index.js`) files to export members from a module for easier importing. + - Example: + + // src/components/Button/index.ts + export { default as Button } from './Button'; + + - **Component Architecture:** + - Favor functional components with hooks for managing state and side effects. + - Separate concerns by creating presentational (UI) and container (logic) components. + - Use component composition to build complex UIs from smaller, reusable components. + - **Code Splitting Strategies:** + - Implement lazy loading for screens or components that are not immediately needed. + - Utilize `React.lazy` and `Suspense` for dynamic imports. + - Expo supports dynamic imports; leverage them to reduce initial bundle size. + +- **Common Patterns and Anti-patterns** + - **Design Patterns:** + - **Higher-Order Components (HOCs):** Use cautiously; prefer hooks or render props for better composability. + - **Render Props:** A pattern for sharing code between React components using a prop whose value is a function. + - **Compound Components:** Create components that implicitly share state (e.g., Tabs and Tab). + - **Recommended Approaches:** + - Use Expo's APIs for accessing device features (camera, location, notifications) instead of relying on native modules directly where possible. + - Leverage Expo's managed workflow for a smoother development experience. + - **Anti-patterns:** + - Directly manipulating the DOM (use React's state and props instead). + - Writing complex logic directly within components (extract into hooks or utility functions). + - Neglecting error handling and edge cases. + - **State Management:** + - Use React Context for simple state management. + - Consider libraries like Zustand, Redux, or Jotai for more complex state management needs. + - Leverage `useReducer` for managing complex state transitions. + - **Error Handling:** + - Implement try-catch blocks to handle potential errors. + - Use error boundary components to catch errors during rendering. + - Log errors using a centralized logging service (e.g., Sentry). + +- **Performance Considerations** + - **Optimization Techniques:** + - Use `React.memo` to prevent unnecessary re-renders of components. + - Implement `shouldComponentUpdate` (for class components) or `useMemo` and `useCallback` (for functional components) to optimize rendering. + - Debounce or throttle event handlers to reduce the frequency of updates. + - **Memory Management:** + - Avoid creating large arrays or objects in component state if not necessary. + - Clean up event listeners and timers when components unmount. + - Release resources when they are no longer needed. + - **Rendering Optimization:** + - Virtualize long lists using `FlatList` or `SectionList` to improve scrolling performance. + - Optimize image sizes and formats to reduce loading times. + - Use the `useNativeDriver: true` prop in animations for better performance. + - **Bundle Size Optimization:** + - Use code splitting to reduce the initial bundle size. + - Remove unused code and dependencies. + - Optimize images and other assets. + - **Lazy Loading:** + - Implement lazy loading for images and other resources that are not immediately visible. + - Use the `` component from `react-native` or `expo-image` with placeholder and loading indicators. + +- **Security Best Practices** + - **Common Vulnerabilities:** + - Cross-Site Scripting (XSS) - Not typically a risk in React Native/Expo, but be mindful when rendering user-provided content via WebView. + - Data injection - Protect against SQL or command injection if interacting with backend systems. + - Insecure data storage - Never store sensitive information (API keys, credentials) directly in the app code. + - **Input Validation:** + - Validate user input on both the client and server sides. + - Use appropriate data types and formats. + - Sanitize user input to prevent injection attacks. + - **Authentication and Authorization:** + - Use secure authentication mechanisms (e.g., OAuth 2.0, JWT). + - Implement proper authorization to restrict access to sensitive data and functionality. + - Store authentication tokens securely (e.g., using Expo SecureStore). + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS for all API communication. + - Avoid storing sensitive information in logs. + - **Secure API Communication:** + - Use HTTPS for all API requests. + - Validate API responses. + - Implement rate limiting to prevent abuse. + +- **Testing Approaches** + - **Unit Testing:** + - Write unit tests for individual components, hooks, and utility functions. + - Use testing libraries like Jest and React Testing Library. + - Mock dependencies to isolate units of code. + - **Integration Testing:** + - Test the interactions between multiple components or modules. + - Use tools like Detox or Appium for end-to-end testing on real devices or emulators. + - **End-to-end Testing:** + - Simulate user interactions to test the entire application flow. + - Use tools like Detox or Appium for end-to-end testing on real devices or emulators. + - **Test Organization:** + - Organize tests in a clear and maintainable structure. + - Group tests by component or module. + - Use descriptive names for test cases. + - **Mocking and Stubbing:** + - Use mocking to isolate units of code and simulate dependencies. + - Use stubbing to replace complex or external dependencies with simplified versions. + +- **Common Pitfalls and Gotchas** + - **Frequent Mistakes:** + - Forgetting to clean up event listeners or timers. + - Mutating state directly instead of using `setState` or state update functions. + - Over-rendering components due to unnecessary state updates. + - **Edge Cases:** + - Handling different screen sizes and orientations. + - Dealing with slow network connections or API failures. + - Managing application state during interruptions (e.g., phone calls). + - **Version-specific Issues:** + - Be aware of breaking changes in React Native and Expo SDK updates. + - Test your application thoroughly after upgrading dependencies. + - **Compatibility Concerns:** + - Test your application on different devices and operating systems. + - Use platform-specific code only when necessary. + - **Debugging Strategies:** + - Use the React Native debugger or Chrome DevTools for debugging. + - Use console.log statements or debugging tools to inspect variables and application state. + - Use error boundary components to catch and log errors. + +- **Tooling and Environment** + - **Recommended Tools:** + - VS Code with Expo and ESLint extensions + - Expo CLI for managing Expo projects. + - React Native Debugger or Chrome DevTools for debugging. + - **Build Configuration:** + - Use environment variables to configure different build environments (development, staging, production). + - Configure your build process to optimize assets and reduce bundle size. + - **Linting and Formatting:** + - Use ESLint with the Airbnb or Standard style guide. + - Use Prettier to automatically format your code. + - Configure your editor to automatically run ESLint and Prettier on save. + - **Deployment:** + - Use Expo Application Services (EAS) for building and deploying your application. + - Follow Expo's deployment documentation for best practices. + - **CI/CD Integration:** + - Integrate your application with a CI/CD pipeline (e.g., GitHub Actions, CircleCI). + - Automate testing, linting, and deployment processes. + +- **Expo Specific Recommendations** + - **Use Expo Modules:** Prefer Expo modules for accessing native features over community libraries when available, as they are guaranteed to be compatible and well-maintained within the Expo ecosystem. + - **EAS Build:** Use Expo Application Services (EAS) for building native binaries. This simplifies the build process and handles much of the complexity of native builds. + - **Expo Updates:** Implement Expo Updates for over-the-air updates. This allows for quicker iteration and bug fixes without requiring users to download a new version from the app store. + - **Managed Workflow:** Stick to the managed workflow whenever possible. It handles much of the native configuration and simplifies development. + - **Expo SecureStore:** Use `expo-secure-store` to securely store sensitive data like API keys and tokens. + - **Environment Variables:** Use `.env` files and `expo-constants` to manage environment-specific configurations. + - **Asset Management:** Place assets (images, fonts) in the `assets` folder and use the `Image` and `Font` components to load them. + +- **TypeScript Best Practices** + - **Strict Mode:** Enable TypeScript's strict mode (`strict: true` in `tsconfig.json`) for enhanced type safety. + - **Explicit Types:** Explicitly define types for function parameters, return values, and variables. + - **Interfaces vs. Types:** Use interfaces for defining contract between objects, and types for defining data structures. + - **Utility Types:** Leverage TypeScript's utility types (e.g., `Partial`, `Required`, `Readonly`, `Pick`, `Omit`) for more concise and maintainable code. + - **Type Guards:** Use type guards to narrow down types within conditional blocks. + - **Async/Await:** Use `async/await` for asynchronous operations to improve code readability and avoid callback hell. + +- **Resources** + - Expo Documentation: [https://docs.expo.dev/](https://docs.expo.dev/) + - React Native Documentation: [https://reactnative.dev/](https://reactnative.dev/) + - Expo JavaScript Style Guide: [https://github.com/expo/expo/blob/main/guides/Expo%20JavaScript%20Style%20Guide.md](https://github.com/expo/expo/blob/main/guides/Expo%20JavaScript%20Style%20Guide.md) \ No newline at end of file diff --git a/rules-mdc/cross_platform/mobile/flutter.mdc b/rules-mdc/cross_platform/mobile/flutter.mdc new file mode 100644 index 0000000..cbe19b5 --- /dev/null +++ b/rules-mdc/cross_platform/mobile/flutter.mdc @@ -0,0 +1,262 @@ +--- +description: Comprehensive guidelines and best practices for Flutter development, covering code organization, performance optimization, security, testing, and tooling. +globs: **/*.dart +--- +- Adhere to the official Flutter style guide. This forms the foundation for maintainable and consistent code. +- Utilize the latest stable version of Flutter, keeping up-to-date with new features and security patches. Review Flutter's breaking changes and migration guides during updates. + +## 1. Code Organization and Structure + +- **1.1 Directory Structure Best Practices:** + - **`lib/` (Source Code):** + - Use a feature-based structure, grouping related components into modules. + - Example: + + lib/ + ├── auth/ + │ ├── models/ + │ ├── providers/ + │ ├── screens/ + │ ├── services/ + │ ├── widgets/ + │ └── auth.dart + ├── home/ + │ ├── models/ + │ ├── screens/ + │ ├── widgets/ + │ └── home.dart + ├── common/ + │ ├── models/ + │ ├── widgets/ + │ └── utils/ + ├── core/ + │ ├── services/ + │ ├── theme/ + │ └── utils/ + ├── main.dart + └── app.dart + + - **`test/` (Tests):** Mirror the `lib/` structure for easy test discovery. + - **`android/`, `ios/`, `web/`, `macos/`, `windows/`, `linux/` (Platform-Specific Code):** Contain platform-specific native code. Limit direct modification unless necessary; utilize Flutter's platform channels. + - **`assets/` (Assets):** Store images, fonts, and other static resources. Organize subfolders by type (e.g., `images/`, `fonts/`, `data/`). Use `pubspec.yaml` to declare assets. + +- **1.2 File Naming Conventions:** + - Use `snake_case` for file names (e.g., `user_profile_screen.dart`). + - For classes within a file, the file name typically reflects the main class it contains. Example: `user_profile_screen.dart` containing `UserProfileScreen`. + - Exceptions: Grouping multiple related enums, typedefs, or small helper functions into a single file is acceptable if it improves clarity. + +- **1.3 Module Organization:** + - A module encapsulates a specific feature or functionality. Modules should have well-defined interfaces and minimize dependencies on other modules. + - Implement a layered architecture within each module (e.g., UI, business logic, data access). + - Consider using packages for large, independent features to promote reusability across projects. + +- **1.4 Component Architecture:** + - Favor a component-based architecture using Flutter widgets. Break down complex UIs into smaller, reusable widgets. + - Separate presentation logic from business logic. + - Widgets should be pure functions of their input data (state). + - Follow the principles of Single Responsibility Principle (SRP) for widget design. + +- **1.5 Code Splitting Strategies:** + - **Deferred Loading:** Load features on demand to reduce initial app size. + - **Route-Based Splitting:** Split code based on app routes. + - **Feature-Based Splitting:** Split code based on features. + - Use the `dart:ui` library's `loadFontFromList` or `ImageProvider.loadBuffer` to load font or image resources dynamically. + +## 2. Common Patterns and Anti-patterns + +- **2.1 Design Patterns Specific to Flutter:** + - **BLoC (Business Logic Component):** Separates business logic from the UI, making the code more testable and maintainable. + - **Provider:** Simple dependency injection and state management solution. + - **Riverpod:** An improved version of Provider with compile-time safety. + - **GetX:** A microframework that provides state management, dependency injection, and route management. + - **MVVM (Model-View-ViewModel):** Another pattern for separating concerns. Often used with reactive programming. + - **Redux/Flux:** For predictable state management, especially in complex applications. + - **InheritedWidget:** Implicit dependency injection for theming and configuration. + +- **2.2 Recommended Approaches for Common Tasks:** + - **State Management:** Choose a state management solution that fits the complexity of the app. + - **Networking:** Use the `http` package or `dio` for making API requests. + - **Asynchronous Operations:** Use `async/await` for handling asynchronous operations. + - **Data Persistence:** Use `shared_preferences` for simple data storage or SQLite (using packages like `sqflite`) or NoSQL databases (using packages like `hive` or `isar`) for structured data. + - **Navigation:** Use `go_router` or `auto_route` for type-safe navigation. + - **Form Handling:** Use `Form` widget with `TextFormField` and validators. + +- **2.3 Anti-patterns and Code Smells to Avoid:** + - **Massive Widgets:** Widgets with too much logic or UI code. Break them down into smaller, reusable components. + - **Logic in Widgets:** Avoid putting business logic directly inside widgets. + - **Deeply Nested Widgets:** Can lead to performance issues and difficult-to-read code. Simplify the widget tree. + - **Unmanaged State:** Forgetting to dispose of resources like `StreamSubscription` or `AnimationController` leading to memory leaks. + - **Hardcoded Values:** Avoid hardcoding values like colors, sizes, and strings in the code. Use constants or theme data. + - **Ignoring Errors:** Not handling exceptions properly can lead to unexpected crashes. Use `try-catch` blocks and logging. + +- **2.4 State Management Best Practices:** + - Choose a state management solution that fits the complexity of the app. + - Keep the state as close to where it is needed as possible. Avoid global state for everything. + - Use immutable data structures to prevent unexpected state changes. + - Separate state from UI components to improve testability. + - Manage side effects properly. + - Consider reactive programming with streams for complex state transitions. + +- **2.5 Error Handling Patterns:** + - Use `try-catch` blocks to handle exceptions. + - Implement custom error classes for specific error scenarios. + - Log errors to a file or remote service for debugging. + - Show user-friendly error messages. + - Use `ErrorWidget` to display custom error screens. + - Handle asynchronous errors using `Future.catchError` or `Stream.handleError`. + +## 3. Performance Considerations + +- **3.1 Optimization Techniques:** + - **Avoid Unnecessary Widget Rebuilds:** Use `const` constructors for immutable widgets, `shouldRebuild` method in `StatefulWidget`, and `ValueKey` for widgets that change position in a list. + - **Minimize `setState` Calls:** Use state management solutions to optimize state updates. + - **Use `ListView.builder` or `GridView.builder`:** For large lists or grids, build widgets lazily. + - **Use `RepaintBoundary`:** Isolate parts of the UI that don't need to be repainted often. + - **Use `Opacity` and `Clip` Sparingly:** These operations can be expensive. + - **Use `Transform` carefully:** transforms can break batching and cause additional draw calls. + +- **3.2 Memory Management:** + - Dispose of resources like `StreamSubscription`, `AnimationController`, and `TextEditingController` in the `dispose` method. + - Avoid creating unnecessary objects. + - Use the `dart:developer` package's memory profiling tools to identify memory leaks. + - Minimize the use of global variables and static fields. + +- **3.3 Rendering Optimization:** + - Use the Flutter Performance Overlay to identify performance bottlenecks. + - Reduce the complexity of the widget tree. + - Optimize image loading and caching. + - Avoid using custom paint operations unless necessary. + +- **3.4 Bundle Size Optimization:** + - Use `flutter build apk --split-per-abi` or `flutter build appbundle` to split the APK/AAB by ABI (Application Binary Interface). + - Remove unused assets and code. + - Compress images. + - Use code obfuscation and minification. + - Use deferred loading for infrequently used features. + +- **3.5 Lazy Loading Strategies:** + - **Image Lazy Loading:** Load images only when they are visible on the screen. + - **Data Lazy Loading:** Load data in chunks as the user scrolls. + - Use the `VisibilityDetector` package to detect when a widget becomes visible. + - Use pagination or infinite scrolling for large datasets. + +## 4. Security Best Practices + +- **4.1 Common Vulnerabilities and How to Prevent Them:** + - **Data Injection:** Sanitize user input to prevent SQL injection, XSS, and other injection attacks. + - **Sensitive Data Storage:** Avoid storing sensitive data in plain text. Use encryption and secure storage mechanisms. + - **Insecure API Communication:** Use HTTPS for all API communication. + - **Code Tampering:** Use code obfuscation to make it harder to reverse engineer the app. + - **Man-in-the-Middle Attacks:** Implement certificate pinning to prevent MITM attacks. + +- **4.2 Input Validation:** + - Validate all user input on both the client and server sides. + - Use regular expressions or custom validation logic to enforce data constraints. + - Encode data properly before displaying it in the UI. + +- **4.3 Authentication and Authorization Patterns:** + - Use secure authentication protocols like OAuth 2.0 or OpenID Connect. + - Implement multi-factor authentication (MFA) for added security. + - Use role-based access control (RBAC) to restrict access to sensitive data and functionality. + - Store authentication tokens securely. + +- **4.4 Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use secure storage mechanisms like the Keychain (iOS) or Keystore (Android). + - Follow the principle of least privilege when granting access to data. + +- **4.5 Secure API Communication:** + - Use HTTPS for all API communication. + - Implement proper authentication and authorization. + - Validate API responses. + - Rate limit API requests to prevent abuse. + +## 5. Testing Approaches + +- **5.1 Unit Testing Strategies:** + - Test individual functions, classes, and widgets in isolation. + - Use mock objects to isolate the code under test from its dependencies. + - Write tests for all critical business logic. + +- **5.2 Integration Testing:** + - Test the interaction between different parts of the app. + - Test the integration with external services like APIs and databases. + +- **5.3 End-to-End Testing:** + - Test the entire app from start to finish. + - Simulate user interactions to ensure that the app works as expected. + +- **5.4 Test Organization:** + - Create a `test/` directory that mirrors the `lib/` directory structure. + - Use descriptive test names. + - Keep tests small and focused. + +- **5.5 Mocking and Stubbing:** + - Use mocking frameworks like `mockito` to create mock objects. + - Use stubbing to replace external dependencies with predefined values. + - Avoid over-mocking, as it can make tests less effective. + +## 6. Common Pitfalls and Gotchas + +- **6.1 Frequent Mistakes Developers Make:** + - Not disposing of resources. + - Ignoring errors. + - Hardcoding values. + - Using `setState` excessively. + - Creating massive widgets. + - Not validating user input. + - Over-complicating the state management. + +- **6.2 Edge Cases to Be Aware Of:** + - Network connectivity issues. + - Device orientation changes. + - Background app state. + - Low memory conditions. + - Localization and internationalization. + +- **6.3 Version-Specific Issues:** + - Be aware of breaking changes in new Flutter releases. + - Test the app on different Flutter versions to ensure compatibility. + - Use version constraints in `pubspec.yaml` to specify the required Flutter version. + +- **6.4 Compatibility Concerns:** + - Test the app on different devices and operating systems. + - Consider accessibility for users with disabilities. + - Follow platform-specific guidelines for UI and functionality. + +- **6.5 Debugging Strategies:** + - Use the Flutter DevTools for debugging and profiling. + - Use logging to track down errors. + - Use breakpoints to step through the code. + - Use the Flutter Inspector to inspect the widget tree. + +## 7. Tooling and Environment + +- **7.1 Recommended Development Tools:** + - Visual Studio Code or Android Studio. + - Flutter DevTools. + - Android Emulator or iOS Simulator. + - Git for version control. + +- **7.2 Build Configuration:** + - Use `flutter build` to build the app for different platforms. + - Configure build settings in `pubspec.yaml`. + - Use different build configurations for development, staging, and production. + +- **7.3 Linting and Formatting:** + - Use `flutter_lints` package for linting. + - Use `dart format` or Prettier for code formatting. + - Configure the IDE to automatically format the code on save. + +- **7.4 Deployment Best Practices:** + - Follow the deployment guidelines for each platform. + - Use code signing to ensure the authenticity of the app. + - Use version control to manage releases. + - Monitor the app for crashes and errors after deployment. + +- **7.5 CI/CD Integration:** + - Use a CI/CD tool like GitHub Actions, GitLab CI, or Jenkins to automate the build, test, and deployment process. + - Configure the CI/CD pipeline to run linting, formatting, and testing. + - Automate the release process to the app stores. + +This document provides comprehensive guidelines and best practices for Flutter development. Following these guidelines will help you write maintainable, performant, and secure Flutter apps. \ No newline at end of file diff --git a/rules-mdc/cross_platform/mobile/react-native.mdc b/rules-mdc/cross_platform/mobile/react-native.mdc new file mode 100644 index 0000000..4818a0c --- /dev/null +++ b/rules-mdc/cross_platform/mobile/react-native.mdc @@ -0,0 +1,217 @@ +--- +description: This rule provides comprehensive best practices and coding standards for React Native development, covering code organization, performance, security, testing, and common pitfalls. +globs: **/*.{js,jsx,ts,tsx} +--- +- Use TypeScript for type safety and improved code maintainability. +- Prefer functional components with hooks over class components for simplicity and reusability. +- Maintain a clear and consistent project structure for scalability and maintainability. + +## 1. Code Organization and Structure: + +- **Directory Structure:** + - Adopt a feature-based or component-based structure. For example: + + src/ + ├── components/ + │ ├── Button/ + │ │ ├── Button.tsx + │ │ ├── Button.styles.ts + │ │ ├── Button.test.tsx + │ ├── Input/ + │ └── ... + ├── screens/ + │ ├── Home/ + │ │ ├── HomeScreen.tsx + │ │ ├── HomeScreen.styles.ts + │ │ ├── HomeScreen.test.tsx + │ ├── Profile/ + │ └── ... + ├── navigation/ + ├── services/ + ├── utils/ + ├── types/ + └── App.tsx + + - Separate concerns into distinct directories (e.g., components, screens, navigation, services, utils, types). + +- **File Naming Conventions:** + - Use descriptive names for files and components (e.g., `HomeScreen.tsx`, `useUserData.ts`). + - Follow a consistent naming convention (e.g., PascalCase for components, camelCase for functions and variables). + - Use `.styles.ts` for style files and `.test.tsx` for test files to keep components readable and organized. + +- **Module Organization:** + - Group related components and modules into logical units. + - Use absolute imports and module aliases to avoid long relative paths (e.g., `@components/Button` instead of `../../../components/Button`). + - Configure module aliases in `tsconfig.json` or `jsconfig.json`. + +- **Component Architecture:** + - Favor small, reusable components with a single responsibility (Single Responsibility Principle). + - Use composition over inheritance to create complex components. + - Consider using a UI library like React Native Paper or NativeBase for pre-built components. + +- **Code Splitting Strategies:** + - Implement lazy loading for screens or components that are not immediately needed. + - Use `React.lazy` and `Suspense` to load components on demand. + - Utilize dynamic imports for conditional loading of modules. + +## 2. Common Patterns and Anti-patterns: + +- **Design Patterns:** + - **Higher-Order Components (HOCs):** Use HOCs for cross-cutting concerns like authentication or logging. + - **Render Props:** Use render props to share code between React components. + - **Hooks:** Use custom hooks to encapsulate logic and stateful behavior. + +- **Recommended Approaches:** + - **State Management:** + - Use React Context for simple state management. + - Use Redux, Zustand, or Jotai for complex state management. + - Consider using Recoil for fine-grained state management. + - **API Calls:** + - Use `axios` or `fetch` for making API requests. + - Create a service layer to handle API calls and data transformations. + - **Navigation:** + - Use React Navigation for managing app navigation. + - Define navigation stacks and routes in a separate module. + +- **Anti-patterns and Code Smells:** + - **Long Component Files:** Break down large components into smaller, more manageable pieces. + - **Deeply Nested Components:** Avoid excessive nesting, which can impact performance. + - **Mutating State Directly:** Always use `setState` or a state management library to update state. + - **Unnecessary Re-renders:** Optimize components to prevent unnecessary re-renders. + - **Global Styles:** Avoid using global styles, as they can lead to conflicts and make it difficult to maintain the application. + +- **State Management Best Practices:** + - Choose a state management solution that fits the complexity of your application. + - Keep state minimal and derive values when possible. + - Use selectors to access state and memoize computed values. + +- **Error Handling Patterns:** + - Use `try...catch` blocks to handle errors gracefully. + - Implement a global error handler to catch unhandled exceptions. + - Log errors to a remote monitoring service. + +## 3. Performance Considerations: + +- **Optimization Techniques:** + - **Memoization:** Use `React.memo` to memoize components and prevent unnecessary re-renders. + - **Pure Components:** Extend `React.PureComponent` for components that only depend on props. + - **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of function calls. + - **Virtualization:** Use `FlatList` or `SectionList` for rendering large lists of data. + +- **Memory Management:** + - Avoid memory leaks by properly cleaning up event listeners and timers. + - Use `useCallback` and `useMemo` to prevent creating new functions and objects on every render. + +- **Rendering Optimization:** + - Minimize the number of re-renders by optimizing component updates. + - Use `shouldComponentUpdate` (for class components) or `React.memo` to control re-renders. + - Avoid using inline styles, as they are re-created on every render. + +- **Bundle Size Optimization:** + - Use code splitting to reduce the initial bundle size. + - Remove unused code and dependencies. + - Use a bundler like Metro or Webpack with tree shaking enabled. + - Compress images and other assets. + +- **Lazy Loading Strategies:** + - Implement lazy loading for images and other assets using `React.lazy` and `Suspense`. + - Use dynamic imports to load modules on demand. + +## 4. Security Best Practices: + +- **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. + - **SQL Injection:** Use parameterized queries to prevent SQL injection attacks. + - **Cross-Site Request Forgery (CSRF):** Implement CSRF protection tokens. + - **Man-in-the-Middle (MITM) Attacks:** Use HTTPS to encrypt communication. + +- **Input Validation:** + - Validate user input on both the client and server sides. + - Use regular expressions or validation libraries to enforce input constraints. + +- **Authentication and Authorization Patterns:** + - Use a secure authentication protocol like OAuth 2.0 or JWT. + - Implement role-based access control (RBAC) to restrict access to sensitive resources. + +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use secure storage mechanisms for storing API keys and other secrets. + +- **Secure API Communication:** + - Use HTTPS for all API communication. + - Implement API rate limiting to prevent abuse. + - Validate API responses to prevent data injection attacks. + +## 5. Testing Approaches: + +- **Unit Testing Strategies:** + - Write unit tests for individual components and modules. + - Use a testing framework like Jest or Mocha. + - Mock dependencies to isolate the component being tested. + +- **Integration Testing:** + - Write integration tests to verify the interaction between components and modules. + - Test the integration with external APIs and services. + +- **End-to-End Testing:** + - Write end-to-end tests to verify the entire application flow. + - Use a testing framework like Detox or Appium. + +- **Test Organization:** + - Organize tests into separate directories based on component or module. + - Use descriptive names for test files and test cases. + +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate components and control their behavior during testing. + - Use a mocking library like Jest or Sinon. + +## 6. Common Pitfalls and Gotchas: + +- **Frequent Mistakes:** + - **Directly Mutating State:** Always use `setState` or a state management library to update state. + - **Ignoring Platform Differences:** Test your application on both iOS and Android devices. + - **Over-Optimizing:** Optimize only when necessary, as premature optimization can lead to complex code. + - **Not Using a Debugger:** Utilize the React Native debugger for efficient debugging. + +- **Edge Cases:** + - **Handling Device Orientation Changes:** Implement logic to handle device orientation changes gracefully. + - **Handling Network Connectivity Issues:** Implement error handling for network connectivity issues. + - **Handling Different Screen Sizes and Densities:** Design your UI to adapt to different screen sizes and densities. + +- **Version-Specific Issues:** + - Be aware of breaking changes in React Native and its dependencies. + - Test your application with different versions of React Native. + +- **Compatibility Concerns:** + - Ensure that your application is compatible with the target operating systems and devices. + - Use polyfills to support older browsers and devices. + +- **Debugging Strategies:** + - Use the React Native debugger to inspect the component tree and state. + - Use the console to log messages and debug code. + - Use a remote debugging tool to debug on a physical device. + +## 7. Tooling and Environment: + +- **Recommended Development Tools:** + - **VS Code:** Use VS Code with the React Native Tools extension for debugging and code completion. + - **React Native CLI:** Use the React Native CLI for creating and managing React Native projects. + - **Expo CLI:** Use the Expo CLI for developing and testing React Native applications without native code. + - **Android Studio:** Use Android Studio for building and debugging Android applications. + - **Xcode:** Use Xcode for building and debugging iOS applications. + +- **Build Configuration:** + - Use a build system like Gradle (Android) or CocoaPods (iOS) to manage dependencies. + - Configure build variants for different environments (e.g., development, staging, production). + +- **Linting and Formatting:** + - Use ESLint and Prettier to enforce code style and catch potential errors. + - Configure ESLint and Prettier to automatically format code on save. + +- **Deployment Best Practices:** + - Use a continuous integration and continuous deployment (CI/CD) pipeline to automate the deployment process. + - Use a service like App Center or Bitrise for building and deploying React Native applications. + +- **CI/CD Integration:** + - Integrate your code repository with a CI/CD service like GitHub Actions or CircleCI. + - Configure the CI/CD pipeline to run tests and build the application on every commit. \ No newline at end of file diff --git a/rules-mdc/database_tools/analytics/duckdb.mdc b/rules-mdc/database_tools/analytics/duckdb.mdc new file mode 100644 index 0000000..b274446 --- /dev/null +++ b/rules-mdc/database_tools/analytics/duckdb.mdc @@ -0,0 +1,285 @@ +--- +description: This rule file outlines best practices for developing with DuckDB, covering code organization, performance optimization, security considerations, and testing strategies. It aims to improve code quality, maintainability, and overall project health when using DuckDB. +globs: **/*.{sql,ddl,md,duckdb} +--- +# DuckDB Best Practices and Coding Standards + +This document provides guidelines and best practices for developing with DuckDB. Following these recommendations will lead to more maintainable, performant, and secure DuckDB projects. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure Best Practices + +* **Project Root:** + * `.cursor/`: Contains Cursor rule files. + * `data/`: Stores data files (CSV, Parquet, etc.). Consider subdirectories based on data source or type. + * `sql/`: Contains SQL scripts (DDL, DML, queries). + * `scripts/`: Python, Bash, or other scripts for data processing and automation. + * `docs/`: Project documentation. + * `tests/`: Test scripts and data. + * `venv/` (or `.venv/`): Virtual environment for Python dependencies (if applicable). + * `Makefile`: Automation of common tasks (e.g., data loading, testing). + * `README.md`: Project overview and instructions. + * `.gitignore`: Specifies intentionally untracked files that Git should ignore. + +* **Example:** + + + my_duckdb_project/ + ├── .cursor/ + │ └── rules.mdc + ├── data/ + │ ├── raw/ + │ │ └── sales_data.csv + │ └── processed/ + │ └── sales_summary.parquet + ├── sql/ + │ ├── create_tables.sql + │ ├── queries/ + │ │ ├── monthly_sales.sql + │ │ └── top_customers.sql + │ └── data_validation.sql + ├── scripts/ + │ └── process_data.py + ├── docs/ + │ └── user_guide.md + ├── tests/ + │ ├── unit/ + │ │ └── test_queries.py + │ └── integration/ + │ └── test_data_pipeline.py + ├── venv/ + ├── Makefile + ├── README.md + └── .gitignore + + +### 1.2. File Naming Conventions + +* **SQL Scripts:** Use descriptive names with underscores (e.g., `create_tables.sql`, `monthly_sales_report.sql`). +* **Data Files:** Use names reflecting the data content (e.g., `customer_data.csv`, `product_catalog.parquet`). Prefix with dates if versioning is needed (e.g., `2024-01-01_customer_data.csv`). +* **Scripts:** Use names indicating the script's purpose (e.g., `load_data.py`, `run_tests.sh`). +* **DDL Files:** `schema.sql`, `tables.sql` etc. for defining database structures + +### 1.3. Module Organization (if using a scripting language like Python) + +* **Separate Modules:** Divide code into logical modules (e.g., `data_loading.py`, `query_execution.py`, `utils.py`). +* **Clear Interfaces:** Define clear functions and classes with well-defined inputs and outputs. +* **Avoid Global State:** Minimize the use of global variables to improve code testability and maintainability. + +### 1.4. Component Architecture + +* **Data Layer:** Handles data loading, transformation, and storage using DuckDB. +* **Logic Layer:** Encapsulates business logic and data processing routines. +* **Presentation Layer:** (If applicable) Presents data to users (e.g., through a web application). +* **Configuration Layer:** Loads external configurations (e.g., environment variables) that the script needs to run properly. + +### 1.5. Code Splitting Strategies + +* **Split Large SQL Scripts:** Break down complex SQL scripts into smaller, more manageable files. +* **Modularize Python Code:** Use functions and classes to create reusable components. +* **Separate Configuration:** Store configuration settings (database paths, API keys) in separate files. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to DuckDB + +* **Embedded Database:** Use DuckDB as an embedded database for lightweight data analysis and prototyping. +* **Data Pipeline:** Build data pipelines with DuckDB for ETL (Extract, Transform, Load) processes. +* **Analytical Queries:** Leverage DuckDB's columnar storage and vectorized execution for efficient analytical queries. +* **Federated Querying:** Utilize DuckDB's ability to query data from various sources (CSV, Parquet, JSON, HTTP) using a unified SQL interface. + +### 2.2. Recommended Approaches for Common Tasks + +* **Data Loading:** + * Use `COPY` command for efficient bulk loading of data from files. + * Consider Parquet format for optimal storage and query performance. + * Use `read_csv_auto` or `read_parquet` functions. +* **Querying:** + * Write clear and concise SQL queries. + * Use parameterized queries to prevent SQL injection. + * Utilize window functions for complex aggregations and ranking. +* **Data Transformation:** + * Use SQL functions for data cleaning and transformation. + * Create views for commonly used data transformations. +* **Joining Tables:** + * Understand different join types (INNER, LEFT, RIGHT, FULL) and choose the appropriate one. + * Ensure join columns are properly indexed for performance. + * Use explicit `JOIN` syntax for readability. +* **Error Handling:** Implement robust error handling to prevent unexpected crashes. + * Utilize `TRY/CATCH` blocks in SQL scripts. + * Log errors to files or databases for debugging and monitoring. + +### 2.3. Anti-patterns and Code Smells to Avoid + +* `SELECT *`: Avoid selecting all columns unless necessary. Specify only the columns you need to improve performance. +* Nested Subqueries: Excessive use of nested subqueries can impact performance. Consider using `WITH` clauses (Common Table Expressions - CTEs) to improve readability and performance. +* Lack of Indexing: Missing indexes on frequently queried columns can lead to slow query performance. Add indexes where appropriate. +* Hardcoded Values: Avoid hardcoding values in SQL queries or scripts. Use parameters or configuration files instead. +* Ignoring Error Handling: Failing to handle errors gracefully can lead to unexpected application behavior. +* Over-complicating Queries: Strive for clarity and simplicity in SQL queries. Break down complex logic into smaller, more manageable steps. +* Not closing database connections after usage. + +### 2.4. State Management Best Practices + +* **Minimize State:** Keep the amount of mutable state in your application to a minimum. +* **Centralized State:** If state is necessary, manage it in a centralized location (e.g., a configuration file or dedicated state management module). +* **Immutable Data:** Prefer immutable data structures whenever possible to avoid unintended side effects. + +### 2.5. Error Handling Patterns + +* **Try-Catch Blocks:** Use `TRY/CATCH` blocks in SQL scripts to handle potential errors. +* **Logging:** Log errors to files or databases for debugging and monitoring. +* **Custom Error Messages:** Provide informative error messages to help users understand and resolve issues. +* **Graceful Degradation:** Design your application to handle errors gracefully and continue functioning (albeit with reduced functionality) if possible. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Column Selection:** Use specific column selections instead of `SELECT *` to improve performance. +* **Filtering Before Joining:** Optimize queries by filtering data before joining tables. +* **Prepared Statements:** Utilize prepared statements for repeated queries to enhance execution speed. +* **Indexing:** Create indexes on frequently queried columns to speed up data retrieval. +* **Query Plan Analysis:** Use `EXPLAIN ANALYZE` to understand query execution plans and identify bottlenecks. +* **Chunking:** Implement chunking for large datasets to manage memory better. +* **Data Types:** Use appropriate data types to minimize storage space and improve query performance. Avoid using TEXT for numerical data. Use INTEGER or BIGINT where possible. +* **Compression:** DuckDB supports lightweight compression. Consider using persistent databases to take advantage of this. +* **Parallelism:** DuckDB parallelizes workload based on row groups. Ensure your data is large enough to benefit from multi-core processing. Manually limit the number of threads if necessary using `SET threads = X`. + +### 3.2. Memory Management + +* **Memory Limits:** Monitor memory usage and set appropriate memory limits. +* **Spilling to Disk:** Larger-than-memory workloads are supported by spilling to disk. Configure the temporary directory using `SET temp_directory = '/path/to/temp_dir.tmp/'`. +* **Avoid Large Intermediate Results:** Optimize queries to minimize the size of intermediate results. +* **`preserve_insertion_order`:** Disable `preserve_insertion_order` for large imports/exports if order is not important (`SET preserve_insertion_order = false`). + +### 3.3. Avoiding Reading Unnecessary Data (Remote Files) + +* **Column Selection:** Avoid `SELECT *`. Only select columns that are actually used. +* **Filter Pushdown:** Apply filters on remote parquet files when possible. DuckDB can use these filters to reduce the amount of data that is scanned. +* **Sorting/Partitioning:** Either sort or partition data by columns that are regularly used for filters: this increases the effectiveness of the filters in reducing IO. +* **Avoid Reading Data More Than Once:** If data needs to be accessed multiple times, store it locally. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +* **SQL Injection:** Prevent SQL injection by using parameterized queries and avoiding string concatenation in SQL statements. +* **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit. Use appropriate access controls to restrict access to sensitive data. +* **Denial of Service (DoS):** Limit resource consumption (memory, CPU) to prevent DoS attacks. +* **Unauthorized Access:** Implement strong authentication and authorization mechanisms to prevent unauthorized access to the database. + +### 4.2. Input Validation + +* **Validate User Inputs:** Validate all user inputs to prevent malicious data from entering the database. Check data types, ranges, and formats. +* **Sanitize Inputs:** Sanitize user inputs to remove potentially harmful characters or code. + +### 4.3. Authentication and Authorization Patterns + +* **Role-Based Access Control (RBAC):** Implement RBAC to grant users only the necessary permissions to access data. +* **Least Privilege Principle:** Grant users the minimum level of access required to perform their tasks. +* **Secure Connection:** Ensure that connections to the database are encrypted using TLS/SSL. + +### 4.4. Data Protection Strategies + +* **Encryption:** Encrypt sensitive data at rest and in transit. +* **Data Masking:** Mask sensitive data in non-production environments to protect user privacy. +* **Data Auditing:** Track all data access and modification activities for auditing purposes. +* **Regular Backups:** Regularly back up the database to prevent data loss in case of failures. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +* **Test Individual Components:** Write unit tests to verify the functionality of individual SQL functions, Python modules, or other components. +* **Mock Database Connections:** Mock database connections to isolate the code being tested from the actual database. +* **Assertion Frameworks:** Use assertion frameworks (e.g., `pytest`, `unittest`) to verify expected results. + +### 5.2. Integration Testing + +* **Test Interactions:** Write integration tests to verify the interactions between different components of the system. +* **Real Database:** Use a real DuckDB database for integration tests (preferably a test database). +* **Data Validation:** Verify that data is correctly loaded, transformed, and stored in the database. + +### 5.3. End-to-End Testing + +* **Test Complete Workflows:** Write end-to-end tests to verify the functionality of complete workflows from start to finish. +* **Simulate User Actions:** Simulate user actions to test the system's behavior under realistic conditions. + +### 5.4. Test Organization + +* **Separate Test Directory:** Create a separate `tests/` directory to store test scripts. +* **Organize Tests:** Organize tests into subdirectories based on the component or feature being tested. +* **Descriptive Names:** Use descriptive names for test files and functions. + +### 5.5. Mocking and Stubbing + +* **Mock External Dependencies:** Mock external dependencies (e.g., file systems, network connections) to isolate the code being tested. +* **Stub Database Interactions:** Stub database interactions to control the behavior of the database during testing. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +* **Not Using Indexes:** Forgetting to create indexes on frequently queried columns. +* **Incorrect Join Types:** Using the wrong join type (e.g., INNER instead of LEFT). +* **SQL Injection Vulnerabilities:** Failing to prevent SQL injection attacks. +* **Memory Leaks:** Not properly closing database connections or releasing resources. +* **Lack of Error Handling:** Ignoring potential errors in SQL scripts or Python code. + +### 6.2. Edge Cases to Be Aware Of + +* **Null Values:** Handle null values correctly in SQL queries and data transformations. +* **Empty Datasets:** Test the system's behavior with empty datasets. +* **Large Datasets:** Test the system's behavior with large datasets to ensure performance. +* **Concurrency:** Consider potential concurrency issues when multiple users or processes access the database simultaneously. + +### 6.3. Version-Specific Issues + +* **Check Release Notes:** Review the release notes for each new version of DuckDB to identify any breaking changes or known issues. +* **Compatibility Testing:** Perform compatibility testing to ensure that the application works correctly with different versions of DuckDB. + +### 6.4. Compatibility Concerns + +* **Operating System:** Ensure that the application is compatible with the target operating system (Windows, macOS, Linux). +* **Programming Language:** Ensure that the application is compatible with the programming language being used (Python, Java, etc.). +* **Database Drivers:** Use compatible database drivers. + +### 6.5. Debugging Strategies + +* **Logging:** Add logging statements to the code to track execution flow and variable values. +* **Print Statements:** Use print statements to display intermediate results and debug issues. +* **Debuggers:** Use debuggers (e.g., `pdb` in Python) to step through the code and inspect variables. +* **Query Plan Analysis:** Use `EXPLAIN ANALYZE` to understand query execution plans and identify bottlenecks. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +* **Text Editor/IDE:** VSCode, Sublime Text, IntelliJ IDEA, etc. +* **Database Client:** DBeaver, DataGrip, SQL Developer, DuckDB CLI. +* **Version Control:** Git. +* **Virtual Environment Manager:** `venv` (Python), Conda. +* **Task Runner:** Make, Invoke (Python). + +### 7.2. Build Configuration + +* **Dependency Management:** Use a dependency management tool (e.g., `pip` for Python) to manage project dependencies. +* **Configuration Files:** Use configuration files (e.g., `config.ini`, `settings.json`) to store project settings and parameters. + +### 7.3. Linting and Formatting + +* **Linters:** Use linters (e.g., `flake8`, `pylint` for Python, `sqlfluff` for SQL) to enforce code style and identify potential errors. +* **Formatters:** Use formatters (e.g., `black` for Python, `sqlformat` for SQL) to automatically format code according to a defined style. + +### 7.4. Deployment Best Practices + +* **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies into a single unit. +* **Infrastructure as Code (IaC):** Use IaC tools (e.g., Terraform, CloudFormation) to automate the provisioning and management of infrastructure. +* **Configuration Management:** Use configuration management tools (e.g., Ansible, Chef, Puppet) to automate the configuration of servers and applications. + +### 7.5. CI/CD Integration + +* **Continuous Integration (CI):** Integrate automated testing into the CI pipeline to ensure code quality. +* **Continuous Delivery (CD):** Automate the deployment process to ensure frequent and reliable releases. \ No newline at end of file diff --git a/rules-mdc/database_tools/nosql/mongodb.mdc b/rules-mdc/database_tools/nosql/mongodb.mdc new file mode 100644 index 0000000..ea586a6 --- /dev/null +++ b/rules-mdc/database_tools/nosql/mongodb.mdc @@ -0,0 +1,148 @@ +--- +description: Comprehensive best practices for developing with MongoDB, covering schema design, code organization, performance optimization, security considerations, and testing strategies. This rule provides actionable guidance to help developers build robust and scalable MongoDB applications. +globs: **/*.{js,ts,mongodb} +--- +- **Understand Schema Differences Between Relational and Document-based Databases:** Recognize that MongoDB's document-oriented model differs significantly from relational databases. Design schemas that reflect the relationships within the data itself, rather than relying on joins. +- **Embed Your Data Instead of Relying on Joins:** Favor embedding related data within a single document to minimize the need for costly join operations. This approach can significantly improve read performance. +- **Use Indexes For Frequent Operations:** Create indexes on fields that are frequently queried to optimize performance. Carefully consider the types of queries your application will perform and create indexes accordingly. Compound indexes are beneficial for queries involving multiple fields. +- **Properly Size Your Servers:** Ensure that your MongoDB server resources are adequately sized for your workload. Monitor resource utilization and scale as needed to maintain optimal performance. Consider CPU, memory, and disk I/O. +- **Use Replication or Sharding:** Implement replication or sharding to enhance scalability and reliability. Replication provides data redundancy and high availability, while sharding distributes data across multiple servers to handle larger datasets and higher traffic volumes. + +### 1. Code Organization and Structure: + +- **Directory Structure Best Practices:** + - `config/`: Contains configuration files for database connections, authentication, and other settings. + - `models/`: Defines data models using Mongoose or other ODM libraries. Each model represents a MongoDB collection. + - `routes/`: Handles API endpoints and routes for interacting with the database. + - `controllers/`: Implements the logic for handling requests, interacting with models, and returning responses. + - `services/`: Contains reusable business logic related to data access and manipulation. + - `utils/`: Provides utility functions for common tasks such as validation, formatting, and error handling. + - `tests/`: Includes unit, integration, and end-to-end tests. +- **File Naming Conventions:** + - Use descriptive names that reflect the purpose of the file (e.g., `user.model.js`, `auth.controller.ts`, `product.service.js`). + - Follow a consistent naming convention across the project (e.g., camelCase or snake_case). +- **Module Organization:** + - Organize code into modules based on functionality or domain (e.g., `user` module, `product` module). + - Use ES modules or CommonJS modules to encapsulate code and manage dependencies. +- **Component Architecture:** + - Design reusable components for common tasks such as data validation, error handling, and authentication. + - Follow the principles of separation of concerns and single responsibility. +- **Code Splitting Strategies:** + - Implement lazy loading of modules or components to improve initial load time. + - Use code splitting to break down large bundles into smaller chunks. + +### 2. Common Patterns and Anti-patterns: + +- **Design Patterns Specific to MongoDB:** + - **Embedded Document Pattern:** Embed related data within a single document to minimize the need for joins. + - **Polymorphic Pattern:** Store different types of documents in the same collection using a common base schema and discriminator fields. + - **Bucket Pattern:** Group data into buckets based on time or other criteria for efficient querying and aggregation. +- **Recommended Approaches for Common Tasks:** + - Use Mongoose or other ODM libraries to simplify data modeling and validation. + - Implement pagination for large result sets. + - Use aggregation pipelines for complex queries and data transformations. +- **Anti-patterns and Code Smells to Avoid:** + - **Over-indexing:** Creating too many indexes can degrade write performance. + - **Ignoring Performance:** Neglecting to analyze query performance can lead to slow response times. + - **Schema Violations:** Allowing inconsistent data to be stored in collections can cause unexpected errors. +- **State Management Best Practices:** + - Use a state management library such as Redux or Zustand to manage application state. + - Store state in a centralized store to ensure consistency and predictability. +- **Error Handling Patterns:** + - Implement robust error handling to catch and handle exceptions gracefully. + - Use try-catch blocks to handle potential errors. + - Log errors for debugging and monitoring. + +### 3. Performance Considerations: + +- **Optimization Techniques:** + - Use indexes to optimize query performance. + - Avoid using `$where` operator, as it can be slow. + - Use projection to retrieve only the necessary fields. +- **Memory Management:** + - Monitor memory usage and identify potential memory leaks. + - Use connection pooling to reuse database connections. +- **Rendering Optimization:** (If applicable for UI-based apps using MongoDB data) + - Implement virtualization for large lists. + - Use memoization to avoid unnecessary re-renders. +- **Bundle Size Optimization:** (If applicable) + - Minify and compress JavaScript and CSS files. + - Remove unused code. +- **Lazy Loading Strategies:** (If applicable) + - Lazy load images and other resources. + - Use code splitting to load modules on demand. + +### 4. Security Best Practices: + +- **Common Vulnerabilities and How to Prevent Them:** + - **NoSQL Injection:** Sanitize user inputs to prevent injection attacks. + - **Authentication Bypass:** Implement strong authentication and authorization mechanisms. + - **Data Exposure:** Protect sensitive data by encrypting it and controlling access. +- **Input Validation:** + - Validate all user inputs to prevent malicious data from being stored in the database. + - Use a validation library such as Joi or Yup to define validation schemas. +- **Authentication and Authorization Patterns:** + - Use a secure authentication protocol such as OAuth 2.0 or JWT. + - Implement role-based access control (RBAC) to restrict access to sensitive data and functionality. +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use data masking to protect personally identifiable information (PII). +- **Secure API Communication:** + - Use HTTPS to encrypt communication between the client and server. + - Implement rate limiting to prevent abuse. + +### 5. Testing Approaches: + +- **Unit Testing Strategies:** + - Write unit tests to verify the functionality of individual modules and components. + - Use a testing framework such as Jest or Mocha. +- **Integration Testing:** + - Write integration tests to verify the interaction between different modules and components. + - Test the integration between the application and the database. +- **End-to-End Testing:** + - Write end-to-end tests to verify the functionality of the entire application. + - Use a testing framework such as Cypress or Playwright. +- **Test Organization:** + - Organize tests into separate directories based on functionality or module. + - Use descriptive names for test files and test cases. +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate units of code during testing. + - Use a mocking library such as Sinon or Jest's built-in mocking. + +### 6. Common Pitfalls and Gotchas: + +- **Frequent Mistakes Developers Make:** + - **Not Understanding MongoDB's Query Language:** Failing to grasp the nuances of MongoDB's query language can lead to inefficient queries. + - **Ignoring Indexes:** Neglecting to create indexes on frequently queried fields can significantly impact performance. + - **Not Handling Errors Properly:** Failing to handle errors gracefully can lead to unexpected application behavior. +- **Edge Cases to Be Aware Of:** + - **Data Type Mismatches:** Ensure that data types are consistent across the application and the database. + - **Concurrency Issues:** Handle concurrency issues carefully to prevent data corruption. +- **Version-Specific Issues:** + - Be aware of compatibility issues between different versions of MongoDB and related libraries. + - Consult the documentation for the specific version you are using. +- **Compatibility Concerns:** + - Ensure that the application is compatible with different operating systems and browsers. + - Test the application on different devices and screen sizes. +- **Debugging Strategies:** + - Use logging to track the execution flow and identify potential issues. + - Use a debugger to step through the code and inspect variables. + +### 7. Tooling and Environment: + +- **Recommended Development Tools:** + - **MongoDB Compass:** A GUI tool for exploring and managing MongoDB databases. + - **MongoDB Shell:** A command-line interface for interacting with MongoDB. + - **VS Code Extension for MongoDB:** Provides syntax highlighting, code completion, and other features for MongoDB development. +- **Build Configuration:** + - Use a build tool such as Webpack or Parcel to bundle and optimize the application. + - Configure the build tool to minify and compress JavaScript and CSS files. +- **Linting and Formatting:** + - Use a linter such as ESLint to enforce coding standards. + - Use a formatter such as Prettier to automatically format code. +- **Deployment Best Practices:** + - Use a containerization technology such as Docker to package the application and its dependencies. + - Deploy the application to a cloud platform such as AWS, Azure, or Google Cloud. +- **CI/CD Integration:** + - Integrate the application with a CI/CD pipeline to automate the build, test, and deployment process. + - Use a CI/CD tool such as Jenkins, Travis CI, or CircleCI. \ No newline at end of file diff --git a/rules-mdc/database_tools/nosql/redis.mdc b/rules-mdc/database_tools/nosql/redis.mdc new file mode 100644 index 0000000..dd5e5ce --- /dev/null +++ b/rules-mdc/database_tools/nosql/redis.mdc @@ -0,0 +1,75 @@ +--- +description: This rule provides best practices for working with Redis, covering code organization, performance, security, testing, and common pitfalls to ensure efficient and reliable usage. It applies to any language file interacting with Redis. +globs: **/*.{py,js,go,java,c,cpp,rb,php,ts,rs,kt,scala} +--- +- **General Best Practices** + - Follow official Redis documentation and community best practices. + - Use the most recent stable version of the Redis client library for your language. + - Regularly update the Redis server and client libraries to benefit from bug fixes, performance improvements, and security patches. + +- **Connection Management** + - **Connection Pooling:** Use connection pooling to reduce the overhead of creating new connections for each operation. This significantly improves performance, especially in high-traffic scenarios. + - **Connection Timeout:** Configure appropriate connection timeouts to prevent indefinite blocking in case of network issues. + - **Retry Logic:** Implement retry logic with exponential backoff for transient connection errors. + - **Secure Connections:** When connecting to a remote Redis instance, always use TLS/SSL encryption (redis+ssl://) to protect data in transit, especially when dealing with sensitive information. Ensure proper certificate validation. + +- **Data Modeling and Serialization** + - **Key Naming:** Use consistent and meaningful key naming conventions. Consider using namespaces or prefixes to organize keys and avoid collisions. + - **Data Serialization:** Choose an efficient serialization format (e.g., JSON, Protocol Buffers, MessagePack) and use it consistently. Consider the trade-offs between human readability, storage space, and serialization/deserialization performance. + - **Smaller Values:** Redis works best with smaller values. Break larger data structures into smaller chunks and distribute them across multiple keys. This improves memory utilization and performance. + - **Data Types:** Leverage Redis's rich data types (strings, lists, sets, sorted sets, hashes, streams) effectively to optimize data storage and operations. Choose the data type that best suits the use case. + +- **Command Usage** + - **Transactions:** Use transactions (`MULTI`, `EXEC`, `DISCARD`, `WATCH`) to ensure atomicity when performing multiple operations. Be aware of the limitations of Redis transactions (no rollback on individual command failure). + - **Pipelines:** Use pipelines to batch multiple commands together and reduce network round-trip time. This dramatically improves performance for bulk operations. + - **Lua Scripting:** Use Lua scripting for complex operations that require atomicity and server-side processing. This reduces network traffic and improves performance compared to executing multiple individual commands. + - **Avoid Blocking Commands:** Avoid using blocking commands like `KEYS`, `FLUSHALL`, `FLUSHDB`, `SORT` without `LIMIT` in production environments. These commands can block the Redis server and degrade performance. + - **Use SCAN:** Instead of `KEYS`, use the `SCAN` command for iterating over keys in a non-blocking manner. This allows the Redis server to continue serving other requests while iterating. + - **Efficient Deletion:** Instead of `FLUSHALL` or `FLUSHDB`, use `SCAN` with `DEL` to delete keys in batches, minimizing disruption to the server. + - **TTL Management:** Set appropriate Time-To-Live (TTL) values for keys to automatically expire data that is no longer needed. This helps manage memory usage and prevent data from becoming stale. + +- **Memory Management** + - **Maxmemory:** Configure the `maxmemory` directive to limit the amount of memory Redis can use. When the limit is reached, Redis will evict keys based on the configured eviction policy. + - **Eviction Policies:** Choose an appropriate eviction policy (e.g., `LRU`, `LFU`, `volatile-ttl`) based on your application's needs. Understand the trade-offs between different eviction policies. + - **Memory Fragmentation:** Monitor memory fragmentation and consider restarting Redis periodically to defragment memory. The `INFO memory` command provides information about memory usage and fragmentation. + +- **Performance Monitoring and Tuning** + - **Redis Monitor:** Use the `MONITOR` command (with caution in production) to observe real-time commands being executed on the server. This can help identify performance bottlenecks. + - **Redis Slow Log:** Configure the Redis slow log to record commands that take longer than a specified amount of time to execute. Analyze the slow log to identify performance issues. + - **INFO Command:** Use the `INFO` command to gather information about the Redis server, including memory usage, CPU usage, and client connections. This information can be used to monitor performance and identify potential problems. + - **Latency Monitoring:** Monitor Redis latency using tools like `redis-cli --latency` or dedicated monitoring solutions. High latency can indicate performance issues. + +- **Security Considerations** + - **Authentication:** Enable authentication using the `requirepass` directive to protect the Redis server from unauthorized access. Use a strong password. + - **Access Control Lists (ACLs):** Use ACLs to restrict access to specific commands and keys for different users. This provides fine-grained control over access to Redis data. + - **Network Security:** Restrict network access to the Redis server using firewalls or other network security measures. Only allow connections from trusted sources. + - **Disable Unsafe Commands:** Disable or rename potentially dangerous commands like `FLUSHALL`, `FLUSHDB`, `KEYS`, `EVAL` using the `rename-command` directive. This reduces the risk of accidental or malicious misuse. + - **Regular Audits:** Conduct regular security audits of the Redis configuration and usage patterns to identify and address potential vulnerabilities. + - **Input Validation:** Always validate and sanitize any data being stored in Redis to prevent injection attacks. + +- **Testing Strategies** + - **Unit Tests:** Write unit tests to verify the functionality of your code that interacts with Redis. Use mocking or stubbing to isolate the Redis interactions from the rest of the code. + - **Integration Tests:** Write integration tests to verify the interaction between your code and the Redis server. Use a dedicated test Redis instance for integration tests. + - **End-to-End Tests:** Write end-to-end tests to verify the entire application flow, including the interaction with Redis. This ensures that the application works correctly in a realistic environment. + - **Data Population:** When testing, consider populating your redis database with a representative set of data. + - **Test Organization:** Organize tests logically, separating unit, integration, and end-to-end tests into different directories or modules. + - **Mocking and Stubbing:** Use mocking and stubbing frameworks to simulate Redis behavior during unit tests. + +- **Code Organization and Structure** + - **Dedicated Module:** Create a dedicated module or class to encapsulate all Redis-related operations. This promotes code reuse and maintainability. + - **Configuration Management:** Store Redis connection parameters (host, port, password) in a configuration file or environment variables. This makes it easy to change the Redis configuration without modifying code. + - **Abstraction Layer:** Consider creating an abstraction layer on top of the Redis client library to provide a higher-level API for your application. This can improve code readability and make it easier to switch to a different Redis client library in the future. + +- **Common Pitfalls and Gotchas** + - **N+1 Problem:** Avoid the N+1 problem when retrieving data from Redis. Instead of making multiple individual requests, use pipelining or Lua scripting to retrieve the data in a single request. + - **Race Conditions:** Be aware of potential race conditions when updating data in Redis. Use transactions or Lua scripting to ensure atomicity. + - **Large Values:** Avoid storing extremely large values in Redis. This can lead to performance issues and memory exhaustion. + - **Key Expiration:** Be careful when using key expiration (TTL). If keys expire unexpectedly, it can lead to data loss or inconsistent application behavior. + - **Blocking Operations in Event Loops:** Do not perform blocking Redis operations directly in event loops or GUI threads. Use asynchronous operations instead to avoid blocking the main thread. + +- **Tooling and Environment** + - **Redis CLI:** Use the Redis CLI (`redis-cli`) for interacting with the Redis server, executing commands, and monitoring performance. + - **Redis Desktop Manager:** Use a Redis desktop manager (e.g., RedisInsight, Medis) for visualizing data, managing keys, and monitoring the Redis server. + - **Linting and Formatting:** Configure linters and formatters to enforce consistent code style and best practices in your Redis-related code. + - **CI/CD Integration:** Integrate Redis testing and deployment into your CI/CD pipeline to automate the testing and deployment process. + - **Monitoring Tools:** Utilize monitoring tools like Prometheus, Grafana, or Datadog to monitor Redis performance and health in production environments. \ No newline at end of file diff --git a/rules-mdc/database_tools/sql/postgresql.mdc b/rules-mdc/database_tools/sql/postgresql.mdc new file mode 100644 index 0000000..53524c9 --- /dev/null +++ b/rules-mdc/database_tools/sql/postgresql.mdc @@ -0,0 +1,107 @@ +--- +description: Enforces PostgreSQL coding standards, best practices, and performance optimization techniques to ensure maintainable, efficient, and secure database interactions. This rule covers code formatting, data integrity, security, and performance considerations. +globs: **/*.{sql,plpgsql,c,h} +--- +- **Code Formatting and Comments:** + - Maintain consistent code formatting using a tool like `pgformatter` or similar. + - Use clear and concise comments to explain complex logic and intentions. Update comments regularly to avoid confusion. + - Use inline comments sparingly; prefer block comments for detailed explanations. + - Write comments in plain, easy-to-follow English. + - Add a space after line comments (`-- a comment`); do not add a space for commented-out code (`--raise notice`). + - Keep comments up-to-date; incorrect comments are worse than no comments. + +- **Naming Conventions:** + - Use `snake_case` for identifiers (e.g., `user_id`, `customer_name`). + - Use plural nouns for table names (e.g., `customers`, `products`). + - Use consistent naming conventions for functions, procedures, and triggers. + - Choose descriptive and meaningful names for all database objects. + +- **Data Integrity and Data Types:** + - Use appropriate data types for columns to ensure data integrity (e.g., `INTEGER`, `VARCHAR`, `TIMESTAMP`). + - Use constraints (e.g., `NOT NULL`, `UNIQUE`, `CHECK`, `FOREIGN KEY`) to enforce data integrity. + - Define primary keys for all tables. + - Use foreign keys to establish relationships between tables. + - Utilize domains to enforce data type constraints reusable across multiple columns. + +- **SQL Injection Prevention:** + - Always use parameterized queries or prepared statements to prevent SQL injection attacks. + - Sanitize user inputs before using them in SQL queries. + - Avoid constructing SQL queries by concatenating strings directly. + - Use the `quote_literal()` and `quote_ident()` functions to properly escape strings and identifiers. + +- **Transaction Management:** + - Use explicit transactions to ensure data consistency and atomicity. + - Start transactions with `BEGIN;` and end them with `COMMIT;` or `ROLLBACK;`. + - Handle transaction errors properly to prevent data corruption. + - Use savepoints to allow partial rollbacks within a transaction. + +- **Indexing:** + - Create indexes on columns frequently used in `WHERE` clauses and `JOIN` conditions. + - Avoid over-indexing, as it can slow down write operations. + - Consider using partial indexes for specific query patterns. + - Use appropriate index types (e.g., `B-tree`, `Hash`, `GIN`, `GiST`) based on the data and query requirements. + - Regularly analyze and maintain indexes using `ANALYZE` and `VACUUM`. + +- **Query Optimization:** + - Use `EXPLAIN ANALYZE` to analyze query execution plans and identify performance bottlenecks. + - Avoid using `SELECT *` and specify only the necessary columns. + - Use `JOIN` operations instead of subqueries where possible. + - Optimize `WHERE` clauses to reduce the number of rows processed. + - Consider using materialized views for frequently executed, complex queries. + - Rewrite slow performing queries with more efficient alternatives. + +- **PL/pgSQL Best Practices:** + - Keep PL/pgSQL functions and procedures short and focused. + - Use exception handling to gracefully handle errors. + - Use `RAISE NOTICE`, `RAISE WARNING`, and `RAISE EXCEPTION` for logging and error reporting. + - Avoid using cursors unless absolutely necessary; prefer set-based operations. + - Use the `STRICT` attribute to ensure that a function returns a value. + +- **Security Best Practices:** + - Grant the least privileges necessary to database users. + - Use roles to manage permissions. + - Regularly audit database activity. + - Encrypt sensitive data at rest and in transit. + - Use the `SECURITY DEFINER` attribute for functions that require elevated privileges. + - Configure appropriate authentication mechanisms (e.g., `SCRAM-SHA-256`). + +- **Connection Management:** + - Use connection pooling to reduce the overhead of establishing new connections. + - Close connections when they are no longer needed. + - Configure connection timeouts to prevent idle connections from consuming resources. + +- **Backup and Recovery:** + - Implement a robust backup and recovery strategy. + - Regularly back up the database. + - Test the recovery process to ensure it works as expected. + - Consider using replication for high availability. + +- **Code Organization and Structure:** + - Organize database objects into schemas based on functionality or application modules. + - Use version control for database scripts and migrations. + - Follow a consistent directory structure for database-related files. + +- **Common Pitfalls and Gotchas:** + - Avoid using reserved keywords as identifiers. + - Be aware of the limitations of data types (e.g., maximum length of `VARCHAR` columns). + - Handle null values carefully. + - Test database changes thoroughly before deploying them to production. + +- **Tooling and Environment:** + - Use a code editor with SQL syntax highlighting and autocompletion. + - Use a database client tool for querying and managing the database (e.g., `pgAdmin`, `DBeaver`, `psql`). + - Use a version control system (e.g., Git) to manage database scripts and migrations. + - Use a CI/CD pipeline to automate database deployments. + +- **C Coding Standards (When Extending PostgreSQL):** + - Adhere to the C99 standard. Only use language features available in the C99 standard. + - Follow PostgreSQL's source code conventions ([PostgreSQL Documentation](https://www.postgresql.org/docs/current/source-conventions.html)). + - Manage memory carefully; avoid memory leaks. + - Properly handle errors and exceptions. + - Document code thoroughly. + +- **Use Case specific optimizations:** + - Time series data: Consider timescaledb extension + - Geospatial data: Consider postgis extension + +@file ./rules/postgresql_security_rules.mdc \ No newline at end of file diff --git a/rules-mdc/database_tools/sql/prisma.mdc b/rules-mdc/database_tools/sql/prisma.mdc new file mode 100644 index 0000000..fe150b9 --- /dev/null +++ b/rules-mdc/database_tools/sql/prisma.mdc @@ -0,0 +1,190 @@ +--- +description: Enforces Prisma best practices for schema design, data access, and application security. Provides guidelines for writing efficient, secure, and maintainable Prisma applications. +globs: **/*.prisma +--- +- **General Principles:** + - **Never expose the raw Prisma client directly in APIs.** Instead, create abstraction layers (e.g., repositories or services) to handle data access logic. This protects you from accidentally exposing sensitive database details and allows you to easily change your data access implementation in the future. + - **Always use input validation** before performing any database operations. Use a validation library like Zod or Yup to ensure that user input conforms to your expected schema and data types. This helps prevent injection attacks and data corruption. + - **Implement row-level security (RLS) where applicable.** If your application handles sensitive data, use Prisma policies or database-level RLS to restrict data access based on user roles or permissions. Carefully design your policies to prevent unauthorized data access. + - **Sanitize and validate all user inputs** to prevent injection attacks, such as SQL injection. Use Prisma's built-in features to escape user input and prevent it from being interpreted as code. + +- **Code Organization and Structure:** + - **Directory Structure:** + - `prisma/`: Contains the `schema.prisma` file and any seed scripts or migrations. + - `src/`: Contains the main application code. + - `src/lib/prisma.ts`: A single module that exports an instance of the Prisma client. This promotes reuse and simplifies dependency injection. + - `src/models/`: Database model definitions as classes, abstracting Prisma calls. + - `src/repositories/`: Contains data access logic, abstracting Prisma queries. + - `src/services/`: Contains business logic, orchestrating data access through repositories. + - **File Naming Conventions:** + - Use descriptive names for files and directories that reflect their purpose. + - Use consistent naming conventions (e.g., camelCase for variables, PascalCase for components). + - **Module Organization:** + - Organize code into logical modules with clear responsibilities. + - Use dependency injection to decouple modules and improve testability. + - **Component Architecture:** + - Design components that are reusable, testable, and maintainable. + - Follow the single responsibility principle for each component. + - **Code Splitting Strategies:** + - Use dynamic imports to load code on demand and reduce initial bundle size. + - Split code based on routes, features, or user roles. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Repository Pattern:** Abstract data access logic behind repositories. + - **Service Layer Pattern:** Encapsulate business logic in service classes. + - **Unit of Work Pattern:** Manage transactions across multiple repositories. + - **Recommended Approaches:** + - Use Prisma's relation features to model complex relationships between entities. + - Use Prisma's transaction features to ensure data consistency. + - Use Prisma's filtering and sorting options to optimize queries. + - **Anti-patterns:** + - **Exposing the Prisma client directly to the client-side.** This is a major security risk. + - **Writing complex queries directly in components.** Move query logic to repositories or services. + - **Ignoring error handling.** Always handle potential errors when interacting with the database. + - **State Management:** + - Consider using a state management library like Redux, Zustand, or Jotai for complex applications. + - Use server-side data fetching for initial data loading and hydration. + - **Error Handling:** + - Use try-catch blocks to handle potential errors when interacting with the database. + - Log errors to a centralized logging system for monitoring and debugging. + - Return meaningful error messages to the client-side. + +- **Performance Considerations:** + - **Optimization Techniques:** + - Use Prisma's connection pooling to reduce database connection overhead. + - Use Prisma's batching features to reduce the number of database roundtrips. + - Optimize database queries by using indexes and filtering data on the server-side. + - **Memory Management:** + - Avoid loading large amounts of data into memory at once. Use pagination or streaming to process data in smaller chunks. + - Clean up resources after use, such as database connections and file handles. + - **Rendering Optimization:** + - Use virtualization for large lists or tables. + - Optimize images and other assets. + - **Bundle Size Optimization:** + - Use code splitting to reduce the initial bundle size. + - Remove unused code and dependencies. + - **Lazy Loading Strategies:** + - Load data on demand when it is needed. + - Use placeholders or skeletons to improve the user experience during loading. + +- **Security Best Practices:** + - **Common Vulnerabilities:** + - SQL injection: Prevented by using Prisma's prepared statements and escaping user input. + - Cross-site scripting (XSS): Prevented by sanitizing user input and output. + - Cross-site request forgery (CSRF): Prevented by using CSRF tokens. + - **Input Validation:** + - Use a validation library to validate all user input. + - Validate data types, lengths, and formats. + - **Authentication and Authorization:** + - Use a secure authentication library like NextAuth.js or Clerk. + - Implement role-based access control (RBAC) to restrict access to sensitive data and functionality. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between the client and server. + - **Secure API Communication:** + - Use API keys or tokens to authenticate API requests. + - Rate limit API requests to prevent abuse. + +- **Testing Approaches:** + - **Unit Testing:** + - Test individual components and functions in isolation. + - Use mocking and stubbing to isolate components from external dependencies. + - **Integration Testing:** + - Test the interaction between different components and modules. + - Test database interactions using a test database. + - **End-to-End Testing:** + - Test the entire application from end to end. + - Use a testing framework like Cypress or Playwright. + - **Test Organization:** + - Organize tests into logical suites based on functionality. + - Use descriptive names for tests. + - **Mocking and Stubbing:** + - Use mocking to replace external dependencies with test doubles. + - Use stubbing to control the behavior of dependencies. + +- **Common Pitfalls and Gotchas:** + - **Frequent Mistakes:** + - Forgetting to handle errors when interacting with the database. + - Exposing the Prisma client directly to the client-side. + - Writing complex queries directly in components. + - **Edge Cases:** + - Handling large datasets. + - Dealing with concurrency issues. + - Managing database migrations. + - **Version-Specific Issues:** + - Be aware of breaking changes between Prisma versions. + - Use version control to manage dependencies. + - **Compatibility Concerns:** + - Ensure that your code is compatible with different browsers and devices. + - Test your application on different environments. + - **Debugging Strategies:** + - Use logging to track down errors. + - Use a debugger to step through code. + - Use Prisma's query logging feature to inspect database queries. + +- **Tooling and Environment:** + - **Recommended Development Tools:** + - VS Code with the Prisma extension. + - Prisma Studio for visualizing and managing data. + - Docker for containerizing the application. + - **Build Configuration:** + - Use a build tool like Webpack, Parcel, or esbuild to bundle and optimize code. + - Configure the build tool to generate production-ready code. + - **Linting and Formatting:** + - Use ESLint and Prettier to enforce code style and prevent errors. + - Configure the linter and formatter to use consistent settings across the project. + - **Deployment Best Practices:** + - Use a CI/CD pipeline to automate deployments. + - Deploy to a cloud platform like Vercel, Netlify, or AWS. + - **CI/CD Integration:** + - Integrate with CI/CD tools like GitHub Actions, GitLab CI, or CircleCI. + - Run tests and linters as part of the CI/CD pipeline. + +- **Specific Prisma Configuration:** + - **Schema Design:** + - Use clear and concise names for models and fields. + - Define relationships between models using Prisma's relation features. + - Use indexes to optimize query performance. + - Consider using enums for fields with a limited set of values. + - Properly use `@id`, `@unique`, and `@relation` directives for optimal schema design. + - **Data Types:** + - Use the appropriate data types for each field. + - Use `DateTime` for storing timestamps. + - Use `Json` for storing complex data structures. + - **Prisma Client Generation:** + - Ensure your `.env` file is correctly configured for database connection. + - Regularly update the Prisma client to the latest version. + - Use `prisma generate` to generate the client after schema changes. + +- **Query Optimization:** + - **Select only the necessary fields** to reduce the amount of data transferred from the database. + - **Use `include` and `select` carefully** to optimize the query shape. + - **Avoid N+1 queries** by using Prisma's `include` or `join` features. + - **Use pagination** to limit the number of results returned by a query. + - **Use `take` and `skip`** for efficient pagination. + +- **Transaction Management:** + - **Use Prisma's `prisma.$transaction` method** to ensure atomicity of database operations. + - **Handle potential errors** within the transaction to prevent data inconsistency. + - **Keep transactions short** to minimize the impact on database performance. + +- **Seed Data Management:** + - **Create a seed script** to populate the database with initial data. + - **Use Prisma's `prisma.create` method** to create seed data. + - **Use environment variables** to configure seed data for different environments. + +- **Migration Management:** + - **Use Prisma Migrate** to manage database schema changes. + - **Create migrations** for each schema change. + - **Apply migrations** to the database using `prisma migrate deploy`. + - **Use shadow database** to test migrations before deploying them to production. + +- **Monitoring and Logging:** + - **Use Prisma's query logging feature** to monitor database queries. + - **Log errors and warnings** to a centralized logging system. + - **Monitor database performance** using tools like Prometheus or Grafana. + +- **Further Study:** + - Always refer to the [official Prisma documentation](https://www.prisma.io/docs/) for the most up-to-date information. + - Consider taking an [official Prisma course](https://www.prisma.io/learn/). \ No newline at end of file diff --git a/rules-mdc/database_tools/sql/supabase.mdc b/rules-mdc/database_tools/sql/supabase.mdc new file mode 100644 index 0000000..b81b603 --- /dev/null +++ b/rules-mdc/database_tools/sql/supabase.mdc @@ -0,0 +1,283 @@ +--- +description: Comprehensive best practices for developing with Supabase, covering code organization, performance, security, testing, and common pitfalls. This rule provides actionable guidance for developers to build robust and scalable applications using Supabase. +globs: **/*.{js,jsx,ts,tsx,sql} +--- +# Supabase Best Practices: A Comprehensive Guide + +This document outlines best practices for developing with Supabase, covering various aspects from code organization to security and performance. + +## 1. Code Organization and Structure + +A well-organized codebase is crucial for maintainability and scalability. Here's how to structure your Supabase project: + +### 1.1. Directory Structure Best Practices + +Adopt a modular structure that separates concerns: + + +project-root/ +├── src/ +│ ├── components/ # Reusable UI components +│ ├── pages/ # Page-level components (routes) +│ ├── services/ # Supabase client initialization and data fetching +│ │ ├── supabase.ts # Supabase client initialization +│ │ ├── auth.ts # Authentication-related functions +│ │ ├── database.ts # Database interaction functions +│ ├── utils/ # Utility functions (e.g., date formatting) +│ ├── types/ # TypeScript types and interfaces +│ ├── hooks/ # Custom React hooks +│ ├── styles/ # Global styles and theme +│ └── App.tsx # Main application component +├── migrations/ # Database migrations +├── tests/ # Unit and integration tests +├── .env # Environment variables +└── package.json # Project dependencies + + +### 1.2. File Naming Conventions + +* **Components:** Use PascalCase (e.g., `UserProfile.tsx`). +* **Functions:** Use camelCase (e.g., `fetchUserData`). +* **Variables:** Use camelCase (e.g., `userName`). +* **Files:** Use kebab-case (e.g., `user-profile.tsx`). + +### 1.3. Module Organization + +* Group related functionalities into modules. +* Use clear and descriptive module names. +* Export only what is necessary from each module to minimize the API surface. + +### 1.4. Component Architecture + +* Favor small, reusable components. +* Use a component-based approach (e.g., React, Vue.js) to build UIs. +* Separate presentational components from container components to improve reusability and testability. + +### 1.5. Code Splitting Strategies + +* Use dynamic imports to lazy-load modules. +* Split large components into smaller chunks. +* Implement route-based code splitting to load only the necessary code for each route. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to Supabase + +* **Repository Pattern:** Abstract database interactions behind a repository interface for better testability and maintainability. +* **Observer Pattern:** Utilize Supabase's real-time capabilities to implement reactive UIs. + +### 2.2. Recommended Approaches for Common Tasks + +* **Data Fetching:** Create reusable functions for fetching data from Supabase tables. +* **Authentication:** Use Supabase Auth for user authentication and authorization. +* **Real-time Updates:** Leverage Supabase Realtime for real-time data synchronization. +* **File Storage:** Utilize Supabase Storage for managing file uploads and downloads. + +### 2.3. Anti-patterns and Code Smells to Avoid + +* **Direct Database Access from UI Components:** This tightly couples the UI to the database and makes testing difficult. Use a service layer to abstract database interactions. +* **Overusing Supabase Functions and Policies:** Keep business logic in your application code whenever possible to avoid vendor lock-in and improve testability. +* **Manually Creating Tables Without an ORM:** Always use an ORM to manage your database schema and migrations. +* **Ignoring Error Handling:** Implement proper error handling to prevent unexpected crashes and provide informative error messages to users. +* **Storing Sensitive Data in Plain Text:** Never store sensitive data like passwords or API keys in plain text. Use encryption and secure storage mechanisms. + +### 2.4. State Management Best Practices + +* Choose a state management library (e.g., Redux, Zustand, Recoil) based on your project's complexity. +* Use local component state for simple UI state. +* Centralize application state in a global store for complex data dependencies. +* Use asynchronous actions to handle data fetching and updates. + +### 2.5. Error Handling Patterns + +* Use try-catch blocks to handle exceptions. +* Implement a global error handler to catch unhandled exceptions. +* Log errors to a monitoring service for tracking and analysis. +* Display user-friendly error messages to the user. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Indexing:** Add indexes to frequently queried columns to improve query performance. +* **Query Optimization:** Use efficient SQL queries and avoid N+1 query problems. +* **Caching:** Implement caching strategies to reduce database load. +* **Connection Pooling:** Use connection pooling to reuse database connections and reduce overhead. + +### 3.2. Memory Management + +* Avoid memory leaks by properly cleaning up resources. +* Use garbage collection to reclaim unused memory. +* Optimize data structures to reduce memory usage. + +### 3.3. Rendering Optimization + +* Use memoization techniques to prevent unnecessary re-renders. +* Virtualize long lists to improve rendering performance. +* Optimize images and other assets to reduce file sizes. + +### 3.4. Bundle Size Optimization + +* Use tree shaking to remove unused code. +* Minify code to reduce file sizes. +* Compress assets to reduce transfer times. + +### 3.5. Lazy Loading Strategies + +* Lazy load images and other assets that are not immediately visible. +* Implement infinite scrolling to load data in chunks as the user scrolls. +* Use code splitting to load only the necessary code for each route. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +* **SQL Injection:** Prevent SQL injection by using parameterized queries and prepared statements. +* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. +* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent unauthorized requests. +* **Authentication and Authorization Issues:** Secure your authentication and authorization mechanisms to prevent unauthorized access. + +### 4.2. Input Validation + +* Validate all user input to prevent malicious data from entering your system. +* Use server-side validation in addition to client-side validation. +* Sanitize user input to remove potentially harmful characters. + +### 4.3. Authentication and Authorization Patterns + +* Use Supabase Auth for user authentication and authorization. +* Implement role-based access control (RBAC) to manage user permissions. +* Use row-level security (RLS) to control data access at the row level. + +### 4.4. Data Protection Strategies + +* Encrypt sensitive data at rest and in transit. +* Use secure storage mechanisms to store API keys and other secrets. +* Implement data masking to protect sensitive data from unauthorized access. + +### 4.5. Secure API Communication + +* Use HTTPS to encrypt API traffic. +* Implement API rate limiting to prevent abuse. +* Validate API requests to prevent malicious input. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +* Write unit tests for individual functions and components. +* Use mocking and stubbing to isolate units of code. +* Aim for high code coverage. + +### 5.2. Integration Testing + +* Write integration tests to verify the interaction between different parts of your system. +* Test the integration between your application and Supabase. + +### 5.3. End-to-end Testing + +* Write end-to-end tests to simulate user interactions and verify the overall functionality of your application. +* Use tools like Cypress or Playwright to automate end-to-end tests. + +### 5.4. Test Organization + +* Organize tests into separate directories based on functionality. +* Use descriptive test names. +* Keep tests concise and focused. + +### 5.5. Mocking and Stubbing + +* Use mocking to replace external dependencies with controlled substitutes. +* Use stubbing to replace specific method calls with predefined values. +* Avoid over-mocking, as it can make tests less reliable. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +* Not using an ORM for database schema management. +* Over-relying on Supabase functions and policies for business logic. +* Using Supabase-only features without considering open-source alternatives. +* Ignoring error handling and security best practices. + +### 6.2. Edge Cases to Be Aware Of + +* Handling large datasets efficiently. +* Dealing with real-time data synchronization conflicts. +* Managing user sessions and authentication tokens securely. + +### 6.3. Version-Specific Issues + +* Be aware of breaking changes in Supabase and its dependencies. +* Test your application thoroughly after upgrading Supabase or its dependencies. +* Refer to the Supabase documentation for migration guides. + +### 6.4. Compatibility Concerns + +* Ensure compatibility between your application and the Supabase client library. +* Test your application on different browsers and devices. + +### 6.5. Debugging Strategies + +* Use browser developer tools to debug client-side code. +* Use server-side logging to track errors and performance issues. +* Use the Supabase dashboard to monitor database activity. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +* Supabase CLI: For local development and database management. +* VS Code: For code editing and debugging. +* Drizzle ORM: For database schema management. +* Postman/Insomnia: For testing API endpoints. + +### 7.2. Build Configuration + +* Use a build tool like Webpack or Parcel to bundle your code. +* Configure your build tool to optimize for production. +* Use environment variables to configure your application. + +### 7.3. Linting and Formatting + +* Use ESLint to enforce code style and prevent errors. +* Use Prettier to format your code automatically. +* Integrate linting and formatting into your development workflow. + +### 7.4. Deployment Best Practices + +* Use a CI/CD pipeline to automate deployments. +* Deploy your application to a production-ready environment. +* Monitor your application for errors and performance issues. + +### 7.5. CI/CD Integration + +* Use a CI/CD tool like GitHub Actions or GitLab CI to automate your build, test, and deployment processes. +* Configure your CI/CD pipeline to run tests and linting before deployment. +* Use environment variables to configure your application in the CI/CD environment. + +## 8. Database Workflow Design + +* **Avoid Direct Changes in Production**: Once your application is live, refrain from making database changes using the Supabase Dashboard. Instead, utilize migration tools and enforce access control to prevent unauthorized modifications. +* **Multiple Environments**: Adopt a multi-stage development workflow (`local -> staging -> prod`). This approach allows for thorough testing and validation at each stage before changes are deployed to production. +* **Point-in-Time Recovery**: As your database grows, consider moving to Point-in-Time Recovery (PITR) to minimize the impact on database performance during maintenance and ensure data safety. +* **Database Migrations**: Use database migration tools to manage schema changes. This practice helps maintain consistency across different environments and simplifies version control. +* **Access Control**: Be mindful of who has access to your production environment. Limit access to experienced team members and set clear internal workflows to mitigate risks. +* **Security**: Regularly review and update your security measures. Ensure that tables with sensitive data have appropriate access levels and that database secrets and API keys are stored securely. +* **Performance Monitoring**: Utilize Supabase's observability tooling to monitor database performance and optimize queries, indexes, and connection management. + +## 9. Additional Best Practices + +* **Understand Shared Responsibilities:** When using Supabase, be aware of the shared responsibilities model. Supabase manages infrastructure, but you are responsible for application architecture, security, and data management. +* **Proper Indexing:** Essential for query optimization. Indices should be created based on common query patterns to reduce search time. +* **Load Testing**: Before deploying changes to production, perform load testing in a staging environment. Tools such as `k6` can simulate traffic and help identify potential bottlenecks. +* **Resource Upgrades**: Monitor resource usage and upgrade your database when necessary. For significant traffic surges, contact support in advance for assistance. +* **Database Optimization**: Regularly optimize your database by adding filters on large queries, using caching strategies, and managing connections efficiently. +* **Regular Backups:** Schedule regular backups of your database to protect against data loss. +* **Use of Postgres Features**: As Supabase is built around Postgres, understand and leverage Postgres features for performance and scalability. + +## 10. Conclusion + +By following these best practices, you can build robust, scalable, and secure applications with Supabase. Remember to stay up-to-date with the latest Supabase documentation and community resources to continuously improve your development practices. + +@file ./supabase_code_examples.mdc \ No newline at end of file diff --git a/rules-mdc/development_tools/build_tools/turbopack.mdc b/rules-mdc/development_tools/build_tools/turbopack.mdc new file mode 100644 index 0000000..f449bdf --- /dev/null +++ b/rules-mdc/development_tools/build_tools/turbopack.mdc @@ -0,0 +1,188 @@ +--- +description: This rule provides comprehensive best practices for developing with Turbopack, covering code organization, performance, security, testing, and tooling to ensure efficient and maintainable applications. +globs: **/*.{js,jsx,ts,tsx} +--- +# Turbopack Best Practices + +This document outlines best practices for developing with Turbopack, focusing on code organization, performance, security, testing, and tooling. + +## 1. Core Principles + +- **Leverage the Turbo Engine:** Turbopack's core strength lies in its Turbo engine for function-level caching. Understand and utilize this for incremental builds. +- **Embrace Incremental Computation:** Be mindful of how changes affect the build process. Design your application to maximize incremental computation benefits. +- **Use TypeScript:** Turbopack has built-in support for TypeScript and JSX, so use them to improve code quality and developer experience. Make full use of TypeScript's features like generics, interfaces and types. +- **Follow Next.js Conventions:** When using Turbopack within Next.js, adhere to Next.js's recommended patterns and practices. +- **Avoid direct webpack configurations:** Turbopack aims to abstract away webpack configurations, prefer using Next.js configurations to customize Turbopack. + +## 2. Code Organization and Structure + +- **Directory Structure:** + - **`src/`:** All application source code should reside within the `src/` directory. + - **`components/`:** Reusable UI components. + - **`pages/`:** (Next.js) Pages for routing. + - **`api/`:** (Next.js) API routes. + - **`lib/` or `utils/`:** Utility functions and shared logic. + - **`types/` or `interfaces/`:** TypeScript type definitions and interfaces. + - **`styles/` or `css/`:** Global styles and CSS modules. + - **`public/`:** Static assets (images, fonts, etc.). +- **File Naming Conventions:** + - Use descriptive names for files and directories. + - Component files: `ComponentName.jsx` or `ComponentName.tsx`. + - Style files: `ComponentName.module.css` or `ComponentName.module.scss`. + - Utility files: `utilityName.js` or `utilityName.ts`. +- **Module Organization:** + - Group related code into modules with clear responsibilities. + - Export only what is necessary from each module. + - Use ES modules (import/export) for modularity. +- **Component Architecture:** + - **Atomic Design:** Consider using Atomic Design principles to create a scalable and maintainable component architecture. + - **Composition:** Favor composition over inheritance for component reusability. + - **Separation of Concerns:** Separate UI logic, data fetching, and state management within components. + - **Keep components small:** Focus on single responsability principle. +- **Code Splitting Strategies:** + - **Dynamic Imports:** Use dynamic imports (`import()`) to split code into smaller chunks that are loaded on demand. + - **Route-Based Splitting:** (Next.js) Each page in the `pages/` directory is automatically code-split. + - **Component-Based Splitting:** Split large components into smaller, lazily loaded sub-components. + - **Vendor Splitting:** Turbopack automatically splits vendor code (third-party libraries) into separate chunks. + +## 3. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Higher-Order Components (HOCs):** Reusable logic for components (use with caution, consider hooks). + - **Render Props:** Sharing code between React components using a prop whose value is a function. + - **Hooks:** Reusable stateful logic for functional components. + - **Context API:** Share data that is considered "global" for a tree of React components. +- **Recommended Approaches:** + - **Data Fetching:** Use `getServerSideProps`, `getStaticProps`, or `getInitialProps` (Next.js) for data fetching depending on your requirements. + - **API Routes:** Use Next.js API routes to create serverless functions for handling API requests. + - **State Management:** Choose a state management library (Redux, Zustand, Jotai, Recoil) based on the complexity of your application. +- **Anti-patterns:** + - **Global State Mutation:** Avoid directly mutating global state, use reducers or state management libraries. + - **Over-Fetching:** Fetch only the data that is needed by a component. + - **Tight Coupling:** Reduce dependencies between modules to improve maintainability. + - **Long Component Files:** Avoid having components larger than 200-300 lines, break down them into smaller components. +- **State Management Best Practices:** + - **Centralized State:** Manage application state in a central store. + - **Immutability:** Treat state as immutable to prevent unexpected side effects. + - **Reducers:** Use reducers to update state based on actions. + - **Selectors:** Use selectors to derive data from the state. +- **Error Handling Patterns:** + - **Error Boundaries:** Use error boundaries to catch JavaScript errors anywhere in a component tree. + - **Centralized Error Logging:** Log errors to a central service for monitoring and debugging. + - **Graceful Degradation:** Handle errors gracefully and provide informative messages to the user. + - **Retry mechanisms:** Implement retry mechanisms for failed requests. + +## 4. Performance Considerations + +- **Optimization Techniques:** + - **Caching:** Leverage Turbopack's caching capabilities to avoid unnecessary re-builds. + - **Memoization:** Use `React.memo` or `useMemo` to memoize components and values. + - **Debouncing and Throttling:** Use debouncing and throttling to reduce the frequency of function calls. +- **Memory Management:** + - **Avoid Memory Leaks:** Be careful to clean up event listeners and timers when components unmount. + - **Garbage Collection:** Understand how JavaScript garbage collection works and avoid creating unnecessary objects. +- **Rendering Optimization:** + - **Virtualization:** Use virtualization libraries for rendering large lists. + - **Code Splitting:** Split the codebase into smaller chunks using dynamic imports for faster initial load times. + - **Image Optimization:** Optimize images using tools like `next/image` or `cloudinary`. +- **Bundle Size Optimization:** + - **Tree Shaking:** Remove unused code from the bundle by using ES modules and configuring your bundler correctly. + - **Minification:** Minify JavaScript and CSS code to reduce bundle size. + - **Compression:** Compress assets using gzip or Brotli. +- **Lazy Loading Strategies:** + - **Component-Level Lazy Loading:** Lazy load components that are not initially visible. + - **Image Lazy Loading:** Lazy load images that are not initially visible. + - **Route-Based Lazy Loading:** Lazy load routes that are not frequently visited. + +## 5. Security Best Practices + +- **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and using appropriate escaping techniques. + - **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using CSRF tokens. + - **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or ORMs. + - **Authentication and Authorization Issues:** Secure your API endpoints with proper authentication and authorization mechanisms. +- **Input Validation:** + - **Validate all user input:** Sanitize and validate all user input on both the client and server. + - **Use appropriate data types:** Enforce data types to prevent unexpected values. +- **Authentication and Authorization Patterns:** + - **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization. + - **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles. + - **OAuth:** Use OAuth for third-party authentication. +- **Data Protection Strategies:** + - **Encryption:** Encrypt sensitive data at rest and in transit. + - **Data Masking:** Mask sensitive data in logs and reports. + - **Data Retention Policies:** Implement data retention policies to ensure compliance with regulations. +- **Secure API Communication:** + - **HTTPS:** Use HTTPS to encrypt communication between the client and server. + - **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks. + - **API Keys:** Use API keys for authentication. + +## 6. Testing Approaches + +- **Unit Testing Strategies:** + - **Test individual components and functions:** Write unit tests to verify the behavior of individual components and functions. + - **Use mocking and stubbing:** Use mocking and stubbing to isolate components from their dependencies. + - **Test edge cases:** Test edge cases and error conditions. +- **Integration Testing:** + - **Test the interaction between components:** Write integration tests to verify the interaction between components. + - **Test data flow:** Test the flow of data between components and services. +- **End-to-End Testing:** + - **Test the entire application flow:** Write end-to-end tests to verify the entire application flow. + - **Use browser automation tools:** Use browser automation tools like Cypress or Puppeteer. +- **Test Organization:** + - **Keep tests close to the code:** Organize tests in the same directory as the code they test. + - **Use descriptive test names:** Use descriptive test names that clearly describe what the test is verifying. +- **Mocking and Stubbing:** + - **Use mocking libraries:** Use mocking libraries like Jest or Sinon to create mocks and stubs. + - **Avoid over-mocking:** Mock only the dependencies that are necessary. + +## 7. Common Pitfalls and Gotchas + +- **Frequent Mistakes:** + - **Incorrectly configured `tsconfig.json`:** Ensure paths and baseUrl are correctly configured for absolute imports. + - **Misunderstanding caching:** Not utilizing Turbopack's caching efficiently, leading to slower builds. + - **Not using TypeScript features**: Not leveraging the benefits of Typescript and writing javascript code that misses out on typesafety. +- **Edge Cases:** + - **Complex dependencies:** Be aware of how complex dependencies can affect build times. + - **Large file sizes:** Optimize large file sizes to improve performance. +- **Version-Specific Issues:** + - **Breaking changes:** Be aware of breaking changes in Turbopack and Next.js releases. + - **Compatibility issues:** Ensure that your dependencies are compatible with the versions of Turbopack and Next.js that you are using. +- **Compatibility Concerns:** + - **Browser compatibility:** Test your application in different browsers to ensure compatibility. + - **Device compatibility:** Test your application on different devices to ensure compatibility. +- **Debugging Strategies:** + - **Use debugging tools:** Use browser developer tools and debugging tools to identify and fix issues. + - **Log statements:** Use log statements to track the flow of execution and identify errors. + - **Reproducible steps:** Create reproducible steps to help isolate and fix issues. + +## 8. Tooling and Environment + +- **Recommended Development Tools:** + - **VS Code:** A popular code editor with excellent support for JavaScript, TypeScript, and React. + - **ESLint:** A linter that helps you identify and fix code style issues. + - **Prettier:** A code formatter that automatically formats your code. + - **Chrome Developer Tools:** Powerful tools for debugging and profiling web applications. +- **Build Configuration:** + - **Configure `tsconfig.json`:** Configure `tsconfig.json` to enable TypeScript features and specify compiler options. + - **Configure ESLint:** Configure ESLint to enforce code style guidelines. + - **Configure Prettier:** Configure Prettier to automatically format code. +- **Linting and Formatting:** + - **Use ESLint and Prettier:** Use ESLint and Prettier to automatically lint and format your code. + - **Integrate with your editor:** Integrate ESLint and Prettier with your code editor to automatically lint and format code on save. +- **Deployment Best Practices:** + - **Use a CI/CD pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process. + - **Deploy to a CDN:** Deploy static assets to a CDN for faster delivery. + - **Monitor your application:** Monitor your application for errors and performance issues. +- **CI/CD Integration:** + - **Use GitHub Actions, GitLab CI, or CircleCI:** Use a CI/CD platform to automate the build, test, and deployment process. + - **Run tests in CI/CD:** Run tests in your CI/CD pipeline to ensure that code changes do not introduce new bugs. + - **Automate deployments:** Automate deployments to production and staging environments. + +## 9. Additional Considerations + +- **Experimentation:** Turbopack is rapidly evolving. Experiment with new features and configurations to optimize your build process. +- **Community Engagement:** Participate in the Turbopack community to share your experiences and learn from others. +- **Documentation:** Refer to the official Turbopack documentation for the latest information and guidance. + +By following these best practices, you can leverage the full potential of Turbopack to build high-performance, maintainable, and secure applications. \ No newline at end of file diff --git a/rules-mdc/development_tools/build_tools/vite.mdc b/rules-mdc/development_tools/build_tools/vite.mdc new file mode 100644 index 0000000..7a9d29d --- /dev/null +++ b/rules-mdc/development_tools/build_tools/vite.mdc @@ -0,0 +1,224 @@ +--- +description: This rule provides comprehensive best practices, coding standards, and guidelines for developing applications using Vite, covering aspects from code organization and performance to security and testing. +globs: **/*.{js,jsx,ts,tsx,vue,svelte} +--- +- **Introduction:** + - This document outlines best practices for developing applications using Vite, a fast and opinionated build tool that aims to provide a better development experience. + +- **Prerequisites:** + - Ensure Node.js and npm/yarn/pnpm are installed. + - Familiarity with JavaScript/TypeScript, HTML, and CSS. + +- **Code Organization and Structure:** + - **Directory Structure:** + - Adopt a modular structure based on features or components. + + src/ + ├── components/ + │ ├── Button/ + │ │ ├── Button.tsx + │ │ ├── Button.module.css + │ │ └── Button.test.tsx + │ ├── Input/ + │ │ └── ... + ├── pages/ + │ ├── Home.tsx + │ ├── About.tsx + │ └── ... + ├── services/ + │ ├── api.ts + │ └── ... + ├── utils/ + │ ├── helpers.ts + │ └── ... + ├── App.tsx + ├── main.tsx + └── vite-env.d.ts + + - **File Naming Conventions:** + - Use descriptive and consistent names. + - Component files: `ComponentName.tsx` or `component-name.tsx`. + - Style files: `ComponentName.module.css` or `component-name.module.css`. + - Test files: `ComponentName.test.tsx` or `component-name.test.tsx`. + - **Module Organization:** + - Group related files into modules or folders. + - Use `index.ts` (barrel files) to simplify imports. + typescript + // src/components/Button/index.ts + export { default as Button } from './Button'; + + - **Component Architecture:** + - Favor small, reusable components. + - Utilize functional components and hooks in React (or equivalent in Vue/Svelte). + - Separate concerns: presentational vs. container components. + - **Code Splitting Strategies:** + - Use dynamic imports (`import()`) for lazy loading. + - Split routes using `React.lazy` or Vue's dynamic component feature. + - Configure Vite's `rollupOptions.output.manualChunks` for fine-grained control. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Higher-Order Components (HOCs):** Carefully consider alternatives like render props or hooks for better composability. + - **Render Props:** Useful for sharing logic between components, but can lead to deeply nested structures. + - **Hooks:** Promote code reuse and simplify component logic. + - **Recommended Approaches:** + - Use environment variables for configuration. + - Implement a consistent API client for data fetching. + - Centralize state management using libraries like Redux, Zustand, or Vuex. + - **Anti-patterns:** + - Avoid deeply nested component trees without proper optimization. + - Don't mutate state directly; use setState or Vue's reactivity system. + - Overusing global styles; prefer CSS modules or styled components. + - **State Management:** + - Choose a state management solution based on application complexity. + - Use Redux for complex state management with predictable state transitions and time travel debugging. + - Consider Zustand or Jotai for simpler state management with a smaller bundle size. + - For Vue, Vuex or Pinia are popular choices. + - **Error Handling:** + - Implement global error boundaries to catch unhandled exceptions. + - Use try-catch blocks for local error handling. + - Log errors to a central error tracking service (e.g., Sentry, Rollbar). + +- **Performance Considerations:** + - **Optimization Techniques:** + - Use production-ready code minification and bundling. + - Optimize images and other assets using tools like `imagemin` or Vite plugins. + - **Memory Management:** + - Avoid memory leaks by properly cleaning up event listeners and subscriptions. + - Use `useEffect` with a cleanup function in React (or `onUnmounted` in Vue). + - **Rendering Optimization:** + - Use memoization techniques (`React.memo`, `useMemo`, `shouldComponentUpdate`) to prevent unnecessary re-renders. + - Virtualize large lists using libraries like `react-window` or `react-virtualized`. + - **Bundle Size Optimization:** + - Analyze bundle size using `rollup-plugin-visualizer` or similar tools. + - Remove unused code using tree shaking. + - Use code splitting to load only necessary code. + - **Lazy Loading:** + - Lazy load components and images that are not immediately visible. + - Use `IntersectionObserver` to trigger loading when elements enter the viewport. + +- **Security Best Practices:** + - **Common Vulnerabilities:** + - Cross-Site Scripting (XSS): Sanitize user input to prevent XSS attacks. + - Cross-Site Request Forgery (CSRF): Use CSRF tokens to protect against CSRF attacks. + - Injection Attacks: Validate and sanitize input to prevent SQL injection and other injection attacks. + - **Input Validation:** + - Validate all user input on both the client and server side. + - Use a library like `yup` or `joi` for schema validation. + - **Authentication and Authorization:** + - Use a secure authentication and authorization mechanism (e.g., OAuth 2.0, JWT). + - Store passwords securely using bcrypt or Argon2. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS for all communication. + - **Secure API Communication:** + - Implement proper CORS configuration to prevent unauthorized access to your API. + - Rate limit API requests to prevent abuse. + +- **Testing Approaches:** + - **Unit Testing:** + - Write unit tests for individual components and functions. + - Use testing libraries like Jest, Mocha, or Vitest. + - Mock dependencies to isolate units under test. + - **Integration Testing:** + - Test the interaction between different parts of your application. + - Use testing libraries like React Testing Library or Vue Test Utils. + - **End-to-End Testing:** + - Test the entire application from the user's perspective. + - Use tools like Cypress or Playwright. + - **Test Organization:** + - Organize tests into folders based on features or components. + - Use descriptive test names. + - **Mocking and Stubbing:** + - Use mocks and stubs to isolate units under test. + - Avoid over-mocking; test the actual implementation whenever possible. + +- **Common Pitfalls and Gotchas:** + - **Frequent Mistakes:** + - Improperly handling asynchronous operations. + - Neglecting accessibility considerations. + - Using outdated dependencies. + - **Edge Cases:** + - Handling different screen sizes and devices. + - Supporting internationalization and localization. + - Dealing with slow network connections. + - **Version-Specific Issues:** + - Be aware of breaking changes in Vite and its plugins. + - Pin dependencies to specific versions to avoid unexpected issues. + - **Compatibility Concerns:** + - Test your application in different browsers and devices. + - Use polyfills to support older browsers. + - **Debugging Strategies:** + - Use browser developer tools to inspect the DOM, network requests, and console output. + - Use debugging tools like `debugger` or `console.log`. + +- **Tooling and Environment:** + - **Recommended Tools:** + - VS Code with extensions like ESLint, Prettier, and TypeScript. + - Chrome DevTools or Firefox Developer Tools. + - npm/yarn/pnpm for package management. + - **Build Configuration:** + - Configure Vite using `vite.config.ts` or `vite.config.js`. + - Customize build options like `outDir`, `assetsDir`, and `rollupOptions`. + - **Linting and Formatting:** + - Use ESLint with recommended rulesets (e.g., `eslint:recommended`, `plugin:react/recommended`). + - Use Prettier for code formatting. + - Configure ESLint and Prettier to work together. + - **Deployment Best Practices:** + - Deploy to a CDN for optimal performance. + - Use environment variables for configuration. + - Set up proper caching headers. + - **CI/CD Integration:** + - Integrate with a CI/CD pipeline for automated testing and deployment. + - Use tools like GitHub Actions, GitLab CI, or CircleCI. + +- **TypeScript Best Practices (when using TypeScript):** + - **Strict Type-Checking:** + - Enable strict type-checking options in `tsconfig.json` (e.g., `strict: true`, `noImplicitAny: true`, `strictNullChecks: true`). + - **Typing Props and State:** + - Use interfaces or types to define the shape of props and state. + typescript + interface ButtonProps { + label: string; + onClick: () => void; + } + + const Button: React.FC = ({ label, onClick }) => { + return ; + }; + + +- **ESLint Configuration (Example):** + javascript + module.exports = { + env: { + browser: true, + es2021: true, + node: true, + }, + extends: [ + 'eslint:recommended', + 'plugin:react/recommended', + 'plugin:@typescript-eslint/recommended', + 'prettier', + ], + parser: '@typescript-eslint/parser', + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + ecmaVersion: 12, + sourceType: 'module', + }, + plugins: ['react', '@typescript-eslint', 'prettier'], + rules: { + 'prettier/prettier': 'error', + 'react/react-in-jsx-scope': 'off', + '@typescript-eslint/explicit-function-return-type': 'off', + '@typescript-eslint/no-explicit-any': 'warn', + }, + }; + + +- **Conclusion:** + - Following these best practices will help you build efficient, maintainable, and secure applications with Vite. Continuously review and update your practices as the library and ecosystem evolve. \ No newline at end of file diff --git a/rules-mdc/development_tools/build_tools/webpack.mdc b/rules-mdc/development_tools/build_tools/webpack.mdc new file mode 100644 index 0000000..f209e40 --- /dev/null +++ b/rules-mdc/development_tools/build_tools/webpack.mdc @@ -0,0 +1,281 @@ +--- +description: This rule provides comprehensive best practices for Webpack configuration, optimization, and usage within projects. It covers code organization, performance, security, testing, and common pitfalls to ensure robust and efficient builds. +globs: **/webpack.config.js +--- +# Webpack Best Practices: A Comprehensive Guide + +This guide provides a detailed set of best practices for using Webpack effectively, covering various aspects from project setup to production optimization. Following these guidelines will help you create robust, performant, and maintainable webpack configurations. + +## 1. Code Organization and Structure + +### Directory Structure Best Practices + +A well-structured directory is crucial for maintainability and scalability. Here's a recommended directory structure: + + +project-name/ +├── src/ # Source code directory +│ ├── components/ # Reusable UI components +│ ├── modules/ # Independent modules +│ ├── assets/ # Static assets (images, fonts, etc.) +│ │ ├── images/ +│ │ ├── fonts/ +│ │ └── styles/ +│ ├── index.js # Entry point of the application +│ └── ... +├── dist/ # Output directory (generated by Webpack) +├── config/ # Webpack configuration files +│ ├── webpack.common.js # Common configuration for all environments +│ ├── webpack.dev.js # Development-specific configuration +│ └── webpack.prod.js # Production-specific configuration +├── node_modules/ # Node modules (dependencies) +├── package.json # Project metadata and dependencies +├── webpack.config.js # Main webpack configuration entry point (can delegate to config/) +├── .babelrc # Babel configuration file (if using Babel) +└── ... + + +### File Naming Conventions + +* **JavaScript/JSX:** `ComponentName.js` or `ComponentName.jsx` +* **CSS/SCSS/LESS:** `ComponentName.module.css`, `ComponentName.module.scss`, or `ComponentName.module.less` (for CSS Modules) +* **Images:** `descriptive-name.jpg`, `descriptive-name.png`, `descriptive-name.svg` +* **Webpack Config:** `webpack.config.js`, `webpack.common.js`, `webpack.dev.js`, `webpack.prod.js` + +### Module Organization + +Organize modules based on functionality or feature. Use clear and descriptive names. For example: + +javascript +// src/modules/api.js +export function fetchData(url) { + // ... +} + +// src/modules/utils.js +export function formatDate(date) { + // ... +} + + +### Component Architecture + +For UI frameworks like React, Vue, or Angular, adopt a component-based architecture. Separate concerns into reusable components. Use a clear folder structure within the `components` directory (e.g., `src/components/Button/Button.jsx`). + +### Code Splitting Strategies + +* **Entry Points:** Define multiple entry points in `webpack.config.js` for different pages or sections of your application. Useful for multi-page applications. +* **Dynamic Imports:** Use `import()` syntax for lazy-loading modules or components on demand. This can significantly reduce the initial bundle size. + javascript + // Example of dynamic import + async function loadComponent() { + const { default: Component } = await import('./MyComponent'); + // ... + } + +* **SplitChunksPlugin:** Use the `SplitChunksPlugin` to extract common dependencies into separate chunks, which can be cached by the browser. Configure it in `webpack.config.js`: + javascript + // webpack.config.js + optimization: { + splitChunks: { + chunks: 'all', + cacheGroups: { + vendor: { + test: /[\\/]node_modules[\\/]/, + name: 'vendors', + chunks: 'all', + }, + }, + }, + }, + + Consider these `SplitChunksPlugin` options: + * `chunks`: `'all'` (recommended), `'async'`, or `'initial'` + * `cacheGroups`: Define rules for creating chunks (e.g., `vendor` for node_modules) + * `minSize`: Minimum size of a chunk to be created + +## 2. Common Patterns and Anti-patterns + +### Design Patterns Specific to Webpack + +* **Environment-Specific Configurations:** Use separate configuration files for development and production (e.g., `webpack.dev.js`, `webpack.prod.js`). Use `webpack-merge` to combine common configurations with environment-specific settings. +* **Loader Chains:** Configure loaders to process files in a specific order (e.g., `sass-loader` -> `css-loader` -> `style-loader`). +* **Plugin Composition:** Use multiple plugins to achieve complex build processes. + +### Recommended Approaches for Common Tasks + +* **Handling CSS:** Use CSS Modules for component-level styling. Combine with `sass-loader` or `less-loader` for pre-processing. +* **Image Optimization:** Use `image-webpack-loader` to optimize images during the build process. +* **Environment Variables:** Use `DefinePlugin` to inject environment variables into your code. + +### Anti-patterns and Code Smells to Avoid + +* **Overly Complex Configurations:** Keep configurations as simple as possible. Break down complex logic into reusable modules. +* **Large Bundles:** Avoid large bundles by using code splitting and tree shaking. +* **Ignoring Warnings/Errors:** Always address warnings and errors reported by Webpack. +* **Over-relying on Global Styles:** Prefer CSS Modules to avoid naming conflicts. + +### State Management Best Practices + +* If using a state management library like Redux or Vuex, ensure that it is correctly integrated with Webpack. +* Consider using lazy-loading for state modules to improve initial load time. + +### Error Handling Patterns + +* Use try-catch blocks to handle errors in asynchronous operations. +* Implement error boundaries in UI components to prevent crashes. +* Configure Webpack to display meaningful error messages. + +## 3. Performance Considerations + +### Optimization Techniques + +* **Tree Shaking:** Remove unused code by using ES modules and setting `optimization.usedExports: true` in `webpack.config.js`. Ensure that your code is written in ES module syntax (e.g., `import` and `export`). +* **Minification:** Use TerserPlugin (included by default in production mode) or other minification plugins to reduce bundle size. +* **Code Splitting:** Split your code into smaller chunks to improve initial load time (see Code Splitting Strategies above). +* **Compression:** Use Gzip or Brotli compression on your server to reduce the size of transferred files. +* **Caching:** Leverage browser caching by using content hashes in filenames (e.g., `[name].[contenthash].js`). + +### Memory Management + +* Be mindful of memory usage during the build process, especially when using loaders that perform complex transformations. +* Consider using `thread-loader` to offload expensive loaders to a worker pool. + +### Rendering Optimization + +* Optimize images and other assets to reduce their size. +* Use lazy-loading for images and components that are not immediately visible. + +### Bundle Size Optimization + +* Analyze your bundle size using `webpack-bundle-analyzer` to identify large dependencies. +* Remove unnecessary dependencies. +* Use smaller alternatives to large libraries when possible. + +### Lazy Loading Strategies + +* Implement lazy-loading for routes, components, and modules that are not critical for the initial load. +* Use the `React.lazy` or `Vue.component` with a dynamic `import()` to lazy load components. + +## 4. Security Best Practices + +### Common Vulnerabilities and How to Prevent Them + +* **Dependency Vulnerabilities:** Use `npm audit` or `yarn audit` to identify and fix vulnerabilities in your dependencies. Consider using tools like Snyk or Dependabot for automated vulnerability scanning. +* **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks. Be especially careful when using `dangerouslySetInnerHTML` in React. +* **Security Misconfiguration:** Ensure that your Webpack configuration does not expose sensitive information (e.g., API keys). + +### Input Validation + +* Validate user inputs on both the client and server sides. +* Use appropriate validation libraries to prevent injection attacks. + +### Authentication and Authorization Patterns + +* Implement secure authentication and authorization mechanisms. +* Use HTTPS to encrypt communication between the client and server. +* Store sensitive data securely using environment variables and secret management tools. + +### Data Protection Strategies + +* Encrypt sensitive data at rest and in transit. +* Use secure storage mechanisms to protect user data. +* Follow data privacy regulations (e.g., GDPR, CCPA). + +### Secure API Communication + +* Use HTTPS for all API communication. +* Implement proper authentication and authorization for API endpoints. +* Validate API responses to prevent data injection. + +## 5. Testing Approaches + +### Unit Testing Strategies + +* Write unit tests for individual modules and components. +* Use testing frameworks like Jest, Mocha, or Jasmine. +* Mock external dependencies to isolate units under test. + +### Integration Testing + +* Write integration tests to verify the interaction between different modules and components. +* Use tools like Cypress or Puppeteer for end-to-end testing. + +### End-to-end Testing + +* Write end-to-end tests to simulate user interactions and verify the overall functionality of the application. +* Use testing frameworks like Selenium or Playwright. + +### Test Organization + +* Organize tests in a clear and consistent manner (e.g., `src/components/Button/Button.test.js`). +* Use descriptive test names. + +### Mocking and Stubbing + +* Use mocking and stubbing to isolate units under test and simulate external dependencies. +* Use mocking libraries like Jest's `jest.mock()` or Sinon.js. + +## 6. Common Pitfalls and Gotchas + +### Frequent Mistakes Developers Make + +* **Incorrect Loader Configuration:** Double-check the order and configuration of loaders. +* **Missing Dependencies:** Ensure that all required dependencies are installed. +* **Ignoring Cache:** Leverage caching to speed up build times. +* **Not Understanding Context:** Ensure loaders and plugins are applied to the correct files by using `include` and `exclude` options. + +### Edge Cases to Be Aware Of + +* **Circular Dependencies:** Avoid circular dependencies, which can lead to unexpected behavior. +* **Large Files:** Optimize large files (e.g., images, videos) to reduce bundle size. +* **Conflicting Plugins:** Ensure that plugins do not conflict with each other. + +### Version-Specific Issues + +* Be aware of breaking changes in Webpack versions. +* Consult the Webpack documentation for version-specific information. + +### Compatibility Concerns + +* Test your application in different browsers and devices to ensure compatibility. +* Use Babel to transpile your code to older JavaScript versions. + +### Debugging Strategies + +* Use source maps to debug your code in the browser. +* Use the `console.log` statement to inspect variables and data structures. +* Use the Webpack Dev Server's hot module replacement (HMR) feature for faster development cycles. + +## 7. Tooling and Environment + +### Recommended Development Tools + +* **Code Editor:** VS Code, Sublime Text, Atom +* **Browser:** Chrome, Firefox, Safari +* **Node.js:** Latest LTS version +* **NPM/Yarn:** Package managers + +### Build Configuration + +* Use separate configuration files for development and production (e.g., `webpack.dev.js`, `webpack.prod.js`). +* Use `webpack-merge` to combine common configurations with environment-specific settings. + +### Linting and Formatting + +* Use ESLint and Prettier to enforce code style and catch errors early. +* Integrate linting and formatting into your build process. + +### Deployment Best Practices + +* Use a CI/CD pipeline to automate the deployment process. +* Deploy your application to a production-ready environment (e.g., AWS, Azure, Google Cloud). +* Use a CDN to serve static assets. + +### CI/CD Integration + +* Integrate Webpack into your CI/CD pipeline to automate the build, test, and deployment processes. +* Use tools like Jenkins, Travis CI, or CircleCI. +* Automate dependency updates using tools like Dependabot. + +By following these best practices, you can ensure that your Webpack configurations are robust, performant, and maintainable. \ No newline at end of file diff --git a/rules-mdc/development_tools/ci_cd/github-actions.mdc b/rules-mdc/development_tools/ci_cd/github-actions.mdc new file mode 100644 index 0000000..f8d440f --- /dev/null +++ b/rules-mdc/development_tools/ci_cd/github-actions.mdc @@ -0,0 +1,261 @@ +--- +description: This rule provides comprehensive guidelines for GitHub Actions development, covering best practices, coding standards, performance, security, and testing. It aims to ensure efficient, reliable, secure, and maintainable workflows. +globs: .github/workflows/*.yml +--- +# GitHub Actions Best Practices and Coding Standards + +This guide provides comprehensive guidelines for developing efficient, reliable, secure, and maintainable GitHub Actions workflows. It covers various aspects of GitHub Actions development, including code organization, common patterns, performance considerations, security best practices, testing approaches, and tooling. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure Best Practices + +- **Workflows Directory:** Store all workflow files in the `.github/workflows` directory. This is the standard location recognized by GitHub. +- **Reusable Actions Directory (Optional):** If you create custom reusable actions, consider storing them in a dedicated directory like `actions/` within your repository. +- **Scripts Directory (Optional):** For complex workflows, you might have supporting scripts (e.g., shell scripts, Python scripts). Store these in a `scripts/` directory. +- **Example Directory Structure:** + + + .github/ + └── workflows/ + ├── main.yml + ├── deploy.yml + └── release.yml + actions/ + ├── my-custom-action/ + │ ├── action.yml + │ └── index.js + scripts/ + ├── cleanup.sh + └── build.py + + +### 1.2 File Naming Conventions + +- **Workflow Files:** Use descriptive and consistent names for workflow files (e.g., `deploy-staging.yml`, `code-analysis.yml`). Avoid generic names like `main.yml` if possible, especially in repositories with multiple workflows. +- **Action Files:** Name action files `action.yml` or `action.yaml` to clearly indicate their purpose. +- **Script Files:** Use appropriate extensions for scripts (e.g., `.sh` for shell scripts, `.py` for Python scripts). + +### 1.3 Module Organization + +- **Reusable Workflows:** Break down complex workflows into smaller, reusable workflows using the `uses:` syntax. This promotes modularity, reduces duplication, and improves maintainability. +- **Composite Actions:** For reusable steps within a workflow, consider creating composite actions. These group multiple steps into a single action. +- **Modular Scripts:** If you're using scripts, organize them into modules or functions for better readability and reusability. + +### 1.4 Component Architecture + +- **Workflow as a Component:** Treat each workflow as a self-contained component responsible for a specific task (e.g., building, testing, deploying). +- **Separation of Concerns:** Separate concerns within a workflow. For example, use different jobs for building, testing, and deploying. +- **Inputs and Outputs:** Define clear inputs and outputs for reusable workflows and composite actions to improve their composability. + +### 1.5 Code Splitting Strategies + +- **Job Splitting:** Divide a workflow into multiple jobs that run in parallel to reduce overall execution time. +- **Step Splitting:** Break down long-running steps into smaller, more manageable steps. +- **Conditional Execution:** Use `if:` conditions to conditionally execute jobs or steps based on specific criteria (e.g., branch name, file changes). + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to GitHub Actions + +- **Fan-out/Fan-in:** Use matrix builds to parallelize testing across different environments, then aggregate the results in a subsequent job. +- **Workflow Orchestration:** Use reusable workflows to orchestrate complex processes involving multiple steps and dependencies. +- **Event-Driven Workflows:** Trigger workflows based on specific GitHub events (e.g., push, pull request, issue creation) to automate tasks. +- **Policy Enforcement:** Implement workflows that enforce coding standards, security policies, or other organizational guidelines. + +### 2.2 Recommended Approaches for Common Tasks + +- **Dependency Caching:** Use the `actions/cache` action to cache dependencies (e.g., npm packages, Maven artifacts) to speed up subsequent workflow runs. +- **Secret Management:** Store sensitive information (e.g., API keys, passwords) as GitHub Secrets and access them in your workflows using the `${{ secrets.SECRET_NAME }}` syntax. Never hardcode secrets in your workflow files. +- **Artifact Storage:** Use the `actions/upload-artifact` and `actions/download-artifact` actions to store and retrieve build artifacts (e.g., compiled binaries, test reports). +- **Environment Variables:** Use environment variables to configure workflows and steps. Set environment variables at the workflow, job, or step level. +- **Workflow Status Badges:** Add workflow status badges to your repository's README file to provide a visual indication of the workflow's health. + +### 2.3 Anti-patterns and Code Smells to Avoid + +- **Hardcoding Secrets:** Never hardcode secrets directly in your workflow files. Use GitHub Secrets instead. +- **Ignoring Errors:** Don't ignore errors or warnings in your workflows. Implement proper error handling to ensure workflows fail gracefully. +- **Overly Complex Workflows:** Avoid creating overly complex workflows that are difficult to understand and maintain. Break them down into smaller, reusable workflows. +- **Lack of Testing:** Don't skip testing your workflows. Implement unit tests, integration tests, and end-to-end tests to ensure they function correctly. +- **Unnecessary Dependencies:** Avoid including unnecessary dependencies in your workflows. This can increase build times and introduce security vulnerabilities. +- **Directly Modifying `GITHUB_PATH` or `GITHUB_ENV`:** While these environment variables exist, using the recommended step outputs is preferred for cleaner, more robust interaction with other steps. + +### 2.4 State Management Best Practices + +- **Artifacts:** Use artifacts for persisting files between jobs. Upload at the end of one job, download at the start of another. +- **Environment Variables:** Define environment variables at the workflow or job level to pass configuration settings between steps. +- **Outputs:** Use step outputs to pass data between steps within a job. +- **GitHub API:** Use the GitHub API to store and retrieve data related to your workflows (e.g., workflow run status, deployment information). +- **External Databases:** For more complex state management requirements, consider using an external database. + +### 2.5 Error Handling Patterns + +- **`if: always()`:** Ensures a step runs even if a previous step failed, useful for cleanup or notification tasks. `if: always()` should be used with caution, as it can mask underlying issues. +- **`continue-on-error: true`:** Allows a job to continue even if a step fails. This is useful for non-critical steps or when you want to collect information about multiple failures before failing the workflow. +- **`try...catch...finally` (within Scripts):** Use `try...catch...finally` blocks in your scripts to handle exceptions and ensure proper cleanup. +- **Notifications:** Send notifications (e.g., email, Slack) when workflows fail or succeed to keep stakeholders informed. +- **Workflow Retries:** Consider using the `retry:` keyword to automatically retry failed jobs. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Caching:** Use the `actions/cache` action aggressively to cache dependencies and intermediate build artifacts. +- **Concurrency:** Use concurrency to prevent multiple workflows from running at the same time. +- **Parallel Execution:** Run jobs in parallel to reduce overall execution time. +- **Optimized Images:** Optimize images before uploading them to your repository to reduce their size. +- **Minify Code:** Minify JavaScript and CSS files to reduce their size. + +### 3.2 Memory Management + +- **Resource Limits:** Be aware of the resource limits imposed by GitHub Actions runners. Monitor memory and CPU usage to prevent workflows from exceeding these limits. +- **Garbage Collection:** Ensure that your scripts and actions properly manage memory and avoid memory leaks. +- **Large Datasets:** If you're processing large datasets, consider using streaming techniques or splitting the data into smaller chunks. + +### 3.3 Rendering Optimization + +- N/A - Not typically relevant for GitHub Actions workflows themselves, but may be applicable to applications built and deployed by workflows. + +### 3.4 Bundle Size Optimization + +- N/A - Not typically relevant for GitHub Actions workflows themselves, but may be applicable to applications built and deployed by workflows. + +### 3.5 Lazy Loading Strategies + +- N/A - Not typically relevant for GitHub Actions workflows themselves, but may be applicable to applications built and deployed by workflows. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **Code Injection:** Prevent code injection by validating all inputs and sanitizing data before using it in scripts or commands. +- **Secret Exposure:** Avoid exposing secrets in logs or error messages. Mask secrets using the `::add-mask::` command. +- **Third-Party Actions:** Carefully vet third-party actions before using them in your workflows. Pin actions to specific versions or commits to prevent unexpected changes. +- **Privilege Escalation:** Run workflows with the least privileges necessary to perform their tasks. +- **Workflow Command Injection:** Be cautious when dynamically constructing commands. If possible, use parameters or environment variables instead of concatenating strings. + +### 4.2 Input Validation + +- **Validate Inputs:** Validate all inputs to your workflows and actions to prevent malicious data from being processed. +- **Data Sanitization:** Sanitize data before using it in scripts or commands to prevent code injection vulnerabilities. +- **Regular Expressions:** Use regular expressions to validate the format of inputs. + +### 4.3 Authentication and Authorization Patterns + +- **GitHub Tokens:** Use GitHub tokens to authenticate with the GitHub API. Grant tokens the minimum necessary permissions. +- **Service Accounts:** Use service accounts to authenticate with external services. Store service account credentials as GitHub Secrets. +- **Role-Based Access Control (RBAC):** Implement RBAC to control access to your workflows and actions. + +### 4.4 Data Protection Strategies + +- **Encryption:** Encrypt sensitive data at rest and in transit. +- **Data Masking:** Mask sensitive data in logs and error messages. +- **Data Retention:** Establish a data retention policy to ensure that sensitive data is not stored indefinitely. + +### 4.5 Secure API Communication + +- **HTTPS:** Use HTTPS for all API communication. +- **TLS:** Use TLS encryption to protect data in transit. +- **API Keys:** Protect API keys and other credentials. Store them as GitHub Secrets and use them securely in your workflows. +- **Rate Limiting:** Implement rate limiting to prevent abuse of your APIs. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- **Test Reusable Actions:** Unit test your custom reusable actions to ensure they function correctly. +- **Test Scripts:** Unit test your scripts to ensure they handle different inputs and edge cases correctly. +- **Mock Dependencies:** Use mocking to isolate units of code and test them in isolation. + +### 5.2 Integration Testing + +- **Test Workflow Integration:** Integrate test your workflows to ensure that all components work together correctly. +- **Test API Integrations:** Test your integrations with external APIs to ensure they function correctly. +- **Test Database Integrations:** Test your integrations with databases to ensure data is read and written correctly. + +### 5.3 End-to-end Testing + +- **Full Workflow Tests:** Run end-to-end tests to verify that your workflows function correctly from start to finish. +- **Simulate Real-World Scenarios:** Simulate real-world scenarios to ensure that your workflows can handle different situations. + +### 5.4 Test Organization + +- **Dedicated Test Directory:** Create a dedicated `tests/` directory for your tests. +- **Test Naming Conventions:** Follow consistent naming conventions for your test files and functions. +- **Test Suites:** Organize your tests into test suites based on functionality or component. + +### 5.5 Mocking and Stubbing + +- **Mock External Services:** Mock external services to isolate your tests from external dependencies. +- **Stub Functions:** Stub functions to control the behavior of dependencies during testing. +- **Mock GitHub API:** Mock the GitHub API to test your workflows without making real API calls. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Incorrect Syntax:** YAML syntax can be tricky. Use a linter or validator to catch syntax errors. +- **Incorrect Indentation:** Indentation is crucial in YAML. Use consistent indentation throughout your workflow files. +- **Missing Permissions:** Grant workflows the necessary permissions to access resources (e.g., repository contents, secrets). +- **Typos in Secrets:** Double-check the names of your secrets to avoid typos. +- **Not Pinning Action Versions:** Always pin actions to specific versions or commits to prevent unexpected changes. + +### 6.2 Edge Cases to Be Aware Of + +- **Rate Limits:** Be aware of GitHub API rate limits. Implement retry logic to handle rate limit errors. +- **Concurrent Workflow Runs:** Handle concurrent workflow runs gracefully to avoid conflicts. +- **Network Issues:** Implement error handling to handle network issues and transient errors. +- **Large File Sizes:** Be aware of the maximum file sizes supported by GitHub Actions. + +### 6.3 Version-Specific Issues + +- **Action Compatibility:** Ensure that your actions are compatible with the version of GitHub Actions you are using. +- **Runner Images:** Be aware of the changes in runner images and update your workflows accordingly. + +### 6.4 Compatibility Concerns + +- **Cross-Platform Compatibility:** Ensure that your workflows are compatible with different operating systems (e.g., Linux, Windows, macOS). +- **Browser Compatibility:** If your workflows involve web applications, test them in different browsers. + +### 6.5 Debugging Strategies + +- **Workflow Logs:** Examine workflow logs to identify errors and warnings. +- **Debugging Actions:** Use debugging actions to inspect the state of your workflows. +- **Step-by-Step Debugging:** Insert `echo` statements or debugging actions to trace the execution of your workflows step by step. +- **Local Testing:** Use tools like `act` to test your workflows locally before pushing them to GitHub. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **VS Code with GitHub Actions Extension:** Use VS Code with the GitHub Actions extension for syntax highlighting, code completion, and validation. +- **GitHub CLI:** Use the GitHub CLI to interact with the GitHub API from your workflows. +- **`act`:** Use `act` to test your workflows locally. +- **YAML Linter:** Use a YAML linter to catch syntax errors in your workflow files. + +### 7.2 Build Configuration + +- **`.github/workflows/`:** Place all workflow files in this directory. +- **`action.yml`:** For reusable actions, define their metadata in this file. + +### 7.3 Linting and Formatting + +- **YAML Lint:** Use a YAML linting tool to enforce consistent formatting and catch syntax errors. +- **Shellcheck:** Use Shellcheck to lint your shell scripts. +- **Prettier:** Use Prettier to format your JavaScript and CSS files. + +### 7.4 Deployment Best Practices + +- **Environment Variables:** Use environment variables to configure your deployments. +- **Deployment Strategies:** Use appropriate deployment strategies (e.g., blue/green deployment, canary deployment) to minimize downtime. +- **Rollback Strategies:** Implement rollback strategies to revert to a previous version if a deployment fails. + +### 7.5 CI/CD Integration + +- **Continuous Integration (CI):** Run automated tests on every commit to ensure code quality. +- **Continuous Delivery (CD):** Automate the deployment process to deliver new features and bug fixes to users quickly. +- **Automated Releases:** Automate the release process to create and publish releases automatically. + +## Conclusion + +By following these best practices and coding standards, you can create efficient, reliable, secure, and maintainable GitHub Actions workflows. Remember to adapt these guidelines to your specific needs and context. Continuously review and improve your workflows to ensure they meet your evolving requirements. \ No newline at end of file diff --git a/rules-mdc/development_tools/containerization/docker.mdc b/rules-mdc/development_tools/containerization/docker.mdc new file mode 100644 index 0000000..c6b7a43 --- /dev/null +++ b/rules-mdc/development_tools/containerization/docker.mdc @@ -0,0 +1,217 @@ +--- +description: This rule file provides comprehensive guidance on Docker best practices, covering Dockerfile construction, image optimization, and security considerations. It aims to improve the efficiency, maintainability, and security of Docker-based projects. +globs: **/{Dockerfile,docker-compose.yml,*.dockerfile} +--- +# Docker Best Practices + +This document provides comprehensive guidance on Docker best practices, covering Dockerfile construction, image optimization, security considerations, and more. It aims to improve the efficiency, maintainability, and security of Docker-based projects. + +## 1. Code Organization and Structure + +- **Directory Structure Best Practices:** + - Organize your project with a clear separation of concerns. For example: + + project-root/ + ├── Dockerfile # Dockerfile for building the image + ├── docker-compose.yml # Docker Compose file for multi-container setup + ├── .dockerignore # Specifies intentionally untracked files that Docker should ignore + ├── app/ # Application source code + │ ├── ... + ├── config/ # Configuration files + │ ├── ... + ├── data/ # Data files (if any, though consider volumes) + │ ├── ... + ├── scripts/ # Scripts for building, deploying, or managing the container + │ ├── ... + + - Keep the `Dockerfile` and `docker-compose.yml` at the root of your project for easy access. + +- **File Naming Conventions:** + - Use descriptive names for your Dockerfiles (e.g., `Dockerfile.web`, `Dockerfile.api`). + - Follow a consistent naming convention for all files and directories. + +- **Module Organization:** + - Structure your application into modular components to improve reusability and maintainability. This directly affects what goes into a docker image. + - Use appropriate build tools (e.g., Maven, Gradle, npm) to manage dependencies and package your application. + +- **Component Architecture:** + - Design your application as a set of microservices or components, each running in its own container, when appropriate. + - Use Docker Compose to orchestrate multi-container applications. + +- **Code Splitting Strategies:** + - Break down large applications into smaller, more manageable parts to reduce image size and improve build times. + - Consider multi-stage builds to include build-time dependencies in one stage and only the runtime dependencies in the final image. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns Specific to Docker:** + - **Sidecar Pattern:** Run a utility container alongside your main application container (e.g., for logging, monitoring). + - **Ambassador Pattern:** Proxy requests to a service running outside the container. + - **Adapter Pattern:** Adapt the interface of a service to match the expected interface of a client. + - **Init Container Pattern:** Run initialization tasks before the main application container starts. Often used to set up configuration, prepare databases, etc. + +- **Recommended Approaches for Common Tasks:** + - **Configuration Management:** Use environment variables to configure your application. + - **Logging:** Centralize logging using a logging driver or a dedicated logging container (e.g., Fluentd, Logstash). + - **Health Checks:** Implement health checks to ensure that your services are running correctly. + - **Process Management:** Use a process manager (e.g., `tini`, `dumb-init`) to handle signal forwarding and zombie process reaping. + +- **Anti-patterns and Code Smells to Avoid:** + - **Storing secrets in Dockerfile or images:** Never hardcode passwords or API keys in your Dockerfile. + - **Running services as root:** Avoid running your application as the root user. + - **Installing unnecessary packages:** Keep your images lean by only installing the required dependencies. + - **Ignoring `.dockerignore`:** Make sure to use `.dockerignore` to exclude unnecessary files from the build context, reducing image size and build time. + - **Using `ADD` instead of `COPY` unnecessarily:** `COPY` is usually more transparent and predictable. + +- **State Management Best Practices:** + - **Stateless Applications:** Design your application to be stateless whenever possible. + - **Volumes:** Use volumes for persistent storage (e.g., databases, logs). + - **Bind Mounts:** Use bind mounts for development to allow code changes to be reflected immediately in the container. + +- **Error Handling Patterns:** + - Implement robust error handling in your application. + - Use appropriate logging levels to capture errors and warnings. + - Implement retry mechanisms for transient errors. + - Monitor your application for errors and take corrective actions. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - **Multi-stage builds:** Use multi-stage builds to create smaller, more efficient images. + - **Minimize layers:** Combine multiple commands into a single layer using `&&`. + - **Use a lightweight base image:** Choose a minimal base image like Alpine Linux. + - **Optimize caching:** Order your Dockerfile commands to maximize cache reuse. + +- **Memory Management:** + - Set memory limits for your containers to prevent them from consuming excessive resources. + - Monitor memory usage and optimize your application accordingly. + +- **Rendering Optimization (if applicable):** + - If your application involves rendering, optimize the rendering process (e.g., using caching, lazy loading). + +- **Bundle Size Optimization:** + - Minimize the size of your application bundle by removing unnecessary dependencies and assets. + - Use tools like webpack or Parcel to optimize your bundle. + +- **Lazy Loading Strategies:** + - Implement lazy loading for resources that are not immediately needed. + +## 4. Security Best Practices + +- **Common Vulnerabilities and How to Prevent Them:** + - **Image vulnerabilities:** Regularly scan your images for vulnerabilities using tools like Clair or Trivy. + - **Configuration vulnerabilities:** Secure your container configurations to prevent unauthorized access. + - **Network vulnerabilities:** Limit network exposure and use network policies to isolate containers. + - **Privilege escalation:** Avoid running containers with unnecessary privileges. + +- **Input Validation:** + - Validate all input data to prevent injection attacks. + +- **Authentication and Authorization Patterns:** + - Implement robust authentication and authorization mechanisms. + - Use secure protocols like HTTPS. + - Store secrets securely using tools like HashiCorp Vault or Kubernetes Secrets. + +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use appropriate access control mechanisms to protect data. + +- **Secure API Communication:** + - Use secure protocols like HTTPS for API communication. + - Implement authentication and authorization for API endpoints. + - Rate limit API requests to prevent abuse. + +## 5. Testing Approaches + +- **Unit Testing Strategies:** + - Write unit tests to verify the functionality of individual components. + - Use mocking and stubbing to isolate components during testing. + +- **Integration Testing:** + - Write integration tests to verify the interaction between different components. + - Test the integration with external services and databases. + +- **End-to-end Testing:** + - Write end-to-end tests to verify the entire application flow. + - Use tools like Selenium or Cypress to automate end-to-end tests. + +- **Test Organization:** + - Organize your tests into a clear and maintainable structure. + - Use descriptive names for your test cases. + +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate components during testing. + - Mock external services and databases to simulate different scenarios. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes Developers Make:** + - **Not using `.dockerignore`:** This can lead to large image sizes and slow build times. + - **Not pinning package versions:** This can lead to unexpected build failures due to dependency updates. + - **Exposing unnecessary ports:** This can increase the attack surface of your application. + - **Not cleaning up after installing packages:** This can lead to larger image sizes. + - **Using the shell form of `CMD` or `ENTRYPOINT`:** Use the exec form (`["executable", "param1", "param2"]`) to avoid shell injection vulnerabilities and signal handling issues. + +- **Edge Cases to Be Aware Of:** + - **File permissions:** Ensure that your application has the correct file permissions. + - **Timezone configuration:** Configure the correct timezone for your container. + - **Resource limits:** Set appropriate resource limits for your containers. + +- **Version-Specific Issues:** + - Be aware of version-specific issues and compatibility concerns. + - Test your application with different Docker versions to ensure compatibility. + +- **Compatibility Concerns:** + - Ensure that your application is compatible with the base image you are using. + - Test your application on different platforms to ensure cross-platform compatibility. + +- **Debugging Strategies:** + - Use `docker logs` to view container logs. + - Use `docker exec` to execute commands inside a running container. + - Use `docker inspect` to inspect container metadata. + - Use a debugger to debug your application code. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - **Docker Desktop:** For local development and testing. + - **Docker Compose:** For orchestrating multi-container applications. + - **Visual Studio Code with Docker extension:** For enhanced Docker development experience. + - **Container image scanners (e.g., Trivy, Clair):** For identifying vulnerabilities in container images. + +- **Build Configuration:** + - Use a consistent build configuration for all your images. + - Automate the build process using a build tool (e.g., Make, Gradle). + +- **Linting and Formatting:** + - Use a linter to enforce code style and best practices. + - Use a formatter to automatically format your code. + +- **Deployment Best Practices:** + - Use a container orchestration platform like Kubernetes or Docker Swarm. + - Implement rolling updates and rollbacks. + - Monitor your application for performance and availability. + +- **CI/CD Integration:** + - Integrate Docker into your CI/CD pipeline. + - Automate the build, test, and deployment process. + - Use tools like Jenkins, GitLab CI, or CircleCI. + +--- + +## Additional Notes: + +- Always use a specific tag for the base image (e.g., `ubuntu:20.04`) instead of `latest` to ensure reproducibility. +- Use `.dockerignore` to exclude files and directories that are not needed in the image. This reduces the image size and improves build performance. +- When possible, use the official Docker images from Docker Hub. They are usually well-maintained and optimized. +- Consider using a tool like `docker-slim` to further reduce the size of your Docker images by removing unnecessary files and dependencies after the build process. +- Understand the Docker build context and ensure you're only including necessary files and directories. A large build context slows down builds and increases image sizes. +- Regularly update your base images to patch security vulnerabilities. +- Use environment variables to configure your application, making it more flexible and portable. +- Implement health checks in your Dockerfiles to ensure that your containers are running correctly. This can be done using the `HEALTHCHECK` instruction. +- Consider using a private Docker registry to store your images securely. +- Document your Dockerfiles and images to make them easier to understand and maintain. +- Review your Dockerfiles regularly to ensure they are up-to-date and following best practices. +- Consider using a Dockerfile linter like `hadolint` to identify potential issues and enforce best practices. + +By following these guidelines, you can create efficient, maintainable, and secure Docker-based applications. \ No newline at end of file diff --git a/rules-mdc/development_tools/containerization/kubernetes.mdc b/rules-mdc/development_tools/containerization/kubernetes.mdc new file mode 100644 index 0000000..90eab77 --- /dev/null +++ b/rules-mdc/development_tools/containerization/kubernetes.mdc @@ -0,0 +1,353 @@ +--- +description: This rule provides comprehensive best practices for developing and maintaining Kubernetes applications and infrastructure, covering coding standards, security, performance, testing, and deployment. +globs: **/*.{go,yaml,yml,sh,tf,tfvars,json} +--- +# Kubernetes Development and Operations Best Practices + +This document outlines a collection of guidelines, style suggestions, and tips for writing code and managing infrastructure within the Kubernetes ecosystem. It emphasizes clarity, maintainability, security, and performance. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +- **Root Level:** + - `cmd/`: Main application entry points. Each subdirectory represents a separate command-line tool or service. + - `pkg/`: Reusable libraries and components that can be imported by other projects. + - `internal/`: Private code that should not be imported by external projects. Enforces encapsulation. + - `api/`: API definitions, including protobuf files and OpenAPI specifications. + - `config/`: Configuration files, such as YAML manifests, Kustomize configurations, and Helm charts. + - `scripts/`: Utility scripts for building, testing, and deploying the application. + - `docs/`: Documentation for the project. + - `examples/`: Example usage of the library or application. + - `vendor/`: (If using `go modules` without external dependency management) Contains vendored dependencies. Generally discouraged in modern Go with `go modules`. +- **Component-Specific Directories:** Inside `pkg/` or `internal/`, organize code by component or module. Each component should have its own directory with clear separation of concerns. + +Example: + + +my-kubernetes-project/ +├── cmd/ +│ └── controller/ +│ └── main.go +├── pkg/ +│ └── api/ +│ ├── types.go +│ └── controller/ +│ ├── controller.go +│ ├── reconciler.go +│ └── util/ +│ └── util.go +├── internal/ +│ └── admission/ +│ └── webhook.go +├── config/ +│ ├── deploy/ +│ │ └── deployment.yaml +│ └── kustomize/ +│ ├── base/ +│ │ ├── kustomization.yaml +│ │ └── ... +│ └── overlays/ +│ ├── dev/ +│ │ ├── kustomization.yaml +│ │ └── ... +│ └── prod/ +│ ├── kustomization.yaml +│ └── ... +├── scripts/ +│ └── build.sh +├── docs/ +│ └── architecture.md +└── go.mod + + +### 1.2 File Naming Conventions + +- **Go Files:** Use lowercase with underscores (e.g., `my_controller.go`). +- **YAML Files:** Use lowercase with dashes (e.g., `deployment.yaml`). +- **Configuration Files:** Be descriptive and consistent (e.g., `config.yaml`, `kustomization.yaml`). +- **Test Files:** Follow the standard Go convention: `*_test.go` (e.g., `my_controller_test.go`). + +### 1.3 Module Organization (Go) + +- **Packages:** Organize code into meaningful packages that represent logical units of functionality. +- **Internal Packages:** Use `internal/` directories to create packages that are only visible within the project. +- **Interfaces:** Define interfaces to abstract dependencies and promote testability. + +### 1.4 Component Architecture + +- **Microservices:** Design applications as a collection of loosely coupled microservices. +- **Separation of Concerns:** Each component should have a single responsibility and well-defined interfaces. +- **API Gateway:** Use an API gateway to handle routing, authentication, and rate limiting for external requests. +- **Service Mesh:** Consider using a service mesh (e.g., Istio, Linkerd) to manage inter-service communication, observability, and security. + +### 1.5 Code Splitting Strategies + +- **Feature-Based Splitting:** Group code by feature or functionality. +- **Layer-Based Splitting:** Separate code into layers, such as data access, business logic, and presentation. +- **Component-Based Splitting:** Divide code into reusable components that can be shared across multiple projects. + +## 2. Common Patterns and Anti-Patterns + +### 2.1 Design Patterns + +- **Controller Pattern:** Implement controllers to reconcile the desired state of Kubernetes resources with the actual state. +- **Operator Pattern:** Extend the Kubernetes API with custom resources and controllers to automate complex application management tasks. +- **Sidecar Pattern:** Deploy a sidecar container alongside the main application container to provide supporting functionality, such as logging, monitoring, or security. +- **Ambassador Pattern:** Use an ambassador container to proxy network traffic to the main application container, providing features such as load balancing, routing, and authentication. +- **Adapter Pattern:** Translate requests from one interface to another, allowing different components to work together. +- **Singleton Pattern:** Implement a singleton pattern for managing global resources, such as database connections or configuration settings. Be extremely cautious, as this can hurt testability and introduce implicit dependencies. + +### 2.2 Recommended Approaches for Common Tasks + +- **Resource Management:** Use Kubernetes resource requests and limits to ensure that applications have sufficient resources and prevent resource contention. +- **Configuration Management:** Use ConfigMaps and Secrets to manage configuration data and sensitive information separately from the application code. +- **Service Discovery:** Use Kubernetes services to provide a stable endpoint for accessing applications, even when pods are scaled up or down. +- **Health Checks:** Implement liveness and readiness probes to monitor the health of applications and automatically restart unhealthy pods. +- **Logging and Monitoring:** Use a centralized logging and monitoring system to collect and analyze application logs and metrics. +- **Rolling Updates:** Use Kubernetes deployments to perform rolling updates of applications with zero downtime. + +### 2.3 Anti-Patterns and Code Smells + +- **Naked Pods:** Avoid creating pods directly without a deployment or replica set, as they will not be automatically rescheduled if a node fails. +- **Hardcoded Configuration:** Avoid hardcoding configuration data in the application code. Use ConfigMaps and Secrets instead. +- **Ignoring Resource Limits:** Failing to set resource requests and limits can lead to resource contention and performance issues. +- **Oversized Containers:** Keep container images small and focused to improve startup time and reduce security risks. +- **Privileged Containers:** Avoid running containers in privileged mode, as it can create security vulnerabilities. +- **Long-Lived Branches:** Avoid creating long-lived branches, and prefer small, frequent merges to the main branch. +- **God Classes:** Avoid creating classes that are too large and complex. Break them down into smaller, more manageable classes. +- **Shotgun Surgery:** Avoid making changes to multiple classes when a single feature is modified. This suggests poor class design and coupling. +- **Feature Envy:** Avoid methods that access the data of another object more than their own. This suggests that the method might be in the wrong class. + +### 2.4 State Management Best Practices + +- **Stateless Applications:** Prefer stateless applications whenever possible, as they are easier to scale and manage. +- **Persistent Volumes:** Use Persistent Volumes to store persistent data for stateful applications. +- **External Databases:** Consider using external databases for managing application state, such as databases hosted on cloud providers. +- **Kubernetes Operators:** Implement Kubernetes operators to automate the management of stateful applications. +- **Etcd:** Understand the importance of etcd as Kubernetes' data store and protect it accordingly. + +### 2.5 Error Handling Patterns + +- **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions and log errors consistently. +- **Retry Mechanism:** Implement a retry mechanism to automatically retry failed operations. +- **Circuit Breaker Pattern:** Use a circuit breaker pattern to prevent cascading failures in distributed systems. +- **Logging Error Details:** Log detailed error messages, including stack traces and relevant context, to help with debugging. +- **Graceful Degradation:** Design applications to gracefully degrade functionality when errors occur. +- **Alerting on Critical Errors:** Set up alerts to notify administrators when critical errors occur. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +- **Caching:** Implement caching to reduce latency and improve performance. +- **Load Balancing:** Use load balancing to distribute traffic across multiple instances of an application. +- **Connection Pooling:** Use connection pooling to reuse database connections and reduce overhead. +- **Compression:** Use compression to reduce the size of data transmitted over the network. +- **Gzip:** Enable Gzip compression in web servers to reduce the size of HTTP responses. + +### 3.2 Memory Management + +- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage. +- **Garbage Collection:** Understand how garbage collection works in the programming language used for the application. +- **Resource Limits:** Set memory resource limits for containers to prevent them from consuming excessive memory. +- **Monitor Memory Usage:** Monitor memory usage regularly to identify potential issues. + +### 3.3 Rendering Optimization + +- **Minimize DOM Manipulation:** Reduce the number of DOM manipulations to improve rendering performance in web applications. +- **Virtual DOM:** Use a virtual DOM to optimize rendering updates in web applications. +- **Lazy Loading:** Use lazy loading to load images and other resources only when they are needed. + +### 3.4 Bundle Size Optimization + +- **Code Minification:** Use code minification to reduce the size of JavaScript and CSS files. +- **Tree Shaking:** Use tree shaking to remove unused code from JavaScript bundles. +- **Image Optimization:** Optimize images to reduce their file size without sacrificing quality. +- **Code Splitting:** Split the application code into smaller bundles that can be loaded on demand. + +### 3.5 Lazy Loading Strategies + +- **On-Demand Loading:** Load resources only when they are needed by the application. +- **Intersection Observer:** Use the Intersection Observer API to detect when elements are visible in the viewport and load them accordingly. +- **Placeholder Images:** Use placeholder images while loading the actual images to improve the user experience. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +- **Injection Attacks:** Prevent injection attacks by validating and sanitizing all user input. +- **Cross-Site Scripting (XSS):** Prevent XSS attacks by escaping all user-generated content before rendering it in the browser. +- **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using anti-CSRF tokens. +- **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms to protect sensitive data and resources. +- **Security Misconfiguration:** Avoid using default configurations and ensure that all components are properly configured with security in mind. +- **Using Components with Known Vulnerabilities:** Keep all dependencies up to date to patch known vulnerabilities. +- **Insufficient Logging and Monitoring:** Implement comprehensive logging and monitoring to detect and respond to security incidents. +- **Container Security:** Follow best practices for securing containers, such as using minimal images, running as non-root, and limiting capabilities. +- **Network Policies:** Use network policies to restrict network traffic between pods. +- **RBAC (Role-Based Access Control):** Implement RBAC to control access to Kubernetes resources. +- **Secrets Management:** Use Kubernetes Secrets to store sensitive information, and encrypt secrets at rest. +- **Pod Security Policies/Pod Security Standards:** Enforce Pod Security Standards to restrict the capabilities of pods. + +### 4.2 Input Validation + +- **Validate All Input:** Validate all input, including user input, API requests, and configuration data. +- **Use Strong Data Types:** Use strong data types to enforce data integrity. +- **Sanitize Input:** Sanitize input to remove potentially harmful characters and prevent injection attacks. +- **Whitelist Input:** Use a whitelist approach to only allow known good input. +- **Blacklist Input:** Avoid using a blacklist approach, as it can be easily bypassed. + +### 4.3 Authentication and Authorization Patterns + +- **Multi-Factor Authentication (MFA):** Use MFA to enhance authentication security. +- **OAuth 2.0:** Use OAuth 2.0 for authorization and delegation of access. +- **JSON Web Tokens (JWT):** Use JWTs for securely transmitting claims between parties. +- **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on roles. +- **Least Privilege Principle:** Grant users and applications only the minimum necessary permissions. + +### 4.4 Data Protection Strategies + +- **Encryption at Rest:** Encrypt sensitive data at rest to protect it from unauthorized access. +- **Encryption in Transit:** Encrypt sensitive data in transit using HTTPS or other secure protocols. +- **Data Masking:** Mask sensitive data to prevent it from being exposed to unauthorized users. +- **Data Anonymization:** Anonymize data to remove personally identifiable information (PII). +- **Data Loss Prevention (DLP):** Implement DLP measures to prevent sensitive data from leaving the organization. + +### 4.5 Secure API Communication + +- **HTTPS:** Use HTTPS for all API communication to encrypt data in transit. +- **API Authentication:** Implement API authentication to verify the identity of clients. +- **API Authorization:** Implement API authorization to control access to API endpoints. +- **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks. +- **Input Validation:** Validate all API requests to prevent injection attacks and other vulnerabilities. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +- **Test-Driven Development (TDD):** Write unit tests before writing the application code. +- **Mock Dependencies:** Use mocks to isolate the unit being tested from its dependencies. +- **Test Boundary Conditions:** Test boundary conditions and edge cases to ensure that the code handles them correctly. +- **Test Error Conditions:** Test error conditions to ensure that the code handles errors gracefully. +- **Code Coverage:** Aim for high code coverage to ensure that all parts of the code are tested. +- **Table-Driven Tests:** Use table-driven tests to easily test multiple inputs and outputs. + +### 5.2 Integration Testing + +- **Test Interactions Between Components:** Test the interactions between different components of the application. +- **Test with Real Dependencies:** Use real dependencies or integration mocks for integration tests. +- **Test Data Flows:** Test the data flows through the application to ensure that data is processed correctly. +- **Contract Tests:** Use contract tests to ensure that services adhere to a defined contract. + +### 5.3 End-to-End Testing + +- **Test the Entire System:** Test the entire system from end to end to ensure that all components work together correctly. +- **Automate End-to-End Tests:** Automate end-to-end tests to ensure that they are run regularly. +- **Use Realistic Test Data:** Use realistic test data to simulate real-world scenarios. +- **CI/CD Integration:** Integrate end-to-end tests into the CI/CD pipeline. + +### 5.4 Test Organization + +- **Keep Tests Separate from Code:** Keep tests separate from the application code in a dedicated `test/` directory. +- **Organize Tests by Component:** Organize tests by component or module to make them easier to find and maintain. +- **Use Clear Naming Conventions:** Use clear naming conventions for test files and test functions. + +### 5.5 Mocking and Stubbing + +- **Use Mocking Frameworks:** Use mocking frameworks to simplify the creation of mocks and stubs. +- **Mock External Dependencies:** Mock external dependencies, such as databases and APIs, to isolate the unit being tested. +- **Stub Responses:** Use stubs to provide predefined responses for external dependencies. +- **Verify Interactions:** Verify that the code under test interacts with dependencies as expected. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +- **Ignoring Error Handling:** Failing to handle errors properly can lead to unexpected behavior and crashes. +- **Not Using Version Control:** Not using version control can lead to lost code and conflicts. +- **Hardcoding Configuration:** Hardcoding configuration data can make it difficult to deploy the application in different environments. +- **Not Securing Sensitive Data:** Not securing sensitive data can lead to security breaches. +- **Not Testing Thoroughly:** Not testing thoroughly can lead to bugs and performance issues. +- **Over-Engineering:** Adding unnecessary complexity to the code can make it difficult to understand and maintain. +- **Premature Optimization:** Optimizing code before it is necessary can waste time and make the code harder to read. +- **Not Documenting Code:** Not documenting code can make it difficult for others to understand and maintain it. + +### 6.2 Edge Cases to Be Aware Of + +- **Network Connectivity Issues:** Handle network connectivity issues gracefully. +- **Resource Exhaustion:** Handle resource exhaustion gracefully. +- **Concurrency Issues:** Avoid concurrency issues by using proper synchronization mechanisms. +- **Data Corruption:** Protect against data corruption by using checksums and other data integrity techniques. +- **Time Zone Issues:** Be aware of time zone issues when working with dates and times. + +### 6.3 Version-Specific Issues + +- **API Version Compatibility:** Be aware of API version compatibility issues when upgrading Kubernetes or other dependencies. +- **Feature Deprecation:** Be aware of feature deprecation when upgrading Kubernetes or other dependencies. +- **Configuration Changes:** Be aware of configuration changes when upgrading Kubernetes or other dependencies. + +### 6.4 Compatibility Concerns + +- **Operating System Compatibility:** Ensure that the application is compatible with the target operating systems. +- **Architecture Compatibility:** Ensure that the application is compatible with the target architectures (e.g., x86, ARM). +- **Browser Compatibility:** Ensure that web applications are compatible with the target browsers. + +### 6.5 Debugging Strategies + +- **Logging:** Use detailed logging to help identify the root cause of issues. +- **Debugging Tools:** Use debugging tools, such as debuggers and profilers, to analyze the code and identify performance bottlenecks. +- **Remote Debugging:** Use remote debugging to debug applications running in Kubernetes. +- **Log Aggregation:** Use log aggregation tools (e.g., Elasticsearch, Loki) to centralize and analyze logs. +- **Metrics Monitoring:** Use metrics monitoring tools (e.g., Prometheus, Grafana) to track application performance. +- **Tracing:** Implement distributed tracing (e.g., Jaeger, Zipkin) to track requests across multiple services. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +- **IDE:** Use a modern IDE with support for the programming language used for the application (e.g., VS Code, IntelliJ IDEA, GoLand). +- **Kubectl:** Use `kubectl` for interacting with Kubernetes clusters. +- **Minikube/Kind:** Use Minikube or Kind for local Kubernetes development. +- **Helm:** Use Helm for managing Kubernetes packages. +- **Kustomize:** Use Kustomize for customizing Kubernetes configurations. +- **Docker:** Use Docker for building and managing container images. +- **Tilt:** Use Tilt for fast, local Kubernetes development. +- **Skaffold:** Use Skaffold for automated build, push, and deploy workflows. +- **Telepresence:** Use Telepresence to debug applications running in Kubernetes from your local machine. + +### 7.2 Build Configuration + +- **Makefile:** Use a Makefile to automate common build tasks. +- **CI/CD Pipeline:** Integrate the build process into a CI/CD pipeline. +- **Dependency Management:** Use a dependency management tool, such as `go modules`, to manage dependencies. +- **Version Control:** Use version control to track changes to the build configuration. + +### 7.3 Linting and Formatting + +- **Linters:** Use linters to enforce code style and best practices (e.g., `golangci-lint`, `eslint`, `stylelint`). +- **Formatters:** Use formatters to automatically format code according to a predefined style (e.g., `go fmt`, `prettier`). +- **Pre-Commit Hooks:** Use pre-commit hooks to run linters and formatters before committing code. + +### 7.4 Deployment Best Practices + +- **Infrastructure as Code (IaC):** Use IaC tools, such as Terraform or CloudFormation, to manage infrastructure. +- **Immutable Infrastructure:** Deploy immutable infrastructure to ensure consistency and repeatability. +- **Blue-Green Deployments:** Use blue-green deployments to minimize downtime during deployments. +- **Canary Deployments:** Use canary deployments to test new versions of the application with a small subset of users. +- **Rolling Updates:** Use rolling updates to gradually update the application with zero downtime. +- **Automated Rollbacks:** Implement automated rollbacks to quickly revert to a previous version of the application if something goes wrong. + +### 7.5 CI/CD Integration + +- **Automated Testing:** Automate all tests in the CI/CD pipeline. +- **Automated Deployment:** Automate the deployment process in the CI/CD pipeline. +- **Continuous Integration:** Use continuous integration to automatically build and test the application whenever code is committed. +- **Continuous Delivery:** Use continuous delivery to automatically deploy the application to production whenever a new version is released. +- **Pipeline Security:** Secure the CI/CD pipeline to prevent unauthorized access and code injection. + +## Bibliography + +- Kubernetes documentation: [https://kubernetes.io/docs/](https://kubernetes.io/docs/) +- Kubernetes Best Practices: [https://kubernetes.io/docs/concepts/configuration/overview/](https://kubernetes.io/docs/concepts/configuration/overview/) +- Application Security Checklist: [https://kubernetes.io/docs/concepts/security/application-security-checklist/](https://kubernetes.io/docs/concepts/security/application-security-checklist/) +- Kubernetes coding conventions: [https://www.kubernetes.dev/docs/guide/coding-convention/](https://www.kubernetes.dev/docs/guide/coding-convention/) \ No newline at end of file diff --git a/rules-mdc/development_tools/documentation/mkdocs.mdc b/rules-mdc/development_tools/documentation/mkdocs.mdc new file mode 100644 index 0000000..8236171 --- /dev/null +++ b/rules-mdc/development_tools/documentation/mkdocs.mdc @@ -0,0 +1,270 @@ +--- +description: Comprehensive guidelines for mkdocs development, covering code organization, best practices, performance, security, testing, common pitfalls, and tooling. This rule aims to ensure maintainable, performant, and secure documentation using mkdocs. +globs: **/*.md +--- +# mkdocs Best Practices + +This document provides comprehensive guidelines for developing documentation using mkdocs. It covers various aspects including code organization, common patterns, performance, security, testing, common pitfalls, and tooling. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure Best Practices + +- **docs/**: All documentation source files should reside within this directory. This is the default and recommended location for mkdocs. + - `index.md`: The project homepage. + - `about.md`: An example of another page. + - `user-guide/`: A subdirectory for a section of documentation. + - `getting-started.md`: A sub-page within the user guide. + - `configuration-options.md`: Another sub-page. + - `img/`: A directory to store images used in the documentation. Store your images as close as possible to the document that references it. + - `screenshot.png` +- **mkdocs.yml**: The main configuration file for mkdocs, located at the root of the project alongside the `docs/` directory. + +Example: + + +mkdocs.yml +docs/ + index.md + about.md + license.md + img/ + screenshot.png +user-guide/ + getting-started.md + configuration-options.md + + +### 1.2. File Naming Conventions + +- Use `.md` as the extension for Markdown files. +- Name the homepage `index.md` or `README.md`. +- Use descriptive names for other pages (e.g., `getting-started.md`, `configuration-options.md`). +- Use lowercase and hyphens for file names to create clean URLs. + +### 1.3. Module Organization + +- mkdocs itself doesn't have modules in the traditional programming sense. Structure your documentation content logically into sections and sub-sections using directories and files. +- Use the `nav` configuration in `mkdocs.yml` to define the structure of the navigation menu. + +Example: + + +nav: + - Home: index.md + - User Guide: + - Getting Started: user-guide/getting-started.md + - Configuration Options: user-guide/configuration-options.md + - About: about.md + - License: license.md + + +### 1.4. Component Architecture + +- mkdocs is not a component-based system like React or Vue.js. +- Instead, think of each Markdown file as a page or section of your documentation. +- Use includes or macros (via plugins) to reuse content across multiple pages (see Snippets and Includes section). + +### 1.5. Code Splitting Strategies + +- Divide your documentation into logical sections and sub-sections. +- Create separate Markdown files for each section. +- Use the `nav` configuration to structure the navigation menu. +- Use `include-markdown` plugin to avoid repeating content in multiple pages. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to mkdocs + +- **Navigation as Code**: Managing the navigation structure directly within `mkdocs.yml` is a fundamental pattern. It allows for centralized control over the site's hierarchy. +- **Content Reusability**: Utilizing plugins like `include-markdown` to reuse common elements like disclaimers, notices, or standard procedures. +- **Theming Customization**: Overriding the default theme templates to tailor the look and feel of the documentation to match branding or specific aesthetic requirements. +- **Plugin Extension**: Extending the functionality of mkdocs by using and customizing existing plugins or creating custom ones to fulfill specific documentation needs, such as generating API documentation or integrating with external tools. + +### 2.2. Recommended Approaches for Common Tasks + +- **Linking to Pages**: Use relative paths for internal links to avoid issues when deploying (e.g., `[link to about](about.md)`). +- **Linking to Sections**: Use anchor links to link to specific sections within a page (e.g., `[link to license](about.md#license)`). +- **Including Images**: Place images in the `docs/img/` directory and link to them using relative paths (e.g., `![Screenshot](img/screenshot.png)`). +- **Adding Meta-Data**: Add YAML or MultiMarkdown style meta-data to the beginning of Markdown files to control page templates or add information such as authors or descriptions. + +### 2.3. Anti-patterns and Code Smells to Avoid + +- **Absolute Paths in Links**: Avoid using absolute paths for internal links. Use relative paths instead. +- **Large Markdown Files**: Avoid creating very large Markdown files. Break them into smaller, more manageable files and use the `nav` configuration to link them. +- **Ignoring the `nav` Configuration**: Relying on the automatic navigation generation instead of explicitly defining it in `mkdocs.yml` can lead to a disorganized navigation menu. +- **Over-Customization**: Excessively customizing the theme or adding too many plugins can make the documentation difficult to maintain and update. +- **Lack of a Clear File Structure**: An unstructured or inconsistent file structure makes it difficult to navigate and understand the documentation. + +### 2.4. State Management Best Practices + +- mkdocs is a static site generator, so it doesn't have a traditional concept of state management. +- However, you can use plugins to add dynamic content or interact with external data sources. + +### 2.5. Error Handling Patterns + +- mkdocs doesn't have runtime error handling in the traditional sense. +- Errors typically occur during the build process (e.g., invalid configuration, broken links). +- Use a CI/CD pipeline to automatically build and test the documentation and catch errors early. +- Utilize linters and validators (plugins) to ensure the integrity of your Markdown and configuration files. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +- **Optimize Images**: Use optimized images to reduce file sizes and improve loading times. +- **Minify HTML, CSS, and JavaScript**: Use the `mkdocs-minify-plugin` to minify the generated HTML, CSS, and JavaScript files. +- **Lazy Loading Images**: Lazy load images below the fold to improve initial page load time. +- **Use a CDN**: Use a CDN (Content Delivery Network) to serve static assets (images, CSS, JavaScript) from multiple locations around the world. + +### 3.2. Memory Management + +- mkdocs itself doesn't have specific memory management considerations. +- However, if you're using plugins that generate dynamic content, be mindful of memory usage. + +### 3.3. Rendering Optimization + +- mkdocs generates static HTML files, so rendering performance is generally not a concern. +- However, complex Markdown structures can slow down the build process. Keep your Markdown files as simple as possible. + +### 3.4. Bundle Size Optimization + +- Optimize the size of your images and other static assets. +- Use the `mkdocs-minify-plugin` to minify the generated HTML, CSS, and JavaScript files. +- Avoid including unnecessary CSS or JavaScript in your theme. + +### 3.5. Lazy Loading Strategies + +- Implement lazy loading for images using JavaScript. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +- **Cross-Site Scripting (XSS)**: Since mkdocs generates static sites, the risk of XSS is minimal, but if you incorporate user-generated content or external data, sanitize inputs properly. +- **Injection Attacks**: Avoid using untrusted data to generate content. If you must use untrusted data, sanitize it properly. + +### 4.2. Input Validation + +- If your mkdocs site incorporates forms or user input via plugins, validate all inputs to prevent injection attacks. + +### 4.3. Authentication and Authorization Patterns + +- mkdocs doesn't provide built-in authentication or authorization. +- If you need to protect certain pages, you can implement authentication at the web server level or use a plugin. + +### 4.4. Data Protection Strategies + +- Since mkdocs generates static sites, there is no sensitive data stored on the server. +- However, be careful not to include sensitive information in your documentation source files. + +### 4.5. Secure API Communication + +- If your mkdocs site communicates with external APIs, use HTTPS to encrypt the communication. +- Verify the API server's SSL certificate. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +- mkdocs itself doesn't have unit tests in the traditional programming sense. +- However, if you create custom plugins, you should write unit tests for them. + +### 5.2. Integration Testing + +- Create integration tests to verify that your mkdocs site is built correctly and that all links are working. +- Use a tool like `htmlproofer` to validate URLs in the rendered HTML files. + +### 5.3. End-to-end Testing + +- Use an end-to-end testing framework to verify that your mkdocs site is working as expected in a browser. + +### 5.4. Test Organization + +- Organize your tests into separate directories (e.g., `tests/`). +- Use descriptive names for your test files and test functions. + +### 5.5. Mocking and Stubbing + +- If you're testing custom plugins that interact with external APIs, use mocking and stubbing to isolate your tests. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +- **Incorrect File Paths**: Using incorrect file paths in links or image references. +- **Ignoring the `nav` Configuration**: Relying on the automatic navigation generation instead of explicitly defining it in `mkdocs.yml`. +- **Over-Customization**: Customizing the theme too much can make the documentation difficult to maintain and update. +- **Not Keeping Documentation Up-to-Date**: Forgetting to update the documentation when the codebase changes. + +### 6.2. Edge Cases to Be Aware Of + +- **Long File Paths**: Long file paths can cause issues on some operating systems. +- **Special Characters in File Names**: Avoid using special characters in file names. +- **Conflicting Plugin Options**: Some plugins may have conflicting options. + +### 6.3. Version-Specific Issues + +- mkdocs is constantly evolving, so be aware of version-specific issues. +- Always test your documentation with the latest version of mkdocs before deploying. + +### 6.4. Compatibility Concerns + +- Ensure that your documentation is compatible with different browsers and devices. +- Test your documentation on different platforms to ensure that it looks good everywhere. + +### 6.5. Debugging Strategies + +- **Check the mkdocs Build Log**: The mkdocs build log contains valuable information about errors and warnings. +- **Use a Debugger**: Use a debugger to step through the mkdocs build process and identify issues. +- **Simplify Your Configuration**: Simplify your `mkdocs.yml` file to isolate the issue. +- **Disable Plugins**: Disable plugins one by one to identify the plugin causing the issue. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +- **Text Editor**: VS Code, Sublime Text, Atom +- **Markdown Editor**: Typora, Mark Text +- **Web Browser**: Chrome, Firefox, Safari +- **mkdocs CLI**: The mkdocs command-line interface. + +### 7.2. Build Configuration + +- Use a `mkdocs.yml` file to configure your mkdocs site. +- The `mkdocs.yml` file should be located at the root of your project. +- The `mkdocs.yml` file should contain the following information: + - `site_name`: The name of your site. + - `site_description`: A description of your site. + - `site_author`: The author of your site. + - `docs_dir`: The directory containing your documentation source files. + - `theme`: The theme to use for your site. + - `nav`: The navigation menu for your site. + - `markdown_extensions`: A list of Markdown extensions to enable. + - `plugins`: A list of plugins to enable. + +### 7.3. Linting and Formatting + +- Use a linter to enforce code style and identify potential issues. +- Use a formatter to automatically format your Markdown files. + +### 7.4. Deployment Best Practices + +- **Use a CI/CD Pipeline**: Use a CI/CD pipeline to automatically build and deploy your mkdocs site. +- **Deploy to a CDN**: Deploy your mkdocs site to a CDN to improve performance. +- **Use HTTPS**: Use HTTPS to encrypt communication with your site. +- **Configure a Custom Domain**: Configure a custom domain for your site. + +### 7.5. CI/CD Integration + +- Use a CI/CD tool like GitHub Actions, GitLab CI, or Travis CI to automatically build and deploy your mkdocs site. +- Configure your CI/CD pipeline to run tests and linters. +- Configure your CI/CD pipeline to deploy your site to a CDN. + +## Additional Notes + +- Always refer to the official mkdocs documentation for the most up-to-date information. +- Consider contributing to the mkdocs community by creating plugins or themes. +- Stay informed about the latest best practices and security vulnerabilities. + +This comprehensive guide should help you create maintainable, performant, and secure documentation using mkdocs. \ No newline at end of file diff --git a/rules-mdc/development_tools/infrastructure/terraform.mdc b/rules-mdc/development_tools/infrastructure/terraform.mdc new file mode 100644 index 0000000..0cdfa14 --- /dev/null +++ b/rules-mdc/development_tools/infrastructure/terraform.mdc @@ -0,0 +1,166 @@ +--- +description: This rule provides guidelines for Terraform best practices, coding standards, and security considerations to ensure maintainable, efficient, and secure infrastructure-as-code. +globs: **/*.tf +--- +- **Use Remote State**: Store Terraform state files remotely to enable collaboration and prevent conflicts. Consider using Terraform Cloud, HashiCorp Consul, AWS S3 with DynamoDB locking, or Azure Storage Account with Blob Storage Locking. + - Properly configure access controls for your remote state backend to prevent unauthorized access. + - Implement versioning for state files to track changes and facilitate rollbacks. +- **Consistent Naming Conventions**: Adopt a consistent naming convention for resources, modules, and variables to improve readability and maintainability. + - Use nouns for resource names (e.g., `aws_instance.web_server` instead of `web_server_instance`). + - Include environment or project context in names (e.g., `dev_web_server` or `prod_db`). + - Follow a consistent casing style (e.g., snake_case or camelCase). +- **Modularity and Code Structure**: Organize Terraform code into modules to promote reusability and maintainability. + - Create modules for common infrastructure components (e.g., VPC, EC2 instance, database). + - Follow a standard module structure (e.g., `variables.tf`, `outputs.tf`, `main.tf`, `versions.tf`). + - Limit the use of custom scripts within modules; prefer Terraform resources and data sources. +- **Validation and Formatting**: Always validate and format Terraform code using `terraform fmt` and `terraform validate` to ensure quality and consistency. + - Integrate `terraform fmt` and `terraform validate` into your CI/CD pipeline. + - Use a linter such as TFLint to enforce organization-specific coding best practices. +- **Use Existing Shared and Community Modules**: Leverage pre-built modules from the Terraform Registry or other trusted sources to avoid reinventing the wheel. + - Thoroughly review modules before use to understand their functionality and security implications. + - Pin module versions to prevent unexpected changes. +- **Import Existing Infrastructure**: Use the `terraform import` command to bring existing infrastructure under Terraform management. + - Understand the limitations of `terraform import` and manually verify the imported configuration. +- **Avoid Hard-coding Variables**: Use variables to parameterize Terraform configurations and avoid hard-coding values. + - Define variables in `variables.tf` with appropriate descriptions, types, and default values. + - Use environment variables or Terraform Cloud variables to pass sensitive values. +- **Tag Resources**: Tag all Terraform resources with relevant metadata (e.g., `Name`, `Environment`, `Project`, `Owner`). + - Use consistent tagging conventions across your infrastructure. + - Leverage tags for cost allocation and resource management. +- **Introduce Policy as Code**: Implement policy as code using tools like HashiCorp Sentinel or Open Policy Agent (OPA) to enforce compliance and security policies. + - Define policies for resource configurations, naming conventions, and security settings. + - Integrate policy checks into your CI/CD pipeline. +- **Code Organization and Structure:** + - **Directory Structure Best Practices:** Organize your Terraform project with a clear directory structure. A common pattern: + + ├── modules/ + │ ├── vpc/ + │ │ ├── main.tf + │ │ ├── variables.tf + │ │ └── outputs.tf + │ ├── ec2/ + │ │ ├── main.tf + │ │ ├── variables.tf + │ │ └── outputs.tf + ├── environments/ + │ ├── dev/ + │ │ ├── main.tf + │ │ ├── variables.tf + │ │ └── terraform.tfvars + │ ├── prod/ + │ │ ├── main.tf + │ │ ├── variables.tf + │ │ └── terraform.tfvars + ├── main.tf # Top-level resources (if any) + ├── variables.tf # Global variables + └── outputs.tf # Global outputs + + - **File Naming Conventions:** Adhere to consistent file naming. Use `main.tf` for the primary resource definitions, `variables.tf` for variables, `outputs.tf` for outputs, and `terraform.tfvars` for environment-specific variable values. + - **Module Organization:** Keep modules self-contained and reusable. Each module should have a specific purpose (e.g., creating a VPC, an EC2 instance, or a database). + - **Component Architecture:** Design your infrastructure as a collection of loosely coupled components (modules) that can be composed together. + - **Code Splitting Strategies:** Break down large configurations into smaller, more manageable modules and files. +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Singleton Pattern:** Ensure only one instance of a critical resource exists (e.g., a VPC). Use `count = var.create_vpc ? 1 : 0` to conditionally create a single VPC. + - **Factory Pattern:** Use modules to create multiple instances of a resource with different configurations (e.g., multiple EC2 instances with different sizes and roles). + - **Facade Pattern:** Create a module that simplifies the creation of complex infrastructure by abstracting away the underlying details. + - **Recommended Approaches:** + - Use data sources to retrieve information about existing resources instead of hardcoding their IDs or names. + - Use dynamic blocks to create multiple resources or configure resource properties based on variable values. + - Use lifecycle rules to manage resource creation, modification, and deletion. + - **Anti-patterns:** + - **Hardcoding values:** Avoid hardcoding values in your Terraform configurations. Use variables instead. + - **Creating monolithic configurations:** Break down large configurations into smaller, more manageable modules. + - **Ignoring errors:** Always handle errors and provide meaningful error messages. + - **State Management Best Practices:** + - **Remote State:** Always use remote state to store Terraform state files. + - **State Locking:** Enable state locking to prevent concurrent modifications. + - **State Encryption:** Encrypt state files to protect sensitive data. + - **State Versioning:** Implement versioning for state files. + - **Error Handling Patterns:** + - Use the `try` and `can` functions to handle errors when retrieving data or evaluating expressions. + - Use `validation` blocks to validate variable values and prevent invalid configurations. + - Provide meaningful error messages to help users diagnose and fix issues. +- **Performance Considerations:** + - **Optimization Techniques:** + - Use the `count` and `for_each` meta-arguments to create multiple resources efficiently. + - Use data sources to retrieve information about existing resources instead of creating new ones. + - Use the `depends_on` meta-argument sparingly to avoid unnecessary dependencies. + - **Memory Management:** + - Be mindful of the memory usage of your Terraform configurations, especially when working with large datasets. + - Avoid creating large variables or outputs that can consume excessive memory. + - **Rendering Optimization:** + - Use efficient string interpolation techniques to avoid unnecessary string concatenation. + - Use the `templatefile` function to render complex templates efficiently. +- **Security Best Practices:** + - **Common Vulnerabilities:** + - **Hardcoded secrets:** Avoid hardcoding secrets in your Terraform configurations. + - **Publicly accessible resources:** Ensure that resources are not publicly accessible unless explicitly required. + - **Insufficient access controls:** Implement strict access controls to prevent unauthorized access to resources. + - **Input Validation:** + - Validate variable values to prevent invalid or malicious input. + - Use regular expressions to enforce specific input formats. + - **Authentication and Authorization Patterns:** + - Use IAM roles and policies to grant resources the necessary permissions. + - Use Terraform Cloud or other secrets management tools to manage sensitive credentials. + - **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use encryption keys managed by a key management service (KMS). + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Validate API responses to prevent data injection attacks. +- **Testing Approaches:** + - **Unit Testing Strategies:** + - Use `terraform show` and `terraform plan` to verify that your Terraform configurations create the expected resources. + - Use `terratest` or other testing frameworks to write automated unit tests. + - **Integration Testing:** + - Deploy your Terraform configurations to a test environment and verify that the resources are functioning correctly. + - Use automated testing tools to perform integration tests. + - **End-to-end Testing:** + - Simulate real-world scenarios and verify that your infrastructure can handle them. + - Use automated testing tools to perform end-to-end tests. + - **Test Organization:** + - Organize your tests into a clear directory structure. + - Use meaningful test names to describe the purpose of each test. + - **Mocking and Stubbing:** + - Use mocking and stubbing to isolate your tests and prevent dependencies on external resources. + - Use testing frameworks that support mocking and stubbing. +- **Common Pitfalls and Gotchas:** + - **Frequent Mistakes:** + - **Incorrect resource dependencies:** Ensure that resource dependencies are correctly defined. + - **Ignoring resource lifecycle:** Understand the lifecycle of Terraform resources and how they are created, modified, and deleted. + - **Using outdated Terraform versions:** Keep your Terraform version up to date to take advantage of new features and bug fixes. + - **Edge Cases:** + - **Handling resource conflicts:** Be prepared to handle resource conflicts that can occur when multiple Terraform configurations are applied simultaneously. + - **Managing resources with external dependencies:** Be aware of resources that have external dependencies (e.g., DNS records) and handle them appropriately. + - **Version-specific Issues:** + - Be aware of version-specific issues and compatibility concerns when upgrading Terraform or provider versions. + - Consult the Terraform and provider documentation for any breaking changes or migration guides. + - **Compatibility Concerns:** + - Ensure that your Terraform configurations are compatible with the target infrastructure environment. + - Use provider versions that are compatible with the Terraform version. + - **Debugging Strategies:** + - Use the `terraform plan` command to preview the changes that will be made to your infrastructure. + - Use the `terraform apply` command with the `-auto-approve` flag to apply changes automatically. + - Use the `terraform show` command to inspect the current state of your infrastructure. +- **Tooling and Environment:** + - **Recommended Development Tools:** + - **Terraform CLI:** The official Terraform command-line interface. + - **Terraform Cloud/Enterprise:** A collaboration and automation platform for Terraform. + - **IDE/Text Editor:** Visual Studio Code with the Terraform extension, Atom, or Sublime Text. + - **TFLint:** A linter for Terraform code. + - **Terratest:** A testing framework for Terraform code. + - **Build Configuration:** + - Use a consistent build configuration across all environments. + - Use environment variables or Terraform Cloud variables to configure the build environment. + - **Linting and Formatting:** + - Integrate linting and formatting into your CI/CD pipeline. + - Use `terraform fmt` and TFLint to ensure code quality and consistency. + - **Deployment Best Practices:** + - Use a CI/CD pipeline to automate Terraform deployments. + - Use version control to track changes to your Terraform configurations. + - Use infrastructure-as-code principles to manage your infrastructure. + - **CI/CD Integration:** + - Integrate Terraform into your CI/CD pipeline using tools like Jenkins, GitLab CI, or GitHub Actions. + - Automate the execution of `terraform plan` and `terraform apply` commands. + - Implement automated testing and validation as part of the CI/CD process. \ No newline at end of file diff --git a/rules-mdc/development_tools/testing/detox.mdc b/rules-mdc/development_tools/testing/detox.mdc new file mode 100644 index 0000000..dcd95b9 --- /dev/null +++ b/rules-mdc/development_tools/testing/detox.mdc @@ -0,0 +1,348 @@ +--- +description: This rule file provides guidelines for writing stable and maintainable end-to-end tests using Detox, covering code structure, testing strategies, and performance considerations. It includes best practices for test ID usage, dealing with flakiness, and integrating with CI/CD pipelines. +globs: **/*.{e2e.js,e2e.ts,spec.js,spec.ts} +--- +# Detox E2E Testing Best Practices for React Native + +This document outlines best practices for writing stable, maintainable, and performant end-to-end (E2E) tests for React Native applications using Detox. + +## Ground Rules + +- **Isolate Tests:** Each test should start fresh and not depend on the execution of previous tests. Restart the app before each test. +- **Consistent Input, Consistent Output:** Ensure identical app behavior across test iterations by managing varying server responses and app states. Mock server responses to prevent external variations. +- **End every test with an expectation:** Ensures a validation phase that confirms the intended outcome of the test. + +## 1. Code Organization and Structure + +### Directory Structure + + +/ + e2e/ + config.js # Detox configuration file + utils.js # Helper functions for tests + firstTest.spec.js # Example test file + ... # More test files + src/ + ... # Your application source code + + +- **`e2e` directory:** Dedicated directory for all Detox-related files. +- **`config.js`:** Contains Detox configuration, including device settings, build paths, and test runner configuration. +- **`utils.js` (or similar):** Houses reusable helper functions, such as custom matchers, navigation helpers, and data generation functions. +- **`*.spec.js` or `*.e2e.js`:** Test files containing the actual test cases. Choose a consistent naming convention. + +### File Naming Conventions + +- **Test files:** `[ComponentName].spec.js`, `[FeatureName].e2e.js`. +- **Helper functions:** `helpers.js`, `utils.js`, `testData.js`. +- **Configuration:** `detox.config.js` or `e2e.config.js`. + +### Module Organization + +- **Separate test logic from application code:** Tests reside in the `e2e` directory, separate from the `src` directory containing the app's source code. +- **Group related tests into modules:** For example, put all tests related to user authentication in an `e2e/auth/` directory. +- **Use helper modules:** Extract common test logic, like logging in a user or navigating to a specific screen, into reusable helper functions. + +### Component Architecture (Page Object Model) + +- **Implement the Page Object Model (POM):** Create classes or modules that represent UI screens or components. Each page object should encapsulate the selectors and actions for that screen. + +javascript +// e2e/pageObjects/LoginPage.js +const { element, by, expect } = require('detox'); + +class LoginPage { + constructor() { + this.usernameField = element(by.id('username_input')); + this.passwordField = element(by.id('password_input')); + this.loginButton = element(by.id('login_button')); + } + + async enterUsername(username) { + await this.usernameField.typeText(username); + } + + async enterPassword(password) { + await this.passwordField.typeText(password); + } + + async tapLoginButton() { + await this.loginButton.tap(); + } + + async isLoggedIn() { + await expect(element(by.id('home_screen'))).toBeVisible(); + } +} + +module.exports = new LoginPage(); + + +- **Benefits of POM:** + - Improved test readability and maintainability. + - Reduced code duplication. + - Easier refactoring of UI elements. + +### Code Splitting Strategies (Not directly applicable to Detox, but consider app bundle size) + +- **Dynamic imports:** Utilize dynamic imports in the app code to load modules only when needed, improving initial load time. This is a React Native concern, not Detox itself, but Detox tests will execute faster on a faster-loading app. +- **Route-based splitting:** Split your app into separate bundles based on routes or features. + +## 2. Common Patterns and Anti-patterns + +### Design Patterns Specific to Detox + +- **Wait for element to be visible:** + +javascript +await waitFor(element(by.id('my_element'))).toBeVisible().withTimeout(5000); + + +- **Retry flaky tests:** Implement a retry mechanism for tests that occasionally fail due to timing issues or other unpredictable factors. Use Jest's retryTimes: + +javascript +jest.retryTimes(3); // Retry the test up to 3 times + + +- **Use `beforeAll` and `beforeEach` wisely:** `beforeAll` is for setup that only needs to happen once for the entire test suite, while `beforeEach` is for setup that must be done before each test. + +### Recommended Approaches for Common Tasks + +- **Simulating user interactions:** + +javascript +await element(by.id('my_button')).tap(); +await element(by.id('my_input')).typeText('Hello, Detox!'); +await element(by.id('my_scroll_view')).scroll(50, 'down'); + + +- **Asserting element visibility and text content:** + +javascript +await expect(element(by.id('my_element'))).toBeVisible(); +await expect(element(by.text('Expected Text'))).toBeVisible(); +await expect(element(by.id('my_element'))).toHaveText('Actual Text'); + + +- **Handling alerts and dialogs:** + +javascript +await expect(element(by.text('Alert Title'))).toBeVisible(); +await element(by.text('OK')).tap(); // Dismiss the alert + + +### Anti-patterns and Code Smells to Avoid + +- **Hardcoded timeouts:** Avoid using `setTimeout` directly. Rely on Detox's built-in synchronization and waiting mechanisms. +- **Incomplete Test Coverage:** Focus on critical paths and user flows, ensuring comprehensive coverage of the core functionalities. +- **Over-reliance on Thread.sleep() (or equivalent):** Try to use `waitFor` or Detox's synchronization primitives instead. Sleeping is almost always a sign that Detox's sync isn't working right. +- **Ignoring console.log statements:** Keep console log statements clean and helpful for debugging purposes. + +### State Management Best Practices (App-level, impacts test environment) + +- **Mock external dependencies:** Mock API calls, database interactions, and other external dependencies to ensure consistent test results and isolate the app's logic. +- **Control app state before each test:** Use `beforeEach` to reset the app's state to a known value before running each test. This can involve clearing data, logging out users, or navigating to a specific screen. + +### Error Handling Patterns + +- **Use `try...catch` blocks:** Wrap test actions in `try...catch` blocks to handle potential errors gracefully. +- **Log errors:** Log any errors that occur during test execution to help with debugging. +- **Fail tests on unexpected errors:** If a test encounters an unexpected error, mark the test as failed to prevent false positives. + +## 3. Performance Considerations + +### Optimization Techniques (Mainly React Native app optimization) + +- **Minimize UI updates:** Reduce the number of UI updates during animations or interactions to improve rendering performance. +- **Use virtualization for long lists:** Virtualize long lists to render only the visible items, reducing memory consumption and improving scrolling performance. This improves the app's performance generally, leading to faster test execution. +- **Optimize image loading:** Optimize image sizes and use caching mechanisms to reduce image loading times. + +### Memory Management (React Native app concern) + +- **Release resources:** Properly release resources, such as event listeners and timers, when they are no longer needed to prevent memory leaks. +- **Use memoization:** Use memoization techniques to avoid recomputing expensive values when they haven't changed. + +### Rendering Optimization (React Native app concern) + +- **Use `shouldComponentUpdate` or `React.memo`:** Implement `shouldComponentUpdate` or `React.memo` to prevent unnecessary re-renders of components. +- **Avoid inline styles:** Avoid using inline styles, as they can cause performance issues. + +### Bundle Size Optimization (React Native app concern) + +- **Use code splitting:** Split your app into smaller chunks to reduce the initial bundle size. +- **Remove unused code:** Remove any unused code, such as dead code or unused libraries. +- **Optimize images:** Optimize image sizes and use appropriate image formats. + +### Lazy Loading Strategies (React Native app concern) + +- **Load components on demand:** Load components only when they are needed, such as when a user navigates to a specific screen. +- **Use lazy-loaded images:** Load images only when they are visible in the viewport. + +## 4. Security Best Practices (App Security - Impacts Test Scope) + +### Common Vulnerabilities and How to Prevent Them + +- **Data injection:** Protect against data injection attacks by validating all user input and using parameterized queries. +- **Cross-site scripting (XSS):** Prevent XSS attacks by sanitizing all user-generated content before rendering it. +- **Man-in-the-middle (MITM) attacks:** Implement SSL/TLS to encrypt communication between the app and the server. + +### Input Validation + +- **Validate all user input:** Validate all user input on both the client and server sides to prevent invalid or malicious data from being processed. +- **Use appropriate validation libraries:** Use established validation libraries to simplify the validation process and ensure consistency. + +### Authentication and Authorization Patterns + +- **Use secure authentication protocols:** Use secure authentication protocols, such as OAuth 2.0 or OpenID Connect. +- **Implement proper authorization checks:** Implement proper authorization checks to ensure that users can only access the resources they are authorized to access. + +### Data Protection Strategies + +- **Encrypt sensitive data:** Encrypt sensitive data, such as passwords and credit card numbers, both in transit and at rest. +- **Store data securely:** Store data in secure locations, such as encrypted databases or keychains. + +### Secure API Communication + +- **Use HTTPS:** Always use HTTPS to encrypt communication between the app and the server. +- **Validate API responses:** Validate API responses to ensure that they are not tampered with. + +## 5. Testing Approaches + +### Unit Testing Strategies (Generally not used with Detox) + +- **Test individual components or functions in isolation:** Use unit tests to verify the behavior of individual components or functions in isolation. +- **Use mocking to isolate dependencies:** Use mocking to isolate dependencies and ensure that the unit tests are not affected by external factors. + +### Integration Testing + +- **Test interactions between multiple components or modules:** Use integration tests to verify the interactions between multiple components or modules. +- **Use stubs to simulate external dependencies:** Use stubs to simulate external dependencies and ensure that the integration tests are not affected by real-world conditions. + +### End-to-End Testing + +- **Test the entire application from end to end:** Use end-to-end tests to verify the entire application flow from the user's perspective. +- **Simulate real user interactions:** Simulate real user interactions as closely as possible to ensure that the tests accurately reflect the user experience. + +### Test Organization + +- **Organize tests by feature or functionality:** Group tests by feature or functionality to improve test discoverability and maintainability. +- **Use descriptive test names:** Use descriptive test names to clearly indicate what each test is verifying. +- **Keep tests small and focused:** Keep tests small and focused on verifying a single aspect of the application. + +### Mocking and Stubbing (Used sparingly with Detox. More common is configuring the backend) + +- **Mock external dependencies:** Mock external dependencies, such as API calls or database interactions, to ensure consistent test results. +- **Use stubs to simulate specific scenarios:** Use stubs to simulate specific scenarios, such as error conditions or edge cases. + +## 6. Common Pitfalls and Gotchas + +### Frequent Mistakes Developers Make + +- **Using brittle selectors:** Avoid using selectors that are based on text or position, as these can easily break when the UI changes. Use `testID` whenever possible. +- **Not handling asynchronous operations correctly:** Ensure that all asynchronous operations are properly handled to prevent race conditions and timing issues. +- **Ignoring error messages:** Pay attention to error messages and logs to identify and fix problems quickly. + +### Edge Cases to Be Aware Of + +- **Handling different screen sizes and orientations:** Test the app on different screen sizes and orientations to ensure that the UI adapts correctly. +- **Handling network connectivity issues:** Test the app's behavior when the network connection is slow or unavailable. +- **Handling different languages and locales:** Test the app with different languages and locales to ensure that it is properly localized. + +### Version-Specific Issues + +- **Keep Detox up to date:** Stay up to date with the latest version of Detox to take advantage of bug fixes and performance improvements. +- **Be aware of compatibility issues:** Be aware of compatibility issues between different versions of Detox, React Native, and other dependencies. + +### Compatibility Concerns + +- **Test on multiple devices and operating systems:** Test the app on a variety of devices and operating systems to ensure that it is compatible with the target audience. +- **Use a device farm:** Use a device farm, such as HeadSpin, to test the app on a wide range of real devices. + +### Debugging Strategies + +- **Use the Detox CLI:** Use the Detox CLI to run tests, inspect the app's state, and debug issues. +- **Use logging statements:** Use logging statements to track the execution flow and identify potential problems. +- **Use breakpoints:** Use breakpoints in your test code to pause execution and inspect variables. + +## 7. Tooling and Environment + +### Recommended Development Tools + +- **Visual Studio Code:** A popular code editor with excellent support for JavaScript and React Native. +- **Detox CLI:** The Detox command-line interface for running tests and managing the Detox environment. +- **HeadSpin:** For running tests on real devices and analyzing performance metrics. + +### Build Configuration + +- **Configure Detox in `package.json`:** Configure Detox in the `package.json` file, including device settings, build paths, and test runner configuration. +- **Use different configurations for different environments:** Use different configurations for development, staging, and production environments. + +### Linting and Formatting + +- **Use ESLint:** Use ESLint to enforce code style and detect potential errors. +- **Use Prettier:** Use Prettier to automatically format code. + +### Deployment Best Practices + +- **Automate the deployment process:** Automate the deployment process using tools like Fastlane or Bitrise. +- **Use continuous integration and continuous delivery (CI/CD):** Use CI/CD to automatically build, test, and deploy the app whenever changes are made. + +### CI/CD Integration + +- **Integrate Detox tests into your CI/CD pipeline:** Integrate Detox tests into your CI/CD pipeline to automatically run tests whenever changes are made. +- **Use a CI/CD service like Jenkins, CircleCI, or Travis CI:** Use a CI/CD service like Jenkins, CircleCI, or Travis CI to automate the build, test, and deployment process. + +## Working with Test IDs + +### Benefits of Test IDs + +* Stable matchers that don't depend on UI text. +* Locale-agnostic testing. +* Clear code navigability. + +### Assigning Test IDs + +* **React Native:** Use the `testID` prop on View components. + + jsx + + + Next + + + + +* **iOS Native:** Use the `accessibilityIdentifier` property. +* **Android Native:** Use the `viewTag` property. + +### Best Practices for Naming Test IDs + +* Use a consistent naming system (e.g., `ITEM_NAME_ALL_CAPS` or `ItemNameUpperCamelCase`). +* Use notations for special items (e.g., `_ROOT` for screen roots, `_BTN` for buttons). +* Apply consistent prefixes as categories (e.g., `EDIT_PROFILE_SCREEN.DONE_BTN`). +* Drill down to details of elements via chains of contexts (e.g., `SITE_LIST_ITEM1.OPTIONS`). +* In large projects, use module identifiers (e.g., `AUTH.LOGIN_SCREEN.EDIT_PASSWORD`). + +#### Examples of good test ID usage: + + +EDIT_PROFILE_SCREEN.DONE_BTN +SITE_LIST_ROOT +SITE_LIST_ITEM1.OPTIONS + + +### Rules of Thumb for test IDs + +* Use unique, simple, and concise names. +* Dissociate test ID names from element text/labels. +* Do not utilize the element's text / label in the naming of a test ID! + +### Finding Test IDs + +* **MacOS Accessibility Inspector:** Use the built-in accessibility inspector to verify test IDs on iOS. +* **Detox Layout Inspector:** Set up and use the Detox Layout Inspector for Android. +* Incorrect or absent testID is a common cause for test failure. If your test can't find your testID and you can't see it either using tools described above, that usually means you haven't passed it down to this component. +Make sure you keep forwarding it down until it reaches a native component. + +By following these best practices, you can create a robust and maintainable suite of Detox E2E tests for your React Native application. \ No newline at end of file diff --git a/rules-mdc/development_tools/testing/jest.mdc b/rules-mdc/development_tools/testing/jest.mdc new file mode 100644 index 0000000..8e1b13a --- /dev/null +++ b/rules-mdc/development_tools/testing/jest.mdc @@ -0,0 +1,139 @@ +--- +description: This rule provides guidelines for writing clean, maintainable, and effective tests using Jest. It covers code organization, performance, common pitfalls, and best practices for testing JavaScript and TypeScript projects. +globs: **/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts} +--- +- **Organize tests by feature or module:** + - Group tests into files or directories that correspond to the features or modules they are testing. This makes it easier to locate and maintain tests. + - Create a `__tests__` directory alongside your source code files. This is a common convention that Jest recognizes. + +- **Use descriptive test names:** + - Write test names that clearly describe what the test is verifying. This makes it easier to understand the purpose of each test and to diagnose failures. + - Use the `describe` and `it` blocks to structure your tests and provide context. + - Example: `describe('User authentication', () => { it('should log in a user with valid credentials', () => { /* ... */ }); });` + +- **Keep tests isolated and independent:** + - Each test should be independent of other tests. Avoid sharing state or dependencies between tests. + - Use `beforeEach` and `afterEach` hooks to set up and tear down the environment for each test. + +- **Avoid testing implementation details:** + - Focus on testing the public API of your code, rather than the internal implementation details. + - This makes your tests more resilient to changes in the implementation. + - Test the "what", not the "how". + +- **Use setup and teardown methods:** + - Use `beforeAll`, `afterAll`, `beforeEach`, and `afterEach` hooks to set up and tear down the environment for your tests. + - `beforeAll` and `afterAll` run once before and after all tests in a `describe` block. + - `beforeEach` and `afterEach` run before and after each test in a `describe` block. + +- **Mock external dependencies:** + - Use mocking to isolate your code from external dependencies, such as network requests or database connections. + - Jest provides built-in mocking capabilities with `jest.mock` and `jest.spyOn`. + - Consider using a library like `axios-mock-adapter` for mocking HTTP requests. + +- **Write tests that are easy to read and maintain:** + - Keep your tests concise and focused. + - Use clear and consistent formatting. + - Add comments to explain complex logic. + - Refactor your tests regularly to keep them up to date. + +- **Aim for high test coverage, but prioritize meaningful tests over quantity:** + - Aim for high test coverage to ensure that your code is well-tested. + - However, prioritize writing meaningful tests that verify the core functionality of your code. + - Don't just aim for 100% coverage without considering the value of each test. + +- **Use Jest's built-in matchers effectively:** + - Jest provides a rich set of matchers for asserting different conditions. + - Use matchers like `toBe`, `toEqual`, `toBeGreaterThan`, `toContain`, `toHaveBeenCalled`, etc. + - Explore the Jest documentation for the full list of matchers. + +- **Handle asynchronous code correctly:** + - Use `async/await` or Promises to handle asynchronous code in your tests. + - Use the `resolves` and `rejects` matchers to assert that a Promise resolves or rejects. + - Example: `expect(myAsyncFunction()).resolves.toBe(expectedValue);` + +- **Test error handling:** + - Write tests to verify that your code handles errors correctly. + - Use the `toThrow` matcher to assert that a function throws an error. + - Example: `expect(() => myDangerousFunction()).toThrow(Error);` + +- **Use snapshots sparingly:** + - Snapshots can be useful for verifying the output of a component or function. + - However, they can also be brittle and difficult to maintain if used excessively. + - Use snapshots strategically and review them carefully when they change. + +- **Configure Jest correctly:** + - Configure Jest using the `jest.config.js` or `jest.config.ts` file. + - Configure settings such as test environment, module file extensions, and coverage thresholds. + - Consider using presets like `ts-jest` or `babel-jest` for TypeScript or Babel support. + +- **Leverage code coverage reports:** + - Use Jest's code coverage reports to identify areas of your code that are not well-tested. + - Aim to increase coverage in critical areas of your codebase. + - Use the `--coverage` flag to generate coverage reports. + +- **Keep test data separate from test logic:** + - Externalize test data to improve readability and maintainability. + - Use fixtures or factories to generate test data. + - Avoid hardcoding data directly in your tests. + +- **Consider using test-driven development (TDD):** + - Write tests before you write code to drive the development process. + - This can help you write more testable and well-designed code. + +- **Run tests frequently:** + - Run your tests frequently to catch errors early. + - Use Jest's watch mode to automatically run tests when files change. + - Integrate tests into your CI/CD pipeline. + +- **Document your tests:** + - Add comments to explain the purpose of each test and the expected behavior. + - This will make it easier for others to understand and maintain your tests. + +- **Code Organization and Structure:** + - **Directory structure best practices:** Organize test files alongside the component/module they test (e.g., `src/components/MyComponent/MyComponent.test.js`) + - **File naming conventions:** Use `.test.js` or `.spec.js` suffixes for test files (e.g., `MyComponent.test.js`, `MyModule.spec.ts`). + - **Module organization:** Keep test files close to the modules they are testing. Use a consistent naming convention for test files. + - **Component architecture:** Test components in isolation, mocking dependencies where necessary. + - **Code splitting strategies:** Ensure tests cover all code paths in dynamically imported modules. + +- **Common Patterns and Anti-patterns:** + - **Design patterns specific to Jest:** Use Page Object Model (POM) for UI tests, Factory pattern for test data generation. + - **Recommended approaches for common tasks:** Use `jest.mock` for mocking modules, `jest.spyOn` for spying on methods, and `fakeTimers` for controlling time-dependent behavior. + - **Anti-patterns and code smells to avoid:** Avoid testing implementation details, relying on global state, and creating brittle snapshots. + - **State management best practices:** Mock external state dependencies and verify state changes using `expect` assertions. + - **Error handling patterns:** Test for specific error messages and ensure error boundaries are properly tested. + +- **Performance Considerations:** + - **Optimization techniques:** Use `jest.clearAllMocks` and `jest.resetAllMocks` in `beforeEach` blocks to prevent state leakage and improve test performance. + - **Memory management:** Avoid creating large data structures in tests that are not necessary. Manually trigger garbage collection in tests where large objects are created and released. + - **Rendering optimization:** Mock expensive rendering logic to speed up tests that involve React components. + - **Bundle size optimization:** Not applicable, as Jest primarily tests individual modules or components. + - **Lazy loading strategies:** Ensure tests cover all code paths in dynamically imported modules. + +- **Security Best Practices:** + - **Common vulnerabilities and how to prevent them:** Avoid using sensitive data in test snapshots. Sanitize test data to prevent potential injection attacks. + - **Input validation:** Test input validation logic and ensure that invalid inputs are handled correctly. + - **Authentication and authorization patterns:** Mock authentication and authorization logic to test different user roles and permissions. + - **Data protection strategies:** Not directly applicable, as Jest primarily focuses on functional testing. + - **Secure API communication:** Mock API calls and verify that data is transmitted securely. + +- **Testing Approaches:** + - **Unit testing strategies:** Test individual functions, classes, or components in isolation. + - **Integration testing:** Test interactions between different modules or components. + - **End-to-end testing:** Use tools like Cypress or Playwright for end-to-end tests. + - **Test organization:** Group tests into logical suites based on functionality or module. + - **Mocking and stubbing:** Use `jest.mock` and `jest.spyOn` to create mocks and stubs for dependencies. + +- **Common Pitfalls and Gotchas:** + - **Frequent mistakes developers make:** Forgetting to mock dependencies, testing implementation details, and creating brittle snapshots. + - **Edge cases to be aware of:** Testing asynchronous code correctly, handling errors, and testing different input types. + - **Version-specific issues:** Be aware of breaking changes in Jest updates and update your tests accordingly. + - **Compatibility concerns:** Ensure tests are compatible with different browsers or environments. + - **Debugging strategies:** Use `console.log` statements, debuggers, or Jest's interactive mode to debug tests. + +- **Tooling and Environment:** + - **Recommended development tools:** VS Code, WebStorm, Jest Runner extension. + - **Build configuration:** Configure Jest using `jest.config.js` or `package.json`. + - **Linting and formatting:** Use ESLint and Prettier to enforce code style and prevent errors. + - **Deployment best practices:** Integrate tests into your CI/CD pipeline to ensure code quality. + - **CI/CD integration:** Use tools like GitHub Actions, Jenkins, or CircleCI to automate testing and deployment. \ No newline at end of file diff --git a/rules-mdc/development_tools/testing/playwright.mdc b/rules-mdc/development_tools/testing/playwright.mdc new file mode 100644 index 0000000..f033ff5 --- /dev/null +++ b/rules-mdc/development_tools/testing/playwright.mdc @@ -0,0 +1,151 @@ +--- +description: This rule enforces best practices and coding standards for Playwright tests, including stable selectors, test isolation, user-centric testing, and performance considerations. +globs: **/*.spec.ts +--- +- **General Principles** + - **Test User-Visible Behavior:** Focus tests on how users interact with your application, not on internal implementation details. + - **Isolate Tests:** Ensure tests are independent of each other to prevent cascading failures and ensure predictable results. + - **Avoid Testing Third-Party Dependencies:** Mock or stub external services and APIs to isolate your application's behavior. + +- **Code Organization and Structure** + - **Directory Structure:** + - `tests/`: Contains all test files. + - `tests/e2e/`: End-to-end tests. + - `tests/unit/`: Unit tests (if applicable, though Playwright is primarily for E2E). + - `tests/utils/`: Helper functions and page object models. + - **File Naming Conventions:** + - Use `.spec.ts` or `.spec.js` for test files (e.g., `login.spec.ts`). + - Group related tests in the same file. + - **Module Organization:** + - Employ Page Object Model (POM) to encapsulate UI elements and interactions. + - **Component Architecture:** + - Structure tests around components or features of your application. + - **Code Splitting Strategies:** + - Not directly applicable to tests, but keep test files concise and focused. + +- **Common Patterns and Anti-patterns** + - **Design Patterns:** + - **Page Object Model (POM):** A common pattern where each page is represented as a class, with methods for interacting with the page's elements. This improves reusability and maintainability. Example: + typescript + class LoginPage { + constructor(private readonly page: Page) {} + + async goto() { + await this.page.goto('/login'); + } + + async login(username: string, password: string) { + await this.page.fill('#username', username); + await this.page.fill('#password', password); + await this.page.click('#login-button'); + } + + async getErrorMessage() { + return await this.page.textContent('#error-message'); + } + } + + - **Fixture pattern:** Use Playwright's built-in fixtures to manage test setup and teardown. This ensures each test starts in a clean state. + - **Recommended Approaches:** + - Use `baseURL` in `playwright.config.ts` to avoid hardcoding URLs in tests. + - Utilize `expect` matchers for assertions (e.g., `expect(page.locator('#success')).toBeVisible()`). + - Use auto-waiting features for improved stability. + - **Anti-patterns:** + - Hardcoding URLs. + - Using brittle selectors (e.g., XPath based on DOM structure). + - Writing tests that depend on each other. + - **State Management:** + - Keep tests stateless. Reset the application state before each test. + - Use database transactions or API calls to seed data for tests. + - **Error Handling:** + - Use `try...catch` blocks to handle expected errors. + - Log errors and failures with descriptive messages. + - Use `expect.soft()` for non-critical assertions that shouldn't fail the test immediately. + +- **Performance Considerations** + - **Optimization Techniques:** + - Run tests in parallel to reduce overall test execution time. + - Use `reuseExistingServer: true` in `playwright.config.ts` during development to speed up debugging. + - Use `codegen` to generate selectors automatically. + - **Memory Management:** + - Close pages and browsers after each test or group of tests to release resources. + - **Rendering Optimization:** + - Not directly applicable but optimize your application's rendering for faster testing. + - **Bundle Size Optimization:** + - Not directly applicable, but optimize your application's bundle size for faster loading. + - **Lazy Loading Strategies:** + - Not directly applicable to tests. + +- **Security Best Practices** + - **Common Vulnerabilities:** + - Avoid exposing sensitive data (e.g., passwords, API keys) in test code or logs. + - **Input Validation:** + - Test input validation to ensure your application handles invalid data correctly. + - **Authentication and Authorization:** + - Test different user roles and permissions. + - **Data Protection:** + - Ensure sensitive data is encrypted in the database. + - **Secure API Communication:** + - Test that API calls are made over HTTPS. + +- **Testing Approaches** + - **Unit Testing:** + - While Playwright primarily focuses on E2E testing, unit tests can be written for utility functions or components. + - **Integration Testing:** + - Test the interaction between different parts of your application. + - **End-to-End Testing:** + - Simulate user flows to test the entire application. + - **Test Organization:** + - Group tests by feature or functionality. + - Use `describe` blocks to organize tests. + - **Mocking and Stubbing:** + - Use Playwright's `route` API to mock API responses. + - Use `locator.evaluate` to stub JavaScript functions. + +- **Common Pitfalls and Gotchas** + - **Frequent Mistakes:** + - Using XPath instead of CSS selectors. + - Not using auto-waiting features. + - Writing flaky tests. + - **Edge Cases:** + - Handling different screen sizes and devices. + - Testing error conditions and edge cases. + - **Version-Specific Issues:** + - Stay up-to-date with Playwright's release notes and upgrade guides. + - **Compatibility Concerns:** + - Test on different browsers and operating systems. + - **Debugging Strategies:** + - Use Playwright Inspector to debug tests visually. + - Use `console.log` statements to log information during test execution. + - Use `pause()` to halt test execution and inspect the page. + +- **Tooling and Environment** + - **Recommended Development Tools:** + - VS Code with the Playwright extension. + - **Build Configuration:** + - Use TypeScript for type safety and autocompletion. + - **Linting and Formatting:** + - Use ESLint and Prettier to enforce code style. + - **Deployment Best Practices:** + - Run tests in CI/CD pipeline before deploying to production. + - **CI/CD Integration:** + - Integrate Playwright with CI/CD tools like GitHub Actions, Jenkins, or GitLab CI. + +- **Specific Best Practices & Details** + - **Stable Selectors:** Prefer CSS selectors based on attributes like `data-testid` or `data-test-id` over XPath or fragile CSS classnames. + - **Leverage Auto-waiting:** Playwright automatically waits for elements to be actionable before performing actions. Avoid explicit waits where possible. However, use explicit waits (e.g. `waitForSelector`) when necessary. + - **Web-First Assertions:** Use `expect` assertions, which retry and wait for conditions to be met. They help to avoid flakiness. + - **Configure Debugging Highlights:** Configure `playwright.config.ts` to highlight actions performed by playwright in the browser during debugging to see what's happening step by step. Example: + typescript + use: { + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + video: 'on', + screenshot: 'only-on-failure', + } + + +- **Additional Notes** + - Regularly review and update your test suite to reflect changes in your application. + - Document your tests to make them easier to understand and maintain. + - Use a consistent naming convention for your tests. \ No newline at end of file diff --git a/rules-mdc/development_tools/testing/vitest.mdc b/rules-mdc/development_tools/testing/vitest.mdc new file mode 100644 index 0000000..c88181d --- /dev/null +++ b/rules-mdc/development_tools/testing/vitest.mdc @@ -0,0 +1,363 @@ +--- +description: This rule file provides comprehensive best practices for using Vitest, covering code organization, testing strategies, performance, and security within Vitest projects. These guidelines ensure clean, maintainable, and reliable test suites. +globs: **/*.{js,jsx,ts,tsx,vue,svelte,spec,test}.* +--- +# Vitest Best Practices and Coding Standards + +This document outlines best practices for using Vitest to create reliable, maintainable, and performant test suites. It covers various aspects of testing, from code organization to performance considerations and security measures. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure + +* **Keep tests close to the source code:** Place test files in the same directory as the components or modules they test. This improves discoverability and maintainability. + + + src/ + components/ + MyComponent.vue + MyComponent.spec.ts + MyComponent.test.ts # Alternative naming + utils/ + math.ts + math.test.ts + App.vue + App.spec.ts + + +* **Use a dedicated `tests` directory for end-to-end tests or shared utilities:** For larger projects, a `tests` directory at the root level can house end-to-end tests, integration tests that require a specific environment, or shared testing utilities. + + + tests/ + e2e/ + specs/ + home.spec.ts + support/ + commands.ts + unit/ + utils.test.ts # Tests for general utilities + integration/ + db.setup.ts # Setup for integration tests + src/ + ... + + +### 1.2 File Naming Conventions + +* **Use consistent naming:** Adopt a consistent naming scheme for test files. Common conventions include: + * `[component/module].spec.ts` + * `[component/module].test.ts` + * `[component/module].e2e.ts` (for end-to-end tests) + +* **Be descriptive:** Name test files to clearly indicate what they are testing. For example, `MyComponent.props.spec.ts` might test specific props of `MyComponent`. + +### 1.3 Module Organization + +* **Group related tests:** Organize tests into modules using `describe` blocks. This improves readability and helps structure test output. + + typescript + import { describe, it, expect } from 'vitest'; + import { add } from './math'; + + describe('Math functions', () => { + describe('add', () => { + it('should add two numbers correctly', () => { + expect(add(2, 3)).toBe(5); + }); + + it('should handle negative numbers', () => { + expect(add(-1, 1)).toBe(0); + }); + }); + }); + + +### 1.4 Component Architecture + +* **Test component logic separately:** Extract complex logic from components into separate, testable functions or modules. This promotes reusability and simplifies component testing. + +* **Focus on component interactions:** When testing components, concentrate on verifying that the component renders correctly given certain props or state and that it emits the correct events in response to user interactions. + +### 1.5 Code Splitting Strategies + +* **Test code splitting:** If your application uses code splitting, ensure your tests cover different code chunks and lazy-loaded modules. + +* **Mock dynamic imports:** Use Vitest's mocking capabilities to simulate dynamic imports during testing. + + typescript + import { describe, it, expect, vi } from 'vitest'; + + describe('Dynamic import', () => { + it('should mock dynamic import', async () => { + const mockModule = { value: 'mocked' }; + vi.mock('./dynamic-module', () => ({ + default: mockModule, + })); + + const dynamicModule = await import('./dynamic-module'); + expect(dynamicModule.default).toBe(mockModule); + }); + }); + + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to Vitest + +* **AAA (Arrange, Act, Assert):** Structure each test case following the AAA pattern for clarity and maintainability. + + typescript + it('should add two numbers correctly', () => { + // Arrange + const a = 2; + const b = 3; + + // Act + const result = add(a, b); + + // Assert + expect(result).toBe(5); + }); + + +* **Page Object Model (POM):** For end-to-end tests, use the Page Object Model to abstract away the details of the user interface and make tests more resilient to UI changes. Define dedicated classes representing different pages or components. + +### 2.2 Recommended Approaches for Common Tasks + +* **Mocking external dependencies:** Use Vitest's mocking capabilities to isolate units of code during testing. Use `vi.mock()` to mock modules and `vi.spyOn()` to spy on specific methods or properties. + +* **Testing asynchronous code:** Utilize `async/await` and Vitest's `expect.resolves` and `expect.rejects` matchers for testing asynchronous functions. + + typescript + it('should resolve with the correct value', async () => { + await expect(Promise.resolve(42)).resolves.toBe(42); + }); + + it('should reject with an error', async () => { + await expect(Promise.reject(new Error('Something went wrong'))).rejects.toThrow('Something went wrong'); + }); + + +### 2.3 Anti-patterns and Code Smells to Avoid + +* **Over-mocking:** Avoid mocking everything. Mock only external dependencies or components that are not under test. Testing against mocks rather than real implementations reduces test confidence. + +* **Flaky tests:** Tests that pass or fail intermittently are a sign of underlying issues. Investigate flaky tests to identify and fix the root cause, such as race conditions or reliance on external resources. + +* **Ignoring edge cases:** Ensure your tests cover all possible scenarios, including edge cases, error conditions, and boundary values. Don't only test the "happy path". + +* **Long test functions:** Break down overly complex test functions into smaller, more focused tests. This improves readability and makes it easier to identify the cause of failures. + +### 2.4 State Management Best Practices + +* **Isolate state:** When testing code that relies on state management libraries (e.g., Vuex, Pinia, Redux), isolate the state and actions being tested. + +* **Mock store actions/getters:** Mock actions and getters to control the state during testing and verify that they are called correctly. + + typescript + import { describe, it, expect, vi } from 'vitest'; + import { useStore } from './store'; + + describe('Store actions', () => { + it('should dispatch the correct action', () => { + const store = useStore(); + const mockAction = vi.fn(); + store.dispatch = mockAction; + + store.commit('increment'); + expect(mockAction).toHaveBeenCalledWith('increment'); + }); + }); + + +### 2.5 Error Handling Patterns + +* **Test error handling:** Ensure your tests cover error handling scenarios. Use `try...catch` blocks or `expect.rejects` to verify that errors are thrown and handled correctly. + +* **Mock error responses:** Mock API responses to simulate error conditions and test how your code handles them. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +* **Run tests in parallel:** Vitest supports running tests in parallel. Enable this feature to speed up test execution. + + json + // vitest.config.ts + import { defineConfig } from 'vitest/config' + + export default defineConfig({ + test: { + threads: true, // Enable parallel execution + }, + }) + + +* **Use `--changed` and `--related` flags:** When running tests, use the `--changed` flag to only run tests that have changed since the last commit or the `--related` flag to run tests related to specific files. + + bash + vitest --changed + vitest --related src/components/MyComponent.vue + + +* **Optimize test setup:** Minimize the amount of setup required for each test. Use `beforeAll` and `afterAll` hooks to perform setup and teardown operations once for each test suite, rather than for each test case. + +### 3.2 Memory Management + +* **Clean up after tests:** Ensure that your tests do not leak memory. Use `afterEach` hooks to clean up any resources created during the test, such as mocks or temporary files. + +* **Avoid creating large objects in tests:** Minimize the size of objects created in tests to reduce memory consumption. + +### 3.3 Rendering Optimization + +* **Use shallow rendering:** When testing components, use shallow rendering to avoid rendering the entire component tree. This can significantly improve test performance. + + typescript + import { shallowMount } from '@vue/test-utils'; + import MyComponent from './MyComponent.vue'; + + it('should render correctly', () => { + const wrapper = shallowMount(MyComponent); + expect(wrapper.exists()).toBe(true); + }); + + +### 3.4 Bundle Size Optimization + +* **Keep tests small:** Avoid including unnecessary dependencies in your test files. This can help reduce the bundle size of your tests and improve startup time. + +### 3.5 Lazy Loading Strategies + +* **Mock lazy-loaded modules:** When testing code that uses lazy loading, mock the lazy-loaded modules to avoid loading them during testing. This can improve test performance and reduce dependencies. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by sanitizing user input and encoding output. Ensure the testing framework is not vulnerable either. Check versions of plugins. + +* **Injection Attacks:** Prevent injection attacks by validating user input and using parameterized queries. + +* **Sensitive Data Exposure:** Avoid storing sensitive data in test files. Use environment variables or secure configuration files to manage sensitive data. + +### 4.2 Input Validation + +* **Test input validation:** Ensure your tests cover input validation scenarios. Verify that your code correctly validates user input and handles invalid input gracefully. + +### 4.3 Authentication and Authorization Patterns + +* **Mock authentication:** When testing code that requires authentication, mock the authentication service to avoid making actual API calls. Verify that your code correctly handles authenticated and unauthenticated states. + +* **Test authorization:** Ensure your tests cover authorization scenarios. Verify that your code correctly enforces access control and prevents unauthorized access to resources. + +### 4.4 Data Protection Strategies + +* **Protect sensitive data in tests:** Avoid including sensitive data in your test files. Use mock data or anonymized data for testing. + +### 4.5 Secure API Communication + +* **Mock API responses:** Mock API responses to avoid making actual API calls during testing. Use HTTPS for secure communication. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +* **Focus on individual units:** Unit tests should focus on testing individual functions, classes, or modules in isolation. Avoid testing multiple units of code in a single test. + +* **Test all code paths:** Ensure your unit tests cover all possible code paths, including normal execution paths, error conditions, and edge cases. + +* **Use mocks and stubs:** Use mocks and stubs to isolate units of code and control their behavior during testing. + +### 5.2 Integration Testing + +* **Test interactions between units:** Integration tests should focus on testing the interactions between different units of code. Verify that units of code work together correctly. + +* **Use real dependencies:** Use real dependencies in integration tests whenever possible. This can help ensure that your code works correctly in a real-world environment. + +### 5.3 End-to-End Testing + +* **Test the entire application:** End-to-end tests should focus on testing the entire application, from the user interface to the backend services. Verify that the application works correctly from the user's perspective. + +* **Use a real browser:** Use a real browser for end-to-end testing. This can help ensure that your application works correctly in different browsers and environments. + +### 5.4 Test Organization + +* **Group related tests:** Organize tests into modules using `describe` blocks. This improves readability and helps structure test output. (See 1.3 Module Organization) + +* **Use meaningful test names:** Use descriptive test names that clearly indicate what the test is verifying. This makes it easier to understand the purpose of the test and to identify the cause of failures. + +* **Keep tests short and focused:** Keep tests short and focused on a single aspect of the code. This improves readability and makes it easier to maintain the tests. + +### 5.5 Mocking and Stubbing + +* **Use mocks to verify interactions:** Use mocks to verify that functions are called with the correct arguments and that they return the correct values. + +* **Use stubs to control behavior:** Use stubs to control the behavior of functions during testing. This allows you to simulate different scenarios and test how your code handles them. + +* **Avoid over-mocking:** Only mock dependencies that are not under test. Over-mocking can lead to tests that are brittle and do not accurately reflect the behavior of the code. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +* **Not writing enough tests:** Ensure that you have sufficient test coverage to catch bugs and prevent regressions. + +* **Writing brittle tests:** Avoid writing tests that are too tightly coupled to the implementation details of the code. This makes the tests brittle and difficult to maintain. + +* **Ignoring test failures:** Address test failures promptly. Ignoring test failures can lead to regressions and make it more difficult to maintain the code. + +### 6.2 Edge Cases to Be Aware Of + +* **Null and undefined values:** Ensure your tests cover scenarios where values are null or undefined. + +* **Empty strings and arrays:** Ensure your tests cover scenarios where strings or arrays are empty. + +* **Boundary values:** Ensure your tests cover boundary values, such as the minimum and maximum values of numeric types. + +### 6.3 Version-Specific Issues + +* **Keep Vitest up to date:** Stay up-to-date with the latest version of Vitest to benefit from bug fixes, performance improvements, and new features. + +### 6.4 Compatibility Concerns + +* **Test on different browsers and environments:** Ensure your tests cover different browsers and environments to catch compatibility issues. + +### 6.5 Debugging Strategies + +* **Use debugging tools:** Utilize debugging tools to step through your tests and identify the cause of failures. Vitest integrates with popular debuggers. + +* **Write clear and concise tests:** Write clear and concise tests to make it easier to understand the purpose of the test and to identify the cause of failures. + +* **Use logging:** Add logging statements to your tests to help track the flow of execution and identify the source of problems. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +* **VS Code with the Vitest extension:** VS Code with the Vitest extension provides a rich development experience, including test discovery, execution, and debugging. + +* **Other IDEs with Vitest support:** Many other IDEs, such as WebStorm and IntelliJ IDEA, also offer support for Vitest. + +### 7.2 Build Configuration + +* **Use a build tool:** Use a build tool, such as Vite or esbuild, to bundle your code and optimize it for testing. + +* **Configure Vitest:** Configure Vitest to suit your project's needs. Use the `vitest.config.ts` file to customize Vitest's behavior. + +### 7.3 Linting and Formatting + +* **Use ESLint and Prettier:** Use ESLint and Prettier to enforce consistent coding styles and catch potential errors. Integrate these tools into your development workflow. + +### 7.4 Deployment Best Practices + +* **Run tests before deployment:** Always run your tests before deploying your code to ensure that it is working correctly. Automate this process as part of your CI/CD pipeline. + +### 7.5 CI/CD Integration + +* **Integrate Vitest with your CI/CD pipeline:** Integrate Vitest with your CI/CD pipeline to automatically run tests on every commit. This helps catch bugs early and prevent regressions. + +* **Use a CI/CD service:** Use a CI/CD service, such as GitHub Actions or GitLab CI, to automate your build, test, and deployment processes. + +## Conclusion + +By following these best practices, you can create robust and maintainable test suites with Vitest that ensure the quality and reliability of your code. \ No newline at end of file diff --git a/rules-mdc/development_tools/version_control/git.mdc b/rules-mdc/development_tools/version_control/git.mdc new file mode 100644 index 0000000..a7bafd0 --- /dev/null +++ b/rules-mdc/development_tools/version_control/git.mdc @@ -0,0 +1,85 @@ +--- +description: This rule outlines best practices for effective use of Git, including code organization, commit strategies, branching models, and collaborative workflows. +globs: **/.git/* +--- +- **Commit Strategies:** + - **Atomic Commits:** Keep commits small and focused. Each commit should address a single, logical change. This makes it easier to understand the history and revert changes if needed. + - **Descriptive Commit Messages:** Write clear, concise, and informative commit messages. Explain the *why* behind the change, not just *what* was changed. Use a consistent format (e.g., imperative mood: "Fix bug", "Add feature"). + - **Commit Frequently:** Commit early and often. This helps avoid losing work and makes it easier to track progress. + - **Avoid Committing Broken Code:** Ensure your code compiles and passes basic tests before committing. + - **Sign Your Commits (Optional but Recommended):** Use GPG signing to verify the authenticity of your commits. + +- **Branching Model:** + - **Use Feature Branches:** Create branches for each new feature or bug fix. This isolates changes and allows for easier code review. + - **Gitflow or Similar:** Consider adopting a branching model like Gitflow for managing releases, hotfixes, and feature development. + - **Short-Lived Branches:** Keep branches short-lived. The longer a branch exists, the harder it becomes to merge. + - **Regularly Rebase or Merge:** Keep your feature branches up-to-date with the main branch (e.g., `main`, `develop`) by rebasing or merging regularly. + - **Avoid Direct Commits to Main Branch:** Protect your main branch from direct commits. Use pull requests for all changes. + +- **Code Organization:** + - **Consistent Formatting:** Use a consistent coding style guide (e.g., PEP 8 for Python, Google Style Guide for other languages) and enforce it with linters and formatters (e.g., `flake8`, `pylint`, `prettier`). + - **Modular Code:** Break down your codebase into smaller, manageable modules or components. This improves readability, maintainability, and testability. + - **Well-Defined Interfaces:** Define clear interfaces between modules and components to promote loose coupling. + - **Avoid Global State:** Minimize the use of global variables and state to reduce complexity and potential conflicts. + - **Documentation:** Document your code with comments and docstrings. Explain the purpose of functions, classes, and modules. + +- **Collaboration and Code Review:** + - **Pull Requests:** Use pull requests for all code changes. This provides an opportunity for code review and discussion. + - **Code Review Checklist:** Create a code review checklist to ensure consistency and thoroughness. + - **Constructive Feedback:** Provide constructive feedback during code reviews. Focus on improving the code, not criticizing the author. + - **Address Feedback:** Respond to and address feedback from code reviews promptly. + - **Pair Programming:** Consider pair programming for complex or critical tasks. + +- **Ignoring Files and Directories:** + - **.gitignore:** Use a `.gitignore` file to exclude files and directories that should not be tracked by Git (e.g., build artifacts, temporary files, secrets). + - **Global .gitignore:** Configure a global `.gitignore` file to exclude files that you never want to track in any Git repository. + +- **Handling Secrets and Sensitive Information:** + - **Never Commit Secrets:** Never commit secrets, passwords, API keys, or other sensitive information to your Git repository. + - **Environment Variables:** Store secrets in environment variables and access them at runtime. + - **Secret Management Tools:** Use secret management tools like HashiCorp Vault or AWS Secrets Manager to store and manage secrets securely. + - **git-secret or similar:** If secrets must exist in the repo (strongly discouraged), encrypt them. + +- **Submodules and Subtrees:** + - **Use Sparingly:** Use Git submodules and subtrees sparingly, as they can add complexity. + - **Understand the Implications:** Understand the implications of using submodules and subtrees before adopting them. + - **Consider Alternatives:** Consider alternatives to submodules and subtrees, such as package managers or build systems. + +- **Large File Storage (LFS):** + - **Use for Large Files:** Use Git LFS for storing large files (e.g., images, videos, audio files). This prevents your repository from becoming bloated. + - **Configure LFS:** Configure Git LFS properly to track the large files in your repository. + +- **Reverting and Resetting:** + - **Understand the Differences:** Understand the differences between `git revert`, `git reset`, and `git checkout` before using them. + - **Use with Caution:** Use `git reset` and `git checkout` with caution, as they can potentially lose data. + - **Revert Public Commits:** Use `git revert` to undo changes that have already been pushed to a public repository. This creates a new commit that reverses the changes. + +- **Tagging Releases:** + - **Create Tags:** Create tags to mark significant releases or milestones. + - **Semantic Versioning:** Follow semantic versioning (SemVer) when tagging releases. + - **Annotated Tags:** Use annotated tags to provide additional information about the release. + +- **Dealing with Merge Conflicts:** + - **Understand the Conflict:** Understand the source of the merge conflict before attempting to resolve it. + - **Communicate with Others:** Communicate with other developers who may be affected by the conflict. + - **Use a Merge Tool:** Use a merge tool to help resolve the conflict. + - **Test After Resolving:** Test your code thoroughly after resolving the conflict. + +- **Repository Maintenance:** + - **Regularly Clean Up:** Regularly clean up your Git repository by removing unused branches and tags. + - **Optimize the Repository:** Optimize the repository with `git gc` to improve performance. + +- **CI/CD Integration:** + - **Automate Testing:** Integrate Git with a CI/CD system to automate testing and deployment. + - **Run Tests on Every Commit:** Run tests on every commit to ensure code quality. + +- **Common Pitfalls and Gotchas:** + - **Accidental Commits:** Accidentally committing sensitive information or large files. + - **Merge Conflicts:** Difficulty resolving merge conflicts. + - **Losing Work:** Losing work due to incorrect use of `git reset` or `git checkout`. + - **Ignoring .gitignore:** Forgetting to add files to `.gitignore`. + +- **Tooling and Environment:** + - **Git Clients:** Use a Git client that suits your needs (e.g., command line, GUI). + - **IDE Integration:** Use Git integration in your IDE to streamline workflows. + - **Online Repositories:** Use a reliable online Git repository hosting service (e.g., GitHub, GitLab, Bitbucket). \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/angular/angular.mdc b/rules-mdc/frontend_frameworks/angular/angular.mdc new file mode 100644 index 0000000..cfe0e4e --- /dev/null +++ b/rules-mdc/frontend_frameworks/angular/angular.mdc @@ -0,0 +1,278 @@ +--- +description: This rule provides comprehensive guidelines for Angular development, covering coding standards, best practices, performance optimization, security considerations, and testing approaches to ensure maintainable, scalable, and high-performing applications. +globs: **/*.{ts,html,scss,css} +--- +# Angular Best Practices and Coding Standards + +This document outlines comprehensive best practices and coding standards for developing Angular applications. Adhering to these guidelines will promote maintainability, scalability, performance, and security. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure Best Practices + +- **Feature-based Modules:** Organize your application into feature modules, where each module encapsulates a specific feature or functionality. +- **Shared Module:** Create a `shared` module for commonly used components, directives, pipes, and services. +- **Core Module:** Create a `core` module for application-wide services and singleton instances (e.g., authentication service, configuration service). +- **Lazy-loaded Modules:** Group related features into lazy-loaded modules to improve initial load time. +- **Directory structure example:** + + + src/ + ├── app/ + │ ├── core/ + │ │ ├── core.module.ts + │ │ └── auth.service.ts + │ ├── shared/ + │ │ ├── shared.module.ts + │ │ └── components/ + │ │ └── ... + │ ├── features/ + │ │ ├── dashboard/ + │ │ │ ├── dashboard.module.ts + │ │ │ ├── dashboard.component.ts + │ │ │ └── dashboard.component.html + │ │ ├── user-management/ + │ │ │ ├── user-management.module.ts + │ │ │ └── ... + │ │ └── ... + │ ├── app.component.ts + │ └── app.module.ts + └── ... + + +### 1.2. File Naming Conventions + +- **Consistent Naming:** Use a consistent naming pattern for all files and symbols, following the `feature.type.ts` convention (e.g., `user.component.ts`, `user.service.ts`). +- **Type Abbreviations:** Use abbreviations for file types (e.g., `component.ts` -> `.component.ts`, `service.ts` -> `.service.ts`, `module.ts` -> `.module.ts`). +- **Descriptive Names:** Use descriptive names that clearly indicate the purpose of the file. + +### 1.3. Module Organization + +- **Single Responsibility:** Each module should have a single responsibility. +- **Declarations:** Declare components, directives, and pipes within the appropriate module. +- **Imports:** Import only the necessary modules in each module. +- **Exports:** Export components, directives, and pipes that need to be used by other modules. +- **forRoot() pattern:** Use the `forRoot()` pattern for modules that provide singleton services to ensure they are only instantiated once in the application. + +### 1.4. Component Architecture + +- **Smart vs. Dumb Components:** Distinguish between smart (container) components that handle data and logic, and dumb (presentational) components that focus on rendering UI. +- **Component Reusability:** Design components for reusability. +- **Input and Output Properties:** Use `@Input()` and `@Output()` properties to pass data and events between components. +- **Change Detection:** Be mindful of change detection strategies (e.g., `OnPush`) to optimize rendering performance. + +### 1.5. Code Splitting Strategies + +- **Lazy Loading:** Implement lazy loading for modules to reduce the initial bundle size and improve load time. +- **Route-based Code Splitting:** Split your application into modules based on routes. +- **Feature-based Code Splitting:** Split your application into modules based on features. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to Angular + +- **Dependency Injection (DI):** Use DI to manage dependencies between components and services. +- **Observables:** Use RxJS Observables for handling asynchronous data streams. +- **Services:** Use services for encapsulating reusable business logic. +- **Pipes:** Use pipes for transforming data in templates. +- **Directives:** Use directives for manipulating the DOM. + +### 2.2. Recommended Approaches for Common Tasks + +- **Data Binding:** Use data binding (`{{ }}`, `[]`, `()`) to synchronize data between the component and the template. +- **Event Handling:** Use event binding (`()`) to handle user interactions. +- **Form Handling:** Use reactive forms or template-driven forms to manage user input. +- **HTTP Requests:** Use the `HttpClient` to make HTTP requests to backend APIs. + +### 2.3. Anti-patterns and Code Smells to Avoid + +- **Deeply Nested Components:** Avoid deeply nested component hierarchies, which can make it difficult to manage state and events. +- **Large Components:** Break large components into smaller, reusable components. +- **Logic in Templates:** Avoid complex logic in templates; move it to the component class. +- **Direct DOM Manipulation:** Avoid direct DOM manipulation; use Angular's data binding and directives instead. +- **Unnecessary Subscriptions:** Unsubscribe from Observables to prevent memory leaks. Use the `async` pipe in templates to automatically handle subscriptions and unsubscriptions. + +### 2.4. State Management Best Practices + +- **Choose a State Management Library:** Consider using a state management library like NgRx, Akita, or MobX for complex applications. +- **Centralized State:** Store application state in a central store. +- **Immutability:** Treat state as immutable to simplify change detection and debugging. +- **Actions and Reducers:** Use actions to describe state changes and reducers to update the state. +- **Selectors:** Use selectors to efficiently retrieve data from the store. + +### 2.5. Error Handling Patterns + +- **Centralized Error Handling:** Implement a centralized error handling mechanism using an `ErrorHandler`. +- **Error Interceptors:** Use HTTP interceptors to handle errors from backend APIs. +- **User-Friendly Error Messages:** Display user-friendly error messages to the user. +- **Logging:** Log errors to a central logging service for debugging and monitoring. +- **Retry mechanism:** Implement retry mechanism for failed requests using RxJS retry operators. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +- **Change Detection Optimization:** Use `OnPush` change detection strategy for components that only depend on their input properties. +- **TrackBy Function:** Use the `trackBy` function with `ngFor` to optimize rendering of lists. +- **Virtualization:** Use virtual scrolling for large lists to improve performance. +- **Ahead-of-Time (AOT) Compilation:** Use AOT compilation to compile templates during the build process, improving startup time. +- **Minification and Uglification:** Minify and uglify your code to reduce bundle size. + +### 3.2. Memory Management + +- **Unsubscribe from Observables:** Unsubscribe from Observables when they are no longer needed to prevent memory leaks. +- **Avoid Circular Dependencies:** Avoid circular dependencies, which can lead to memory leaks. +- **Detach Event Listeners:** Detach event listeners when they are no longer needed. + +### 3.3. Rendering Optimization + +- **Minimize DOM Manipulation:** Minimize DOM manipulation, as it can be expensive. +- **Use CSS Transforms:** Use CSS transforms instead of modifying layout properties. +- **Debouncing and Throttling:** Use debouncing and throttling to reduce the frequency of event handlers. + +### 3.4. Bundle Size Optimization + +- **Lazy Loading:** Implement lazy loading for modules to reduce the initial bundle size. +- **Tree Shaking:** Use tree shaking to remove unused code from your bundle. +- **Code Splitting:** Split your application into smaller bundles to improve load time. +- **Image Optimization:** Optimize images to reduce their file size. +- **Vendor Libraries:** Use only necessary vendor libraries, and ensure they are up-to-date for optimized versions. + +### 3.5. Lazy Loading Strategies + +- **Route-based Lazy Loading:** Load modules when navigating to a specific route. +- **Feature-based Lazy Loading:** Load modules based on feature requirements. +- **Preloading:** Preload modules in the background to improve perceived performance. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and avoiding the use of `innerHTML`. +- **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using anti-CSRF tokens. +- **Injection Attacks:** Prevent injection attacks by validating user input and using parameterized queries. + +### 4.2. Input Validation + +- **Client-Side Validation:** Perform client-side validation to provide immediate feedback to the user. +- **Server-Side Validation:** Perform server-side validation to ensure data integrity. +- **Whitelist Validation:** Use whitelist validation to allow only specific characters or patterns. + +### 4.3. Authentication and Authorization Patterns + +- **Authentication:** Implement authentication to verify the user's identity. +- **Authorization:** Implement authorization to control access to resources based on the user's roles and permissions. +- **JSON Web Tokens (JWT):** Use JWTs for secure authentication and authorization. +- **OAuth 2.0:** Use OAuth 2.0 for delegating authorization to third-party applications. + +### 4.4. Data Protection Strategies + +- **Encryption:** Encrypt sensitive data at rest and in transit. +- **Hashing:** Hash passwords before storing them in the database. +- **Data Masking:** Mask sensitive data to prevent unauthorized access. + +### 4.5. Secure API Communication + +- **HTTPS:** Use HTTPS for secure communication between the client and the server. +- **API Keys:** Use API keys to authenticate API requests. +- **Rate Limiting:** Implement rate limiting to prevent abuse of your API. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +- **Test Driven Development (TDD):** Write tests before writing code. +- **Component Testing:** Test components in isolation using mock data. +- **Service Testing:** Test services in isolation using dependency injection. +- **Pipe Testing:** Test pipes to ensure they transform data correctly. + +### 5.2. Integration Testing + +- **Module Testing:** Test modules to ensure they integrate correctly. +- **Component Interaction Testing:** Test the interaction between components. +- **HTTP Testing:** Test HTTP requests and responses. + +### 5.3. End-to-End Testing + +- **User Interface (UI) Testing:** Test the UI to ensure it behaves as expected. +- **Workflow Testing:** Test complete workflows to ensure they function correctly. +- **Cross-Browser Testing:** Test your application in different browsers. + +### 5.4. Test Organization + +- **Test Directory Structure:** Mirror your source code directory structure in your test directory. +- **Test File Naming:** Use consistent naming conventions for test files (e.g., `user.component.spec.ts`). +- **Test Suites:** Group related tests into test suites. + +### 5.5. Mocking and Stubbing + +- **Mock Dependencies:** Mock dependencies to isolate units of code for testing. +- **Stub HTTP Requests:** Stub HTTP requests to avoid making actual API calls during testing. +- **Use Mocking Libraries:** Use mocking libraries like Jasmine or Jest to simplify mocking and stubbing. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +- **Forgetting to Unsubscribe from Observables:** Always unsubscribe from Observables to prevent memory leaks. +- **Using `any` Type:** Avoid using the `any` type, as it bypasses type checking. +- **Not Handling Errors:** Handle errors gracefully to prevent unexpected behavior. +- **Ignoring Performance:** Optimize your code for performance from the beginning. + +### 6.2. Edge Cases to Be Aware Of + +- **Empty Arrays:** Handle empty arrays correctly. +- **Null Values:** Handle null values correctly. +- **Unexpected Input:** Validate user input to prevent unexpected behavior. + +### 6.3. Version-Specific Issues + +- **Breaking Changes:** Be aware of breaking changes in new versions of Angular and third-party libraries. +- **Deprecated APIs:** Avoid using deprecated APIs. +- **Migration Guides:** Follow migration guides when upgrading to new versions of Angular. + +### 6.4. Compatibility Concerns + +- **Browser Compatibility:** Test your application in different browsers to ensure compatibility. +- **Device Compatibility:** Test your application on different devices to ensure compatibility. + +### 6.5. Debugging Strategies + +- **Browser Developer Tools:** Use browser developer tools to debug your code. +- **Logging:** Use logging to track the flow of execution and identify errors. +- **Debugging Tools:** Use debugging tools like VS Code's debugger to step through your code. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +- **VS Code:** Use VS Code as your code editor. +- **Angular CLI:** Use the Angular CLI for scaffolding, building, and deploying your application. +- **Chrome Developer Tools:** Use Chrome Developer Tools for debugging and performance profiling. + +### 7.2. Build Configuration + +- **Angular CLI Configuration:** Configure your Angular CLI settings in the `angular.json` file. +- **Environment Variables:** Use environment variables to configure your application for different environments. +- **Build Optimization:** Configure your build process to optimize your code for production. + +### 7.3. Linting and Formatting + +- **ESLint:** Use ESLint to enforce coding standards. +- **Prettier:** Use Prettier to format your code automatically. +- **Husky:** Use Husky to run linters and formatters before committing code. + +### 7.4. Deployment Best Practices + +- **Continuous Integration/Continuous Deployment (CI/CD):** Use a CI/CD pipeline to automate the build, test, and deployment process. +- **Deployment Environments:** Use different deployment environments for development, testing, and production. +- **CDN:** Use a content delivery network (CDN) to serve static assets. + +### 7.5. CI/CD Integration + +- **Jenkins:** Use Jenkins for CI/CD. +- **GitHub Actions:** Use GitHub Actions for CI/CD. +- **Azure DevOps:** Use Azure DevOps for CI/CD. +- **GitLab CI:** Use GitLab CI for CI/CD. + +By following these best practices and coding standards, you can build robust, maintainable, and scalable Angular applications. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/qwik/qwik.mdc b/rules-mdc/frontend_frameworks/qwik/qwik.mdc new file mode 100644 index 0000000..06c8894 --- /dev/null +++ b/rules-mdc/frontend_frameworks/qwik/qwik.mdc @@ -0,0 +1,204 @@ +--- +description: This rule provides comprehensive best practices for developing Qwik applications, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers in writing maintainable, efficient, and secure Qwik code. +globs: **/*.ts?(x) +--- +# Qwik Library Best Practices + +This document outlines the best practices for developing Qwik applications. Adhering to these guidelines will help you write maintainable, efficient, and secure code. + +## 1. Code Organization and Structure + +- **Directory Structure:** + - `src/`: Contains the source code of your application. + - `components/`: Reusable UI components. + - `routes/`: Defines the application's routes and pages. Use the file system routing for easy setup. Each file under `routes` will become a route based on the filename. + - `services/`: Contains business logic and data fetching services. + - `utils/`: Utility functions and helpers. + - `styles/`: Global styles and themes. + - `types/`: Type definitions used throughout the application. + - `public/`: Static assets like images, fonts, and favicons. + - `vite.config.ts`: Vite configuration file. + - `tsconfig.json`: TypeScript configuration file. + - `.eslintrc.js`: ESLint configuration file. + +- **File Naming Conventions:** + - Components: `ComponentName.tsx` (e.g., `MyButton.tsx`). + - Services: `serviceName.ts` (e.g., `userService.ts`). + - Utilities: `utilityName.ts` (e.g., `dateUtils.ts`). + - Styles: `componentName.css` or `componentName.module.css`. + - Routes: Filename dictates the route path (e.g., `index.tsx` for `/`, `about.tsx` for `/about`). + +- **Module Organization:** + - Group related components, services, and utilities into modules. + - Use `index.ts` files to re-export members from a module for cleaner imports. + - Keep modules focused and avoid creating large, monolithic modules. + +- **Component Architecture:** + - Favor small, reusable components. + - Use a component-based architecture for building UIs. + - Separate concerns: presentational components and container components. + - Presentational components: Focus on rendering UI elements based on props. + - Container components: Handle data fetching, state management, and business logic. + - Use Qwik's `component$` and `use*` APIs for creating and managing components. + +- **Code Splitting Strategies:** + - Use Qwik's automatic code splitting capabilities. + - Ensure routes are lazily loaded by their nature in Qwik. + - For larger components or modules, consider manually triggering lazy loading. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Composition:** Build complex components by composing smaller, reusable components. + - **Provider Pattern:** Use Context to share state or services across multiple components. + - **Hooks:** Use Qwik's `use*` hooks to manage state, effects, and other side effects. + - **Factories:** For complex object creation, consider using factory functions. + +- **Recommended Approaches:** + - Use Qwik's state management features (`useStore`, `useSignal`) for managing component state. + - Use Qwik City's routing capabilities for defining routes and navigation. + - Use Qwik's optimizer and server rendering for performance. + +- **Anti-patterns and Code Smells:** + - **Large Components:** Avoid creating overly large components. Break them down into smaller, more manageable pieces. + - **Tight Coupling:** Reduce dependencies between components and modules. + - **Mutating Props:** Never directly modify props passed to a component. + - **Global State Abuse:** Avoid using global state excessively. Prefer component-level state management. + - **Ignoring Server Rendering:** Ensure your components are server-renderable for initial page load performance. + +- **State Management Best Practices:** + - Use Qwik's `useStore` for reactive state management. + - Consider `useSignal` for simpler reactive values. + - Avoid direct DOM manipulation; rely on Qwik's component rendering. + +- **Error Handling Patterns:** + - Use `try...catch` blocks to handle errors gracefully. + - Display user-friendly error messages. + - Log errors for debugging and monitoring. + - Consider using error boundary components to prevent entire application crashes. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - Use Qwik's optimizer to minimize bundle size and improve performance. + - Leverage server rendering to improve initial page load time. + - Optimize images and other assets. + - Use Qwik's built-in lazy loading features. + +- **Memory Management:** + - Avoid memory leaks by properly cleaning up resources. + - Unsubscribe from subscriptions and event listeners when components unmount. + +- **Rendering Optimization:** + - Use `track` property in `useStore` to selectively trigger updates. + - Memoize expensive computations using `useComputed$()` + - Avoid unnecessary re-renders by ensuring component props are stable. + +- **Bundle Size Optimization:** + - Use code splitting to reduce the initial bundle size. + - Remove unused code and dependencies. + - Use tree shaking to eliminate dead code. + +- **Lazy Loading Strategies:** + - Use Qwik's built-in lazy loading features for components and routes. + - Consider using dynamic imports for loading modules on demand. + +## 4. Security Best Practices + +- **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and using Qwik's built-in escaping mechanisms. + - **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by using tokens and validating requests. + - **Injection Attacks:** Prevent SQL injection and other injection attacks by using parameterized queries and escaping user inputs. + +- **Input Validation:** + - Validate all user inputs on both the client and server sides. + - Use appropriate data types and formats. + - Sanitize user inputs to prevent XSS attacks. + +- **Authentication and Authorization Patterns:** + - Use a secure authentication mechanism, such as OAuth or JWT. + - Implement proper authorization checks to ensure users only have access to the resources they are authorized to access. + +- **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between the client and server. + - Implement proper access controls to protect data from unauthorized access. + +- **Secure API Communication:** + - Use HTTPS for all API requests. + - Validate API responses. + - Implement rate limiting to prevent abuse. + +## 5. Testing Approaches + +- **Unit Testing Strategies:** + - Write unit tests for individual components, services, and utilities. + - Use a testing framework like Jest or Vitest. + - Mock dependencies to isolate units under test. + +- **Integration Testing:** + - Write integration tests to verify interactions between different parts of the application. + - Test the integration of components, services, and routes. + +- **End-to-end Testing:** + - Write end-to-end tests to verify the entire application flow. + - Use a testing framework like Playwright or Cypress. + - Test user interactions and navigation. + +- **Test Organization:** + - Organize tests into separate directories based on the type of test. + - Use descriptive test names. + - Follow a consistent testing style. + +- **Mocking and Stubbing:** + - Use mocking and stubbing to isolate units under test. + - Mock external dependencies, such as APIs and databases. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes:** + - Forgetting to use Qwik's `component$` for creating components. + - Not using `use*` hooks for managing state and effects. + - Over-reliance on `globalThis`. + +- **Edge Cases:** + - Handling errors during server rendering. + - Dealing with different browser environments. + - Managing application state across multiple pages. + +- **Version-Specific Issues:** + - Be aware of breaking changes between Qwik versions. + - Consult the Qwik changelog for migration instructions. + +- **Compatibility Concerns:** + - Ensure your application is compatible with different browsers and devices. + - Use polyfills to support older browsers. + +- **Debugging Strategies:** + - Use browser developer tools for debugging. + - Use Qwik's built-in debugging features. + - Log errors and warnings. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - Visual Studio Code with the Qwik extension. + - Node.js and npm. + - A modern web browser. + +- **Build Configuration:** + - Use Vite for building and bundling Qwik applications. + - Configure Vite to optimize the build for production. + +- **Linting and Formatting:** + - Use ESLint and Prettier for linting and formatting code. + - Configure ESLint and Prettier to follow Qwik's coding style. + +- **Deployment Best Practices:** + - Deploy your application to a serverless environment, such as Netlify or Vercel. + - Configure your server to serve static assets efficiently. + - Use a CDN to cache static assets. + +- **CI/CD Integration:** + - Integrate your application with a CI/CD pipeline. + - Automate testing, building, and deployment. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/react/next-js.mdc b/rules-mdc/frontend_frameworks/react/next-js.mdc new file mode 100644 index 0000000..8f5e2b8 --- /dev/null +++ b/rules-mdc/frontend_frameworks/react/next-js.mdc @@ -0,0 +1,169 @@ +--- +description: Enforces Next.js best practices for code organization, performance, security, and maintainability. This rule provides guidelines for structuring Next.js projects, optimizing performance, and avoiding common pitfalls. +globs: **/*.{js,jsx,ts,tsx} +--- +- **General Principles** + - **Use Static Generation (SSG) or Incremental Static Regeneration (ISR) where possible.** SSG offers the best performance by pre-rendering pages at build time. ISR allows you to update static pages after build time. + - **Optimize Images.** Use `next/image` for automatic image optimization, including resizing, format conversion, and lazy loading. + - **Utilize API Routes.** Create API endpoints using the `pages/api` directory for serverless functions. + - **Follow a Consistent Component Structure.** Maintain a clear and predictable component structure for reusability and maintainability. + - **Implement Code Splitting.** Split your code into smaller chunks using dynamic imports (`next/dynamic`) to improve initial load time. + - **Lazy Load Non-Essential Resources.** Defer loading of resources that are not critical for the initial page load. + - **Prefer Functional Programming and Immutable Data Structures.** This can improve code readability and reduce the risk of bugs. + - **Handle Errors Robustly.** Implement comprehensive error handling and logging throughout your application. + +- **Code Organization and Structure** + - **Directory Structure:** + - `pages/`: Contains page components and API routes. + - `components/`: Stores reusable UI components. + - `styles/`: Holds global and component-specific CSS/SCSS modules. + - `public/`: Static assets like images, fonts, and favicons. + - `lib/` or `utils/`: Utility functions and helper modules. + - `contexts/`: React Context providers for state management. + - `hooks/`: Custom React hooks. + - `types/` or `interfaces/`: TypeScript type definitions. + - **File Naming Conventions:** + - Use descriptive names for components and files (e.g., `ProductCard.tsx`, `useAuth.js`). + - Employ camelCase for JavaScript filenames and PascalCase for component filenames. + - Use kebab-case for CSS class names. + - **Module Organization:** + - Group related components and utilities into modules (e.g., `components/auth`, `utils/api`). + - Export modules using named exports for better discoverability and tree-shaking. + - **Component Architecture:** + - Favor small, reusable components. + - Use composition over inheritance. + - Separate concerns by creating presentational (UI) and container (logic) components. + - Utilize the `children` prop to create flexible and reusable components. + - **Code Splitting Strategies:** + - Use dynamic imports (`next/dynamic`) for large components or modules that are not critical for the initial page load. + - Split code based on routes or user interactions. + - Utilize Next.js's automatic code splitting. + +- **Common Patterns and Anti-patterns** + - **Design Patterns:** + - **Higher-Order Components (HOCs):** For cross-cutting concerns like authentication or data fetching. + - **Render Props:** For sharing logic between components. + - **Compound Components:** For creating complex UI elements with implicit state sharing. + - **Recommended Approaches:** + - **Data Fetching:** Use `getStaticProps`, `getServerSideProps`, or `getInitialProps` (legacy) for data fetching. + - **State Management:** Consider using React Context, Zustand, Redux Toolkit, or Jotai for managing application state. + - **Routing:** Utilize `next/link` for client-side navigation and `next/router` for programmatic routing. + - **Anti-patterns:** + - **Direct DOM Manipulation:** Avoid manipulating the DOM directly; use React's state and props instead. + - **Global CSS Conflicts:** Use CSS Modules or CSS-in-JS to prevent style conflicts. + - **Over-fetching Data:** Fetch only the data that is needed by the component. + - **Unnecessary Re-renders:** Optimize component rendering using `React.memo` or `useMemo`. + - **State Management Best Practices:** + - Choose a state management solution that fits the complexity of your application. + - Centralize state that is shared between multiple components. + - Use immutable data structures to avoid unexpected side effects. + - Use selectors to derive data from the state. + - **Error Handling Patterns:** + - Use `try...catch` blocks to handle errors gracefully. + - Implement error boundaries to prevent crashes in production. + - Log errors to a monitoring service for debugging. + - Display user-friendly error messages. + +- **Performance Considerations** + - **Optimization Techniques:** + - **Minimize JavaScript Bundle Size:** Remove unused code, use tree-shaking, and compress your code. + - **Optimize Third-Party Libraries:** Choose lightweight alternatives or lazy-load libraries. + - **Cache API Responses:** Use caching to reduce the load on your API servers. + - **Use a CDN:** Serve static assets from a Content Delivery Network (CDN). + - **Memory Management:** + - **Avoid Memory Leaks:** Clean up event listeners and timers when components unmount. + - **Use Efficient Data Structures:** Choose data structures that are appropriate for the task. + - **Rendering Optimization:** + - **Use `React.memo`:** Prevent unnecessary re-renders of components. + - **Virtualize Long Lists:** Render only the visible items in a long list to improve performance. + - **Defer Expensive Calculations:** Use `useMemo` or `useCallback` to memoize expensive calculations. + - **Bundle Size Optimization:** + - **Analyze Bundle Size:** Use tools like `webpack-bundle-analyzer` to identify large dependencies. + - **Remove Unused Dependencies:** Remove dependencies that are not being used. + - **Use Code Splitting:** Split your code into smaller chunks to reduce initial load time. + - **Lazy Loading Strategies:** + - **Lazy Load Images:** Use `next/image` with the `lazy` loading prop. + - **Lazy Load Components:** Use `next/dynamic` to lazy load components. + - **Lazy Load Data:** Fetch data only when it is needed. + +- **Security Best Practices** + - **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. + - **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks. + - **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks. + - **Authentication and Authorization Vulnerabilities:** Implement secure authentication and authorization mechanisms. + - **Input Validation:** + - **Validate all user input:** Ensure that the input is of the expected type and format. + - **Sanitize user input:** Remove or escape potentially harmful characters. + - **Authentication and Authorization Patterns:** + - **Use a secure authentication provider:** Consider using a third-party authentication provider like Auth0 or Firebase Authentication. + - **Implement role-based access control (RBAC):** Restrict access to resources based on user roles. + - **Use JSON Web Tokens (JWTs) for authentication:** JWTs are a secure and stateless way to authenticate users. + - **Data Protection Strategies:** + - **Encrypt sensitive data:** Encrypt data at rest and in transit. + - **Use HTTPS:** Use HTTPS to encrypt communication between the client and server. + - **Store passwords securely:** Use a strong hashing algorithm to store passwords. + - **Secure API Communication:** + - **Use API keys or tokens for authentication:** Require API keys or tokens for all API requests. + - **Rate limit API requests:** Prevent abuse by limiting the number of requests that can be made from a single IP address. + - **Validate API requests:** Ensure that the API requests are valid and authorized. + +- **Testing Approaches** + - **Unit Testing Strategies:** + - **Test individual components and functions in isolation.** + - **Use mocking and stubbing to isolate dependencies.** + - **Write tests for different scenarios and edge cases.** + - **Integration Testing:** + - **Test the interaction between multiple components or modules.** + - **Test data flow and state management.** + - **End-to-End Testing:** + - **Test the entire application flow from the user's perspective.** + - **Use tools like Cypress or Playwright for end-to-end testing.** + - **Test Organization:** + - **Keep tests close to the code they are testing.** + - **Use a consistent naming convention for tests.** + - **Organize tests into logical groups.** + - **Mocking and Stubbing:** + - **Use mocking to replace external dependencies with mock objects.** + - **Use stubbing to replace functions with predefined return values.** + +- **Common Pitfalls and Gotchas** + - **Frequent Mistakes:** + - **Forgetting to handle errors.** + - **Over-complicating state management.** + - **Not optimizing images.** + - **Not securing API routes.** + - **Edge Cases:** + - **Handling different screen sizes and devices.** + - **Dealing with slow network connections.** + - **Handling unexpected user input.** + - **Version-Specific Issues:** + - **Breaking changes in Next.js updates.** + - **Compatibility issues with third-party libraries.** + - **Compatibility Concerns:** + - **Browser compatibility issues.** + - **Accessibility issues.** + - **Debugging Strategies:** + - **Use the browser's developer tools to debug JavaScript code.** + - **Use the Next.js devtools extension for debugging Next.js applications.** + - **Use logging to track the flow of execution and identify errors.** + +- **Tooling and Environment** + - **Recommended Development Tools:** + - **VS Code:** A popular code editor with excellent support for JavaScript and TypeScript. + - **ESLint:** A linter for identifying and fixing code style issues. + - **Prettier:** A code formatter for automatically formatting code. + - **Webpack Bundle Analyzer:** A tool for analyzing the size of your JavaScript bundles. + - **Build Configuration:** + - **Configure Webpack to optimize your code for production.** + - **Use environment variables to configure your application for different environments.** + - **Linting and Formatting:** + - **Use ESLint and Prettier to enforce a consistent code style.** + - **Configure your editor to automatically format code on save.** + - **Deployment Best Practices:** + - **Deploy your application to a platform like Vercel or Netlify.** + - **Use environment variables to configure your application for production.** + - **Monitor your application for errors and performance issues.** + - **CI/CD Integration:** + - **Use a CI/CD pipeline to automate the build, test, and deployment process.** + - **Integrate your linting and formatting tools into your CI/CD pipeline.** \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/react/react-mobx.mdc b/rules-mdc/frontend_frameworks/react/react-mobx.mdc new file mode 100644 index 0000000..053e956 --- /dev/null +++ b/rules-mdc/frontend_frameworks/react/react-mobx.mdc @@ -0,0 +1,203 @@ +--- +description: This rule provides comprehensive best practices for developing React applications with Mobx, covering code organization, performance, testing, and security considerations. It aims to guide developers in building robust and maintainable applications using React-Mobx. +globs: **/*.{js,jsx,ts,tsx} +--- +# React-Mobx Best Practices + +This document outlines best practices for developing React applications with Mobx. Following these guidelines will help you build robust, maintainable, and performant applications. + +## 1. Core Principles + +- **Model observable state:** Define the source of truth in your Mobx stores and make them observable. +- **Use derived state (computed properties):** Derive data from your observable state using `computed` properties to avoid unnecessary re-renders and ensure data consistency. +- **Embrace mutability:** Mobx encourages direct mutation of observable state within actions. +- **Use strict mode:** Enforce predictable state changes by using `use strict` or enabling strict mode in Mobx to ensure all state modifications happen within actions. +- **Keep actions in MobX stores:** Encapsulate state mutations within Mobx actions to ensure data integrity and simplify debugging. +- **Prefer class vs object syntax:** Use class syntax for creating stores as it offers better structure, inheritance, and maintainability. +- **Inject store rather than importing:** Use dependency injection (e.g., React Context) to provide stores to components instead of importing them directly to improve testability and reduce tight coupling. + +## 2. Code Organization and Structure + +- **Directory Structure:** + - `/src`: + - `/components`: React components (presentational and container components). + - `/stores`: Mobx stores containing observable state and actions. + - `/models`: Data models and types definitions. + - `/services`: API clients and other services. + - `/utils`: Utility functions. + - `/hooks`: Custom React hooks. + - `/constants`: Application-wide constants. + - `/test`: Unit, integration, and end-to-end tests. + +- **File Naming Conventions:** + - Components: `ComponentName.jsx` or `ComponentName.tsx` + - Stores: `StoreName.store.js` or `StoreName.store.ts` + - Models: `ModelName.model.js` or `ModelName.model.ts` + - Services: `ServiceName.service.js` or `ServiceName.service.ts` + - Hooks: `useHookName.js` or `useHookName.ts` + +- **Module Organization:** + - Group related components, stores, and models into modules. + - Use clear and descriptive module names. + - Avoid circular dependencies between modules. + +- **Component Architecture:** + - **Presentational Components:** Responsible for rendering UI and receiving data via props. + - **Container Components:** Connect presentational components to Mobx stores and manage state updates. + - Use the `observer` decorator/function from `mobx-react-lite` to make components react to observable changes. + +- **Code Splitting Strategies:** + - Use React's `lazy` and `Suspense` components for lazy loading routes or components. + - Implement route-based code splitting to load only necessary code for the current route. + - Consider using `dynamic imports` for on-demand loading of modules. + +## 3. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Observer Pattern:** Mobx uses the observer pattern to automatically update components when observable state changes. + - **Dependency Injection:** Use React Context to inject stores into components, making them more testable and reusable. + - **Provider Pattern:** Use a Provider component to make stores available to the component tree. + +- **Recommended Approaches:** + - **Form Handling:** Use Mobx to manage form state and validation. + - **Asynchronous Operations:** Use Mobx actions to handle asynchronous operations and update the state accordingly. + - **List Rendering:** Optimize list rendering using `key` props and `React.memo`. + +- **Anti-patterns and Code Smells:** + - **Modifying State Outside Actions:** Always modify observable state within Mobx actions to ensure data consistency. + - **Deeply Nested Observables:** Avoid deeply nested observable objects as they can impact performance. + - **Computing Data in Components:** Use `computed` properties in stores to derive data instead of computing it directly in components. + - **Over-Observing:** Only observe the specific parts of the store that a component needs. + +- **State Management Best Practices:** + - **Single Source of Truth:** Keep the application state in Mobx stores and avoid duplicating data. + - **Normalization:** Normalize data to reduce redundancy and improve data consistency. + - **Immutability (with Mutation):** While Mobx encourages mutation, treat observable state as immutable from the perspective of components (i.e., components shouldn't directly mutate the store). + +- **Error Handling Patterns:** + - Implement centralized error handling using a dedicated error store. + - Use try-catch blocks within actions to handle potential errors. + - Display user-friendly error messages to the user. + +## 4. Performance Considerations + +- **Optimization Techniques:** + - **`React.memo`:** Wrap components with `React.memo` to prevent unnecessary re-renders when props haven't changed. + - **`useMemo` and `useCallback`:** Use `useMemo` and `useCallback` hooks to memoize values and callbacks, preventing unnecessary re-renders of child components. + - **Computed Properties:** Use `computed` properties to derive data from observable state and cache the results. + - **Optimize List Rendering:** Use `key` props when rendering lists and consider using virtualized lists for large datasets. + +- **Memory Management:** + - **Dispose of Observers:** Dispose of observers when components unmount to prevent memory leaks. + - **Avoid Retaining Large Data Sets:** Remove or release references to large data sets when they are no longer needed. + +- **Rendering Optimization:** + - **Minimize Re-renders:** Optimize component rendering by using `React.memo` and avoiding unnecessary state updates. + - **Use ShouldComponentUpdate (if needed):** In class components, use `shouldComponentUpdate` lifecycle method to control when a component should re-render. This is less common with `observer`. Be careful, can lead to bugs. + +- **Bundle Size Optimization:** + - **Code Splitting:** Implement code splitting to reduce the initial bundle size. + - **Tree Shaking:** Use a bundler that supports tree shaking to remove unused code. + - **Minification:** Minify your code to reduce the bundle size. + +- **Lazy Loading Strategies:** + - **React.lazy and Suspense:** Use React's built-in lazy loading mechanism. + - **Dynamic Imports:** Use dynamic imports to load modules on demand. + +## 5. Security Best Practices + +- **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks. + - **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms. + - **Injection Attacks:** Validate user inputs to prevent SQL injection and other injection attacks. + +- **Input Validation:** + - **Server-Side Validation:** Always validate user inputs on the server-side. + - **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user. + +- **Authentication and Authorization Patterns:** + - **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization. + - **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application. + +- **Data Protection Strategies:** + - **Encryption:** Encrypt sensitive data both in transit and at rest. + - **Data Masking:** Mask sensitive data to protect user privacy. + +- **Secure API Communication:** + - **HTTPS:** Use HTTPS for all API communication. + - **Rate Limiting:** Implement rate limiting to prevent abuse. + +## 6. Testing Approaches + +- **Unit Testing Strategies:** + - Test individual components and stores in isolation. + - Mock dependencies to isolate the unit under test. + - Use testing libraries like Jest and React Testing Library. + +- **Integration Testing:** + - Test the interaction between different components and stores. + - Use a testing environment that closely resembles the production environment. + +- **End-to-End Testing:** + - Test the entire application flow from the user's perspective. + - Use testing frameworks like Cypress or Selenium. + +- **Test Organization:** + - Organize tests into separate directories for unit, integration, and end-to-end tests. + - Use descriptive test names. + +- **Mocking and Stubbing:** + - Use mocking libraries to mock dependencies in unit tests. + - Use stubbing to replace complex dependencies with simpler implementations. + +## 7. Common Pitfalls and Gotchas + +- **Frequent Mistakes:** + - Forgetting to decorate components with `observer`. + - Modifying state outside of actions. + - Not disposing of observers properly. + - Over-observing state. + +- **Edge Cases:** + - Handling large datasets efficiently. + - Dealing with complex asynchronous operations. + - Managing nested observable objects. + +- **Version-Specific Issues:** + - Be aware of breaking changes in Mobx and React versions. + - Consult the Mobx and React documentation for migration guides. + +- **Compatibility Concerns:** + - Ensure compatibility with different browsers and devices. + - Test your application on different platforms. + +- **Debugging Strategies:** + - Use the Mobx devtools to inspect observable state and track changes. + - Use browser developer tools to debug React components. + - Add logging statements to track the flow of data and execution. + +## 8. Tooling and Environment + +- **Recommended Development Tools:** + - **VS Code:** A popular code editor with excellent support for React and Mobx. + - **Mobx Devtools:** A browser extension for inspecting Mobx state. + - **React Devtools:** A browser extension for inspecting React components. + +- **Build Configuration:** + - **Webpack:** A popular module bundler for React applications. + - **Parcel:** A zero-configuration bundler that's easy to use. + - **Rollup:** A bundler focused on creating libraries and smaller bundles. + +- **Linting and Formatting:** + - **ESLint:** A JavaScript linter for enforcing code style and preventing errors. + - **Prettier:** A code formatter for automatically formatting code. + - **Husky/lint-staged:** Tools to automatically lint code before commits + +- **Deployment Best Practices:** + - **Continuous Integration/Continuous Deployment (CI/CD):** Automate the build, test, and deployment process. + - **Caching:** Use caching to improve performance. + - **Content Delivery Network (CDN):** Use a CDN to serve static assets. + +- **CI/CD Integration:** + - Integrate your application with a CI/CD pipeline to automate the build, test, and deployment process. + - Use tools like Jenkins, Travis CI, or CircleCI. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/react/react-native.mdc b/rules-mdc/frontend_frameworks/react/react-native.mdc new file mode 100644 index 0000000..59e8b08 --- /dev/null +++ b/rules-mdc/frontend_frameworks/react/react-native.mdc @@ -0,0 +1,196 @@ +--- +description: This rule provides comprehensive guidelines for React Native development, covering code organization, performance, security, testing, and common pitfalls. Adhering to these practices ensures maintainable, scalable, and efficient React Native applications. +globs: **/*.{js,jsx,ts,tsx} +--- +# React Native Best Practices + +This document outlines best practices for developing React Native applications, covering various aspects from code organization to performance optimization. + +## 1. Code Organization and Structure + +* **Directory Structure:** + * Adopt a scalable and maintainable directory structure. Feature-based organization is often preferred. + * Example: + + src/ + ├── components/ # Reusable UI components + ├── screens/ # App screens/views + ├── navigation/ # Navigation configurations + ├── services/ # API services and data fetching + ├── utils/ # Utility functions + ├── constants/ # Constant values + ├── context/ # React Context providers + ├── types/ # TypeScript type definitions + └── App.tsx # Root component + +* **File Naming Conventions:** + * Use descriptive and consistent file names. + * Components: `ComponentName.tsx` (or `.jsx`) + * Styles: `ComponentName.styles.ts` (or `.js`) + * Utility functions: `utilityName.ts` (or `.js`) + * Consider using kebab-case for folders. +* **Module Organization:** + * Group related components, styles, and assets within the same directory. + * Use `index.ts` (or `.js`) files to export modules, simplifying imports. + * Example: + + // components/Button/index.ts + export { default as Button } from './Button'; + +* **Component Architecture:** + * Favor functional components with hooks over class components. + * Separate concerns using container and presentational components. + * **Container components:** Handle data fetching and state management. + * **Presentational components:** Focus on rendering UI based on props. + * Use composition to create flexible and reusable components. +* **Code Splitting Strategies:** + * Implement lazy loading for screens and components to reduce initial bundle size. + * Use `React.lazy` and `Suspense` for code splitting. + * Dynamic imports can be useful for loading non-critical modules on demand. + +## 2. Common Patterns and Anti-patterns + +* **Design Patterns:** + * **Higher-Order Components (HOCs):** Wrap components with shared logic. + * **Render Props:** Share code between React components using a prop whose value is a function. + * **Hooks:** Extract stateful logic into reusable functions. + * **Compound Components:** Allow components to implicitly share state (e.g., Tabs). +* **Recommended Approaches:** + * **State Management:** Use appropriate state management solutions (e.g., Redux, Zustand, React Context) based on the application's complexity. For local state management, `useState` and `useReducer` hooks are preferred. + * **API Calls:** Use `async/await` for asynchronous operations and handle errors gracefully. + * **Navigation:** Utilize `react-navigation` or `react-native-navigation` for screen transitions and navigation logic. +* **Anti-patterns:** + * **Mutating state directly:** Use `setState` or state update functions from hooks. + * **Passing too many props:** Refactor components or use context to share data. + * **Overusing global state:** Consider component-level state when appropriate. + * **Long functions:** Break down functions into smaller, more manageable pieces. +* **State Management Best Practices:** + * Choose the right state management tool for the job (Context API, Redux, Zustand, Recoil). + * Keep state minimal and derive values when possible. + * Use immutable data structures to simplify state updates. + * Optimize re-renders by using `React.memo`, `useMemo`, and `useCallback`. +* **Error Handling Patterns:** + * Use `try/catch` blocks to handle synchronous errors. + * Implement error boundaries to catch errors in React components. + * Log errors to a monitoring service for tracking and analysis (e.g., Sentry, Bugsnag). + * Provide user-friendly error messages and recovery options. + +## 3. Performance Considerations + +* **Optimization Techniques:** + * **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components. + * **PureComponent:** Use `PureComponent` for class components to perform shallow prop comparisons. + * **Virtualization:** Use `FlatList` or `SectionList` for rendering large lists of data efficiently. + * **Debouncing and Throttling:** Limit the rate at which functions are executed in response to rapid events (e.g., scrolling, typing). +* **Memory Management:** + * Avoid memory leaks by properly cleaning up event listeners and timers in `useEffect` hooks. + * Release resources when components unmount. + * Be mindful of image sizes and optimize them for mobile devices. +* **Rendering Optimization:** + * Minimize the number of re-renders by using `useCallback` and `useMemo` to memoize functions and values. + * Avoid inline function definitions in render methods. + * Use `shouldComponentUpdate` (for class components) or `React.memo` to prevent unnecessary renders. +* **Bundle Size Optimization:** + * Use code splitting to reduce the initial bundle size. + * Remove unused code using tree shaking. + * Optimize image assets using tools like ImageOptim or TinyPNG. + * Analyze bundle size using tools like `webpack-bundle-analyzer`. +* **Lazy Loading Strategies:** + * Implement lazy loading for images using libraries like `react-native-fast-image`. + * Lazy load components using `React.lazy` and `Suspense`. + +## 4. Security Best Practices + +* **Common Vulnerabilities:** + * **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input before rendering it in the UI. + * **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks. + * **Insecure Data Storage:** Avoid storing sensitive data in plain text on the device. + * **Man-in-the-Middle (MITM) Attacks:** Use HTTPS to encrypt communication between the app and the server. +* **Input Validation:** + * Validate all user input on both the client and server sides. + * Use regular expressions to enforce input formats. + * Sanitize input to remove potentially malicious characters. +* **Authentication and Authorization Patterns:** + * Use secure authentication methods like OAuth 2.0 or JWT. + * Implement role-based access control to restrict access to sensitive data and functionality. + * Store authentication tokens securely using the device's keychain or secure storage. +* **Data Protection Strategies:** + * Encrypt sensitive data at rest using encryption libraries. + * Use secure storage options provided by the platform (e.g., Keychain on iOS, KeyStore on Android). + * Avoid logging sensitive data. +* **Secure API Communication:** + * Use HTTPS for all API communication. + * Implement proper authentication and authorization for API endpoints. + * Protect against CSRF attacks by using anti-CSRF tokens. + * Rate limit API requests to prevent abuse. + +## 5. Testing Approaches + +* **Unit Testing:** + * Test individual components and functions in isolation. + * Use testing frameworks like Jest or Mocha. + * Write tests for edge cases and error conditions. +* **Integration Testing:** + * Test the interaction between different components and modules. + * Verify that data flows correctly between different parts of the application. +* **End-to-End Testing:** + * Test the entire application flow from start to finish. + * Use testing frameworks like Detox or Appium. + * Run tests on real devices or emulators. +* **Test Organization:** + * Organize tests in a way that mirrors the application's directory structure. + * Use descriptive test names to clearly indicate what is being tested. + * Keep tests small and focused. +* **Mocking and Stubbing:** + * Use mocking libraries like Jest's `jest.mock` to isolate components during testing. + * Stub out dependencies to control their behavior. + +## 6. Common Pitfalls and Gotchas + +* **Frequent Mistakes:** + * **Incorrectly using `setState`:** Understand the asynchronous nature of `setState` and use functional updates when necessary. + * **Not optimizing images:** Large images can significantly impact performance. + * **Ignoring memory leaks:** Failing to clean up event listeners and timers can lead to memory leaks. + * **Over-rendering:** Unnecessary re-renders can degrade performance. +* **Edge Cases:** + * **Handling different screen sizes and densities:** Use responsive design techniques to adapt to various screen sizes. + * **Dealing with network latency:** Implement loading indicators and error handling for API requests. + * **Handling different locales and languages:** Use internationalization (i18n) libraries to support multiple languages. +* **Version-Specific Issues:** + * Be aware of breaking changes in React Native updates. + * Test your application on different versions of React Native to ensure compatibility. + * Use `react-native-upgrade-helper` to help with upgrades. +* **Compatibility Concerns:** + * Test your application on different devices and operating systems. + * Be aware of platform-specific APIs and features. + * Use conditional rendering or platform-specific code when necessary. +* **Debugging Strategies:** + * Use the React Native debugger to inspect component state and props. + * Use `console.log` statements to trace code execution. + * Use error logging to capture and track errors. + * Learn to use the Chrome Developer Tools for debugging JavaScript code. + +## 7. Tooling and Environment + +* **Recommended Development Tools:** + * **VS Code:** A popular code editor with excellent React Native support. + * **React Native Debugger:** A standalone debugger for React Native applications. + * **Expo CLI:** A tool for creating, building, and deploying React Native applications. + * **Android Studio/Xcode:** The official IDEs for Android and iOS development, respectively. +* **Build Configuration:** + * Use environment variables to configure different build environments (e.g., development, staging, production). + * Optimize build settings for performance. +* **Linting and Formatting:** + * Use ESLint and Prettier to enforce code style and prevent errors. + * Configure ESLint with React Native-specific rules. + * Use a pre-commit hook to automatically format code before committing. +* **Deployment Best Practices:** + * Use code signing to ensure the integrity of your application. + * Follow the platform-specific deployment guidelines (e.g., Google Play Store, Apple App Store). + * Use a continuous integration/continuous deployment (CI/CD) pipeline to automate the deployment process. +* **CI/CD Integration:** + * Use CI/CD tools like Jenkins, CircleCI, or GitHub Actions to automate building, testing, and deploying your application. + * Configure CI/CD to run unit tests, integration tests, and end-to-end tests. + * Automate the process of creating and deploying release builds. + +By following these best practices, you can develop robust, scalable, and maintainable React Native applications. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/react/react-query.mdc b/rules-mdc/frontend_frameworks/react/react-query.mdc new file mode 100644 index 0000000..48a00dc --- /dev/null +++ b/rules-mdc/frontend_frameworks/react/react-query.mdc @@ -0,0 +1,267 @@ +--- +description: This rule enforces best practices for using react-query in React applications, covering code organization, performance, security, and testing. +globs: **/*.{js,jsx,ts,tsx} +--- +# react-query Best Practices + +This document outlines the best practices for using react-query in React applications, covering various aspects such as code organization, performance considerations, security, and testing. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure Best Practices + +* **Feature-based Organization:** Group react-query hooks and related components within feature-specific directories. This improves modularity and maintainability. + + src/ + ├── features/ + │ ├── users/ + │ │ ├── components/ + │ │ │ ├── UserList.tsx + │ │ │ └── UserDetails.tsx + │ │ ├── hooks/ + │ │ │ ├── useUsersQuery.ts + │ │ │ └── useCreateUserMutation.ts + │ │ ├── api/ + │ │ │ └── usersApi.ts + │ │ └── types/ + │ │ └── user.ts + │ ├── products/ + │ └── ... + ├── ... + + +* **Dedicated API Service Layer:** Abstract API interaction logic into separate modules. This allows for easier testing and decoupling of components from specific API implementations. Consider using a dedicated `api` directory within each feature. + +### 1.2 File Naming Conventions + +* **Consistent Naming:** Follow a consistent naming convention for react-query hooks. Prefix hooks with `use` and postfix with `Query` or `Mutation` to clearly indicate their purpose (e.g., `usePostsQuery`, `useUpdatePostMutation`). + +* **Descriptive Names:** Use descriptive names for files and variables to improve code readability. For example, `useFetchUsersQuery.ts` is more informative than `useUsers.ts`. + +### 1.3 Module Organization + +* **Custom Hooks for Reusability:** Encapsulate react-query logic within custom hooks to promote reusability and separation of concerns. + + typescript + // src/features/users/hooks/useUsersQuery.ts + import { useQuery } from '@tanstack/react-query'; + import { fetchUsers } from '../api/usersApi'; + + export const useUsersQuery = () => { + return useQuery('users', fetchUsers); + }; + + +* **Separate Query and Mutation Files:** Organize queries and mutations into separate files or modules. This enhances code readability and maintainability. + +### 1.4 Component Architecture + +* **Presentational and Container Components:** Separate presentational components (UI) from container components (data fetching and state management). This improves testability and reusability. + +* **Composition:** Use component composition to build complex UIs from smaller, reusable components. Leverage React Context for shared state when appropriate. + +### 1.5 Code Splitting Strategies + +* **Route-Based Splitting:** Split your application into separate bundles based on routes. This reduces the initial load time and improves perceived performance. React.lazy and React.Suspense can assist with this. + +* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. This can improve the performance of individual pages or components. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to react-query + +* **Custom Hooks for Data Fetching:** As highlighted earlier, encapsulating react-query logic within custom hooks. This promotes reusability and separation of concerns. These hooks will typically return the result of a `useQuery` or `useMutation` call. + +* **Optimistic Updates:** Implement optimistic updates to improve perceived performance. This involves updating the UI before the API request completes, and then reverting the changes if the request fails. react-query provides utilities like `onMutate` to handle this. + +* **Pessimistic Updates:** Update the UI only after a successful response from the API. Simpler to implement but provides a less snappy user experience. + +### 2.2 Recommended Approaches for Common Tasks + +* **Prefetching Data:** Prefetch data for routes or components that the user is likely to visit next. This can significantly improve the user experience. Use `queryClient.prefetchQuery`. + +* **Pagination and Infinite Scrolling:** Implement pagination and infinite scrolling to handle large datasets efficiently. react-query provides hooks like `useInfiniteQuery` to simplify this. + +* **Dependent Queries:** Fetch data based on the result of a previous query. Use the `enabled` option in `useQuery` to conditionally execute queries. + + typescript + const { data: user } = useQuery(['user', userId], () => fetchUser(userId)); + + const { data: posts } = useQuery(['posts', user?.id], () => fetchPosts(user.id), { + enabled: !!user, + }); + + +### 2.3 Anti-patterns and Code Smells to Avoid + +* **Directly Calling API in Components:** Avoid making API calls directly within components. This makes testing difficult and tightly couples components to specific API implementations. + +* **Ignoring Error Handling:** Always handle errors properly. Display user-friendly error messages and provide options for retrying requests. + +* **Over-fetching Data:** Fetch only the data that is required by the component. Use GraphQL or API query parameters to reduce the amount of data transferred. + +* **Deeply Nested Queries:** Avoid deeply nesting queries, as this can lead to performance issues and make the code difficult to understand. Consider combining queries or using a different approach. + +### 2.4 State Management Best Practices + +* **Local vs. Global State:** Determine whether data should be stored in local component state or in a global state management solution. Use local state for component-specific data and global state for data that needs to be shared across multiple components. + +* **react-query as a State Manager:** Leverage react-query's built-in caching and state management capabilities. Avoid using external state management libraries for data that is already managed by react-query. + +### 2.5 Error Handling Patterns + +* **Centralized Error Handling:** Implement centralized error handling to provide consistent error messages and logging. + +* **Retry Logic:** Implement retry logic to automatically retry failed requests. react-query provides options for configuring retry behavior. + +* **Error Boundaries:** Use Error Boundaries to catch errors that occur during rendering. This prevents the entire application from crashing. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +* **Query Invalidation:** Invalidate queries when data changes. This ensures that the UI is always up-to-date. + +* **Stale-While-Revalidate:** Use the `staleTime` and `cacheTime` options to configure how long data should be considered fresh. `staleWhileRevalidate` allows the UI to display cached data while fetching fresh data in the background. + +* **Window Focus Refetching:** Configure refetching on window focus to keep data fresh when the user switches back to the application. + +* **Polling/Refetch Intervals:** Use `refetchInterval` to periodically refetch data. This is useful for data that changes frequently. + +### 3.2 Memory Management + +* **Query Cache Management:** Understand how react-query manages its cache. Configure the `cacheTime` option to control how long data is stored in the cache. + +* **Garbage Collection:** Ensure that unused queries are garbage collected properly. Use the `gcTime` option to configure how long inactive queries should be kept in the cache. + +### 3.3 Rendering Optimization + +* **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components. This is especially important for components that display data fetched from react-query. + +* **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists of data. + +### 3.4 Bundle Size Optimization + +* **Tree Shaking:** Ensure that your build process is configured for tree shaking. This removes unused code from the final bundle. + +* **Code Splitting:** As mentioned earlier, use code splitting to reduce the initial load time. + +### 3.5 Lazy Loading Strategies + +* **Lazy Load Components:** Use `React.lazy` to lazy load components that are not immediately needed. + +* **Lazy Load Data:** Fetch data only when it is needed. Use dependent queries to fetch data based on user interactions. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. Use a library like DOMPurify to sanitize HTML. + +* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent attackers from performing actions on behalf of the user. Use a library or framework that provides CSRF protection. + +* **Injection Attacks:** Protect against injection attacks by validating user input and using parameterized queries. + +### 4.2 Input Validation + +* **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user. + +* **Server-Side Validation:** Always validate user input on the server-side to prevent malicious data from being stored in the database. + +### 4.3 Authentication and Authorization Patterns + +* **JSON Web Tokens (JWT):** Use JWTs for authentication. Store the JWT in a secure cookie or in local storage (with caution). Use `httpOnly` flag on cookies containing JWTs when possible to prevent client-side script access. + +* **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application. Use middleware or custom hooks to check user roles. + +### 4.4 Data Protection Strategies + +* **Encryption:** Encrypt sensitive data at rest and in transit. Use HTTPS to encrypt data in transit. Encrypt sensitive data in the database. + +* **Data Masking:** Mask sensitive data in logs and reports. This prevents sensitive data from being exposed to unauthorized users. + +### 4.5 Secure API Communication + +* **HTTPS:** Use HTTPS for all API communication. This encrypts data in transit and prevents eavesdropping. + +* **API Rate Limiting:** Implement API rate limiting to prevent abuse. + +* **CORS:** Configure CORS properly to prevent cross-origin requests from unauthorized domains. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +* **Test Custom Hooks:** Unit test custom react-query hooks to ensure they are working correctly. Mock the API calls using libraries like `msw` (Mock Service Worker). + +* **Test Components in Isolation:** Unit test components in isolation to ensure they render correctly and handle user interactions properly. Use libraries like `react-testing-library`. + +### 5.2 Integration Testing + +* **Test Data Flow:** Integration test the data flow between components and APIs. Verify that data is fetched correctly and displayed properly. + +* **Test Error Handling:** Integration test error handling scenarios to ensure that errors are handled properly. + +### 5.3 End-to-End Testing + +* **Simulate User Interactions:** Use end-to-end testing frameworks like Cypress or Playwright to simulate user interactions and verify that the application is working correctly from the user's perspective. + +* **Test Critical Paths:** Focus on testing critical user flows, such as login, registration, and checkout. + +### 5.4 Test Organization + +* **Colocate Tests with Components:** Colocate tests with the components they are testing. This makes it easier to find and maintain tests. + +* **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is verifying. + +### 5.5 Mocking and Stubbing + +* **Mock API Calls:** Use mocking libraries like `msw` to mock API calls during testing. This allows you to test components in isolation without relying on a real API. + +* **Stub External Dependencies:** Stub external dependencies to isolate components and make tests more predictable. + +## 6. Common Pitfalls and Gotchas + +* **Forgetting to Invalidate Queries:** Failing to invalidate queries when data changes can lead to stale data being displayed in the UI. + +* **Incorrect Cache Configuration:** Incorrectly configuring the `cacheTime` and `staleTime` options can lead to performance issues or stale data. + +* **Not Handling Errors Properly:** Not handling errors properly can lead to unexpected behavior and a poor user experience. + +* **Over-relying on Default Configuration:** Customizing react-query to match specific needs is essential. + +* **Ignoring Devtools:** The react-query devtools are invaluable for debugging and understanding what is happening under the hood. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +* **VS Code:** Use VS Code with extensions like ESLint, Prettier, and TypeScript to improve developer productivity. + +* **React Developer Tools:** Use the React Developer Tools browser extension to inspect React components and state. + +* **react-query Devtools:** Use the react-query Devtools to inspect the react-query cache and track query and mutation status. + +### 7.2 Build Configuration + +* **Webpack or Parcel:** Use a bundler like Webpack or Parcel to bundle your code for production. Configure the bundler for tree shaking and code splitting. + +* **Babel:** Use Babel to transpile your code to older versions of JavaScript. This ensures that your code is compatible with older browsers. + +### 7.3 Linting and Formatting + +* **ESLint:** Use ESLint to enforce coding standards and prevent errors. Configure ESLint to use a popular style guide like Airbnb or Google. + +* **Prettier:** Use Prettier to automatically format your code. This ensures that your code is consistently formatted and easy to read. + +### 7.4 Deployment Best Practices + +* **CDN:** Use a CDN to serve static assets. This improves performance and reduces the load on your server. + +* **Caching:** Configure caching properly on your server and CDN. This reduces the number of requests to your server and improves performance. + +### 7.5 CI/CD Integration + +* **Automated Testing:** Integrate automated testing into your CI/CD pipeline. This ensures that your code is tested automatically before it is deployed. + +* **Automated Deployment:** Automate the deployment process to reduce the risk of errors and improve efficiency. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/react/react-redux.mdc b/rules-mdc/frontend_frameworks/react/react-redux.mdc new file mode 100644 index 0000000..cf83432 --- /dev/null +++ b/rules-mdc/frontend_frameworks/react/react-redux.mdc @@ -0,0 +1,283 @@ +--- +description: Enforces best practices for structuring and maintaining React-Redux applications, focusing on code organization, performance, and maintainability. This rule provides guidelines for developers to write efficient, scalable, and testable React-Redux code. +globs: **/*.{js,jsx,ts,tsx} +--- +# React-Redux Best Practices + +This document outlines best practices for developing React applications with Redux for state management. Following these guidelines will help you write maintainable, scalable, and performant code. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure + +Organize your code around features rather than technical concerns. A feature-based directory structure promotes modularity and makes it easier to understand the application's purpose. + + +src/ + ├── app/ + │ ├── components/ + │ │ └── App.tsx + │ └── App.css + ├── features/ + │ ├── featureName/ + │ │ ├── components/ + │ │ │ ├── FeatureComponent.tsx + │ │ │ └── FeatureComponent.css + │ │ ├── FeatureSlice.ts # Redux slice for the feature + │ │ ├── FeatureSelectors.ts # Selectors for accessing feature state + │ │ ├── FeatureActions.ts # Actions related to this feature + │ │ └── api.ts # API calls related to the feature + │ ├── anotherFeature/ + │ │ └── ... + ├── store.ts # Redux store configuration + ├── index.tsx # Entry point for the React application + └── ... + + +### 1.2. File Naming Conventions + +* **Components:** Use PascalCase (e.g., `MyComponent.tsx`). +* **Redux Slice Files:** Use PascalCase and end with `Slice.ts` or `Slice.js` (e.g., `UserSlice.ts`). +* **Selectors:** `selectors.ts` or `selectors.js` or `FeatureSelectors.ts` to include a feature name prefix +* **Actions:** `actions.ts` or `actions.js` or `FeatureActions.ts` to include a feature name prefix +* **Styles:** Use either `ComponentName.module.css` (for CSS Modules) or `ComponentName.css` (for global styles). +* **Utility Functions:** Use camelCase (e.g., `formatDate.ts`). + +### 1.3. Module Organization + +* **Encapsulation:** Each feature should be a self-contained module with its components, actions, reducers, and selectors. +* **Single Responsibility Principle:** Each module should have a single, well-defined purpose. +* **Clear Boundaries:** Define clear boundaries between modules to minimize dependencies and prevent tight coupling. + +### 1.4. Component Architecture + +* **Presentational and Container Components:** + * **Presentational (Dumb) Components:** Focus on rendering UI and receiving data and callbacks as props. They should be reusable and independent of Redux. + * **Container (Smart) Components:** Connect to the Redux store and pass data and actions to presentational components. Use `connect` or `useSelector` and `useDispatch` hooks. +* **Small and Reusable Components:** Break down complex UIs into smaller, reusable components to promote code reuse and maintainability. +* **Component Composition:** Build complex UIs by composing smaller components. + +### 1.5. Code Splitting Strategies + +* **Route-Based Splitting:** Split the application into chunks based on routes to reduce the initial load time. Use `React.lazy` and `Suspense` for lazy loading components. +* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. Use dynamic imports for loading components asynchronously. +* **Library Splitting:** Extract commonly used libraries into separate chunks to allow browsers to cache them independently. + +## 2. Common Patterns and Anti-Patterns + +### 2.1. Design Patterns + +* **Selectors:** Use selectors to abstract the state shape and compute derived data. Selectors improve performance by memoizing results and prevent components from re-rendering unnecessarily. +* **Custom Hooks:** Create custom hooks for accessing Redux state and dispatching actions. This simplifies component logic and promotes code reuse. For example: + + typescript + import { useDispatch, useSelector } from 'react-redux'; + import { increment, decrement } from './counterSlice'; + import { RootState } from './store'; + + export const useCounter = () => { + const count = useSelector((state: RootState) => state.counter.value); + const dispatch = useDispatch(); + + const handleIncrement = () => { + dispatch(increment()); + }; + + const handleDecrement = () => { + dispatch(decrement()); + }; + + return { count, handleIncrement, handleDecrement }; + }; + +* **Redux Toolkit:** Utilize Redux Toolkit to simplify Redux setup and reduce boilerplate code. Redux Toolkit provides utilities for creating reducers, actions, and the store. + +### 2.2. Recommended Approaches + +* **Normalize State:** Structure your state as a normalized data structure, where each piece of data has a unique ID, and relationships between data are represented by IDs. This improves performance and simplifies data management. Use libraries like Normalizr to help with this. +* **Immutability:** Treat your state as immutable and use immutable update patterns. This ensures predictable state transitions and prevents unexpected side effects. +* **Middleware for Side Effects:** Use Redux middleware (e.g., Redux Thunk, Redux Saga) to handle asynchronous operations and side effects. Avoid performing side effects directly in reducers. + +### 2.3. Anti-Patterns and Code Smells + +* **Mutating State Directly:** Never mutate the state directly in reducers. Always create a new copy of the state with the desired changes. +* **Performing Side Effects in Reducers:** Reducers should be pure functions and should not perform any side effects (e.g., API calls, logging). +* **Storing UI State in Redux:** Avoid storing UI-specific state (e.g., component visibility, form input values) in the Redux store. Store UI state locally in component state. +* **Over-reliance on Global State:** Avoid putting everything in the Redux store. Only store data that needs to be accessed by multiple components or across the entire application. Consider React Context or local component state for component-specific data. + +### 2.4. State Management Best Practices + +* **Minimize Global State:** Only store data in the Redux store that needs to be shared across multiple components. For component-specific state, use local component state. +* **Use Selectors:** Use selectors to access and transform data from the Redux store. This allows you to abstract the state shape and prevent components from re-rendering unnecessarily. +* **Immutable Updates:** Always update state immutably to ensure predictable state transitions and prevent unexpected side effects. Use libraries like Immer to simplify immutable updates. + +### 2.5. Error Handling Patterns + +* **Centralized Error Handling:** Implement a centralized error handling mechanism to catch and handle errors consistently throughout the application. Use error boundary components to catch errors in the UI. +* **Action Creators for Errors:** Dispatch error actions to the Redux store when errors occur. This allows you to track errors and display error messages in the UI. +* **Logging Errors:** Log errors to a central logging service for debugging and monitoring purposes. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Memoization:** Use memoization techniques (e.g., `React.memo`, `useMemo`, Reselect) to prevent components from re-rendering unnecessarily. +* **Batch Updates:** Batch multiple Redux dispatches into a single update to improve performance. Use `redux-batched-updates` or `unstable_batchedUpdates` from React DOM. +* **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists and tables. +* **Code Splitting:** Split the application into smaller chunks to reduce the initial load time. + +### 3.2. Memory Management + +* **Avoid Memory Leaks:** Be mindful of memory leaks, especially in event listeners, timers, and subscriptions. Clean up resources properly when components unmount. +* **Use WeakRefs:** Use WeakRefs to hold references to objects without preventing them from being garbage collected. +* **Profile Memory Usage:** Use the browser's developer tools to profile memory usage and identify potential memory leaks. + +### 3.3. Rendering Optimization + +* **ShouldComponentUpdate / React.memo:** Use `shouldComponentUpdate` (for class components) or `React.memo` (for functional components) to prevent components from re-rendering unnecessarily. +* **Pure Components:** Use pure components to automatically implement `shouldComponentUpdate` based on prop comparisons. +* **Immutable Data Structures:** Use immutable data structures to make it easier to detect changes and prevent re-renders. + +### 3.4. Bundle Size Optimization + +* **Tree Shaking:** Use tree shaking to remove dead code from your bundles. Configure your bundler (e.g., Webpack, Parcel) to enable tree shaking. +* **Code Splitting:** Split the application into smaller chunks to reduce the initial load time. +* **Minification:** Minify your code to reduce the bundle size. +* **Compression:** Compress your bundles using gzip or Brotli. + +### 3.5. Lazy Loading Strategies + +* **Route-Based Lazy Loading:** Load components only when their corresponding routes are visited. +* **Component-Based Lazy Loading:** Load components on demand when they become visible in the UI. +* **Image Lazy Loading:** Load images only when they scroll into view. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and Prevention + +* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by sanitizing user input and escaping output. +* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens. +* **Injection Attacks:** Prevent injection attacks (e.g., SQL injection, command injection) by validating user input and using parameterized queries. +* **Authentication and Authorization:** Implement secure authentication and authorization mechanisms to protect sensitive data and resources. + +### 4.2. Input Validation + +* **Server-Side Validation:** Always validate user input on the server-side to prevent malicious data from being stored in the database. +* **Client-Side Validation:** Use client-side validation to provide immediate feedback to users and reduce the load on the server. +* **Whitelisting:** Use whitelisting to allow only specific characters or patterns in user input. + +### 4.3. Authentication and Authorization Patterns + +* **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization. JWTs are stateless and can be easily verified on the server-side. +* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. OAuth 2.0 allows users to grant third-party applications access to their resources without sharing their credentials. +* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles. + +### 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 remove personally identifiable information (PII). + +### 4.5. Secure API Communication + +* **HTTPS:** Use HTTPS to encrypt communication between the client and the server. +* **API Keys:** Use API keys to authenticate API requests. +* **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +* **Test Reducers:** Test reducers to ensure that they handle actions correctly and update the state as expected. +* **Test Selectors:** Test selectors to ensure that they return the correct data from the state. +* **Test Actions:** Test action creators to ensure that they return the correct actions. +* **Test Components:** Test components to ensure that they render correctly and handle user interactions as expected. Use tools like React Testing Library. + +### 5.2. Integration Testing + +* **Test Component Interactions:** Test how components interact with each other and with the Redux store. +* **Test Data Flow:** Test the flow of data through the application, from the UI to the Redux store and back. +* **Test API Integrations:** Test how the application integrates with external APIs. + +### 5.3. End-to-End Testing + +* **Test User Flows:** Test complete user flows to ensure that the application functions correctly from end to end. Use tools like Cypress or Playwright. +* **Test Critical Functionality:** Test critical functionality (e.g., login, checkout) to ensure that it is working as expected. +* **Test Accessibility:** Test the application for accessibility to ensure that it is usable by people with disabilities. + +### 5.4. Test Organization + +* **Test Folder Structure:** Organize tests in a way that mirrors the application's directory structure. +* **Test Suites:** Group tests into logical suites based on functionality or component. +* **Test Naming Conventions:** Use clear and consistent naming conventions for tests. + +### 5.5. Mocking and Stubbing + +* **Mock API Calls:** Mock API calls to isolate components and reducers during testing. +* **Stub External Dependencies:** Stub external dependencies to control their behavior during testing. +* **Use Mock Store:** Use a mock Redux store to test components that are connected to the store. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes + +* **Forgetting to Connect Components:** Forgetting to connect components to the Redux store, resulting in components not receiving state updates. +* **Incorrectly Mapping State to Props:** Incorrectly mapping state to props, resulting in components not receiving the correct data. +* **Not Updating State Immutably:** Not updating state immutably, leading to unexpected side effects and re-renders. +* **Using `setState` with Redux:** Mixing `setState` with Redux can lead to inconsistencies and difficult-to-debug issues. Avoid using `setState` in components connected to Redux, unless for purely local, non-Redux-related state. + +### 6.2. Edge Cases + +* **Race Conditions:** Be aware of race conditions when handling asynchronous operations. +* **Memory Leaks:** Watch out for memory leaks in event listeners, timers, and subscriptions. +* **Performance Bottlenecks:** Identify and address performance bottlenecks, such as unnecessary re-renders or slow API calls. + +### 6.3. Version-Specific Issues + +* **Breaking Changes:** Be aware of breaking changes when upgrading React and Redux. +* **Deprecated Features:** Avoid using deprecated features and migrate to the recommended alternatives. + +### 6.4. Compatibility Concerns + +* **Browser Compatibility:** Test the application in different browsers to ensure compatibility. +* **Device Compatibility:** Test the application on different devices to ensure compatibility. + +### 6.5. Debugging Strategies + +* **Redux DevTools:** Use the Redux DevTools to inspect the Redux store, track actions, and time travel through state changes. +* **Console Logging:** Use console logging to debug code and track the flow of data. +* **Breakpoints:** Use breakpoints to pause execution and inspect variables in the debugger. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +* **Redux DevTools:** The Redux DevTools extension for Chrome and Firefox allows you to inspect the Redux store, track actions, and time travel through state changes. +* **React Developer Tools:** The React Developer Tools extension for Chrome and Firefox allows you to inspect the React component tree and profile component performance. +* **ESLint:** ESLint is a linter that helps you identify and fix code style issues and potential errors. +* **Prettier:** Prettier is a code formatter that automatically formats your code to ensure consistency. + +### 7.2. Build Configuration + +* **Webpack:** Webpack is a module bundler that bundles your code and dependencies into optimized bundles for production. +* **Parcel:** Parcel is a zero-configuration bundler that is easy to use and provides fast build times. +* **Create React App:** Create React App is a tool that sets up a React development environment with sensible defaults. + +### 7.3. Linting and Formatting + +* **ESLint:** Use ESLint to enforce code style rules and prevent potential errors. Configure ESLint to use a popular style guide, such as Airbnb or Standard. +* **Prettier:** Use Prettier to automatically format your code to ensure consistency. Integrate Prettier with ESLint to automatically fix code style issues. +* **Husky and Lint-Staged:** Use Husky and Lint-Staged to automatically run linters and formatters on staged files before committing code. + +### 7.4. Deployment Best Practices + +* **Environment Variables:** Use environment variables to configure the application for different environments (e.g., development, staging, production). +* **Continuous Integration:** Use a continuous integration (CI) system to automatically build and test the application whenever code is committed. +* **Continuous Deployment:** Use a continuous deployment (CD) system to automatically deploy the application to production whenever a new release is created. +* **Caching:** Configure caching on the server-side and client-side to improve performance. + +### 7.5. CI/CD Integration + +* **GitHub Actions:** Use GitHub Actions to automate the build, test, and deployment process. +* **CircleCI:** Use CircleCI to automate the build, test, and deployment process. +* **Jenkins:** Use Jenkins to automate the build, test, and deployment process. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/react/react.mdc b/rules-mdc/frontend_frameworks/react/react.mdc new file mode 100644 index 0000000..ab4f14f --- /dev/null +++ b/rules-mdc/frontend_frameworks/react/react.mdc @@ -0,0 +1,167 @@ +--- +description: Enforces best practices for React development, covering code structure, performance, security, and testing to ensure maintainable and efficient applications. +globs: **/*.{js,jsx,ts,tsx} +--- +- **Use Functional Components with Hooks:** + - Favor functional components over class components for simplicity and better performance. + - Leverage React Hooks (useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue) for managing state, side effects, and context. + +- **Component Composition:** + - Build complex UIs by composing smaller, reusable components. + - Use props to pass data down the component tree and callbacks to handle events. + +- **Meaningful Component Names:** + - Give component names that accurately reflect their functionality. + - Follow a consistent naming convention (e.g., PascalCase for components, camelCase for props). + +- **Keep Components Small and Focused:** + - Adhere to the Single Responsibility Principle; each component should have a clear, focused purpose. + - Break down large components into smaller, more manageable pieces. + +- **Destructuring Props:** + - Use destructuring to access props within functional components for improved readability. + +- **Avoid Inline Styles:** + - Use CSS modules, styled-components, or a CSS-in-JS library for managing styles instead of inline styles. + - Keep styles separate from component logic for better maintainability. + +- **Use Arrow Functions:** + - Use arrow functions for concise syntax and lexical `this` binding. + - Be mindful of performance implications when passing arrow functions directly as props; consider using `useCallback`. + +- **PropTypes for Type Checking (with alternatives):** + - Use PropTypes (though consider TypeScript) to define the expected types of props passed to components. + - Enforce type checking at runtime to catch type-related errors early. + - Strongly consider TypeScript for static type checking for enhanced code quality and maintainability. + +- **Immutability:** + - Treat state as immutable; avoid directly modifying state objects. + - Use `setState`, the spread operator (`...`), or immutable data structures (e.g., Immutable.js) to update state. + +- **Code Organization and Structure:** + - **Directory Structure:** + - Organize components into folders based on features or modules. + - Use a `components` directory for reusable UI elements. + - Consider a `hooks` directory for custom hooks. + - Separate API services into a `services` or `api` directory. + - **File Naming Conventions:** + - Use `.jsx` or `.tsx` extensions for React components. + - Name files according to the component they export (e.g., `MyComponent.jsx`). + - Use `index.js` or `index.ts` files to export multiple components from a directory. + - **Module Organization:** + - Use ES modules (`import` and `export`) for modular code. + - Group related components and logic into modules. + - **Component Architecture:** + - **Atomic Design:** Consider using Atomic Design principles (Atoms, Molecules, Organisms, Templates, Pages) to structure your components. + - **Presentational and Container Components:** Separate presentational (UI-focused) and container (logic-focused) components. + - **Code Splitting:** + - Use React.lazy and Suspense to lazy-load components and reduce initial bundle size. + - Implement route-based code splitting for larger applications. + - Consider using dynamic imports for splitting non-route components as well. + +- **Common Patterns and Anti-patterns:** + - **Design Patterns:** + - **Higher-Order Components (HOCs):** Use HOCs to share logic between components. + - **Render Props:** Use render props for more flexible code reuse. + - **Compound Components:** Create components that implicitly share state and behavior with their children (e.g., ``, ``). + - **Provider Pattern:** Use the Context API to provide data to a subtree of components. + - **Recommended Approaches:** + - Use controlled components for forms to manage input values in React state. + - Use keys when rendering lists of elements for efficient updates. + - Use memoization techniques (React.memo, useMemo, useCallback) to prevent unnecessary re-renders. + - **Anti-patterns:** + - **Direct DOM Manipulation:** Avoid directly manipulating the DOM; use React's virtual DOM instead. + - **Mutating State Directly:** Never directly modify state; use `setState` or the appropriate hook update function. + - **Over-reliance on Global State:** Avoid storing too much state in global stores; consider component-level state or context when appropriate. + - **State Management:** + - **Component State:** Use `useState` for simple component-level state. + - **Context API:** Use the Context API for sharing state across a subtree of components. + - **Redux/Zustand/Recoil/MobX:** Consider using a state management library (Redux, Zustand, Recoil, MobX) for complex application state. + - **Error Handling:** + - **Error Boundaries:** Use Error Boundaries to catch errors during rendering and prevent the entire application from crashing. + - **Try/Catch Blocks:** Use try/catch blocks for handling errors in event handlers and lifecycle methods. + +- **Performance Considerations:** + - **Memoization:** + - Use `React.memo` to memoize functional components and prevent unnecessary re-renders. + - Use `useMemo` to memoize computed values and prevent unnecessary recalculations. + - Use `useCallback` to memoize event handler functions and prevent unnecessary re-renders of child components. + - **Virtualization:** + - Use virtualization libraries (e.g., `react-window`, `react-virtualized`) for rendering large lists of data efficiently. + - **Debouncing and Throttling:** + - Use debouncing and throttling techniques to limit the frequency of function calls in response to user input. + - **Image Optimization:** + - Optimize images for the web to reduce file sizes and improve loading times. + - Use lazy loading for images that are not immediately visible. + - **Bundle Size Optimization:** + - Use code splitting to reduce the initial bundle size. + - Remove unused code with tree shaking. + - Compress code with minification. + - **Rendering Optimization:** + - Use `shouldComponentUpdate` (in class components) or `React.memo` (in functional components) to prevent unnecessary re-renders. + - Implement pure components (components that only re-render when their props change) for performance gains. + - **Lazy Loading:** + - Use `React.lazy` and `Suspense` to load components on demand and improve initial load time. + +- **Security Best Practices:** + - **XSS Prevention:** + - Sanitize user input to prevent cross-site scripting (XSS) attacks. + - Use React's built-in escaping mechanisms to render data safely. + - **CSRF Protection:** + - Implement cross-site request forgery (CSRF) protection to prevent unauthorized requests. + - Use anti-CSRF tokens to verify requests. + - **Authentication and Authorization:** + - Use secure authentication and authorization patterns to protect sensitive data and functionality. + - Implement strong password policies. + - Use multi-factor authentication. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS to secure communication between the client and server. + - **Secure API Communication:** + - Validate API responses to prevent unexpected data from compromising the application. + +- **Testing Approaches:** + - **Unit Testing:** + - Write unit tests to verify the behavior of individual components and functions. + - Use testing libraries like Jest and React Testing Library. + - **Integration Testing:** + - Write integration tests to verify the interaction between multiple components and modules. + - **End-to-End Testing:** + - Write end-to-end tests to verify the entire application flow. + - Use testing frameworks like Cypress or Playwright. + - **Test Organization:** + - Organize tests into a `__tests__` directory alongside the component files. + - Follow a consistent naming convention for test files (e.g., `MyComponent.test.jsx`). + - **Mocking and Stubbing:** + - Use mocking and stubbing techniques to isolate components during testing. + - Mock external dependencies like API calls and browser APIs. + +- **Common Pitfalls and Gotchas:** + - **Incorrect `this` Binding:** + - Be mindful of `this` binding in class components; use arrow functions or `bind` to ensure the correct context. + - **Missing Keys in Lists:** + - Provide unique keys to elements when rendering lists to prevent rendering issues. + - **Asynchronous State Updates:** + - Understand how `setState` and hook update functions handle asynchronous updates; use functional updates when necessary. + - **Memory Leaks:** + - Clean up side effects in `useEffect` hooks to prevent memory leaks. + - **Version-Specific Issues:** + - Be aware of compatibility concerns when upgrading React versions. + - Consult the React documentation and release notes for migration guides. + +- **Tooling and Environment:** + - **Recommended Development Tools:** + - VS Code with React-specific extensions (e.g., ESLint, Prettier, Babel). + - Chrome DevTools for debugging. + - React Developer Tools extension for inspecting component hierarchy and state. + - **Build Configuration:** + - Use tools like webpack, Parcel, or Rollup for bundling and optimizing code. + - Configure Babel to transpile JSX and modern JavaScript syntax. + - **Linting and Formatting:** + - Use ESLint with React-specific rules to enforce code style and best practices. + - Use Prettier to automatically format code. + - **Deployment Best Practices:** + - Use a CDN to serve static assets. + - Use server-side rendering (SSR) or static site generation (SSG) for improved performance and SEO. + - **CI/CD Integration:** + - Integrate CI/CD pipelines for automated testing, building, and deployment. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/solid/solidjs.mdc b/rules-mdc/frontend_frameworks/solid/solidjs.mdc new file mode 100644 index 0000000..7d1e8e8 --- /dev/null +++ b/rules-mdc/frontend_frameworks/solid/solidjs.mdc @@ -0,0 +1,322 @@ +--- +description: This comprehensive guide outlines best practices for SolidJS development, covering code organization, performance, security, testing, and common pitfalls. It provides actionable guidelines for building maintainable, efficient, and secure SolidJS applications. +globs: **/*.{js,jsx,ts,tsx} +--- +# SolidJS Best Practices: A Comprehensive Guide + +This document provides a detailed overview of best practices for SolidJS development, covering various aspects from code organization to security and performance. It aims to guide developers in building robust, scalable, and maintainable SolidJS applications. + +## 1. Code Organization and Structure + +### 1.1 Directory Structure Best Practices + +A well-defined directory structure is crucial for maintaining a large SolidJS application. Here's a recommended structure: + + +my-solid-app/ +├── src/ +│ ├── components/ +│ │ ├── Button/ +│ │ │ ├── Button.tsx +│ │ │ ├── Button.module.css +│ │ │ ├── Button.test.tsx +│ │ ├── Card/ +│ │ │ ├── Card.tsx +│ │ │ ├── Card.module.css +│ │ ├── index.ts # Exports all components +│ ├── contexts/ +│ │ ├── ThemeContext.tsx +│ ├── hooks/ +│ │ ├── useTheme.ts +│ ├── utils/ +│ │ ├── api.ts +│ │ ├── helpers.ts +│ ├── routes/ +│ │ ├── Home.tsx +│ │ ├── About.tsx +│ ├── styles/ +│ │ ├── global.css +│ ├── App.tsx +│ ├── index.tsx +│ ├── types.d.ts # Global type definitions +│ ├── vite-env.d.ts # vite type definitions +├── public/ +│ ├── favicon.svg +│ ├── assets/ +├── .env +├── vite.config.ts +├── tsconfig.json +├── package.json +├── README.md + + +**Explanation:** + +* **src/:** Contains the source code of your application. + * **components/:** Reusable UI components. Each component should have its own directory containing the component file, styles, and tests. + * **contexts/:** SolidJS Context providers for managing global state and shared data. + * **hooks/:** Custom hooks for reusable logic. + * **utils/:** Utility functions such as API calls, data formatting, etc. + * **routes/:** Components that define different routes in your application. + * **styles/:** Global styles or shared CSS modules. + * **App.tsx:** The root component of your application. + * **index.tsx:** Entry point for rendering the App component into the DOM. + * **types.d.ts:** Global typescript type definitions for the project + * **vite-env.d.ts:** vite environment type definitions +* **public/:** Static assets such as images, fonts, etc. +* **.env:** Stores environment variables. +* **vite.config.ts:** Vite configuration file. +* **tsconfig.json:** TypeScript configuration file. +* **package.json:** Node.js package file. +* **README.md:** Project documentation. + +### 1.2 File Naming Conventions + +* **Components:** Use PascalCase for component file names (e.g., `Button.tsx`, `UserProfile.jsx`). +* **Hooks:** Use camelCase prefixed with `use` for hook file names (e.g., `useTheme.ts`, `useFetchData.js`). +* **Utilities:** Use camelCase for utility file names (e.g., `api.ts`, `formatDate.js`). +* **Styles:** Use the `.module.css` extension for CSS modules (e.g., `Button.module.css`). If using other styling solutions like styled-components, follow their recommended practices. + +### 1.3 Module Organization + +* **Keep components modular:** Each component should have a single responsibility. +* **Export components:** Export components to make them reusable in other parts of the application (e.g., `export default Button;`). +* **Create an `index.ts` file:** In each directory (e.g., `components/`) export all the modules in that directory. This allows simpler imports from other components. e.g., `import {Button, Card} from '../components'` + +### 1.4 Component Architecture + +* **Functional Components:** Use functional components with Solid's reactivity system for managing state and UI updates. Avoid class components. +* **Props:** Use props to pass data from parent to child components. Be explicit about prop types using TypeScript. +* **Context API:** Use Solid's Context API for sharing data between components without prop drilling. Use cases: themes, user authentication, global configuration. +* **Signals:** Employ SolidJS Signals for managing component-level state. Prefer derived signals or memoization for expensive computations. + +### 1.5 Code Splitting Strategies + +* **Route-Based Splitting:** Use dynamic imports to load components only when a route is visited. Leverage Solid Router's lazy loading capabilities with `lazy`. +* **Component-Based Splitting:** Split large components into smaller chunks that can be loaded on demand. Use `Suspense` to handle loading states. +* **Library Splitting:** If using large libraries, consider splitting them into smaller chunks or using tree-shaking to remove unused code. + +## 2. Common Patterns and Anti-patterns + +### 2.1 Design Patterns Specific to SolidJS + +* **Renderless Components:** Create components that encapsulate logic without rendering any UI elements. They can be used as hooks or utility functions to share logic between components. +* **Compound Components:** Build components that work together implicitly, often using Context to share state. (e.g., Tabs, Accordions). +* **Reactivity-Based Composition:** Compose components based on shared reactive state, rather than inheritance. This allows more flexibility and better performance. +* **Custom Control Flow Components:** Create reusable components to handle conditional rendering or list iteration with specific optimization strategies. Examples include more performant alternatives to `` in certain specific use cases. + +### 2.2 Recommended Approaches for Common Tasks + +* **Fetching Data:** Use `createResource` for handling asynchronous data fetching. Use `AbortController` for cancelling requests on component unmount or data changes. +* **Managing Forms:** Use signals to track form input values. Implement validation logic and handle form submission. +* **Handling Events:** Attach event handlers to elements using JSX attributes (e.g., `onClick`). Use arrow functions or bind methods to ensure correct `this` context. +* **Global State Management:** Use Solid's Context API or a dedicated state management library (e.g., `solid-zustand`, `solid-js/store`) for sharing data between components. + +### 2.3 Anti-patterns and Code Smells to Avoid + +* **Reading and Writing to the Same Signal in an Effect:** This creates an infinite loop. Use the functional update form `setCount(count => count + 1)` or derived signals. +* **Writing to Signals in Effects for Derived Values:** Prefer derived signals or memoization for expensive computations (using `createMemo`). +* **Destructuring Props:** This breaks reactivity. Access props directly or use `mergeProps` and `splitProps`. +* **Using `.map` and Ternary Operators for Control Flow:** Use Solid's control flow components (``, ``, ``) to avoid unnecessary DOM elements. +* **Mutating Resource Data Directly:** Always create new objects when mutating resource data to prevent unnecessary re-renders. use `createMutable` judiciously only where mutability is needed. +* **Ignoring Cleanup Functions:** Neglecting `onCleanup` can lead to memory leaks and unexpected behavior when components unmount. + +### 2.4 State Management Best Practices + +* **Component-Level State:** Use signals for managing simple, component-specific state. +* **Context API:** For sharing data between components without prop drilling, especially themes or user authentication. +* **Global Stores:** Use store solutions or third-party libraries (e.g., `solid-zustand`, `solid-js/store`) for complex global state management. +* **Immutability:** Treat state as immutable. Always create new objects/arrays when updating state, especially with resources or stores. +* **Single Source of Truth:** Ensure that each piece of state has a single, authoritative source. Avoid duplicating state across components. + +### 2.5 Error Handling Patterns + +* **`Suspense` for Loading States:** Wrap asynchronous operations like `createResource` with `Suspense` to display loading indicators. +* **Error Boundaries:** Implement error boundaries to catch errors during rendering and display fallback UI. +* **Try-Catch Blocks:** Use `try-catch` blocks for handling synchronous errors or errors in event handlers. +* **Centralized Error Logging:** Implement a centralized error logging mechanism to track and monitor errors in your application. +* **User-Friendly Error Messages:** Display user-friendly error messages to guide users on how to resolve issues. + +## 3. Performance Considerations + +### 3.1 Optimization Techniques + +* **Fine-Grained Reactivity:** Solid's fine-grained reactivity ensures that only the necessary parts of the UI are updated when state changes. Leverage this by breaking down components into smaller, more focused units. +* **Derived Signals and Memos:** Use derived signals and memos to avoid recomputing expensive values unnecessarily. +* **Control Flow Components:** Use ``, ``, and `` for efficient conditional rendering and list iteration. +* **Lazy Loading:** Load components and modules only when they are needed. +* **Virtualization:** For rendering large lists, use virtualization techniques to only render the visible items. +* **Debouncing and Throttling:** Implement debouncing or throttling for event handlers that trigger frequent updates. + +### 3.2 Memory Management + +* **Cleanup Functions:** Always use `onCleanup` to release resources when a component is unmounted, such as timers, event listeners, and subscriptions. +* **Avoid Memory Leaks:** Be mindful of potential memory leaks when using closures or retaining references to DOM elements. +* **Weak References:** Use `WeakRef` or `WeakMap` for holding references to objects without preventing them from being garbage collected. + +### 3.3 Rendering Optimization + +* **Minimize DOM Updates:** Solid's reactivity system minimizes DOM updates, but avoid unnecessary renders by optimizing component structure and state management. +* **Batch Updates:** Use `batchedUpdates` to batch multiple state updates into a single render cycle (use with caution). +* **Avoid Inline Styles:** Prefer CSS classes or CSS modules for styling components. +* **Use CSS Transitions and Animations:** Leverage CSS transitions and animations for smoother UI updates. + +### 3.4 Bundle Size Optimization + +* **Tree Shaking:** Use tree shaking to remove unused code from your bundle. Vite automatically performs tree shaking. +* **Code Splitting:** Split your application into smaller chunks that can be loaded on demand. +* **Minification and Compression:** Minify and compress your code to reduce bundle size. Vite handles minification by default. +* **Image Optimization:** Optimize images by compressing them and using appropriate formats (e.g., WebP). +* **Dependency Analysis:** Analyze your dependencies to identify and remove unnecessary libraries. + +### 3.5 Lazy Loading Strategies + +* **Route-Based Lazy Loading:** Load components only when a route is visited using dynamic imports and the `lazy` function from Solid Router. +* **Component-Based Lazy Loading:** Split large components into smaller chunks that can be loaded on demand. +* **Conditional Lazy Loading:** Load components based on specific conditions, such as user interactions or device capabilities. + +## 4. Security Best Practices + +### 4.1 Common Vulnerabilities and How to Prevent Them + +* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and escaping data when rendering it in the DOM. Avoid using `dangerouslySetInnerHTML`. +* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by using anti-CSRF tokens in forms and validating them on the server. +* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or ORMs when interacting with databases. +* **Authentication and Authorization:** Secure your application by implementing proper authentication and authorization mechanisms. +* **Denial-of-Service (DoS):** Protect against DoS attacks by implementing rate limiting, input validation, and resource quotas. + +### 4.2 Input Validation + +* **Server-Side Validation:** Always validate user inputs on the server to prevent malicious data from being stored in your database. +* **Client-Side Validation:** Provide client-side validation for a better user experience, but never rely on it as the sole means of protection. +* **Sanitize Inputs:** Sanitize user inputs to remove potentially harmful characters or code. +* **Use Validation Libraries:** Use validation libraries to simplify the input validation process. + +### 4.3 Authentication and Authorization Patterns + +* **JSON Web Tokens (JWT):** Use JWTs for managing user authentication and authorization. +* **OAuth 2.0:** Implement OAuth 2.0 for third-party authentication and authorization. +* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles. +* **Multi-Factor Authentication (MFA):** Implement MFA for enhanced security. + +### 4.4 Data Protection Strategies + +* **Encryption:** Encrypt sensitive data at rest and in transit using appropriate encryption algorithms. +* **Data Masking:** Mask sensitive data when displaying it to users or storing it in logs. +* **Data Redaction:** Redact sensitive data from logs and audit trails. +* **Data Retention Policies:** Implement data retention policies to ensure that data is only stored for as long as it is needed. + +### 4.5 Secure API Communication + +* **HTTPS:** Use HTTPS for all API communication to encrypt data in transit. +* **API Keys:** Use API keys for authenticating clients and controlling access to your APIs. +* **Rate Limiting:** Implement rate limiting to prevent abuse of your APIs. +* **Input Validation:** Validate all API inputs to prevent malicious data from being processed. +* **Output Encoding:** Encode API outputs to prevent XSS attacks. + +## 5. Testing Approaches + +### 5.1 Unit Testing Strategies + +* **Test Individual Components:** Unit tests should focus on testing individual components in isolation. +* **Mock Dependencies:** Mock dependencies to isolate the component being tested. +* **Test All Scenarios:** Test all possible scenarios and edge cases. +* **Use Assertions:** Use assertions to verify that the component behaves as expected. + +### 5.2 Integration Testing + +* **Test Component Interactions:** Integration tests should focus on testing the interactions between components. +* **Mock External Services:** Mock external services to isolate the component being tested. +* **Test Data Flow:** Test the flow of data between components. + +### 5.3 End-to-End Testing + +* **Test the Entire Application:** End-to-end tests should focus on testing the entire application from the user's perspective. +* **Use a Testing Framework:** Use a testing framework such as Cypress or Playwright to automate the testing process. +* **Test User Flows:** Test common user flows to ensure that the application works as expected. + +### 5.4 Test Organization + +* **Colocate Tests:** Place test files alongside the components they are testing. +* **Use a Consistent Naming Convention:** Use a consistent naming convention for test files (e.g., `Button.test.tsx`). +* **Organize Tests by Feature:** Organize tests by feature or module. + +### 5.5 Mocking and Stubbing + +* **Use Mocking Libraries:** Use mocking libraries such as Jest or Vitest to create mocks and stubs. +* **Mock External Dependencies:** Mock external dependencies to isolate the component being tested. +* **Stub API Calls:** Stub API calls to control the data returned by the API. + +## 6. Common Pitfalls and Gotchas + +### 6.1 Frequent Mistakes Developers Make + +* **Incorrectly Using Effects:** Misunderstanding the dependency tracking of `createEffect` can lead to unnecessary re-runs or infinite loops. +* **Forgetting `onCleanup`:** Not using `onCleanup` for resources and subscriptions causes memory leaks. +* **Mutating State Directly:** Directly mutating objects or arrays used as state leads to unexpected behavior and broken reactivity. +* **Over-Optimizing Prematurely:** Focusing on micro-optimizations before addressing fundamental architectural issues. +* **Not Understanding Solid's Reactivity:** Failing to grasp the nuances of Solid's reactive system can lead to inefficient code. + +### 6.2 Edge Cases to Be Aware Of + +* **SSR Hydration Issues:** When doing SSR, ensure that the initial state on the server matches the client to avoid hydration errors. +* **Reactivity with Non-Reactive Values:** Passing plain JS objects or arrays to components without making them reactive can cause issues with updates. +* **Transitions and Resource Updates:** Interactions between transitions and resource updates can sometimes be tricky, especially around loading states. +* **Nested Reactivity:** Managing reactivity in complex, deeply nested data structures can be challenging. + +### 6.3 Version-Specific Issues + +* **Compatibility:** Consider backwards compatibility when upgrading SolidJS or related libraries. +* **Deprecations:** Be aware of deprecated features and APIs and migrate to the recommended alternatives. +* **Bug Fixes:** Stay up-to-date with bug fixes and security patches in newer versions of SolidJS. + +### 6.4 Compatibility Concerns + +* **Browser Compatibility:** Test your application in different browsers to ensure compatibility. +* **Device Compatibility:** Test your application on different devices, such as desktops, tablets, and mobile phones. +* **Accessibility:** Ensure that your application is accessible to users with disabilities. + +### 6.5 Debugging Strategies + +* **Use Browser Developer Tools:** Use the browser's developer tools to inspect the DOM, network requests, and console output. +* **SolidJS Devtools:** Use the SolidJS Devtools extension to inspect components, signals, and resources. +* **Logging:** Add logging statements to your code to track the flow of execution and the values of variables. +* **Debugging Tools:** Use debugging tools such as VS Code's debugger to step through your code and inspect variables. +* **Reproducible Examples:** Create reproducible examples to isolate and debug issues more effectively. + +## 7. Tooling and Environment + +### 7.1 Recommended Development Tools + +* **Vite:** Use Vite as the build tool. SolidJS uses Vite as its default. +* **VS Code:** Use VS Code as the code editor, along with extensions for TypeScript, ESLint, and Prettier. +* **SolidJS Devtools:** Use the SolidJS Devtools browser extension to inspect components, signals, and resources. +* **TypeScript:** Utilize TypeScript for type safety and improved code maintainability. + +### 7.2 Build Configuration + +* **Vite Configuration:** Configure Vite to optimize your build for production (e.g., code splitting, minification, compression). +* **TypeScript Configuration:** Configure TypeScript to enforce strict type checking and code quality. +* **Environment Variables:** Use environment variables to store sensitive data and configure your application for different environments. + +### 7.3 Linting and Formatting + +* **ESLint:** Use ESLint to enforce code style and identify potential errors. +* **Prettier:** Use Prettier to automatically format your code. +* **Husky:** Use Husky to run linters and formatters before committing code. + +### 7.4 Deployment Best Practices + +* **Choose a Hosting Platform:** Select a suitable hosting platform for your SolidJS application (e.g., Netlify, Vercel, AWS). +* **Configure a Production Environment:** Configure your hosting platform to use a production environment with appropriate settings. +* **Automate Deployment:** Automate the deployment process using CI/CD tools. +* **Monitor Your Application:** Monitor your application for errors and performance issues. + +### 7.5 CI/CD Integration + +* **Choose a CI/CD Tool:** Select a CI/CD tool such as GitHub Actions, GitLab CI, or CircleCI. +* **Configure CI/CD Pipelines:** Configure CI/CD pipelines to automatically build, test, and deploy your application. +* **Automate Testing:** Automate unit tests, integration tests, and end-to-end tests in your CI/CD pipelines. +* **Automate Deployment:** Automate the deployment process to deploy new versions of your application with minimal manual intervention. + +This document provides a comprehensive set of best practices for SolidJS development. By following these guidelines, developers can build high-quality, maintainable, and secure SolidJS applications. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/svelte/svelte.mdc b/rules-mdc/frontend_frameworks/svelte/svelte.mdc new file mode 100644 index 0000000..1ac517d --- /dev/null +++ b/rules-mdc/frontend_frameworks/svelte/svelte.mdc @@ -0,0 +1,157 @@ +--- +description: Comprehensive Svelte best practices covering code structure, performance, security, testing, and common pitfalls. This rule provides guidance on writing maintainable, efficient, and secure Svelte applications. +globs: **/*.svelte +--- +- **Manipulate the DOM with HTML:** Utilize Svelte's HTML-centric approach to manipulate the DOM. +- **Solve challenges with HTML/CSS first:** Prioritize solving problems with HTML and CSS before resorting to JavaScript. +- **Write short components:** Aim for concise and focused components to improve readability and maintainability. +- **Write concise reactive `$:` blocks:** Keep reactive statements short and easy to understand. +- **Scope CSS to the actual component:** Ensure that CSS styles are scoped to the component to avoid conflicts. +- **Avoid hard coding data or dimensions:** Use dynamic data and responsive design techniques instead of hard-coded values. +- **Keep objects immutable:** Treat objects as immutable to prevent unexpected side effects and improve performance. +- **Use two-way binding effectively:** Leverage two-way binding for efficient data synchronization but be mindful of its potential impact on performance for complex scenarios. + +## 1. Code Organization and Structure: + + - **Directory Structure Best Practices:** + - `src/`: Contains all the application source code. + - `src/components/`: Holds reusable Svelte components, categorized further by feature or domain (e.g., `src/components/Button/`, `src/components/Form/`). + - `src/lib/`: Contains utility functions, helper modules, and reusable logic that is not specific to a component. + - `src/routes/`: For SvelteKit applications, this directory defines the application's routes. + - `src/stores/`: Stores for global state management (if using Svelte's stores). + - `static/`: Static assets like images, fonts, and other resources. + - **File Naming Conventions:** + - Components: Use PascalCase (e.g., `MyComponent.svelte`). + - Utility functions: Use camelCase (e.g., `formatDate.js`). + - Stores: Use descriptive names related to the data they hold (e.g., `userStore.js`). + - **Module Organization:** + - Group related components and utilities into modules within their respective directories. + - Use `index.js` or `index.svelte` files to export multiple components or functions from a directory, providing a cleaner import experience. + - **Component Architecture:** + - Favor a component-based architecture where UI is broken down into small, reusable components. + - Consider using a composition pattern where complex components are built by composing simpler ones. + - Separate concerns: Keep components focused on presentation logic and delegate data fetching or business logic to services or stores. + - **Code Splitting Strategies:** + - Use dynamic imports (`import()`) to load components or modules on demand, reducing the initial bundle size. + - Leverage SvelteKit's built-in code splitting capabilities for route-based splitting. + - Consider splitting large components into smaller, lazily loaded sub-components. + +## 2. Common Patterns and Anti-patterns: + + - **Design Patterns Specific to Svelte:** + - **Store pattern:** Use Svelte's stores for managing application state and reactivity. + - **Action pattern:** Use Svelte's actions for manipulating DOM elements or integrating with third-party libraries. + - **Component composition:** Build complex UIs by composing smaller, reusable components. + - **Recommended Approaches for Common Tasks:** + - **Form handling:** Use Svelte's two-way binding (`bind:value`) for simple forms. For more complex scenarios, consider libraries like Formik or Svelte Formly. + - **Data fetching:** Use `fetch` or libraries like Axios for fetching data from APIs. Handle loading and error states appropriately. + - **Event handling:** Use Svelte's event directives (e.g., `on:click`) for handling DOM events. + - **Anti-patterns and Code Smells to Avoid:** + - **Overusing global state:** Avoid putting everything in a global store. Use component-level state when appropriate. + - **Directly manipulating the DOM outside of actions:** Rely on Svelte's reactivity system to update the DOM. + - **Writing overly complex components:** Break down large components into smaller, more manageable ones. + - **State Management Best Practices:** + - Use Svelte's built-in stores for managing global or application-level state. + - Consider using reactive declarations (`$:`) to derive state from other state variables. + - Keep state updates predictable and avoid modifying state directly. + - For complex state management needs, explore libraries like Redux or Zustand (though often unnecessary in Svelte). + - **Error Handling Patterns:** + - Use try-catch blocks to handle potential errors during data fetching or other asynchronous operations. + - Display user-friendly error messages in the UI. + - Log errors to the console or a logging service for debugging purposes. + - Implement global error handling to catch unhandled exceptions. + +## 3. Performance Considerations: + + - **Optimization Techniques:** + - **Minimize DOM updates:** Svelte is very efficient at updating the DOM, but unnecessary updates can still impact performance. Use reactive declarations judiciously. + - **Use `{#each}` blocks efficiently:** Key your `{#each}` blocks with unique identifiers to help Svelte efficiently update the list. + - **Avoid unnecessary component re-renders:** Use the `$:` syntax effectively to only update components when necessary. + - **Memory Management:** + - Avoid memory leaks by properly cleaning up event listeners and subscriptions when components are destroyed (using `onDestroy`). + - Be mindful of large data structures in stores, and consider using techniques like pagination or virtualization to manage them efficiently. + - **Rendering Optimization:** + - Use the `svelte:options` tag with the `immutable` option for components that receive immutable data as props. + - Use `shouldUpdate` to prevent rendering for unchanged immutable props. + - **Bundle Size Optimization:** + - Use production builds with minification and tree shaking to remove unused code. + - Use dynamic imports for code splitting. + - Optimize images and other assets. + - **Lazy Loading Strategies:** + - Use dynamic imports to lazy load components or modules that are not immediately needed. + - Implement lazy loading for images or other resources that are below the fold. + +## 4. Security Best Practices: + + - **Common Vulnerabilities and How to Prevent Them:** + - **Cross-Site Scripting (XSS):** Sanitize user input before displaying it in the UI. Svelte automatically escapes HTML entities, but be careful when using `@html` or `{@debug}`. + - **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks. + - **SQL Injection:** If interacting with a database, use parameterized queries to prevent SQL injection attacks. + - **Input Validation:** + - Validate user input on both the client-side and server-side. + - Use appropriate data types and validation rules to prevent invalid data from being processed. + - **Authentication and Authorization Patterns:** + - Use secure authentication mechanisms like OAuth or JWT. + - Implement proper authorization checks to ensure that users only have access to the resources they are allowed to access. + - **Data Protection Strategies:** + - Encrypt sensitive data at rest and in transit. + - Use secure storage mechanisms for storing sensitive data. + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Validate API responses to ensure that they are valid and not malicious. + +## 5. Testing Approaches: + + - **Unit Testing Strategies:** + - Use a testing framework like Jest or Mocha to write unit tests for individual components and utility functions. + - Mock external dependencies to isolate the code being tested. + - **Integration Testing:** + - Use a testing framework like Cypress or Playwright to write integration tests that verify the interaction between different components or modules. + - Test the integration with APIs and other external services. + - **End-to-End Testing:** + - Use a testing framework like Cypress or Playwright to write end-to-end tests that simulate user interactions with the application. + - Test the entire application flow from start to finish. + - **Test Organization:** + - Organize tests into directories that mirror the application's directory structure. + - Use descriptive names for test files and test cases. + - **Mocking and Stubbing:** + - Use mocking libraries like Jest's `jest.fn()` or Sinon.js to mock external dependencies. + - Use stubbing to replace complex or slow dependencies with simpler implementations for testing purposes. + +## 6. Common Pitfalls and Gotchas: + + - **Frequent Mistakes Developers Make:** + - **Incorrect reactivity usage:** Failing to understand how Svelte's reactivity system works can lead to unexpected behavior. + - **Over-reliance on `$: `:** Although reactive declarations are powerful, overusing them can make code harder to read and debug. Consider if a regular variable or function would be more appropriate. + - **Mutating props directly:** Modifying props directly inside a component can lead to unexpected side effects. + - **Edge Cases to Be Aware Of:** + - **Transition and animation behavior:** Understanding how transitions and animations interact with component updates is important for creating smooth user experiences. + - **Server-side rendering (SSR) considerations:** When using SvelteKit, be aware of the differences between client-side and server-side execution environments. + - **Version-Specific Issues:** + - Consult the Svelte changelog and migration guides when upgrading to a new version to avoid compatibility issues. + - **Compatibility Concerns:** + - Ensure that your code is compatible with the target browsers and devices. + - Use polyfills or transpilers to support older browsers if necessary. + - **Debugging Strategies:** + - Use the Svelte Devtools browser extension for inspecting component state and reactivity. + - Use `console.log` or the `debugger` statement to debug code execution. + - Use SvelteKit's built-in error handling and logging features. + +## 7. Tooling and Environment: + + - **Recommended Development Tools:** + - **VS Code with the Svelte extension:** Provides syntax highlighting, code completion, and other useful features. + - **Svelte Devtools:** A browser extension for inspecting Svelte component state and reactivity. + - **ESLint and Prettier:** For linting and formatting code. + - **Build Configuration:** + - Use a build tool like Vite or Rollup to bundle your Svelte code for production. + - Configure the build tool to perform optimizations like minification and tree shaking. + - **Linting and Formatting:** + - Use ESLint with the `eslint-plugin-svelte3` plugin to lint your Svelte code. + - Use Prettier with the `prettier-plugin-svelte` plugin to format your Svelte code. + - **Deployment Best Practices:** + - Deploy your Svelte application to a CDN or a serverless platform like Netlify or Vercel. + - Configure your server to serve the application's static assets with proper caching headers. + - **CI/CD Integration:** + - Use a CI/CD platform like GitHub Actions or GitLab CI to automate the build, testing, and deployment process. + - Run tests and linting checks on every commit to ensure code quality. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/svelte/sveltekit.mdc b/rules-mdc/frontend_frameworks/svelte/sveltekit.mdc new file mode 100644 index 0000000..a1418d3 --- /dev/null +++ b/rules-mdc/frontend_frameworks/svelte/sveltekit.mdc @@ -0,0 +1,306 @@ +--- +description: This rule provides comprehensive best practices and coding standards for SvelteKit development, covering code structure, performance, security, testing, and common pitfalls. It aims to improve code quality, maintainability, and overall project health. +globs: **/*.svelte +--- +# SvelteKit Best Practices + +This guide provides comprehensive best practices for developing SvelteKit applications. It covers various aspects, including code organization, performance considerations, security measures, and common pitfalls to avoid. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure Best Practices + +* **`src/lib`**: Reusable components, utilities, and stores. Organize by feature or domain. +* **`src/routes`**: Defines the application's routes. Each directory represents a route segment. +* **`src/routes/+page.svelte`**: Represents a page component for a route. +* **`src/routes/+layout.svelte`**: Layout component that wraps the page. Useful for consistent UI elements. +* **`src/routes/+page.server.ts`**: Server-side code for handling data fetching and form submissions for a page. +* **`src/routes/+layout.server.ts`**: Server-side code for layout data, loaded before any +page.server.ts data. +* **`src/hooks.server.ts`**: Handle server-side requests and responses. Useful for authentication and session management. +* **`static`**: Static assets like images, fonts, and other files served directly. +* **`tests`**: Directory for all tests, mirroring the source structure for clarity. + +Example: + + +src/ +├── lib/ +│ ├── components/ +│ │ ├── Button.svelte +│ │ └── Card.svelte +│ ├── utils/ +│ │ ├── api.ts +│ │ └── helpers.ts +│ └── stores/ +│ └── user.ts +├── routes/ +│ ├── + +│ │ └── page.svelte +│ ├── about/ +│ │ ├── + +│ │ │ └── page.svelte +│ │ └── +page.server.ts +│ └── blog/ +│ ├── [slug]/ +│ │ ├── + +│ │ │ └── page.svelte +│ │ └── +page.server.ts +│ └── + +│ └── page.svelte +├── hooks.server.ts +└── app.d.ts + + +### 1.2. File Naming Conventions + +* **Components**: PascalCase (e.g., `MyComponent.svelte`). +* **Utility functions**: camelCase (e.g., `formatDate.ts`). +* **Stores**: camelCase (e.g., `userStore.ts`). +* **Route files**: Follow SvelteKit's routing conventions (`+page.svelte`, `+layout.svelte`, etc.). + +### 1.3. Module Organization + +* Group related functionality into modules. +* Use `src/lib` for reusable modules. +* Employ clear and descriptive module names. +* Leverage SvelteKit's `$lib` alias for importing modules from `src/lib`. + +### 1.4. Component Architecture + +* **Atomic Design**: Break down UI into small, reusable components (atoms, molecules, organisms, templates, pages). +* **Component Composition**: Compose complex UIs from simpler components. +* **Props and Events**: Use props for data input and events for component output. +* **Slots**: Allow parent components to inject content into child components. + +### 1.5. Code Splitting Strategies + +* **Dynamic Imports**: Use dynamic imports (`import()`) to load modules on demand. +* **Route-Based Splitting**: SvelteKit automatically splits code based on routes. +* **Component-Level Splitting**: Split large components into smaller chunks that can be loaded independently. +* **Lazy Loading**: Load non-critical components or modules only when needed. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to SvelteKit + +* **Form Actions**: Use SvelteKit's form actions for handling form submissions on the server. +* **Load Functions**: Utilize `load` functions in `+page.server.ts` and `+layout.server.ts` for data fetching. +* **Stores for State Management**: Employ Svelte stores for managing application state. +* **Server-Side Rendering (SSR)**: Leverage SSR for improved SEO and initial load performance. +* **Progressive Enhancement**: Design applications to work even with JavaScript disabled. + +### 2.2. Recommended Approaches for Common Tasks + +* **Data Fetching**: Use `fetch` API or libraries like `axios` within `load` functions. +* **Form Handling**: Use SvelteKit's form actions for server-side validation and processing. +* **Authentication**: Implement authentication using libraries like `lucia-auth` or integrate with OAuth providers. +* **Authorization**: Implement role-based access control using stores or server-side checks. +* **Error Handling**: Use `try...catch` blocks and SvelteKit's `handleError` hook for global error handling. + +### 2.3. Anti-patterns and Code Smells to Avoid + +* **Over-reliance on Global State**: Avoid using global stores for component-specific state. +* **Direct DOM Manipulation**: Avoid directly manipulating the DOM; use Svelte's reactivity system instead. +* **Large, Unmaintainable Components**: Break down large components into smaller, reusable ones. +* **Ignoring Accessibility**: Ensure components are accessible to users with disabilities (ARIA attributes, semantic HTML). +* **Unnecessary Re-renders**: Optimize components to avoid unnecessary re-renders. + +### 2.4. State Management Best Practices + +* **Use Svelte Stores**: Svelte stores are the recommended way to manage application state. +* **Divide stores according to feature**: Split stores based on logical domain or feature (e.g. UserStore, CartStore). +* **Readable and Writable Stores**: Use readable stores for derived state and writable stores for mutable state. +* **Custom Stores**: Create custom stores for complex state management logic. + +### 2.5. Error Handling Patterns + +* **`try...catch` Blocks**: Use `try...catch` blocks to handle errors within components and functions. +* **`handleError` Hook**: Implement the `handleError` hook in `src/hooks.server.ts` for global error handling. +* **Error Boundaries**: Use error boundaries to catch errors in component trees and display fallback UI. +* **Logging**: Log errors to a server for monitoring and debugging. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Lazy Loading**: Load non-critical resources (images, components) only when needed. +* **Code Splitting**: Split code into smaller chunks to reduce initial load time. +* **Image Optimization**: Optimize images using tools like `squoosh` or `tinypng`. +* **Server-Side Rendering (SSR)**: Use SSR for improved initial load performance and SEO. +* **Caching**: Implement caching strategies for data and assets. +* **Preload critical assets**: use `` to fetch critical assets earlier + +### 3.2. Memory Management + +* **Avoid Memory Leaks**: Properly clean up resources when components unmount. +* **Use WeakRefs**: Use `WeakRefs` for managing objects that might be garbage collected. +* **Minimize Object Creation**: Avoid creating unnecessary objects and arrays. +* **Properly unsubscrive from stores:** Properly unsubscribe to avoid re-renders when the component is unmounted. + +### 3.3. Rendering Optimization + +* **Tracked values**: Use the `$:` syntax to track dependencies of reactive statements. +* **Svelte Compiler**: Utilize Svelte's compiler to optimize component rendering. +* **Virtual DOM**: Svelte doesn't use a virtual DOM, so updates are generally very efficient. +* **Avoid Unnecessary Re-renders**: Use `{#each}` blocks with keys to optimize list rendering. +* **Debouncing and Throttling**: Use debouncing and throttling to limit the frequency of updates. + +### 3.4. Bundle Size Optimization + +* **Tree Shaking**: Ensure unused code is removed during the build process. +* **Minification**: Minify JavaScript and CSS files to reduce bundle size. +* **Compression**: Compress assets using gzip or Brotli. +* **Dependency Analysis**: Analyze dependencies to identify and remove unused libraries. + +### 3.5. Lazy Loading Strategies + +* **Intersection Observer**: Use the Intersection Observer API to detect when elements are visible and load them lazily. +* **Dynamic Imports**: Use dynamic imports to load components and modules on demand. +* **Placeholder UI**: Display a placeholder UI while resources are loading. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities and How to Prevent Them + +* **Cross-Site Scripting (XSS)**: Sanitize user input to prevent XSS attacks. +* **Cross-Site Request Forgery (CSRF)**: Use CSRF tokens to protect against CSRF attacks. +* **SQL Injection**: Use parameterized queries or ORMs to prevent SQL injection. +* **Authentication and Authorization**: Implement secure authentication and authorization mechanisms. +* **Insecure Direct Object References (IDOR)**: Implement proper access controls to prevent unauthorized access to resources. + +### 4.2. Input Validation + +* **Server-Side Validation**: Always validate user input on the server. +* **Client-Side Validation**: Use client-side validation for immediate feedback, but never rely on it solely. +* **Escape User Input**: Escape user input before rendering it in the DOM. +* **Use Validation Libraries**: Use libraries like `zod` or `yup` for input validation. + +### 4.3. Authentication and Authorization Patterns + +* **JWT (JSON Web Tokens)**: Use JWTs for authentication and authorization. +* **OAuth 2.0**: Integrate with OAuth providers like Google and Facebook for social login. +* **Role-Based Access Control (RBAC)**: Implement RBAC to control access to resources based on user roles. +* **Multi-Factor Authentication (MFA)**: Implement MFA for enhanced security. + +### 4.4. Data Protection Strategies + +* **Encryption**: Encrypt sensitive data at rest and in transit. +* **Hashing**: Hash passwords using strong hashing algorithms like bcrypt or Argon2. +* **Data Masking**: Mask sensitive data in logs and reports. +* **Regular Security Audits**: Conduct regular security audits to identify and address vulnerabilities. + +### 4.5. Secure API Communication + +* **HTTPS**: Use HTTPS for all API communication. +* **API Keys**: Protect API keys and secrets. +* **Rate Limiting**: Implement rate limiting to prevent abuse. +* **Input Validation**: Always validate input to your APIs. +* **Output Encoding**: Always encode output from your API to prevent injection attacks. + +## 5. Testing Approaches + +### 5.1. Unit Testing Strategies + +* **Test Individual Components**: Write unit tests for individual components in isolation. +* **Test Utility Functions**: Write unit tests for utility functions and modules. +* **Use Mock Data**: Use mock data for testing components and functions. +* **Test Edge Cases**: Test edge cases and error conditions. +* **Utilize Svelte Testing Library**: Employ `svelte-testing-library` for testing Svelte components. + +### 5.2. Integration Testing + +* **Test Component Interactions**: Write integration tests to ensure components interact correctly. +* **Test Data Flow**: Test the flow of data between components and modules. +* **Test API Integrations**: Test integrations with APIs and external services. + +### 5.3. End-to-End Testing + +* **Simulate User Interactions**: Write end-to-end tests to simulate user interactions. +* **Test Full Workflows**: Test complete user workflows from start to finish. +* **Use Playwright or Cypress**: Use tools like Playwright or Cypress for end-to-end testing. + +### 5.4. Test Organization + +* **Mirror Source Structure**: Organize tests in a directory structure that mirrors the source code. +* **Use Descriptive Names**: Use descriptive names for test files and functions. +* **Separate Test Environments**: Use separate test environments for unit, integration, and end-to-end tests. + +### 5.5. Mocking and Stubbing + +* **Mock API Calls**: Mock API calls to isolate components during testing. +* **Stub External Dependencies**: Stub external dependencies to control their behavior. +* **Use Mocking Libraries**: Use libraries like `jest.mock` or `sinon` for mocking and stubbing. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes Developers Make + +* **Incorrectly Using Reactive Statements**: Not understanding how Svelte's reactivity system works. +* **Ignoring Accessibility**: Neglecting accessibility considerations when building components. +* **Over-complicating State Management**: Using complex state management solutions when simpler ones would suffice. +* **Not Handling Errors Properly**: Ignoring errors or not providing informative error messages. +* **Premature Optimization**: Optimizing code before it is necessary. + +### 6.2. Edge Cases to Be Aware Of + +* **Server-Side Rendering Differences**: Be aware of differences between server-side and client-side rendering. +* **Browser Compatibility**: Test applications in different browsers to ensure compatibility. +* **Network Latency**: Design applications to handle network latency and unreliable connections. +* **Memory Constraints**: Consider memory constraints when building large applications. + +### 6.3. Version-Specific Issues + +* **Breaking Changes**: Be aware of breaking changes in new versions of SvelteKit. +* **Deprecated Features**: Avoid using deprecated features. +* **Upgrade Guides**: Follow upgrade guides when migrating to new versions of SvelteKit. + +### 6.4. Compatibility Concerns + +* **Third-Party Libraries**: Ensure third-party libraries are compatible with SvelteKit. +* **Browser Support**: Check browser support for new features and APIs. +* **Node.js Version**: Ensure the Node.js version is compatible with SvelteKit. + +### 6.5. Debugging Strategies + +* **Browser Developer Tools**: Use browser developer tools for debugging JavaScript and CSS. +* **Svelte Devtools**: Use the Svelte Devtools extension for inspecting Svelte components. +* **Logging**: Use `console.log` statements for debugging. +* **Debuggers**: Use debuggers like VS Code's debugger for step-by-step debugging. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools + +* **VS Code**: VS Code is a popular code editor with excellent Svelte and TypeScript support. +* **Svelte Devtools**: The Svelte Devtools browser extension allows you to inspect Svelte components. +* **ESLint**: ESLint is a linter that helps enforce code style and best practices. +* **Prettier**: Prettier is a code formatter that automatically formats code to a consistent style. +* **TypeScript**: Using typescript is recommended for type safety. + +### 7.2. Build Configuration + +* **`svelte.config.js`**: Configure SvelteKit using the `svelte.config.js` file. +* **Vite**: SvelteKit uses Vite as its build tool. +* **Environment Variables**: Use environment variables for configuration settings. +* **Adapters**: Use adapters to deploy SvelteKit applications to different environments. + +### 7.3. Linting and Formatting + +* **ESLint**: Configure ESLint to enforce code style and best practices. +* **Prettier**: Configure Prettier to automatically format code. +* **Husky**: Use Husky to run linters and formatters before committing code. +* **Lint Staged**: Use lint-staged to run linters and formatters only on staged files. + +### 7.4. Deployment Best Practices + +* **Choose an Adapter**: Use an adapter like `@sveltejs/adapter-node` or `@sveltejs/adapter-static` to deploy the application. +* **Configure Environment Variables**: Configure environment variables for production environments. +* **Set Up HTTPS**: Set up HTTPS for secure communication. +* **Monitor the Application**: Monitor the application for errors and performance issues. + +### 7.5. CI/CD Integration + +* **Use a CI/CD Pipeline**: Use a CI/CD pipeline to automate the build, test, and deployment process. +* **Automated Tests**: Run automated tests in the CI/CD pipeline. +* **Automated Deployments**: Automate deployments to production environments. +* **Use tools like GitHub Actions, GitLab CI, or CircleCI** \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/vue/nuxt.mdc b/rules-mdc/frontend_frameworks/vue/nuxt.mdc new file mode 100644 index 0000000..302f86d --- /dev/null +++ b/rules-mdc/frontend_frameworks/vue/nuxt.mdc @@ -0,0 +1,201 @@ +--- +description: This rule provides comprehensive best practices and coding standards for Nuxt.js projects, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure maintainable, scalable, and secure Nuxt.js applications. +globs: **/*.{vue,js,ts,mjs,mts,jsx,tsx,config.js,config.ts} +--- +- **Enable ESLint support:** Use the `@nuxt/eslint` module for project-aware ESLint configuration. This ensures code quality and consistency. + - `npx nuxi module add eslint` to add the module. + - Customize the generated `eslint.config.mjs` file as needed. +- **Adopt Nuxt.js Modules:** Leverage Nuxt.js modules to encapsulate functionalities and maintain a clean codebase. Explore existing modules before implementing custom solutions (e.g., `@nuxt/auth` for server-side authentication). +- **Convention over Configuration:** Adhere to Nuxt.js conventions to simplify development and collaboration. Avoid deviating from conventions unless absolutely necessary. +- **Efficiently Utilize Nuxt Layouts:** Create reusable layouts for components shared across multiple pages to ensure consistency and save development time. Layouts are located in the `layouts/` directory. +- **Manage State with Pinia:** Use Pinia for state management. Organize store modules based on features or functionalities for better maintainability. +- **Divide Pages into Components:** Break down pages into small, reusable components to enhance maintainability, testability, and reusability. Each component should have a single responsibility. +- **Leverage Nuxt Plugins Wisely:** Use Nuxt plugins to run code before Vue.js initializes or add global functionality. Be mindful of plugin performance impact. Plugins are located in the `plugins/` directory. +- **Optimize for SEO and Performance:** Utilize Nuxt.js's server-side rendering (SSR) for SEO. Implement lazy loading for images and optimize assets to minimize initial load time. Use tools like Lighthouse to identify performance bottlenecks. +- **Implement Error Handling and Validation:** Implement robust error handling and validation mechanisms to provide a seamless user experience. Use Nuxt.js middleware to intercept requests and responses for error handling and data validation. +- **Document Your Code:** Provide clear and concise documentation for components, modules, and custom functions using tools like JSDoc. +- **Embrace Testing:** Write unit tests, integration tests, and end-to-end tests using tools like Jest, Vue Test Utils and Vitest. + +## 1. Code Organization and Structure: + +- **Directory Structure:** + - `components/`: Reusable Vue components. + - `composables/`: Reusable composable functions. + - `layouts/`: Application layouts. + - `middleware/`: Route middleware. + - `pages/`: Application pages (route definitions). + - `plugins/`: Nuxt.js plugins. + - `server/`: API routes and server-side logic. + - `static/`: Static assets (e.g., images, fonts). + - `store/`: Pinia stores (optional, but recommended). + - `utils/`: Utility functions. +- **File Naming Conventions:** + - Components: `PascalCase.vue` (e.g., `MyComponent.vue`) + - Composables: `usePascalCase.js` or `usePascalCase.ts` (e.g., `useCounter.js`) + - Layouts: `kebab-case.vue` (e.g., `default.vue` or `custom-layout.vue`) + - Pages: `kebab-case.vue` (e.g., `index.vue`, `about.vue`, `product-details.vue`) + - Plugins: `kebab-case.js` or `kebab-case.ts` (e.g., `analytics.js`) + - Stores: `kebab-case.js` or `kebab-case.ts` (e.g., `user-store.js`) + - Utility functions: `camelCase.js` or `camelCase.ts` (e.g., `formatDate.js`) +- **Module Organization:** + - Group related functionalities into separate modules. + - Use the `@nuxt/modules` array in `nuxt.config.js` or `nuxt.config.ts` to register modules. + - Create custom modules to encapsulate complex logic. +- **Component Architecture:** + - Favor composition over inheritance. + - Use functional components for simple UI elements. + - Design components for reusability and testability. + - Consider using slots for flexible component composition. +- **Code Splitting:** + - Utilize dynamic imports for route-based code splitting. + - Split large components into smaller chunks using `import()`. + - Analyze bundle size with tools like Webpack Bundle Analyzer. + +## 2. Common Patterns and Anti-patterns: + +- **Design Patterns:** + - **Composition API:** Use the Composition API for organizing component logic. + - **Store Pattern (Pinia):** Implement a centralized state management system with Pinia. + - **Middleware Pattern:** Use middleware for authentication, authorization, and data validation. + - **Plugin Pattern:** Create plugins for global functionality and third-party library integrations. +- **Recommended Approaches:** + - **API Communication:** Use the `useFetch` or `useAsyncData` composables for API calls within components. + - **Form Handling:** Utilize Vue's built-in form handling features with `v-model` and validation libraries like VeeValidate. + - **Authentication:** Implement a secure authentication flow using a library like `@nuxt/auth` or a custom solution. + - **Authorization:** Implement role-based access control (RBAC) using middleware and Pinia stores. +- **Anti-patterns:** + - **Mutating props directly:** Avoid modifying parent component data directly from child components. Use `emit` instead. + - **Overusing global state:** Limit the use of global state to essential application data. Consider component-level state for local data. + - **Ignoring error handling:** Always handle potential errors in API calls and other asynchronous operations. + - **Writing overly complex components:** Break down large components into smaller, more manageable pieces. +- **State Management Best Practices:** + - **Single Source of Truth:** Maintain a single, consistent source of truth for application state in Pinia stores. + - **Immutability:** Treat state as immutable. Use functions to update the store rather than directly manipulating data. + - **Clear Naming Conventions:** Use descriptive names for store modules, actions, and mutations. + - **Modularization:** Divide stores into modules based on features or functionalities. +- **Error Handling Patterns:** + - **Centralized Error Handling:** Implement a global error handler to catch unhandled exceptions. + - **Error Boundaries:** Use error boundaries to isolate component failures and prevent cascading errors. + - **User-Friendly Error Messages:** Provide clear and helpful error messages to users. + +## 3. Performance Considerations: + +- **Optimization Techniques:** + - **Lazy Loading:** Implement lazy loading for images, components, and routes. + - **Code Splitting:** Split the application into smaller chunks for faster initial load times. + - **Tree Shaking:** Remove unused code during the build process. + - **Caching:** Cache API responses and static assets to reduce server load. + - **Image Optimization:** Optimize images using tools like `nuxt/image`. Use appropriate image formats (WebP). Resize the image to appropriate size. Consider using a CDN for image delivery. +- **Memory Management:** + - **Avoid Memory Leaks:** Clean up event listeners and timers when components are unmounted. + - **Use Weak References:** Use weak references for DOM elements when possible. + - **Minimize Object Creation:** Avoid creating unnecessary objects and arrays. +- **Rendering Optimization:** + - **Virtualization:** Use virtualization for large lists to improve rendering performance. + - **Memoization:** Memoize expensive calculations to avoid redundant computations. Use `computed` properties effectively to avoid unnecessary re-renders. + - **Debouncing and Throttling:** Use debouncing and throttling for event handlers to reduce the number of function calls. +- **Bundle Size Optimization:** + - **Analyze Bundle Size:** Use Webpack Bundle Analyzer to identify large dependencies. + - **Remove Unused Dependencies:** Remove unused dependencies to reduce bundle size. + - **Use Smaller Alternatives:** Consider using smaller alternatives to large libraries. + - **Optimize Dependencies:** Review dependencies and ensure you're using the most efficient ones. +- **Lazy Loading Strategies:** + - **Route-based Lazy Loading:** Load components only when the corresponding route is accessed. + - **Component-based Lazy Loading:** Load components only when they are visible in the viewport. + +## 4. Security Best Practices: + +- **Common Vulnerabilities:** + - **Cross-Site Scripting (XSS):** Prevent XSS attacks by properly sanitizing user input and using Vue's built-in HTML escaping. + - **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by implementing CSRF tokens. + - **SQL Injection:** Avoid raw SQL queries. Use an ORM (Object-Relational Mapper) to prevent SQL injection. + - **Authentication and Authorization Flaws:** Implement secure authentication and authorization mechanisms. + - **Insecure Direct Object References (IDOR):** Implement proper access control to prevent unauthorized access to resources. +- **Input Validation:** + - **Server-Side Validation:** Always validate user input on the server-side. + - **Client-Side Validation:** Provide client-side validation for a better user experience (but don't rely on it as the sole source of validation). + - **Sanitize Input:** Sanitize user input to remove potentially harmful characters. +- **Authentication and Authorization Patterns:** + - **JWT (JSON Web Tokens):** Use JWT for authentication and authorization. + - **OAuth 2.0:** Implement OAuth 2.0 for third-party authentication. + - **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles. +- **Data Protection Strategies:** + - **Encryption:** Encrypt sensitive data at rest and in transit. + - **Hashing:** Hash passwords and other sensitive data using strong hashing algorithms. + - **Data Masking:** Mask sensitive data in logs and other non-production environments. +- **Secure API Communication:** + - **HTTPS:** Always use HTTPS for API communication. + - **API Rate Limiting:** Implement API rate limiting to prevent abuse. + - **Authentication and Authorization:** Require authentication and authorization for all API endpoints. + +## 5. Testing Approaches: + +- **Unit Testing:** + - **Test Individual Components:** Test individual components in isolation. + - **Mock Dependencies:** Mock external dependencies to isolate components during testing. + - **Verify Component Behavior:** Verify that components render correctly and behave as expected. +- **Integration Testing:** + - **Test Component Interactions:** Test the interactions between components. + - **Test Data Flow:** Test the data flow between components and stores. + - **Test API Integrations:** Test the integration with external APIs. +- **End-to-End Testing:** + - **Simulate User Interactions:** Simulate user interactions to test the application's functionality. + - **Test the Entire Application Flow:** Test the entire application flow from start to finish. + - **Use a Browser Automation Tool:** Use a browser automation tool like Cypress or Playwright. +- **Test Organization:** + - **Organize Tests by Feature:** Organize tests by feature or functionality. + - **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is testing. + - **Keep Tests Isolated:** Keep tests isolated from each other to avoid interference. +- **Mocking and Stubbing:** + - **Use Mock Objects:** Use mock objects to replace external dependencies during testing. + - **Use Stubs:** Use stubs to replace complex functions with simplified versions. + - **Avoid Over-Mocking:** Avoid mocking too much code, as this can make tests less effective. + +## 6. Common Pitfalls and Gotchas: + +- **Frequent Mistakes:** + - **Incorrect `this` Context:** Be mindful of the `this` context in Vue components and use arrow functions or `bind` to maintain the correct context. + - **Asynchronous Data Handling:** Properly handle asynchronous data loading with `async/await` or Promises. + - **Forgetting to Unsubscribe:** Unsubscribe from event listeners and timers when components are unmounted to prevent memory leaks. + - **Overusing `forceUpdate`:** Avoid using `forceUpdate` unless absolutely necessary, as it can negatively impact performance. +- **Edge Cases:** + - **Server-Side Rendering (SSR):** Be aware of the differences between client-side and server-side rendering. + - **Browser Compatibility:** Test the application in different browsers to ensure compatibility. + - **Accessibility:** Consider accessibility when designing and developing the application. +- **Version-Specific Issues:** + - **Nuxt 2 vs Nuxt 3:** Be aware of the differences between Nuxt 2 and Nuxt 3. + - **Vue 2 vs Vue 3:** Be aware of the differences between Vue 2 and Vue 3. + - **Dependency Updates:** Carefully review dependency updates for potential breaking changes. +- **Compatibility Concerns:** + - **Browser Support:** Ensure compatibility with the target browsers. + - **Device Compatibility:** Test the application on different devices. + - **Operating System Compatibility:** Ensure compatibility with the target operating systems. +- **Debugging Strategies:** + - **Use Browser Developer Tools:** Use browser developer tools to inspect the application's state and network activity. + - **Use Vue Devtools:** Use Vue Devtools to inspect Vue components and data. + - **Use Logging:** Use logging to track the application's behavior. + +## 7. Tooling and Environment: + +- **Recommended Development Tools:** + - **VS Code:** Visual Studio Code is a popular code editor with excellent Vue.js support. + - **Vue Devtools:** Vue Devtools is a browser extension that provides debugging tools for Vue.js applications. + - **ESLint:** ESLint is a linter that enforces coding standards. + - **Prettier:** Prettier is a code formatter that automatically formats code. +- **Build Configuration:** + - **`nuxt.config.js` or `nuxt.config.ts`:** Configure the application's build settings in `nuxt.config.js` or `nuxt.config.ts`. + - **Webpack:** Nuxt uses Webpack to bundle the application. + - **Vite:** Nuxt 3 uses Vite to bundle the application by default, providing faster build and development times. +- **Linting and Formatting:** + - **ESLint:** Use ESLint to enforce coding standards. + - **Prettier:** Use Prettier to automatically format code. + - **Husky:** Use Husky to run linters and formatters before commits. +- **Deployment Best Practices:** + - **Server-Side Rendering (SSR):** Deploy the application to a server that supports SSR. + - **Static Site Generation (SSG):** Generate a static site for content-heavy applications. + - **CDN:** Use a CDN to deliver static assets. +- **CI/CD Integration:** + - **Continuous Integration (CI):** Use a CI tool like Jenkins, GitLab CI, or GitHub Actions to automate the build and testing process. + - **Continuous Deployment (CD):** Use a CD tool to automate the deployment process. + +By following these best practices, you can build robust, maintainable, and scalable Nuxt.js applications. \ No newline at end of file diff --git a/rules-mdc/frontend_frameworks/vue/vue.mdc b/rules-mdc/frontend_frameworks/vue/vue.mdc new file mode 100644 index 0000000..6c07421 --- /dev/null +++ b/rules-mdc/frontend_frameworks/vue/vue.mdc @@ -0,0 +1,298 @@ +--- +description: Comprehensive guidelines for Vue.js development, covering code structure, performance, security, testing, and tooling best practices. This rule provides actionable guidance to enhance code quality, maintainability, and developer productivity in Vue.js projects. +globs: **/*.vue, **/*.js, **/*.ts +--- +# Vue.js Best Practices and Coding Standards + +This document outlines best practices for Vue.js development, covering various aspects to ensure high-quality, maintainable, and performant code. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure + +* **Component-Based Structure:** Organize components into logical folders based on their functionality or feature. This improves code readability and maintainability. + + src/ + ├── components/ + │ ├── Button/ + │ │ ├── Button.vue + │ │ └── Button.spec.js + │ ├── Input/ + │ │ ├── Input.vue + │ │ └── Input.spec.js + │ └── ... + ├── views/ + │ ├── Home.vue + │ ├── About.vue + │ └── ... + ├── services/ + │ ├── api.js + │ └── auth.js + ├── store/ + │ ├── index.js # Vuex store + │ ├── modules/ + │ │ ├── user.js + │ │ └── ... + ├── App.vue + └── main.js + +* **Feature-Based Structure:** Alternatively, organize files by feature, grouping components, routes, and store modules related to a specific feature. + + src/ + ├── features/ + │ ├── user-profile/ + │ │ ├── components/ + │ │ │ ├── UserProfile.vue + │ │ │ └── ... + │ │ ├── routes.js + │ │ ├── store.js + │ │ └── ... + │ ├── shopping-cart/ + │ │ ├── ... + │ └── ... + ├── App.vue + └── main.js + + +### 1.2. File Naming Conventions + +* **Component Files:** Use PascalCase for component file names (e.g., `MyComponent.vue`). +* **Other Files:** Use camelCase or kebab-case for other JavaScript/TypeScript files (e.g., `apiService.js`, `my-helper.js`). +* **Consistency:** Maintain a consistent naming convention throughout the project. + +### 1.3. Module Organization + +* **ES Modules:** Utilize ES modules (`import`/`export`) for modular code organization. +* **Single Responsibility Principle:** Each module should have a single, well-defined responsibility. +* **Avoid Circular Dependencies:** Prevent circular dependencies between modules to avoid unexpected behavior and improve maintainability. + +### 1.4. Component Architecture + +* **Component Composition:** Favor component composition over inheritance for increased flexibility and reusability. +* **Presentational and Container Components:** Separate presentational (dumb) components from container (smart) components. Presentational components focus on rendering UI, while container components handle data fetching and logic. +* **Single File Components (SFCs):** Leverage Vue's SFCs for encapsulating component logic, template, and styling. + +### 1.5. Code Splitting Strategies + +* **Route-Based Splitting:** Use dynamic imports and Vue's `async` component feature to split the application into chunks based on routes. +* **Component-Based Splitting:** Split large components into smaller, lazy-loaded components to improve initial load time. +* **Vendor Splitting:** Separate vendor dependencies into a separate chunk to allow for browser caching and prevent unnecessary reloads. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns Specific to Vue + +* **Provide/Inject:** Use `provide` and `inject` for dependency injection between components, especially when dealing with deeply nested components. +* **Renderless Components:** Create renderless components that encapsulate logic and provide data to be rendered by slot-using components. +* **Higher-Order Components (HOCs):** Use HOCs to reuse component logic or add functionality to existing components. + +### 2.2. Recommended Approaches for Common Tasks + +* **Form Handling:** Use `v-model` for two-way data binding in forms. Consider using a form validation library like Vuelidate or VeeValidate for robust form validation. +* **API Requests:** Use a dedicated service module for handling API requests. Use `async/await` for cleaner asynchronous code. +* **State Management:** Utilize Vuex for centralized state management in larger applications. For simpler applications, consider using Vue's reactivity system directly or a lightweight state management solution like Pinia. +* **Event Handling:** Use component events (`$emit`) for communication between parent and child components. For communication between unrelated components, use a global event bus (with caution) or a state management solution. + +### 2.3. Anti-patterns and Code Smells to Avoid + +* **Mutating Props Directly:** Avoid mutating props directly within a component. Instead, emit an event to the parent component to update the prop value. +* **Overusing Global State:** Avoid storing too much data in global state. Use local component state whenever possible. +* **Direct DOM Manipulation:** Avoid directly manipulating the DOM using `document` APIs. Use Vue's template directives and component APIs to update the DOM reactively. +* **Magic Numbers and Strings:** Avoid using magic numbers and strings directly in the code. Use constants to improve readability and maintainability. +* **Complex Computed Properties:** Keep computed properties simple and focused. Complex computations should be moved to methods or utility functions. + +### 2.4. State Management Best Practices + +* **Single Source of Truth:** Maintain a single source of truth for application state using Vuex or Pinia. +* **Mutations for State Updates:** Only use mutations to update the state in Vuex. Mutations should be synchronous and atomic. +* **Actions for Asynchronous Operations:** Use actions to handle asynchronous operations like API requests. Actions can commit mutations to update the state. +* **Getters for Derived State:** Use getters to derive state from the store. Getters should be pure functions and should not modify the state. +* **Modularity:** Organize the store into modules to improve maintainability and scalability. + +### 2.5. Error Handling Patterns + +* **Centralized Error Handling:** Implement a centralized error handling mechanism to catch and log errors consistently. +* **Error Boundary Components:** Use error boundary components to catch errors within specific parts of the application and prevent crashes. +* **User-Friendly Error Messages:** Provide user-friendly error messages to guide users when errors occur. +* **Logging:** Log errors to a server or error tracking service for monitoring and debugging. +* **Try-Catch Blocks:** Use `try-catch` blocks to handle potential errors in asynchronous operations or complex computations. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +* **Virtual DOM Optimization:** Vue's virtual DOM implementation is already highly optimized, but avoid unnecessary re-renders by using `v-if` instead of `v-show` when elements are rarely displayed. +* **Computed Properties and Watchers:** Use computed properties and watchers judiciously. Avoid performing expensive computations in computed properties that are frequently re-evaluated. Debounce or throttle watchers to limit the number of updates. +* **List Rendering Optimization:** Use the `:key` attribute when rendering lists with `v-for` to help Vue track changes efficiently. Ensure the keys are unique and stable. +* **Functional Components:** Use functional components for simple, stateless components to improve rendering performance. +* **Avoid Inline Templates:** Use pre-compiled templates in single-file components instead of inline templates (using `