Add comprehensive MDC rule files for various technologies

- Add 150+ MDC rule files covering a wide range of programming languages, frameworks, and tools
- Include best practices, coding standards, and guidelines for technologies like Python, JavaScript, React, AWS, CI/CD, and more
- Implement consistent formatting and structure across rule files
- Add concluding sections with recommendations for maintainability, security, and performance
- Enhance project documentation with comprehensive technology-specific guidelines
This commit is contained in:
sanjeed5
2025-02-28 19:31:47 +05:30
parent 69ee481328
commit d96d9ab8c8
159 changed files with 40387 additions and 309 deletions
+2 -1
View File
@@ -12,4 +12,5 @@ wheels/
awesome-cursorrules/
.env
exa_results/
logs/
logs/
.cache/
+338
View File
@@ -0,0 +1,338 @@
---
description: Comprehensive guide for aiohttp development covering code organization, performance, security, testing, and deployment best practices. Provides actionable guidance for developers to build robust and maintainable aiohttp applications.
globs: **/*.py
---
# Aiohttp Best Practices
This document provides a comprehensive guide to aiohttp development, covering code organization, performance, security, testing, and deployment.
Library Information:
- Name: aiohttp
- Tags: web, python, http-client, async
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices:
* **Project Root:**
* `src/`: Contains the main application code.
* `main.py`: Entry point of the application.
* `app.py`: Application factory and setup.
* `routes.py`: Defines application routes.
* `handlers/`: Contains request handlers.
* `user_handlers.py`: User-related handlers.
* `product_handlers.py`: Product-related handlers.
* `middlewares/`: Custom middleware components.
* `logging_middleware.py`: Logging middleware.
* `auth_middleware.py`: Authentication middleware.
* `utils/`: Utility modules.
* `db.py`: Database connection and utilities.
* `config.py`: Configuration management.
* `tests/`: Contains unit and integration tests.
* `conftest.py`: Pytest configuration file.
* `unit/`: Unit tests.
* `integration/`: Integration tests.
* `static/`: Static files (CSS, JavaScript, images).
* `templates/`: Jinja2 or other template files.
* `docs/`: Project documentation.
* `requirements.txt`: Python dependencies.
* `Dockerfile`: Docker configuration file.
* `docker-compose.yml`: Docker Compose configuration.
* `.env`: Environment variables.
* `README.md`: Project description and instructions.
* `.gitignore`: Specifies intentionally untracked files that Git should ignore.
* `.cursor/rules/`: Project specific Cursor AI rules.
### 1.2. File Naming Conventions:
* Python files: `snake_case.py` (e.g., `user_handlers.py`, `database_utils.py`).
* Class names: `CamelCase` (e.g., `UserHandler`, `DatabaseConnection`).
* Function names: `snake_case` (e.g., `get_user`, `create_product`).
* Variables: `snake_case` (e.g., `user_id`, `product_name`).
* Constants: `UPPER_SNAKE_CASE` (e.g., `DEFAULT_PORT`, `MAX_CONNECTIONS`).
### 1.3. Module Organization:
* Group related functionality into modules.
* Use clear and descriptive module names.
* Avoid circular dependencies.
* Keep modules focused and concise.
* Use packages to organize modules into a hierarchical structure.
### 1.4. Component Architecture:
* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access).
* **Microservices Architecture:** Decompose the application into small, independent services.
* **Hexagonal Architecture (Ports and Adapters):** Decouple the application core from external dependencies.
* **MVC (Model-View-Controller):** Organize the application into models (data), views (presentation), and controllers (logic).
### 1.5. Code Splitting Strategies:
* **Route-based splitting:** Load modules based on the requested route.
* **Feature-based splitting:** Divide the application into feature modules.
* **Component-based splitting:** Split the application into reusable components.
* **On-demand loading:** Load modules only when they are needed.
* **Asynchronous loading:** Use `asyncio.gather` or similar techniques to load modules concurrently.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns:
* **Singleton:** For managing shared resources like database connections or configuration objects.
* **Factory:** For creating instances of classes with complex initialization logic.
* **Strategy:** For implementing different algorithms or behaviors.
* **Observer:** For implementing event-driven systems.
* **Middleware:** For handling cross-cutting concerns like logging, authentication, and error handling.
### 2.2. Recommended Approaches for Common Tasks:
* **Request Handling:** Use request handlers to process incoming requests.
* **Routing:** Use `aiohttp.web.RouteTableDef` for defining routes.
* **Middleware:** Implement middleware for request pre-processing and response post-processing.
* **Data Serialization:** Use `aiohttp.web.json_response` for serializing data to JSON.
* **Error Handling:** Implement custom error handlers to handle exceptions gracefully.
* **Session Management:** Use `aiohttp-session` for managing user sessions.
* **WebSockets:** Utilize `aiohttp.web.WebSocketResponse` for handling WebSocket connections.
### 2.3. Anti-patterns and Code Smells:
* **Creating a new `ClientSession` for each request:** This is a performance bottleneck. Reuse a single `ClientSession`.
* **Blocking operations in asynchronous code:** Avoid using blocking operations (e.g., `time.sleep`) in asynchronous code.
* **Ignoring exceptions:** Always handle exceptions properly to prevent unexpected behavior.
* **Overusing global variables:** Avoid using global variables as much as possible to maintain code clarity and testability.
* **Tight coupling:** Decouple components to improve maintainability and reusability.
* **Hardcoding configuration:** Use environment variables or configuration files to manage configuration settings.
### 2.4. State Management:
* **Application State:** Store application-level state in the `aiohttp.web.Application` instance.
* **Request State:** Store request-specific state in the `aiohttp.web.Request` instance.
* **Session State:** Use `aiohttp-session` to manage user session data.
* **Database:** Use a database like PostgreSQL, MySQL, or MongoDB to store persistent state.
* **Redis/Memcached:** Use in-memory data stores for caching frequently accessed data.
### 2.5. Error Handling:
* **Use `try-except` blocks:** Wrap code that may raise exceptions in `try-except` blocks.
* **Handle specific exceptions:** Catch specific exception types instead of using a generic `except Exception`.
* **Log exceptions:** Log exceptions with detailed information for debugging.
* **Return informative error responses:** Return appropriate HTTP status codes and error messages to the client.
* **Implement custom error handlers:** Create custom error handlers to handle specific exception types.
* **Use `aiohttp.web.HTTPException`:** Raise `aiohttp.web.HTTPException` to return HTTP error responses.
## 3. Performance Considerations
### 3.1. Optimization Techniques:
* **Reuse `ClientSession`:** Always reuse a single `ClientSession` instance for making multiple requests.
* **Connection Pooling:** aiohttp automatically uses connection pooling, so reuse your session.
* **Keep-Alive Connections:** Keep-alive connections are enabled by default, reducing connection overhead.
* **Gzip Compression:** Enable Gzip compression for responses to reduce bandwidth usage.
* **Caching:** Implement caching for frequently accessed data to reduce database load.
* **Optimize Database Queries:** Optimize database queries to improve response times.
* **Use Indexes:** Use indexes in your database tables to speed up queries.
* **Limit Payload Size:** Keep request and response payloads as small as possible.
* **Background Tasks:** Use `asyncio.create_task` to offload long-running tasks to the background.
* **Profiling:** Use profiling tools to identify performance bottlenecks.
### 3.2. Memory Management:
* **Avoid Memory Leaks:** Ensure that all resources are properly released to prevent memory leaks.
* **Use Generators:** Use generators to process large datasets in chunks.
* **Limit Object Creation:** Minimize the creation of objects to reduce memory overhead.
* **Use Data Structures Efficiently:** Choose appropriate data structures to optimize memory usage.
* **Garbage Collection:** Understand how Python's garbage collection works and optimize your code accordingly.
### 3.3. Rendering Optimization:
* **Template Caching:** Cache templates to reduce rendering time.
* **Minimize Template Logic:** Keep template logic simple and move complex logic to request handlers.
* **Use Asynchronous Templates:** Use asynchronous template engines like `aiohttp-jinja2`.
* **Optimize Static Files:** Optimize static files (CSS, JavaScript, images) to reduce page load times.
### 3.4. Bundle Size Optimization:
* **Minimize Dependencies:** Reduce the number of dependencies in your project.
* **Tree Shaking:** Use tree shaking to remove unused code from your bundles.
* **Code Minification:** Minify your code to reduce bundle sizes.
* **Code Compression:** Compress your code to further reduce bundle sizes.
### 3.5. Lazy Loading:
* **Lazy Load Modules:** Load modules only when they are needed.
* **Lazy Load Images:** Load images only when they are visible in the viewport.
* **Use Asynchronous Loading:** Use `asyncio.gather` or similar techniques to load resources concurrently.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities:
* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
* **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates.
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens.
* **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms.
* **Denial-of-Service (DoS) Attacks:** Implement rate limiting and other measures to prevent DoS attacks.
* **Insecure Dependencies:** Keep your dependencies up to date to prevent vulnerabilities.
### 4.2. Input Validation:
* **Validate all user input:** Validate all user input to prevent malicious data from entering your application.
* **Use a validation library:** Use a validation library like `marshmallow` or `voluptuous` to simplify input validation.
* **Sanitize user input:** Sanitize user input to remove potentially harmful characters.
* **Limit input length:** Limit the length of input fields to prevent buffer overflows.
* **Use regular expressions:** Use regular expressions to validate input patterns.
### 4.3. Authentication and Authorization:
* **Use a strong authentication scheme:** Use a strong authentication scheme like OAuth 2.0 or JWT.
* **Store passwords securely:** Store passwords securely using a hashing algorithm like bcrypt.
* **Implement role-based access control (RBAC):** Use RBAC to control access to resources based on user roles.
* **Use secure cookies:** Use secure cookies to protect session data.
* **Implement multi-factor authentication (MFA):** Use MFA to add an extra layer of security.
### 4.4. Data Protection:
* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit.
* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server.
* **Store data securely:** Store data in a secure location with appropriate access controls.
* **Regularly back up data:** Regularly back up data to prevent data loss.
* **Comply with data privacy regulations:** Comply with data privacy regulations like GDPR and CCPA.
### 4.5. Secure API Communication:
* **Use HTTPS:** Always use HTTPS for API communication.
* **Implement API authentication:** Use API keys or tokens to authenticate API requests.
* **Rate limit API requests:** Implement rate limiting to prevent abuse.
* **Validate API requests:** Validate API requests to prevent malicious data from entering your application.
* **Log API requests:** Log API requests for auditing and debugging.
## 5. Testing Approaches
### 5.1. Unit Testing:
* **Test individual components:** Unit tests should test individual components in isolation.
* **Use a testing framework:** Use a testing framework like `pytest` or `unittest`.
* **Write clear and concise tests:** Write clear and concise tests that are easy to understand.
* **Test edge cases:** Test edge cases and boundary conditions.
* **Use mocks and stubs:** Use mocks and stubs to isolate components under test.
### 5.2. Integration Testing:
* **Test interactions between components:** Integration tests should test interactions between different components.
* **Test with real dependencies:** Integration tests should use real dependencies whenever possible.
* **Test the entire application flow:** Integration tests should test the entire application flow.
* **Use a testing database:** Use a testing database to isolate integration tests from the production database.
### 5.3. End-to-End Testing:
* **Test the entire system:** End-to-end tests should test the entire system from end to end.
* **Use a testing environment:** Use a testing environment that mimics the production environment.
* **Automate end-to-end tests:** Automate end-to-end tests to ensure that the system is working correctly.
* **Use a browser automation tool:** Use a browser automation tool like Selenium or Puppeteer.
### 5.4. Test Organization:
* **Organize tests by module:** Organize tests by module to improve test discovery and maintainability.
* **Use descriptive test names:** Use descriptive test names that clearly indicate what the test is verifying.
* **Use test fixtures:** Use test fixtures to set up and tear down test environments.
* **Use test markers:** Use test markers to categorize tests and run specific test suites.
### 5.5. Mocking and Stubbing:
* **Use mocks to simulate dependencies:** Use mocks to simulate the behavior of dependencies.
* **Use stubs to provide predefined responses:** Use stubs to provide predefined responses to API calls.
* **Use mocking libraries:** Use mocking libraries like `unittest.mock` or `pytest-mock`.
* **Avoid over-mocking:** Avoid over-mocking, as it can make tests less reliable.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes:
* **Not handling exceptions properly:** Always handle exceptions to prevent unexpected behavior.
* **Using blocking operations in asynchronous code:** Avoid using blocking operations in asynchronous code.
* **Not closing `ClientSession`:** Always close the `ClientSession` to release resources.
* **Not validating user input:** Always validate user input to prevent security vulnerabilities.
* **Not using HTTPS:** Always use HTTPS for secure communication.
### 6.2. Edge Cases:
* **Handling timeouts:** Implement proper timeout handling to prevent requests from hanging indefinitely.
* **Handling connection errors:** Handle connection errors gracefully to prevent application crashes.
* **Handling large payloads:** Handle large payloads efficiently to prevent memory issues.
* **Handling concurrent requests:** Handle concurrent requests properly to prevent race conditions.
* **Handling Unicode encoding:** Be aware of Unicode encoding issues when processing text data.
### 6.3. Version-Specific Issues:
* **aiohttp version compatibility:** Be aware of compatibility issues between different aiohttp versions.
* **asyncio version compatibility:** Be aware of compatibility issues between aiohttp and different asyncio versions.
* **Python version compatibility:** Be aware of compatibility issues between aiohttp and different Python versions.
### 6.4. Compatibility Concerns:
* **Compatibility with other libraries:** Be aware of compatibility issues between aiohttp and other libraries.
* **Compatibility with different operating systems:** Be aware of compatibility issues between aiohttp and different operating systems.
* **Compatibility with different web servers:** Be aware of compatibility issues between aiohttp and different web servers.
### 6.5. Debugging Strategies:
* **Use logging:** Use logging to track application behavior and identify issues.
* **Use a debugger:** Use a debugger to step through code and examine variables.
* **Use a profiler:** Use a profiler to identify performance bottlenecks.
* **Use error reporting tools:** Use error reporting tools to track and fix errors in production.
* **Use a network analyzer:** Use a network analyzer like Wireshark to capture and analyze network traffic.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools:
* **IDE:** Use an IDE like VS Code, PyCharm, or Sublime Text.
* **Virtual Environment:** Use a virtual environment to isolate project dependencies.
* **Package Manager:** Use a package manager like pip or poetry to manage dependencies.
* **Testing Framework:** Use a testing framework like pytest or unittest.
* **Linting Tool:** Use a linting tool like pylint or flake8 to enforce code style.
* **Formatting Tool:** Use a formatting tool like black or autopep8 to format code automatically.
### 7.2. Build Configuration:
* **Use a build system:** Use a build system like Make or tox to automate build tasks.
* **Define dependencies in `requirements.txt` or `pyproject.toml`:** Specify all project dependencies in a `requirements.txt` or `pyproject.toml` file.
* **Use a Dockerfile:** Use a Dockerfile to create a containerized build environment.
* **Use Docker Compose:** Use Docker Compose to manage multi-container applications.
### 7.3. Linting and Formatting:
* **Use a consistent code style:** Use a consistent code style throughout the project.
* **Configure linting tools:** Configure linting tools to enforce code style rules.
* **Configure formatting tools:** Configure formatting tools to format code automatically.
* **Use pre-commit hooks:** Use pre-commit hooks to run linters and formatters before committing code.
### 7.4. Deployment:
* **Use a web server:** Use a web server like Nginx or Apache to serve the application.
* **Use a process manager:** Use a process manager like Supervisor or systemd to manage the application process.
* **Use a reverse proxy:** Use a reverse proxy to improve security and performance.
* **Use a load balancer:** Use a load balancer to distribute traffic across multiple servers.
* **Use a monitoring system:** Use a monitoring system to track application health and performance.
* **Standalone Server:** aiohttp.web.run_app(), simple but doesn't utilize all CPU cores.
* **Nginx + Supervisord:** Nginx prevents attacks, allows utilizing all CPU cores, and serves static files faster.
* **Nginx + Gunicorn:** Gunicorn launches the app as worker processes, simplifying deployment compared to bare Nginx.
### 7.5. CI/CD Integration:
* **Use a CI/CD pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process.
* **Use a CI/CD tool:** Use a CI/CD tool like Jenkins, GitLab CI, or GitHub Actions.
* **Run tests in the CI/CD pipeline:** Run tests in the CI/CD pipeline to ensure that code changes don't break the application.
* **Automate deployment:** Automate deployment to reduce manual effort and improve consistency.
## Additional Best Practices:
* **Session Management:** Always create a `ClientSession` for making requests and reuse it across multiple requests to benefit from connection pooling. Avoid creating a new session for each request, as this can lead to performance issues.
* **Error Handling:** Implement robust error handling in your request handlers. Use try-except blocks to manage exceptions, particularly for network-related errors. For example, handle `ConnectionResetError` to manage client disconnections gracefully.
* **Middleware Usage:** Utilize middleware for cross-cutting concerns such as logging, error handling, and modifying requests/responses. Define middleware functions that accept a request and a handler, allowing you to process requests before they reach your main handler.
* **Graceful Shutdown:** Implement graceful shutdown procedures for your server to ensure that ongoing requests are completed before the application exits. This can be achieved by registering shutdown signals and cleaning up resources.
* **Security Practices:** When deploying, consider using a reverse proxy like Nginx for added security and performance. Configure SSL/TLS correctly to secure your application.
* **Character Set Detection:** If a response does not include the charset needed to decode the body, use `ClientSession` accepts a `fallback_charset_resolver` parameter which can be used to introduce charset guessing functionality.
* **Persistent Session:** Use `Cleanup Context` when creating a persistent session.
By adhering to these practices, developers can enhance the reliability, performance, and security of their `aiohttp` applications.
+317
View File
@@ -0,0 +1,317 @@
---
description: This rule file provides best practices, coding standards, and security guidelines for developing, deploying, and maintaining applications using the amazon-ec2 library within the AWS ecosystem. It focuses on infrastructure as code (IaC), resource management, performance, and security considerations for robust and scalable EC2-based solutions.
globs: **/*.{tf,json,yml,yaml,py,js,ts,sh,java,go,rb,m}
---
- ## General Principles
- **Infrastructure as Code (IaC):** Treat your infrastructure as code. Define and provision AWS resources (EC2 instances, security groups, networks) using code (e.g., AWS CloudFormation, AWS CDK, Terraform). This ensures consistency, repeatability, and version control.
- **Security First:** Integrate security best practices into every stage of development, from IaC template creation to instance configuration. Implement the principle of least privilege, regularly patch instances, and utilize security assessment tools.
- **Modularity and Reusability:** Design your infrastructure and application code in modular components that can be reused across multiple projects or environments.
- **Automation:** Automate as much of the infrastructure provisioning, deployment, and management processes as possible. Use CI/CD pipelines for automated testing and deployment.
- **Monitoring and Logging:** Implement comprehensive monitoring and logging to track the health, performance, and security of your EC2 instances and applications.
- ## 1. Code Organization and Structure
- **Directory Structure Best Practices:**
- Adopt a logical directory structure that reflects the architecture of your application and infrastructure.
- Example:
project-root/
├── modules/ # Reusable infrastructure modules (e.g., VPC, security groups)
│ ├── vpc/ # VPC module
│ │ ├── main.tf # Terraform configuration for the VPC
│ │ ├── variables.tf # Input variables for the VPC module
│ │ ├── outputs.tf # Output values for the VPC module
│ ├── security_group/ # Security Group module
│ │ ├── ...
├── environments/ # Environment-specific configurations
│ ├── dev/ # Development environment
│ │ ├── main.tf # Terraform configuration for the Dev environment
│ │ ├── variables.tf # Environment specific variables
│ ├── prod/ # Production environment
│ │ ├── ...
├── scripts/ # Utility scripts (e.g., deployment scripts, automation scripts)
│ ├── deploy.sh # Deployment script
│ ├── update_ami.py # Python script to update AMI
├── application/ # Application code
│ ├── src/ # Source code
│ ├── tests/ # Unit and integration tests
├── README.md
└── ...
- **File Naming Conventions:**
- Use consistent and descriptive file names.
- Examples:
- `main.tf`: Main Terraform configuration file
- `variables.tf`: Terraform variables file
- `outputs.tf`: Terraform output values file
- `deploy.sh`: Deployment script
- `instance.py`: Python module for instance management
- **Module Organization:**
- Encapsulate reusable infrastructure components into modules (e.g., VPC, security groups, load balancers).
- Each module should have:
- A clear purpose.
- Well-defined input variables and output values.
- Comprehensive documentation.
- Keep modules small and focused.
- **Component Architecture:**
- Design your application as a collection of loosely coupled components.
- Each component should have:
- A well-defined interface.
- Clear responsibilities.
- Independent deployment lifecycle.
- **Code Splitting:**
- Break down large application codebases into smaller, manageable modules.
- Use lazy loading to load modules on demand, reducing initial load time.
- Example (Python):
python
# main.py
import importlib
def load_module(module_name):
module = importlib.import_module(module_name)
return module
# Load the module when needed
my_module = load_module('my_module')
my_module.my_function()
- ## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Singleton:** Use when exactly one instance of a class is needed (e.g., a configuration manager).
- **Factory:** Use to create objects without specifying their concrete classes (e.g., creating different types of EC2 instances).
- **Strategy:** Use to define a family of algorithms, encapsulate each one, and make them interchangeable (e.g., different instance termination strategies).
- **Common Tasks:**
- **Creating an EC2 Instance (AWS CLI):**
bash
aws ec2 run-instances --image-id ami-xxxxxxxxxxxxxxxxx --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-xxxxxxxxxxxxxxxxx
- **Creating an EC2 Instance (AWS CDK):
typescript
import * as ec2 from 'aws-cdk-lib/aws-ec2';
const vpc = new ec2.Vpc(this, 'TheVPC', { maxAzs: 3 });
const instance = new ec2.Instance(this, 'EC2Instance', {
vpc: vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
machineImage: new ec2.AmazonLinux2023Image({generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2}),
});
- **Attaching an EBS Volume:**
- Ensure the EBS volume is in the same Availability Zone as the EC2 instance.
- Use the `aws ec2 attach-volume` command or the equivalent SDK call.
- **Anti-patterns:**
- **Hardcoding AWS Credentials:** Never hardcode AWS credentials in your code. Use IAM roles for EC2 instances and IAM users with restricted permissions for local development.
- **Creating Publicly Accessible S3 Buckets:** Avoid creating S3 buckets that are publicly accessible without proper security controls.
- **Ignoring Error Handling:** Always handle exceptions and errors gracefully. Provide meaningful error messages and logging.
- **Over-Permissive Security Groups:** Implement the principle of least privilege. Grant only the minimum necessary permissions to your security groups.
- **State Management:**
- Use state files (e.g., Terraform state) to track the current state of your infrastructure.
- Store state files securely (e.g., in an S3 bucket with encryption and versioning).
- Use locking mechanisms to prevent concurrent modifications to the state file.
- **Error Handling:**
- Implement robust error handling to catch exceptions and prevent application crashes.
- Use try-except blocks to handle potential errors.
- Log error messages with sufficient detail for debugging.
- ## 3. Performance Considerations
- **Optimization Techniques:**
- **Instance Type Selection:** Choose the appropriate EC2 instance type based on your application's requirements (CPU, memory, network).
- **EBS Optimization:** Use Provisioned IOPS (PIOPS) EBS volumes for high-performance applications.
- **Caching:** Implement caching mechanisms to reduce database load and improve response times (e.g., using Amazon ElastiCache).
- **Load Balancing:** Distribute traffic across multiple EC2 instances using an Elastic Load Balancer (ELB).
- **Auto Scaling:** Use Auto Scaling groups to automatically scale your EC2 instances based on demand.
- **Memory Management:**
- Monitor memory usage on your EC2 instances.
- Optimize application code to reduce memory consumption.
- Use memory profiling tools to identify memory leaks.
- **Bundle Size Optimization:**
- Minimize the size of your application's deployment package.
- Remove unnecessary dependencies.
- Use code minification and compression.
- Example (Python):
bash
# Create a virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Install only necessary dependencies
pip install --no-cache-dir -r requirements.txt
# Create deployment package
zip -r deployment_package.zip *
- **Lazy Loading:**
- Load application modules on demand to reduce initial load time.
- Use code splitting to break down large modules into smaller chunks.
- Example (JavaScript):
javascript
// main.js
async function loadModule() {
const module = await import('./my_module.js');
module.myFunction();
}
loadModule();
- ## 4. Security Best Practices
- **Common Vulnerabilities:**
- **SQL Injection:** Prevent SQL injection by using parameterized queries and input validation.
- **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and encoding output.
- **Remote Code Execution (RCE):** Prevent RCE by validating user input and using secure coding practices.
- **Unsecured API endpoints:** Secure API endpoints using authentication and authorization mechanisms.
- **Input Validation:**
- Validate all user input to prevent malicious code from being injected into your application.
- Use regular expressions and data type validation.
- **Authentication and Authorization:**
- Use strong authentication mechanisms (e.g., multi-factor authentication).
- Implement role-based access control (RBAC) to restrict access to sensitive resources.
- Use AWS IAM roles for EC2 instances to grant access to AWS resources.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS for all API communication.
- Store sensitive data in secure storage (e.g., AWS Secrets Manager).
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Validate API requests and responses.
- Implement rate limiting to prevent abuse.
- Use AWS API Gateway to manage and secure your APIs.
- ## 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for individual components to verify their functionality.
- Use mocking and stubbing to isolate components from external dependencies.
- Example (Python):
python
import unittest
from unittest.mock import Mock
class MyComponent:
def __init__(self, external_dependency):
self.dependency = external_dependency
def my_function(self, input_data):
result = self.dependency.process_data(input_data)
return result
class TestMyComponent(unittest.TestCase):
def test_my_function(self):
# Create a mock for the external dependency
mock_dependency = Mock()
mock_dependency.process_data.return_value = "Mocked Result"
# Create an instance of MyComponent with the mock dependency
component = MyComponent(mock_dependency)
# Call the function to be tested
result = component.my_function("Test Input")
# Assert the expected behavior
self.assertEqual(result, "Mocked Result")
mock_dependency.process_data.assert_called_once_with("Test Input")
if __name__ == '__main__':
unittest.main()
- **Integration Testing:**
- Write integration tests to verify the interaction between components.
- Test the integration of your application with AWS services.
- **End-to-End Testing:**
- Write end-to-end tests to verify the entire application flow.
- Simulate real user scenarios.
- **Test Organization:**
- Organize your tests into a logical directory structure.
- Use meaningful test names.
- Keep tests independent of each other.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate components from external dependencies.
- Example (AWS CDK):
typescript
// Mocking AWS SDK calls in Jest
jest.mock('aws-sdk', () => {
const mEC2 = {
describeInstances: jest.fn().mockReturnValue({
promise: jest.fn().mockResolvedValue({ Reservations: [] }),
}),
};
return {
EC2: jest.fn().mockImplementation(() => mEC2),
};
});
- ## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Incorrect Security Group Configuration:** Incorrectly configured security groups can expose your EC2 instances to security risks.
- **Insufficient Resource Limits:** Exceeding AWS resource limits can cause application failures.
- **Not Using Auto Scaling:** Not using Auto Scaling can lead to performance bottlenecks and outages during periods of high demand.
- **Forgetting to Terminate Unused Instances:** Forgetting to terminate unused EC2 instances can lead to unnecessary costs.
- **Edge Cases:**
- **Spot Instance Interruptions:** Spot instances can be interrupted with short notice. Design your application to handle spot instance interruptions gracefully.
- **Network Connectivity Issues:** Network connectivity issues can prevent your application from accessing AWS services or other resources.
- **Version-Specific Issues:**
- Be aware of version-specific issues with the amazon-ec2 library or AWS services.
- Consult the documentation for the specific versions you are using.
- **Compatibility Concerns:**
- Ensure compatibility between your application and the underlying operating system and libraries.
- Test your application on different operating systems and browsers.
- **Debugging Strategies:**
- Use logging and monitoring to track the behavior of your application.
- Use debugging tools to identify and fix errors.
- Consult the AWS documentation and community forums for help.
- ## 7. Tooling and Environment
- **Recommended Tools:**
- **AWS CLI:** Command-line interface for interacting with AWS services.
- **AWS Management Console:** Web-based interface for managing AWS resources.
- **AWS CloudFormation:** Infrastructure as code service for provisioning and managing AWS resources.
- **AWS CDK:** Cloud Development Kit for defining cloud infrastructure in code.
- **Terraform:** Infrastructure as code tool for provisioning and managing cloud resources.
- **Packer:** Tool for creating machine images.
- **Ansible:** Configuration management tool.
- **Build Configuration:**
- Use a build tool (e.g., Make, Gradle, Maven) to automate the build process.
- Define dependencies and build steps in a build file.
- Example (Python):
makefile
# Makefile
venv:
python3 -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
deploy:
zip -r deployment_package.zip *
aws s3 cp deployment_package.zip s3://my-bucket/deployment_package.zip
aws lambda update-function-code --function-name my-function --s3-bucket my-bucket --s3-key deployment_package.zip
- **Linting and Formatting:**
- Use a linter (e.g., pylint, eslint) to enforce code style and identify potential errors.
- Use a formatter (e.g., black, prettier) to automatically format your code.
- **Deployment Best Practices:**
- Use a deployment pipeline to automate the deployment process.
- Deploy to a staging environment before deploying to production.
- Use blue/green deployments to minimize downtime.
- **CI/CD Integration:**
- Integrate your application with a CI/CD system (e.g., Jenkins, CircleCI, GitLab CI).
- Automate testing, building, and deployment.
- ## Additional Considerations
- **Cost Optimization:** Regularly review your AWS resource usage and identify opportunities for cost savings. Consider using Reserved Instances or Spot Instances to reduce costs.
- **Disaster Recovery:** Implement a disaster recovery plan to ensure business continuity in the event of an outage. Use AWS Backup or other backup solutions to protect your data.
- **Compliance:** Ensure that your application complies with relevant regulations and standards (e.g., PCI DSS, HIPAA).
- ## References
- [AWS EC2 Best Practices](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-best-practices.html)
- [AWS CDK Best Practices](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html)
- [Terraform AWS Provider Best Practices](https://docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/structure.html)
+367
View File
@@ -0,0 +1,367 @@
---
description: This rule file provides comprehensive best practices, coding standards, and security guidelines for developing applications using Amazon S3. It aims to ensure secure, performant, and maintainable S3 integrations.
globs: **/*S3*.{js,ts,jsx,tsx,py,java,go,csharp}
---
- Always disable public access to S3 buckets unless explicitly needed. Use AWS Identity and Access Management (IAM) policies and bucket policies for access control instead of Access Control Lists (ACLs), which are now generally deprecated.
- Implement encryption for data at rest using Server-Side Encryption (SSE), preferably with AWS Key Management Service (KMS) for enhanced security.
- Use S3 Transfer Acceleration for faster uploads over long distances and enable versioning to protect against accidental deletions. Monitor performance using Amazon CloudWatch and enable logging for auditing. Additionally, consider using S3 Storage Lens for insights into storage usage and activity trends.
- Leverage S3's lifecycle policies to transition objects to cheaper storage classes based on access patterns, and regularly review your storage usage to optimize costs. Utilize S3 Intelligent-Tiering for automatic cost savings based on changing access patterns.
## Amazon S3 Best Practices and Coding Standards
This document provides comprehensive best practices, coding standards, and security guidelines for developing applications using Amazon S3. Following these guidelines will help ensure that your S3 integrations are secure, performant, maintainable, and cost-effective.
### 1. Code Organization and Structure
#### 1.1. Directory Structure Best Practices
Organize your code related to Amazon S3 into logical directories based on functionality.
project/
├── src/
│ ├── s3/
│ │ ├── utils.js # Utility functions for S3 operations
│ │ ├── uploader.js # Handles uploading files to S3
│ │ ├── downloader.js # Handles downloading files from S3
│ │ ├── config.js # Configuration for S3 (bucket name, region, etc.)
│ │ ├── errors.js # Custom error handling for S3 operations
│ │ └── index.js # Entry point for S3 module
│ ├── ...
│ └── tests/
│ ├── s3/
│ │ ├── uploader.test.js # Unit tests for uploader.js
│ │ └── ...
│ └── ...
├── ...
#### 1.2. File Naming Conventions
Use descriptive and consistent file names.
* `uploader.js`: Module for uploading files to S3.
* `downloader.js`: Module for downloading files from S3.
* `s3_service.py`: (Python Example) Defines S3 related services.
* `S3Manager.java`: (Java Example) Manages S3 client and configurations.
#### 1.3. Module Organization
* **Single Responsibility Principle:** Each module should have a clear and specific purpose (e.g., uploading, downloading, managing bucket lifecycle).
* **Abstraction:** Hide complex S3 operations behind simpler interfaces.
* **Configuration:** Store S3 configuration details (bucket name, region, credentials) in a separate configuration file.
Example (JavaScript):
javascript
// s3/uploader.js
import AWS from 'aws-sdk';
import config from './config';
const s3 = new AWS.S3(config.s3);
export const uploadFile = async (file, key) => {
const params = {
Bucket: config.s3.bucketName,
Key: key,
Body: file
};
try {
await s3.upload(params).promise();
console.log(`File uploaded successfully: ${key}`);
} catch (error) {
console.error('Error uploading file:', error);
throw error; // Re-throw for handling in the caller.
}
};
#### 1.4. Component Architecture
For larger applications, consider a component-based architecture. This can involve creating distinct components for different S3-related tasks. For example:
* **Upload Component:** Handles file uploads, progress tracking, and error handling.
* **Download Component:** Handles file downloads, progress tracking, and caching.
* **Management Component:** Manages bucket creation, deletion, and configuration.
#### 1.5. Code Splitting
If you have a large application using S3, consider using code splitting to reduce the initial load time. This involves breaking your code into smaller chunks that can be loaded on demand. This is especially relevant for front-end applications using S3 for asset storage.
* **Dynamic Imports:** Use dynamic imports to load S3-related modules only when needed.
* **Webpack/Rollup:** Configure your bundler to create separate chunks for S3 code.
### 2. Common Patterns and Anti-patterns
#### 2.1. Design Patterns
* **Strategy Pattern:** Use a strategy pattern to handle different storage classes or encryption methods.
* **Factory Pattern:** Use a factory pattern to create S3 clients with different configurations.
* **Singleton Pattern:** Use a singleton pattern if you want to use one s3 instance for all the s3 interactions.
#### 2.2. Recommended Approaches for Common Tasks
* **Uploading large files:** Use multipart upload for files larger than 5 MB. This allows you to upload files in parallel and resume interrupted uploads.
* **Downloading large files:** Use byte-range fetches to download files in chunks. This is useful for resuming interrupted downloads and for accessing specific portions of a file.
* **Deleting multiple objects:** Use the `deleteObjects` API to delete multiple objects in a single request. This is more efficient than deleting objects one by one.
#### 2.3. Anti-patterns and Code Smells
* **Hardcoding credentials:** Never hardcode AWS credentials in your code. Use IAM roles or environment variables.
* **Insufficient error handling:** Always handle errors from S3 operations gracefully. Provide informative error messages and retry failed operations.
* **Ignoring bucket access control:** Properly configure bucket policies and IAM roles to restrict access to your S3 buckets.
* **Overly permissive bucket policies:** Avoid granting overly broad permissions in your bucket policies. Follow the principle of least privilege.
* **Not using versioning:** Failing to enable versioning can lead to data loss if objects are accidentally deleted or overwritten.
* **Assuming immediate consistency:** S3 provides eventual consistency for some operations. Be aware of this and design your application accordingly.
* **Polling for object existence:** Instead of polling, use S3 events to trigger actions when objects are created or modified.
* **Inefficient data retrieval:** Avoid retrieving entire objects when only a portion of the data is needed. Use byte-range fetches or S3 Select to retrieve only the necessary data.
#### 2.4. State Management
* **Stateless operations:** Design your S3 operations to be stateless whenever possible. This makes your application more scalable and resilient.
* **Caching:** Use caching to reduce the number of requests to S3. Consider using a CDN (Content Delivery Network) to cache frequently accessed objects.
* **Session management:** If you need to maintain state, store session data in a separate database or cache, not in S3.
#### 2.5. Error Handling
* **Retry mechanism:** Implement retry logic with exponential backoff for transient errors.
* **Specific error handling:** Handle different S3 errors differently (e.g., retry 503 errors, log 403 errors).
* **Centralized error logging:** Log all S3 errors to a centralized logging system for monitoring and analysis.
Example (Python):
python
import boto3
from botocore.exceptions import ClientError
import time
s3 = boto3.client('s3')
def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket"""
if object_name is None:
object_name = file_name
for attempt in range(3): # Retry up to 3 times
try:
response = s3.upload_file(file_name, bucket, object_name)
return True
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucket':
print(f"The bucket {bucket} does not exist.")
return False
elif e.response['Error']['Code'] == 'AccessDenied':
print("Access denied. Check your credentials and permissions.")
return False
else:
print(f"An error occurred: {e}")
if attempt < 2: # Wait and retry
time.sleep(2 ** attempt)
else:
return False
except Exception as e:
print(f"An unexpected error occurred: {e}")
return False
return False # Reached max retries and failed
### 3. Performance Considerations
#### 3.1. Optimization Techniques
* **Use S3 Transfer Acceleration:** If you are uploading or downloading files from a geographically distant location, use S3 Transfer Acceleration to improve performance. S3 Transfer Acceleration utilizes Amazon CloudFront's globally distributed edge locations.
* **Use multipart upload:** For large files, use multipart upload to upload files in parallel. The documentation states the best practice is to use this for files larger than 5MB.
* **Enable gzip compression:** Compress objects before uploading them to S3 to reduce storage costs and improve download times. Set the `Content-Encoding` header to `gzip` when uploading compressed objects.
* **Use HTTP/2:** Enable HTTP/2 on your S3 bucket to improve performance.
* **Optimize object sizes:** Store related data in a single object to reduce the number of requests to S3.
#### 3.2. Memory Management
* **Stream data:** Avoid loading entire files into memory. Use streams to process data in chunks.
* **Release resources:** Release S3 client objects when they are no longer needed.
#### 3.3. Bundle Size Optimization
* **Tree shaking:** Use a bundler that supports tree shaking to remove unused code from your bundle.
* **Code splitting:** Split your code into smaller chunks that can be loaded on demand.
#### 3.4. Lazy Loading
* **Load images on demand:** Load images from S3 only when they are visible on the screen.
* **Lazy load data:** Load data from S3 only when it is needed.
### 4. Security Best Practices
#### 4.1. Common Vulnerabilities
* **Publicly accessible buckets:** Ensure that your S3 buckets are not publicly accessible.
* **Insufficient access control:** Properly configure bucket policies and IAM roles to restrict access to your S3 buckets.
* **Cross-site scripting (XSS):** Sanitize user input to prevent XSS attacks if you are serving content directly from S3.
* **Data injection:** Validate all data before storing it in S3 to prevent data injection attacks.
#### 4.2. Input Validation
* **Validate file types:** Validate the file types of uploaded objects to prevent malicious files from being stored in S3.
* **Validate file sizes:** Limit the file sizes of uploaded objects to prevent denial-of-service attacks.
* **Sanitize file names:** Sanitize file names to prevent directory traversal attacks.
#### 4.3. Authentication and Authorization
* **Use IAM roles:** Use IAM roles to grant permissions to applications running on EC2 instances or other AWS services.
* **Use temporary credentials:** Use temporary credentials for applications that need to access S3 from outside of AWS. You can use AWS STS (Security Token Service) to generate temporary credentials.
* **Principle of least privilege:** Grant only the minimum permissions required for each user or application.
#### 4.4. Data Protection
* **Encrypt data at rest:** Use server-side encryption (SSE) or client-side encryption to encrypt data at rest in S3.
* **Encrypt data in transit:** Use HTTPS to encrypt data in transit between your application and S3.
* **Enable versioning:** Enable versioning to protect against accidental data loss.
* **Enable MFA Delete:** Require multi-factor authentication to delete objects from S3.
* **Object locking:** Use S3 Object Lock to prevent objects from being deleted or overwritten for a specified period of time.
#### 4.5. Secure API Communication
* **Use HTTPS:** Always use HTTPS to communicate with the S3 API.
* **Validate certificates:** Validate the SSL/TLS certificates of the S3 endpoints.
* **Restrict access:** Restrict access to the S3 API using IAM policies and bucket policies.
### 5. Testing Approaches
#### 5.1. Unit Testing
* **Mock S3 client:** Mock the S3 client to isolate your unit tests.
* **Test individual functions:** Test individual functions that interact with S3.
* **Verify error handling:** Verify that your code handles S3 errors correctly.
Example (JavaScript with Jest):
javascript
// s3/uploader.test.js
import { uploadFile } from './uploader';
import AWS from 'aws-sdk';
jest.mock('aws-sdk', () => {
const mS3 = {
upload: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return {
S3: jest.fn(() => mS3),
};
});
describe('uploadFile', () => {
it('should upload file successfully', async () => {
const mockS3 = new AWS.S3();
mockS3.promise.mockResolvedValue({});
const file = 'test file content';
const key = 'test.txt';
await uploadFile(file, key);
expect(AWS.S3).toHaveBeenCalledTimes(1);
expect(mockS3.upload).toHaveBeenCalledWith({
Bucket: 'your-bucket-name',
Key: key,
Body: file
});
});
it('should handle upload error', async () => {
const mockS3 = new AWS.S3();
mockS3.promise.mockRejectedValue(new Error('Upload failed'));
const file = 'test file content';
const key = 'test.txt';
await expect(uploadFile(file, key)).rejects.toThrow('Upload failed');
});
});
#### 5.2. Integration Testing
* **Test with real S3 buckets:** Create a dedicated S3 bucket for integration tests.
* **Test end-to-end flows:** Test complete workflows that involve S3 operations.
* **Verify data integrity:** Verify that data is correctly stored and retrieved from S3.
#### 5.3. End-to-End Testing
* **Simulate user scenarios:** Simulate real user scenarios to test your application's S3 integration.
* **Monitor performance:** Monitor the performance of your S3 integration under load.
#### 5.4. Test Organization
* **Separate test directories:** Create separate test directories for unit tests, integration tests, and end-to-end tests.
* **Descriptive test names:** Use descriptive test names that clearly indicate what is being tested.
#### 5.5. Mocking and Stubbing
* **Mock S3 client:** Use a mocking library (e.g., Jest, Mockito) to mock the S3 client.
* **Stub S3 responses:** Stub S3 API responses to simulate different scenarios.
* **Use dependency injection:** Use dependency injection to inject mocked S3 clients into your components.
### 6. Common Pitfalls and Gotchas
#### 6.1. Frequent Mistakes
* **Forgetting to handle errors:** Failing to handle S3 errors can lead to unexpected behavior and data loss.
* **Using incorrect region:** Using the wrong region can result in connection errors and data transfer costs.
* **Exposing sensitive data:** Storing sensitive data in S3 without proper encryption can lead to security breaches.
* **Not cleaning up temporary files:** Failing to delete temporary files after uploading them to S3 can lead to storage waste.
* **Overusing public read access:** Granting public read access to S3 buckets can expose sensitive data to unauthorized users.
#### 6.2. Edge Cases
* **Eventual consistency:** S3 provides eventual consistency for some operations. Be aware of this and design your application accordingly.
* **Object size limits:** Be aware of the object size limits for S3.
* **Request rate limits:** Be aware of the request rate limits for S3.
* **Special characters in object keys:** Handle special characters in object keys correctly.
#### 6.3. Version-Specific Issues
* **SDK compatibility:** Ensure that your AWS SDK is compatible with the S3 API version.
* **API changes:** Be aware of any API changes that may affect your application.
#### 6.4. Compatibility Concerns
* **Browser compatibility:** Ensure that your application is compatible with different browsers if you are using S3 directly from the browser.
* **Serverless environments:** Be aware of any limitations when using S3 in serverless environments (e.g., Lambda).
#### 6.5. Debugging Strategies
* **Enable logging:** Enable logging to track S3 API calls and errors.
* **Use S3 monitoring tools:** Use S3 monitoring tools to monitor the performance and health of your S3 buckets.
* **Check S3 access logs:** Analyze S3 access logs to identify potential security issues.
* **Use AWS CloudTrail:** Use AWS CloudTrail to track API calls to S3.
* **Use AWS X-Ray:** Use AWS X-Ray to trace requests through your application and identify performance bottlenecks.
### 7. Tooling and Environment
#### 7.1. Recommended Development Tools
* **AWS CLI:** The AWS Command Line Interface (CLI) is a powerful tool for managing S3 resources.
* **AWS SDK:** The AWS SDK provides libraries for interacting with S3 from various programming languages.
* **S3 Browser:** S3 Browser is a Windows client for managing S3 buckets and objects.
* **Cyberduck:** Cyberduck is a cross-platform client for managing S3 buckets and objects.
* **Cloudberry Explorer:** Cloudberry Explorer is a Windows client for managing S3 buckets and objects.
#### 7.2. Build Configuration
* **Use environment variables:** Store S3 configuration details (bucket name, region, credentials) in environment variables.
* **Use a build tool:** Use a build tool (e.g., Maven, Gradle, Webpack) to manage your project dependencies and build your application.
#### 7.3. Linting and Formatting
* **Use a linter:** Use a linter (e.g., ESLint, PyLint) to enforce code style and best practices.
* **Use a formatter:** Use a code formatter (e.g., Prettier, Black) to automatically format your code.
#### 7.4. Deployment
* **Use infrastructure as code:** Use infrastructure as code (e.g., CloudFormation, Terraform) to automate the deployment of your S3 resources.
* **Use a deployment pipeline:** Use a deployment pipeline to automate the deployment of your application.
* **Use blue/green deployments:** Use blue/green deployments to minimize downtime during deployments.
#### 7.5. CI/CD Integration
* **Integrate with CI/CD tools:** Integrate your S3 deployment process with CI/CD tools (e.g., Jenkins, CircleCI, Travis CI).
* **Automate testing:** Automate your unit tests, integration tests, and end-to-end tests as part of your CI/CD pipeline.
* **Automate deployments:** Automate the deployment of your application to S3 as part of your CI/CD pipeline.
By following these best practices and coding standards, you can ensure that your Amazon S3 integrations are secure, performant, maintainable, and cost-effective.
+311
View File
@@ -0,0 +1,311 @@
---
description: This rule file provides comprehensive best practices for Android SDK development, encompassing code organization, performance, security, testing, and common pitfalls. It aims to guide developers in creating robust, maintainable, and efficient Android applications and libraries.
globs: **/*.{java,kt,xml,gradle,properties}
---
- MUST be under source control management (SCM). RECOMMENDED source control management is git
- If you intend your source repo to be public ensure you have received the necessary management and legal approval
- MUST use a .gitignore configuration tailored for Android projects (e.g., ignoring `local.properties`, `build/`, `.gradle/`)
- Source code repositories SHOULD follow the naming convention `[platform]-[library name]`, e.g., `android-analytics`, `java-datastore`
- MUST NOT restrict read access to source code repositories unnecessarily
- RECOMMEND to not have source file header comment blocks as these easily get out of date
## Code Organization and Structure
- SHOULD follow the standard project layout for Android projects. Key directories:
- `src/main/java`: Java/Kotlin source code
- `src/main/res`: Resources (layouts, drawables, strings, etc.)
- `src/test/java`: Unit tests
- `src/androidTest/java`: Instrumentation tests
- MUST prefix all exported resources (layout files, XML files, drawable IDs, color IDs, dimension IDs, string IDs, etc.) with a unique prefix for the library using `resourcePrefix` in the Gradle build file. Example: `sug` for a Suggestion Module. This avoids naming conflicts when the library is used in other projects.
- Use package names that are descriptive and follow the reverse domain name convention (e.g., `com.example.myapp.feature`).
- Organize code into logical modules or features. Each module should have a clear responsibility and be loosely coupled with other modules.
- Use Kotlin for new projects. If working with Java, target Java 8 or higher to utilize modern language features.
- Consider using a multi-module project structure for larger projects to improve build times and code organization. Modules can represent different features, libraries, or build variants.
- Employ a layered architecture (e.g., presentation, domain, data) to separate concerns and improve testability.
### Directory Structure Best Practices:
root/
├── app/
│ ├── build.gradle
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/example/app/
│ │ │ ├── MainActivity.kt
│ │ │ ├── model/
│ │ │ ├── view/
│ │ │ └── viewmodel/
│ │ └── res/
│ │ ├── layout/
│ │ ├── drawable/
│ │ ├── values/
│ │ └── mipmap-xxhdpi/
│ └── test/
│ └── java/
├── library_module/
│ ├── build.gradle
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ └── res/
│ └── test/
├── build.gradle
├── settings.gradle
### File Naming Conventions:
- **Kotlin/Java:** `PascalCase` for class names (e.g., `MainActivity`), `camelCase` for variables and method names (e.g., `userName`, `calculateTotal`).
- **Layout XML:** `snake_case` (e.g., `activity_main.xml`). Use descriptive names reflecting the layout's purpose.
- **Drawable XML:** `snake_case` (e.g., `ic_launcher.xml`). Prefix icons with `ic_`, backgrounds with `bg_`, and other drawables accordingly.
- **Values XML:** `snake_case` (e.g., `strings.xml`, `colors.xml`, `dimens.xml`).
- **Gradle:** `build.gradle` (module-level), `settings.gradle` (project-level).
### Component Architecture Recommendations:
- MVVM (Model-View-ViewModel) is the recommended architecture pattern. Use Android Architecture Components (LiveData, ViewModel, Room) to implement it effectively.
- For complex UI logic, consider using a ViewBindingDelegate to simplify view access and reduce boilerplate.
- Use dependency injection (Hilt or Dagger) to manage dependencies and improve testability.
## Common Patterns and Anti-patterns
- Use `LiveData` and `Flow` for reactive data streams.
- Utilize coroutines for asynchronous operations to simplify threading and avoid callback hell.
- Avoid performing long-running operations on the main thread (UI thread). Use `Dispatchers.IO` or `Dispatchers.Default` with coroutines or `AsyncTask` for background tasks.
- Don't use `AsyncTask` if possible, prefer coroutines.
- Prefer `ConstraintLayout` over other layout types for complex UIs as it is more flexible and performant.
- Use `RecyclerView` for displaying large lists of data efficiently. Implement view holder pattern correctly for optimal performance.
- Apply data binding to reduce boilerplate code in UI updates.
- Use sealed classes for representing state to ensure exhaustive handling of all possible states.
- Implement proper error handling with try-catch blocks and report errors gracefully to the user.
- Log errors and exceptions using a logging framework (Timber) for debugging and analysis.
### Anti-patterns and Code Smells to Avoid:
- **God Classes:** Classes that are too large and have too many responsibilities. Break them down into smaller, more focused classes.
- **Spaghetti Code:** Code that is difficult to read and understand due to complex control flow. Refactor it to improve readability and maintainability.
- **Copy-Paste Programming:** Duplicating code across multiple locations. Extract the common code into reusable functions or classes.
- **Hardcoding Values:** Avoid hardcoding values directly in the code. Use resources (strings, colors, dimensions) for better maintainability and localization.
- **Leaking Context:** Holding onto `Activity` or `Context` instances for longer than necessary, leading to memory leaks.
### State Management Best Practices:
- Use `ViewModel` to store UI-related data that survives configuration changes.
- Utilize `SavedStateHandle` in `ViewModel` to persist data across process death.
- Consider using a state management library (e.g., Redux, MVI) for complex applications with complex state.
- Implement appropriate caching strategies to reduce network requests and improve performance.
### Error Handling Patterns:
- Use try-catch blocks to handle potential exceptions and prevent app crashes.
- Report errors gracefully to the user with informative error messages.
- Log errors and exceptions using a logging framework (Timber) for debugging and analysis.
- Implement retry mechanisms for transient errors (e.g., network connection issues).
## Performance Considerations
- Optimize image loading using libraries like Glide or Coil. Resize images to the required dimensions before loading them into `ImageViews`.
- Use efficient data structures (e.g., `SparseArray` instead of `HashMap` for integer keys).
- Avoid creating unnecessary objects, especially in loops or frequently called methods.
- Use `StringBuilder` instead of string concatenation for building strings efficiently.
- Minimize network requests and optimize data transfer using compression and pagination.
- Analyze app performance using profiling tools (Android Profiler) to identify bottlenecks.
- Utilize the LeakCanary library to detect memory leaks during development.
- Use ProGuard or R8 to shrink, obfuscate, and optimize the code for release builds.
### Memory Management Considerations:
- Avoid creating memory leaks by properly managing object lifecycles and releasing resources when they are no longer needed.
- Use `WeakReference` to hold references to objects that may be garbage collected to prevent memory leaks.
- Monitor memory usage using the Android Profiler and identify potential memory leaks.
### Rendering Optimization:
- Minimize overdraw by reducing the number of layers that are drawn on top of each other.
- Use hardware acceleration to improve rendering performance.
- Optimize custom views by implementing `onDraw()` method efficiently and avoiding unnecessary allocations.
### Bundle Size Optimization:
- Remove unused resources using `shrinkResources` in the Gradle build file.
- Use vector drawables instead of raster images for icons and other simple graphics.
- Enable code shrinking and obfuscation using ProGuard or R8.
- Compress images using tools like TinyPNG or ImageOptim.
- Use app bundles to deliver optimized APKs for different device configurations.
- Utilize dynamic feature modules to defer the download of non-essential features.
### Lazy Loading Strategies:
- Implement lazy loading for images and other resources that are not immediately visible on the screen.
- Use pagination or infinite scrolling to load data in chunks as the user scrolls down the list.
## Security Best Practices
- MUST use Kotlin or Java. Kotlin is RECOMMENDED
- SHOULD use static code analysis, such as detekt or SwiftLint to minimise errors and minimise debates and formatting fix-up commits in PRs. It is RECOMMENDED to integrate these tools with the CI workflow. SHOULD use quality tools available in common config: Android and iOS
- Android: MUST use the Android Support Annotations for public APIs. Non-Android Java code MUST use the Jetbrains Annotations for public APIs
- Secure API communication and proper permission handling are vital to protect user data.
- MUST use a `consumerProguardFiles` file if obfuscation breaks the libraries function.
- SHOULD NOT have unnecessary exported dependencies, in particular SHOULD NOT leak networking library to consumers. SHOULD NOT leak serialization library to consumers. An exception to this rule are optional adapters for popular libraries.
### Common Vulnerabilities and Prevention:
- **SQL Injection:** Avoid using raw SQL queries. Use parameterized queries or an ORM like Room to prevent SQL injection attacks.
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
- **Man-in-the-Middle (MITM) Attacks:** Use HTTPS for all network communication to encrypt data in transit and prevent MITM attacks.
- **Insecure Data Storage:** Encrypt sensitive data before storing it on the device.
- **Improper Platform Usage:** Ensure that permissions are properly requested and handled. Review and minimize the permissions your app requests.
### Input Validation:
- Validate all user input on both the client and server sides to prevent malicious data from being processed.
- Use regular expressions or validation libraries to enforce input constraints.
### Authentication and Authorization:
- Use secure authentication protocols (e.g., OAuth 2.0, OpenID Connect) for user authentication.
- Implement proper authorization mechanisms to control access to resources based on user roles.
- Store user credentials securely using hashing and salting.
### Data Protection:
- Encrypt sensitive data at rest using AES or other strong encryption algorithms.
- Securely transmit data over the network using HTTPS.
- Implement data masking or anonymization techniques to protect user privacy.
### Secure API Communication:
- Use HTTPS for all API communication.
- Verify the server's SSL certificate to prevent MITM attacks.
- Implement API rate limiting to prevent denial-of-service attacks.
## Testing Approaches
- All library (sub-)projects MUST generate coverage test reports (e.g. jacoco, Xcode/slather).
- Unit test coverage MUST be at least 80% and SHOULD be above 85%
- Unit tests MUST NOT rely on reflection to expose otherwise private/internal classes or members.
- Tests SHOULD use JUnit, and MAY use helper libraries such as Mockito or Robolectric
### Unit Testing Strategies:
- Write unit tests for all critical components, including `ViewModels`, repositories, and use cases.
- Use mocking frameworks (Mockito) to isolate units under test and mock dependencies.
- Follow the AAA (Arrange, Act, Assert) pattern for writing clear and concise unit tests.
### Integration Testing Approaches:
- Write integration tests to verify the interaction between different components, such as `ViewModels` and repositories.
- Use dependency injection to provide mock dependencies for integration tests.
### End-to-End Testing:
- Use UI testing frameworks (Espresso, UI Automator) to write end-to-end tests that simulate user interactions.
### Test Organization:
- Organize tests into separate directories based on the type of tests (unit, integration, UI).
- Use descriptive names for test classes and methods to clearly indicate what is being tested.
### Mocking and Stubbing:
- Use mocking frameworks (Mockito) to create mock objects for dependencies.
- Use stubbing to define the behavior of mock objects for specific test cases.
## Common Pitfalls and Gotchas
- Frequent mistakes developers make when using android-sdk
- Edge cases to be aware of when using android-sdk
- Version-specific issues with android-sdk
- Compatibility concerns between android-sdk and other technologies
- Debugging strategies for android-sdk applications
### Frequent Mistakes:
- Not handling configuration changes properly, leading to data loss or unexpected behavior.
- Performing long-running operations on the main thread, causing the UI to freeze.
- Leaking `Context` objects, leading to memory leaks.
- Not properly validating user input, leading to security vulnerabilities.
- Not handling exceptions properly, leading to app crashes.
- Overusing `AsyncTask` and not managing thread pools correctly.
### Edge Cases:
- Handling network connectivity issues gracefully.
- Managing different screen sizes and densities.
- Dealing with low-memory conditions.
- Handling background tasks properly to avoid ANRs (Application Not Responding).
- Handling different Android versions and API levels.
### Version-Specific Issues:
- Be aware of API level differences and use `@TargetApi` and `@RequiresApi` annotations to handle them correctly.
- Test your app on different Android versions to ensure compatibility.
### Compatibility Concerns:
- Ensure compatibility with different device manufacturers and hardware configurations.
- Test your app on different screen sizes and densities.
### Debugging Strategies:
- Use the Android Debug Bridge (ADB) to connect to devices and emulators for debugging.
- Use the Android Profiler to analyze app performance and identify bottlenecks.
- Use logging statements to track the flow of execution and identify errors.
- Use the debugger to step through the code and inspect variables.
## Tooling and Environment
### Recommended Tools:
- Android Studio: The official IDE for Android development.
- Gradle: The build system for Android projects.
- ADB (Android Debug Bridge): A command-line tool for communicating with Android devices and emulators.
- Android Profiler: A tool for analyzing app performance.
- LeakCanary: A library for detecting memory leaks.
- Timber: A logging library for Android.
### Build Configuration:
- MUST use gradle with gradle wrapper to build Android library or Java library
- MUST have consistent minSdk and supportLib versions with other SDKs
- SHOULD use shared build configuration for consistent version with other SDKs/libraries
- MAY use manual configuration with values (same as in shared build configuration), if so SHOULD use a recent minSdk version unless there is an engineering or product decision to support older versions
- SHOULD use latest versions of Android X libraries (if required)
- Configure build variants for different environments (debug, release, staging).
- Use ProGuard or R8 to shrink, obfuscate, and optimize the code for release builds.
- Configure signing configurations to sign the APK for distribution.
### Linting and Formatting:
- Enforce code style guidelines using lint and code formatters (e.g., ktlint for Kotlin).
- Configure lint to run automatically during the build process.
- Resolve lint warnings and errors to improve code quality.
### Deployment:
- Publish libraries to a Maven repository (Maven Central or a private repository).
- Deploy apps to the Google Play Store.
- Implement beta testing using Google Play Console.
### CI/CD Integration:
- Integrate the build process with a CI/CD system (e.g., Jenkins, CircleCI, GitHub Actions).
- Automate testing, linting, and code formatting as part of the CI/CD pipeline.
- Automate deployment to the Google Play Store.
## Additional Considerations
- Limit impact on consumers. SHOULD limit dependencies as much as possible primarily due to risk of version clashes
- RECOMMENDED not to have any exported dependency on other SDK modules e.g. if your module needs authentication, do not depend on Authentication SDK. Instead, require your library consumer to pass an access token string to your API instead.
- Expose minimal Surface area. Keep everything private unless it needs to be public. Every public class, method, property & resource MUST have a strong reason for being public. MAY keep internal source code in a /Private folder to allow tools to more easily ignore those files
- MUST hide classes from generated API documentation that are required to be public solely for technical reasons and are not intended for SDK consumers
- SHOULD declare classes as final to avoid unexpected high-jacking of SDK behavior by subclasses
- For better testability of your library it is RECOMMENDED to use dependency injection
- MUST follow Semantic Versioning
- MUST tag source control management revision/commit that is published
- RECOMMENDED For Android: Use gradle-versions-plugin for automated versioning by git tag
+553
View File
@@ -0,0 +1,553 @@
---
description: This rule file provides comprehensive best practices and coding standards for Ansible projects, covering code organization, common patterns, performance, security, testing, pitfalls, and tooling. It aims to improve maintainability, reusability, and efficiency in Ansible automation.
globs: **/*.{yml,yaml,j2}
---
- Adopt and adhere to the following Ansible best practices to ensure maintainable, reusable, and efficient automation code. This guide provides standards for code organization, common patterns, performance optimization, security, testing, tooling, and common pitfalls to avoid.
## 1. Code Organization and Structure
- Structure your Ansible projects in a clear and consistent manner to enhance readability and maintainability.
### 1.1 Directory Structure Best Practices
- **Root Directory:**
- `ansible.cfg`: Ansible configuration file. This should live in the root directory of your project.
- `inventory/`: Contains your inventory files (hosts, groups, and variables).
- `hosts`: Main inventory file.
- `group_vars/`: Directory for group-specific variables.
- `all/`: Contains variables that apply to all hosts.
- `vars.yml`: Primary file for common variables.
- `vault.yml`: Encrypted variables.
- `<group_name>/`: Directory for variables specific to a group.
- `vars.yml`: Group-specific variables.
- `vault.yml`: Encrypted group variables.
- `host_vars/`: Directory for host-specific variables.
- `<host_name>/`: Directory for a specific host.
- `vars.yml`: Host-specific variables.
- `vault.yml`: Encrypted host variables.
- `playbooks/`: Directory for your Ansible playbooks.
- `site.yml`: Main playbook, orchestrating other playbooks.
- `<environment>.yml`: Playbooks tailored to different environments (e.g., staging.yml, production.yml).
- `<component>.yml`: Playbooks for specific components (e.g., webservers.yml, databases.yml).
- `roles/`: Directory for reusable Ansible roles.
- `<role_name>/`:
- `tasks/`: Contains tasks for the role.
- `main.yml`: Entry point for the role's tasks.
- `handlers/`: Contains handlers for the role.
- `main.yml`: Entry point for the role's handlers.
- `defaults/`: Contains default variable values for the role.
- `main.yml`: Default variable values.
- `vars/`: Contains role-specific variables.
- `main.yml`: Role-specific variables.
- `meta/`: Contains metadata about the role.
- `main.yml`: Role metadata (e.g., dependencies, author).
- `templates/`: Contains Jinja2 templates for the role.
- `files/`: Contains static files used by the role.
- `library/`: (Optional) Custom Ansible modules.
- `filter_plugins/`: (Optional) Custom Jinja2 filter plugins.
- `lookup_plugins/`: (Optional) Custom lookup plugins.
- `plugins/`: All of the above (library, filter, lookup, etc) should be placed in respective subfolders in this directory
- `requirements.yml`: Lists roles to be downloaded from Ansible Galaxy.
- `README.md`: Project documentation.
### 1.2 File Naming Conventions
- **Playbooks:**
- Use lowercase with hyphens for readability (e.g., `webservers.yml`, `database-setup.yml`).
- Name your main playbook `site.yml` for consistency.
- **Roles:**
- Use lowercase with underscores (e.g., `common_setup`, `nginx_configuration`).
- Role names should be descriptive and concise.
- **Variables Files:**
- Use `vars.yml` for general variables and `defaults.yml` for role defaults.
- Use `vault.yml` for encrypted variables.
- Group-specific variables: `<group_name>.yml`.
- Host-specific variables: `<host_name>.yml`.
- **Tasks and Handlers:**
- `main.yml` as the entry point for tasks and handlers within roles.
- **Templates:**
- Give descriptive names to templates, using the `.j2` extension (e.g., `nginx.conf.j2`, `application.properties.j2`).
- **Inventory:**
- Name your inventory file `hosts` or follow a consistent naming convention, such as `<environment>_hosts` (e.g., `staging_hosts`, `production_hosts`).
### 1.3 Module Organization
- Keep custom modules in the `library/` directory at the project root.
- Organize modules into subdirectories based on functionality (e.g., `library/custom_modules/database`, `library/custom_modules/monitoring`).
- Document each custom module with clear usage examples and return values.
- Utilize `module_utils` to create shared code used by multiple modules.
- Follow a consistent naming convention for custom modules (e.g., `my_custom_module.py`).
- All modules should contain argument spec and proper return values (changed, failed, original_message, message, etc).
### 1.4 Component Architecture Recommendations
- **Roles as Building Blocks:**
- Divide your infrastructure into logical components (e.g., web servers, databases, load balancers) and create roles for each.
- Keep roles single-purposed and focused on specific functionality to promote reusability.
- **Playbooks for Orchestration:**
- Use playbooks to orchestrate roles and define the desired state of your infrastructure.
- The main `site.yml` playbook should act as the entry point, calling other component-specific playbooks.
- **Variables for Configuration:**
- Externalize configuration data using variables in `group_vars/` and `host_vars/`.
- Use default variables within roles to provide sane defaults and allow for customization.
- **Handlers for Event-Driven Configuration:**
- Use handlers to manage service restarts and other event-driven tasks.
- Ensure handlers are idempotent and only triggered when necessary.
### 1.5 Code Splitting Strategies
- **Role Decomposition:**
- Break down complex roles into smaller, more manageable roles to improve reusability and maintainability.
- **Task Includes:**
- Use `include_tasks` to split long task lists into smaller, more focused files.
- **Dynamic Includes:**
- Employ `include_vars`, `include_role`, and `include_tasks` with dynamic variables to load configuration data or tasks based on conditions.
- **Blocks for Logical Grouping:**
- Use blocks to group related tasks, providing better error handling and readability.
## 2. Common Patterns and Anti-patterns
- Learn and apply common Ansible design patterns to solve infrastructure automation problems efficiently while avoiding pitfalls.
### 2.1 Design Patterns
- **Idempotency:**
- Design tasks to be idempotent, meaning they should produce the same result regardless of how many times they are executed.
- Use the `changed_when` and `failed_when` directives to customize task result conditions.
- **Variable Prioritization:**
- Understand Ansible's variable precedence and use it effectively to override default values.
- Variable precedence order (highest to lowest): extra vars (-e), command line arguments (-e), role vars, include vars, block vars, task vars, role defaults, inventory vars, registered vars, facts.
- **Handlers for Service Management:**
- Utilize handlers to restart services when configuration files change. Use `notify` directive in tasks to trigger handlers.
- **Template Management:**
- Use the `template` module to manage configuration files. Keep templates simple and focused on configuration logic.
- **Looping with `with_items`:**
- Use `with_items` or `loop` to iterate over lists of items, such as packages to install or users to create.
- **Conditions with `when`:**
- Use the `when` directive to conditionally execute tasks based on variables or facts.
- **Delegation with `delegate_to`:**
- Use the `delegate_to` directive to run tasks on a specific host, such as when managing a load balancer or database server.
- **Error Handling with `block` and `rescue`:**
- Wrap tasks in `block` directives and use `rescue` to handle errors gracefully.
- **Register variables for complex tasks:**
- Register variables to capture output from a task and use it in subsequent tasks.
- **Meta Tasks for Role Management:**
- Use meta tasks (e.g., `meta: clear_host_errors`, `meta: end_play`) to manage role execution and handle errors.
- **Facts for dynamic configuration:**
- Utilize facts to gather system information and dynamically configure tasks.
- **Loops for repetitive tasks:**
- Use loops to perform repetitive tasks, such as creating multiple users or installing multiple packages. Always name the loop so the end user can identify the tasks better.
### 2.2 Recommended Approaches for Common Tasks
- **Package Management:**
- Use the appropriate package manager module (e.g., `apt`, `yum`, `dnf`, `homebrew`) for the target system.
- Always specify the `state` (e.g., `present`, `latest`, `absent`) when managing packages.
- **File Management:**
- Use the `file` module to create, modify, or delete files and directories.
- Use the `copy` module to copy files from the control node to the target nodes.
- Use the `template` module to manage configuration files with Jinja2 templates.
- **Service Management:**
- Use the `service` or `systemd` module to manage services.
- Always specify the `state` (e.g., `started`, `stopped`, `restarted`) when managing services.
- Use handlers to restart services when configuration files change.
- **User Management:**
- Use the `user` module to create, modify, or delete users.
- Use the `group` module to manage groups.
- Use the `authorized_key` module to manage SSH keys.
- **Cron Job Management:**
- Use the `cron` module to create, modify, or delete cron jobs.
- **Firewall Management:**
- Use the `firewalld` or `ufw` module to manage firewalls.
- **SELinux Management:**
- Use the `selinux` module to manage SELinux policies.
- **Line-in-File management:**
- Use the `lineinfile` module to ensure a specific line exists in a file.
- Use the `blockinfile` module to ensure a block of lines exist in a file.
### 2.3 Anti-patterns and Code Smells
- **Shell and Command Modules:**
- Avoid using the `shell` and `command` modules unless absolutely necessary.
- Prefer Ansible's built-in modules for specific tasks, as they provide idempotency and better error handling.
- **Hardcoded Values:**
- Avoid hardcoding values in your playbooks or roles.
- Use variables in `group_vars/` and `host_vars/` to externalize configuration data.
- **Inconsistent Naming Conventions:**
- Follow a consistent naming convention for variables, tasks, roles, and files.
- This improves readability and maintainability.
- **Unnecessary Complexity:**
- Keep your playbooks and roles as simple as possible.
- Avoid over-engineering or introducing unnecessary complexity.
- **Lack of Idempotency:**
- Ensure your tasks are idempotent to avoid unintended side effects.
- Use the `changed_when` and `failed_when` directives to customize task result conditions.
- **Ignoring Errors:**
- Always handle errors gracefully by using `block` and `rescue` directives.
- Use the `fail` module to explicitly fail a playbook when a critical error occurs.
- **Storing Secrets in Plain Text:**
- Never store sensitive data in plain text.
- Use Ansible Vault to encrypt variables and files.
- **Lack of Documentation:**
- Always document your playbooks, roles, and custom modules.
- This improves collaboration and makes it easier to maintain your automation code.
- **Copying the same block of code:**
- Refactor and call the common tasks using `include_tasks` to improve readability and maintainability
- **Using loops when a module can handle multiple arguments:**
- Some modules can perform multiple tasks by passing a list of arguments (e.g. `yum` module), so avoid using loops as much as possible.
- **Creating complex templates:**
- Templates should be simple and contain logic that is easy to read and maintain.
- Avoid implementing complex functionality that increases maintenance cost and reduces code readability.
- **Writing unoptimized Jinja expressions:**
- Use Jinja filters for data manipulation, rather than implementing the logic using Ansible modules
### 2.4 State Management
- **Use Ansible to manage the desired state of your infrastructure.** Avoid manual changes outside of Ansible.
- **Leverage facts to gather system information and dynamically configure tasks.**
- **Use handlers to react to state changes and ensure services are restarted or reconfigured when necessary.**
- **Use variables to store configuration data and customize the desired state for different environments.**
### 2.5 Error Handling Patterns
- **Use `block` and `rescue` to handle errors gracefully.**
- **Use the `fail` module to explicitly fail a playbook when a critical error occurs.**
- **Register variables to capture the output of tasks and use the output in error handling logic.**
- **Use the `ignore_errors` directive to continue playbook execution even when a task fails (use with caution).**
- **Use the `meta: clear_host_errors` task to clear errors on a host and continue playbook execution.**
- **Implement rollback mechanisms to revert changes in case of failures.**
## 3. Performance Considerations
- Optimize your Ansible code to improve execution speed and resource utilization.
### 3.1 Optimization Techniques
- **Use SSH multiplexing:**
- Enable SSH multiplexing in your `ansible.cfg` file to reduce the overhead of establishing SSH connections.
- `pipelining = True`
- **Use ControlPersist:**
- Enable ControlPersist in your SSH configuration to keep SSH connections alive for longer periods of time.
- **Optimize Inventory:**
- Use a dynamic inventory to manage large numbers of hosts.
- Cache the inventory data to reduce the time it takes to load the inventory.
- **Minimize Fact Gathering:**
- Disable fact gathering for tasks that don't require them.
- Use the `gather_facts: false` directive in your playbooks or tasks.
- **Parallel Execution:**
- Increase the number of forks to execute tasks in parallel.
- Use the `-f` or `--forks` option when running Ansible playbooks.
- Be mindful of resource limitations and avoid overloading your control node or target hosts.
- **Avoid Loops When Possible:**
- Prefer modules that can handle lists of items instead of using loops.
- For example, use the `yum` or `apt` module with a list of packages to install instead of using a loop with the `package` module.
- **Optimize Jinja2 Templates:**
- Use Jinja2 filters to perform data manipulation instead of using Ansible modules.
- Cache the results of Jinja2 filters to avoid recomputing them repeatedly.
- **Use Async Tasks:**
- Use async tasks with poll to execute tasks in the background and reduce the time it takes to run your playbooks.
- **Use Connection Type `smart` or `persistent`:**
- These connection types are optimized for performance, especially for larger deployments.
- **Use Caching:**
- Utilize Ansible's fact caching to avoid gathering the same facts repeatedly.
- **Use strategy plugins:**
- Use plugins such as free, debug and host_pinned in your Ansible configuration file to maximize execution performance and concurrency.
### 3.2 Memory Management
- **Limit the number of forks:**
- Reduce the number of forks if your control node is running out of memory.
- **Use smaller inventories:**
- Split large inventories into smaller inventories to reduce memory usage.
- **Avoid loading large files into variables:**
- Use the `slurp` module to read large files into variables only when necessary.
- **Compress large files before transferring them:**
- Use the `compress` module to compress large files before transferring them to target hosts.
### 3.3 Rendering Optimization
- **Cache Jinja2 templates:**
- Enable Jinja2 template caching to reduce the time it takes to render templates.
- **Use filters and tests:**
- Instead of modules, use filters and tests to avoid calling Ansible tasks.
- **Limit Variable Scope:**
- Declare variables in the narrowest scope possible to minimize memory usage and improve performance.
## 4. Security Best Practices
- Secure your Ansible environment and protect sensitive data.
### 4.1 Common Vulnerabilities and Prevention
- **Plaintext Secrets:**
- *Vulnerability:* Storing passwords, API keys, and other sensitive data in plaintext in playbooks or variable files.
- *Prevention:* Use Ansible Vault to encrypt sensitive data.
- Example:
# Encrypt a variable file
ansible-vault encrypt group_vars/all/vault.yml
# Use the variable in a playbook
- name: Deploy application with secret key
template:
src: app.conf.j2
dest: /etc/app/app.conf
- **Unprotected SSH Keys:**
- *Vulnerability:* Leaving private SSH keys unprotected on the control node or target hosts.
- *Prevention:* Restrict access to the control node and use SSH key-based authentication with proper permissions.
- **Command Injection:**
- *Vulnerability:* Using user-supplied data directly in shell commands without proper sanitization.
- *Prevention:* Avoid using the `shell` and `command` modules unless absolutely necessary.
- Use Ansible's built-in modules whenever possible.
- If you must use `shell` or `command`, sanitize user input properly.
- **Privilege Escalation:**
- *Vulnerability:* Granting unnecessary privileges to Ansible users or tasks.
- *Prevention:* Use the `become` directive only when necessary.
- Grant the minimum required privileges to Ansible users.
- **Unvalidated Input:**
- *Vulnerability:* Using unvalidated input from external sources (e.g., APIs, user input) without proper sanitization.
- *Prevention:* Validate all input from external sources before using it in your playbooks or tasks.
- Use the `assert` module to validate input.
- **Insecure Communication:**
- *Vulnerability:* Using insecure communication protocols (e.g., HTTP) to transfer sensitive data.
- *Prevention:* Use HTTPS for all communication with APIs and other external services.
- **Weak SSH Keys:**
- *Vulnerability:* Using weak or compromised SSH keys.
- *Prevention:* Generate strong SSH keys with a key length of at least 2048 bits.
- Rotate SSH keys regularly.
- **Unauthorized Access:**
- *Vulnerability:* Allowing unauthorized access to the control node or target hosts.
- *Prevention:* Use strong passwords and multi-factor authentication.
- Restrict access to the control node and target hosts to authorized users only.
### 4.2 Input Validation
- **Validate all input from external sources before using it in your playbooks or tasks.**
- **Use the `assert` module to validate input.**
- **Use regular expressions to validate input strings.**
- **Use the `int` and `float` filters to validate numeric input.**
- **Use the `bool` filter to validate boolean input.**
- **Use the `list` and `dict` filters to validate list and dictionary input.**
### 4.3 Authentication and Authorization
- **Use SSH key-based authentication instead of passwords.**
- **Restrict access to the control node and target hosts to authorized users only.**
- **Use the `become` directive to escalate privileges only when necessary.**
- **Use the `sudo` module to execute tasks with elevated privileges.**
- **Use the `acl` module to manage access control lists (ACLs) on files and directories.**
- **Integrate with external authentication providers (e.g., LDAP, Active Directory) for centralized user management.**
### 4.4 Data Protection
- **Use Ansible Vault to encrypt sensitive data.**
- **Use HTTPS for all communication with APIs and other external services.**
- **Use the `slurp` module to read sensitive data from files into variables only when necessary.**
- **Use the `compress` module to compress sensitive data before transferring it to target hosts.**
- **Use the `hash` filter to hash sensitive data before storing it in files or databases.**
- **Implement data masking and tokenization techniques to protect sensitive data at rest and in transit.**
### 4.5 Secure API Communication
- **Use HTTPS for all communication with APIs.**
- **Use strong authentication mechanisms (e.g., API keys, OAuth 2.0) to protect your APIs.**
- **Validate all input from APIs before using it in your playbooks or tasks.**
- **Use the `uri` module to interact with APIs securely.**
- **Implement rate limiting and throttling to protect your APIs from abuse.**
- **Monitor your APIs for security vulnerabilities and performance issues.**
## 5. Testing Approaches
- Implement a comprehensive testing strategy to ensure your Ansible code is reliable and error-free.
### 5.1 Unit Testing
- **Unit test custom modules, filter plugins, and lookup plugins.**
- **Use a testing framework such as `pytest` to write and run unit tests.**
- **Mock external dependencies to isolate the code being tested.**
- **Write tests for all possible scenarios, including edge cases and error conditions.**
- **Use continuous integration to run unit tests automatically on every commit.**
- **Test modules for different possible input arguments and check their results.**
### 5.2 Integration Testing
- **Integration test your playbooks and roles to ensure they work together correctly.**
- **Use a testing framework such as `Molecule` to automate integration testing.**
- **Create a test environment that closely resembles your production environment.**
- **Test all critical functionality, including package installation, configuration management, and service management.**
- **Use continuous integration to run integration tests automatically on every commit.**
- **Use an ephemeral infrastructure using Vagrant or Docker to test the playbooks on a fresh machine.**
- **Test for idempotency by running the same playbook multiple times.**
### 5.3 End-to-End Testing
- **End-to-end test your entire infrastructure to ensure all components work together correctly.**
- **Use a testing framework such as `Testinfra` or `Inspec` to write and run end-to-end tests.**
- **Create a test environment that is as close as possible to your production environment.**
- **Test all critical business processes to ensure they work as expected.**
- **Use continuous integration to run end-to-end tests automatically on every commit.**
### 5.4 Test Organization
- **Organize your tests into a directory structure that mirrors your Ansible code.**
- **Create separate directories for unit tests, integration tests, and end-to-end tests.**
- **Use descriptive names for your test files and test functions.**
- **Document your tests with clear explanations of what they are testing.**
- **Use a consistent naming convention for your tests to improve readability and maintainability.**
### 5.5 Mocking and Stubbing Techniques
- **Use mocking and stubbing to isolate your code during unit testing.**
- **Mock external dependencies such as APIs, databases, and operating system commands.**
- **Use a mocking framework such as `unittest.mock` (Python) to create mocks and stubs.**
- **Write tests that verify that your code interacts with the mocked dependencies correctly.**
- **Avoid mocking Ansible modules, instead create a module that is a wrapper around it.**
## 6. Common Pitfalls and Gotchas
- Be aware of common mistakes and edge cases when working with Ansible.
### 6.1 Frequent Mistakes
- **Incorrect YAML Syntax:**
- YAML is whitespace-sensitive. Incorrect indentation or missing colons can cause syntax errors.
- Use a YAML linter to validate your syntax.
- **Variable Scope Issues:**
- Variables can be defined at different levels (e.g., playbook, role, inventory). Understanding variable precedence is crucial.
- Use the `vars_prompt` directive to prompt users for variables.
- **Incorrect Module Usage:**
- Using the wrong module for a task can lead to unexpected results or errors.
- Refer to the Ansible documentation for module usage examples and best practices.
- **Lack of Idempotency:**
- Tasks that are not idempotent can cause unintended side effects when run repeatedly.
- Use the `changed_when` and `failed_when` directives to customize task result conditions.
- **Ignoring Errors:**
- Ignoring errors can lead to cascading failures or inconsistent state.
- Use the `block` and `rescue` directives to handle errors gracefully.
- **Misunderstanding Facts:**
- Facts are variables that contain information about the target hosts. Misunderstanding or misusing facts can lead to incorrect behavior.
- Use the `ansible_facts` variable to access all available facts.
- **Over-reliance on the `shell` module:**
- Avoid the shell module unless absolutely necessary as using it hinders the playbook's idempotency.
- **Not testing playbooks:**
- Always test your playbooks before running them in production to avoid any unexpected issues.
### 6.2 Edge Cases
- **Handling Large Files:**
- Transferring large files can be slow and consume a lot of resources. Use the `synchronize` module or the `archive` and `unarchive` modules to optimize file transfers.
- **Managing Complex Dependencies:**
- Managing complex dependencies between tasks and roles can be challenging. Use the `block` and `rescue` directives to handle errors gracefully.
- **Working with Dynamic Inventories:**
- Dynamic inventories can be complex to set up and maintain. Use a dynamic inventory plugin or script to manage your inventory automatically.
- **Handling Network Latency:**
- Network latency can affect the performance of your playbooks. Use the `async` directive to execute tasks asynchronously.
- **Special characters in variables:**
- Avoid using special characters that can interfere with playbook's execution.
### 6.3 Version-Specific Issues
- **Module Compatibility:**
- Some modules may not be compatible with all versions of Ansible.
- Check the module documentation for compatibility information.
- **Deprecated Features:**
- Some features may be deprecated in newer versions of Ansible.
- Be aware of deprecated features and migrate to the recommended alternatives.
- **Behavioral Changes:**
- Some modules may have different behavior in different versions of Ansible.
- Test your playbooks with different versions of Ansible to ensure they behave as expected.
### 6.4 Compatibility Concerns
- **Operating System Compatibility:**
- Some playbooks and roles may only be compatible with specific operating systems.
- Check the playbook or role documentation for compatibility information.
- **Python Version Compatibility:**
- Ansible requires Python to be installed on the target hosts. Ensure that the target hosts have a compatible version of Python installed.
- **Module Dependencies:**
- Some modules may have external dependencies that need to be installed on the target hosts.
- Check the module documentation for dependency information.
### 6.5 Debugging Strategies
- **Use the `-v` or `--verbose` option to increase the verbosity of Ansible output.**
- **Use the `-C` or `--check` option to perform a dry run of your playbook.**
- **Use the `--diff` option to see the changes that will be made to the target hosts.**
- **Use the `debug` module to print variables and facts.**
- **Use the `assert` module to validate variables and facts.**
- **Use the `pause` module to pause playbook execution and inspect the target hosts.**
- **Use the `register` directive to capture the output of tasks and use the output in debugging logic.**
- **Check the Ansible logs on the control node and the target hosts for error messages.**
## 7. Tooling and Environment
- Utilize recommended tools and environment configurations to streamline your Ansible development and deployment processes.
### 7.1 Recommended Development Tools
- **Text Editor or IDE:**
- Use a text editor or IDE with YAML and Jinja2 syntax highlighting and auto-completion.
- Popular options include VS Code, Sublime Text, Atom, and PyCharm.
- Install Ansible-specific plugins for improved code completion and linting.
- **Ansible Lint:**
- Use `ansible-lint` to check your playbooks and roles for common errors and best practices violations.
- Configure `ansible-lint` to use a custom style guide or to enforce specific rules.
- **Molecule:**
- Use `Molecule` to test your roles in a Docker or Vagrant environment.
- Molecule provides a framework for writing and running integration tests for your roles.
- **Vagrant:**
- Use `Vagrant` to create virtual machines for testing your playbooks and roles.
- Vagrant allows you to easily create and destroy test environments.
- **Docker:**
- Use `Docker` to containerize your Ansible control node and target hosts.
- Docker provides a lightweight and portable environment for running your Ansible code.
- **Testinfra:**
- Use `Testinfra` to write and run end-to-end tests for your infrastructure.
- Testinfra allows you to verify the state of your target hosts after running your playbooks.
### 7.2 Build Configuration
- **Use a build tool such as `Make` or `Grunt` to automate your build process.**
- **Create a `Makefile` or `Gruntfile.js` that defines the tasks for linting, testing, and deploying your Ansible code.**
- **Use environment variables to configure your build process.**
- **Use a version control system such as `Git` to track changes to your build configuration.**
- **Keep your build configuration simple and easy to understand.**
### 7.3 Linting and Formatting
- **Use `ansible-lint` to check your playbooks and roles for common errors and best practices violations.**
- **Configure `ansible-lint` to use a custom style guide or to enforce specific rules.**
- **Use a YAML linter to validate your YAML syntax.**
- **Use a Jinja2 linter to validate your Jinja2 syntax.**
- **Automate linting and formatting as part of your build process.**
- **Use auto-formatting tools such as `Prettier` to automatically format your YAML and Jinja2 code.**
- **Follow a consistent naming convention for your variables, tasks, roles, and files.**
### 7.4 Deployment Best Practices
- **Use a deployment tool such as `Ansible Tower` or `AWX` to manage your deployments.**
- **Use a continuous integration and continuous delivery (CI/CD) pipeline to automate your deployments.**
- **Use a version control system such as `Git` to track changes to your playbooks and roles.**
- **Use a rollback mechanism to revert changes in case of failures.**
- **Use a monitoring tool such as `Nagios` or `Zabbix` to monitor your infrastructure.**
- **Use a logging tool such as `ELK Stack` or `Splunk` to collect and analyze your logs.**
- **Always test your playbooks in a staging environment before deploying them to production.**
### 7.5 CI/CD Integration
- **Integrate your Ansible code into your CI/CD pipeline to automate testing and deployment.**
- **Use a CI/CD tool such as `Jenkins`, `GitLab CI`, or `Travis CI` to automate your pipeline.**
- **Create a CI/CD pipeline that includes linting, testing, and deployment steps.**
- **Use environment variables to configure your CI/CD pipeline.**
- **Use a version control system such as `Git` to trigger your CI/CD pipeline on every commit.**
- **Use automated testing to verify that your infrastructure changes work as expected.**
- **Use automated deployment to deploy your infrastructure changes to your target environment.**
- **Automate configuration management:**
- Ensure consistent configurations for servers and applications.
- **Implement infrastructure as code:**
- Track and manage infrastructure in source control.
- **Automate application deployments:**
- Deploy new versions of software reliably and efficiently.
- **Orchestrate multi-tier deployments:**
- Coordinate deployments across various layers of infrastructure.
+311
View File
@@ -0,0 +1,311 @@
---
description: This rule enforces best practices and coding standards for projects using the Ant Design (antd) UI library within React applications. It covers code organization, performance, security, testing, and common pitfalls to ensure maintainable and efficient applications.
globs: **/*.{js,jsx,ts,tsx}
---
# Ant Design (antd) Best Practices and Coding Standards
This document outlines the recommended best practices for developing React applications using the Ant Design (antd) UI library. Following these guidelines will lead to more maintainable, performant, and secure applications.
## 1. Code Organization and Structure
### 1.1. Directory Structure
- **`src/components/`**: Contains reusable React components, including those utilizing antd components.
- **`src/pages/`**: Contains components representing different application routes or pages.
- **`src/layouts/`**: Contains layout components that provide a consistent structure across pages.
- **`src/services/`**: Contains modules for interacting with APIs and handling data fetching.
- **`src/utils/`**: Contains utility functions and helper modules.
- **`src/styles/`**: Contains global styles, theme customizations, and component-specific stylesheets.
- **`src/assets/`**: Contains static assets such as images, fonts, and icons.
- **`src/context/`**: (Optional) If using context API, store all context definition files here.
Example:
my-app/
├── src/
│ ├── components/
│ │ ├── Button.jsx
│ │ ├── Input.jsx
│ │ └── ...
│ ├── pages/
│ │ ├── HomePage.jsx
│ │ ├── LoginPage.jsx
│ │ └── ...
│ ├── layouts/
│ │ ├── MainLayout.jsx
│ │ └── ...
│ ├── services/
│ │ ├── api.js
│ │ └── ...
│ ├── utils/
│ │ ├── date-formatter.js
│ │ └── ...
│ ├── styles/
│ │ ├── global.css
│ │ ├── theme.js
│ │ └── ...
│ ├── App.jsx
│ └── index.js
└── ...
### 1.2. File Naming Conventions
- **Components**: Use PascalCase for component file names (e.g., `MyComponent.jsx`, `UserProfile.tsx`).
- **Styles**: Use kebab-case for style file names (e.g., `my-component.css`, `user-profile.module.scss`).
- **Modules**: Use camelCase for module file names (e.g., `api.js`, `dateFormatter.ts`).
### 1.3. Module Organization
- Group related components, styles, and assets within the same directory.
- Create separate modules for API interactions, data transformations, and utility functions.
### 1.4. Component Architecture
- **Presentational Components**: Focus on rendering UI elements and receiving data via props.
- **Container Components**: Handle data fetching, state management, and logic, passing data to presentational components.
- Use functional components with hooks whenever possible for simplicity and reusability.
### 1.5. Code Splitting
- Utilize React.lazy and Suspense to load components on demand, improving initial load time.
- Split routes into separate chunks to minimize the initial bundle size.
- Consider using dynamic imports for less frequently used components or modules.
Example:
jsx
import React, { Suspense } from 'react';
const MyComponent = React.lazy(() => import('./MyComponent'));
function MyPage() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Higher-Order Components (HOCs)**: Use for cross-cutting concerns like authentication or data fetching. Prefer hooks where possible.
- **Render Props**: An alternative to HOCs for sharing code between components. Prefer hooks where possible.
- **Compound Components**: Create reusable components with implicit state sharing (e.g., `Tabs` and `Tab` components).
### 2.2. Recommended Approaches
- **Form Handling**: Use `antd`'s `Form` component for managing form state, validation, and submission.
- **Data Display**: Leverage `antd`'s `Table`, `List`, and `Card` components for structured data presentation.
- **Navigation**: Use `antd`'s `Menu` and `Breadcrumb` components for creating intuitive navigation.
### 2.3. Anti-patterns and Code Smells
- **Direct DOM Manipulation**: Avoid directly manipulating the DOM; let React manage updates.
- **Over-reliance on `any` type**: Using `any` in TypeScript defeats the purpose of static typing. Provide explicit types.
- **Mutating Props**: Treat props as read-only and avoid modifying them directly.
- **Inline Styles**: Keep styles in CSS files or use styled-components for better organization and maintainability. Prefer CSS Modules or Styled Components for component specific styles.
### 2.4. State Management
- **Component State**: Use `useState` for simple, local component state.
- **Context API**: Use for sharing state across multiple components without prop drilling.
- **Redux/Zustand**: Consider for complex applications with global state and predictable state transitions.
- **MobX**: Consider for complex applications where you want to observe changes in your data and derive calculations from that data.
### 2.5. Error Handling
- **Try-Catch Blocks**: Use for handling synchronous errors.
- **Error Boundaries**: Use to catch errors during rendering and prevent the entire application from crashing.
- **Global Error Handling**: Implement a global error handler to log errors and provide user feedback.
Example (Error Boundary):
jsx
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Caught error: ', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
// Usage:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Memoization**: Use `React.memo` to prevent unnecessary re-renders of components with the same props.
- **Pure Components**: Extend `React.PureComponent` for class components to perform shallow prop comparisons.
- **Virtualization**: Use `antd`'s `Table` and `List` components with virtualization for large datasets.
- **Debouncing/Throttling**: Use for event handlers that trigger frequent updates (e.g., search input).
### 3.2. Memory Management
- **Avoid Memory Leaks**: Properly clean up event listeners and timers in `useEffect` hooks.
- **Release Resources**: Release unused objects and data structures to free up memory.
### 3.3. Rendering Optimization
- **ShouldComponentUpdate**: Implement `shouldComponentUpdate` (for class components) or use `React.memo` (for functional components) to prevent unnecessary re-renders.
- **Immutable Data**: Use immutable data structures to simplify change detection.
### 3.4. Bundle Size Optimization
- **Modular Imports**: Import only the necessary components from `antd` to reduce bundle size (e.g., `import { Button } from 'antd';`). Use `babel-plugin-import` for automatic modular imports.
- **Tree Shaking**: Ensure your build process supports tree shaking to remove unused code.
- **Code Splitting**: As mentioned earlier, split your code into smaller chunks to reduce the initial bundle size.
### 3.5. Lazy Loading
- Use `React.lazy` and `Suspense` to load components on demand.
- Implement lazy loading for images and other assets using libraries like `react-lazyload`.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
- **Cross-Site Scripting (XSS)**: Prevent XSS by sanitizing user input and encoding output.
- **Cross-Site Request Forgery (CSRF)**: Protect against CSRF attacks by implementing CSRF tokens.
- **SQL Injection**: Avoid directly embedding user input in SQL queries; use parameterized queries or ORMs.
### 4.2. Input Validation
- **Server-Side Validation**: Always validate user input on the server-side.
- **Client-Side Validation**: Use `antd`'s `Form` component for client-side validation to provide immediate feedback to the user.
- **Sanitize Input**: Sanitize user input to remove potentially harmful characters or code.
### 4.3. Authentication and Authorization
- **Secure Authentication**: Use secure authentication mechanisms like JWT (JSON Web Tokens) or OAuth.
- **Role-Based Access Control (RBAC)**: Implement RBAC to control access to different parts of the application based on user roles.
### 4.4. Data Protection
- **Encryption**: Encrypt sensitive data both in transit and at rest.
- **Data Masking**: Mask sensitive data in the UI to prevent unauthorized access.
### 4.5. Secure API Communication
- **HTTPS**: Use HTTPS to encrypt communication between the client and the server.
- **API Rate Limiting**: Implement rate limiting to prevent abuse and denial-of-service attacks.
## 5. Testing Approaches
### 5.1. Unit Testing
- Test individual components in isolation to ensure they function correctly.
- Use testing libraries like Jest and React Testing Library.
- Mock dependencies to isolate the component being tested.
### 5.2. Integration Testing
- Test the interaction between multiple components or modules.
- Use testing libraries like React Testing Library and Cypress.
### 5.3. End-to-End Testing
- Test the entire application from the user's perspective.
- Use testing frameworks like Cypress or Playwright.
### 5.4. Test Organization
- Create a `tests/` directory at the root of your project.
- Place test files alongside the components or modules they test (e.g., `MyComponent.test.jsx`).
- Use descriptive test names to clearly indicate what is being tested.
### 5.5. Mocking and Stubbing
- Use mocking libraries like Jest's `jest.mock()` to mock external dependencies.
- Use stubbing to replace functions or methods with predefined behavior.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Not using modular imports**: Importing the entire `antd` library can significantly increase bundle size.
- **Ignoring TypeScript errors**: Failing to address TypeScript errors can lead to runtime issues.
- **Not handling asynchronous operations correctly**: Failing to handle promises or async/await can lead to unhandled rejections and unexpected behavior.
- **Not localizing strings correctly**: Hardcoding strings instead of using `antd` i18n features.
### 6.2. Edge Cases
- **Handling different screen sizes and devices**: Ensuring responsive design using `antd` grid system.
- **Accessibility**: Consider accessibility when using components, making sure to include `aria` attributes.
- **Browser compatibility**: Test the app on various browsers (Chrome, Firefox, Safari, Edge, etc).
### 6.3. Version-Specific Issues
- **Breaking changes**: Be aware of breaking changes when upgrading `antd` versions.
- **Deprecated APIs**: Avoid using deprecated APIs and migrate to the recommended alternatives.
- **CSS class conflicts:** Potential issues with CSS specificity or conflicts with global styles. Use CSS Modules or Styled Components for more robust style isolation.
### 6.4. Compatibility Concerns
- **React version**: Ensure compatibility between `antd` and your React version.
- **Other UI libraries**: Avoid conflicts with other UI libraries by using consistent styling and naming conventions.
### 6.5. Debugging
- **Use browser developer tools**: Inspect the DOM, network requests, and console output.
- **Use React DevTools**: Inspect the component tree, props, and state.
- **Use logging and debugging statements**: Add `console.log` statements to trace the execution flow and inspect variable values.
## 7. Tooling and Environment
### 7.1. Recommended Tools
- **IDE**: VS Code, WebStorm.
- **Build Tool**: Webpack, Parcel, Rollup, esbuild.
- **Testing Libraries**: Jest, React Testing Library, Cypress.
- **Linting**: ESLint, Prettier.
### 7.2. Build Configuration
- **Optimize for production**: Use production-specific build configurations to minimize bundle size and improve performance.
- **Configure code splitting**: Set up code splitting to load components on demand.
- **Enable tree shaking**: Ensure your build process supports tree shaking to remove unused code.
### 7.3. Linting and Formatting
- **ESLint**: Use ESLint with recommended React and `antd` plugins to enforce coding standards and detect potential errors.
- **Prettier**: Use Prettier to automatically format your code for consistency.
- **Stylelint:** Use Stylelint to enforce consistent style practices.
### 7.4. Deployment
- **Choose a hosting platform**: Netlify, Vercel, AWS, Google Cloud, Azure.
- **Configure environment variables**: Set up environment variables for API keys, database credentials, and other sensitive information.
- **Use a CDN**: Use a Content Delivery Network (CDN) to cache static assets and improve loading times.
### 7.5. CI/CD Integration
- **Set up a CI/CD pipeline**: Use tools like Jenkins, Travis CI, CircleCI, or GitHub Actions to automate testing, building, and deployment.
- **Automate testing**: Run unit, integration, and end-to-end tests in your CI/CD pipeline.
- **Automate deployment**: Automate the deployment process to reduce manual effort and errors.
+169
View File
@@ -0,0 +1,169 @@
---
description: This rule provides best practices and coding standards for developing with the AnyIO library, focusing on structured concurrency, task management, and proper use of synchronization primitives to create robust, cross-backend asynchronous applications.
globs: **/*.py
---
# AnyIO Best Practices and Coding Standards
This document provides comprehensive guidelines for developing with the AnyIO library, covering code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and recommended tooling.
## Library Information:
- Name: anyio
- Tags: python, async, compatibility-layer
## 1. Code Organization and Structure
- **Directory Structure:** Organize your project to separate concerns clearly.
- `src/`: Contains the main application code.
- `tests/`: Contains unit, integration, and end-to-end tests.
- `examples/`: Contains example code showcasing AnyIO features.
- `docs/`: Contains project documentation (using Sphinx, for example).
- `tasks.py`: Invoke tasks for building, testing, and deploying (using Invoke).
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- `my_component.py` for a component's source code.
- `my_component_test.py` for its tests.
- `conftest.py` in the `tests/` directory for test fixtures.
- **Module Organization:**
- Group related functionality into modules.
- Use packages to further structure your code.
- Employ clear and concise module-level docstrings.
- **Component Architecture:**
- Design components with clear responsibilities.
- Use interfaces or abstract base classes for decoupling.
- Consider using dependency injection to improve testability.
- **Code Splitting:**
- Break down large functions into smaller, more manageable ones.
- Decompose complex modules into simpler sub-modules.
- Consider lazy-loading modules or components to improve startup time.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Task Groups (Nurseries):** Use task groups (`anyio.create_task_group()`) for structured concurrency. This is the most crucial pattern in AnyIO.
- **Resource Acquisition Is Initialization (RAII):** Use `async with` statements for managing resources (e.g., sockets, files) to ensure proper cleanup, even in case of exceptions or cancellations.
- **Observer Pattern:** Use AnyIO's `Event` or `Condition` primitives to implement observer patterns for asynchronous communication.
- **Producer-Consumer Pattern:** Use `anyio.Queue` for implementing producer-consumer patterns with asynchronous tasks.
- **Recommended Approaches:**
- Use `anyio.sleep()` for non-blocking delays.
- Employ `anyio.to_thread.run_sync()` to run blocking code in a separate thread to avoid blocking the event loop.
- Utilize `anyio.Path` for asynchronous file I/O operations.
- **Anti-patterns:**
- **Blocking the Event Loop:** Avoid performing long-running synchronous operations in the main event loop. Use `anyio.to_thread.run_sync()` to offload such tasks to worker threads.
- **Ignoring Exceptions:** Always handle exceptions gracefully within tasks and task groups. Unhandled exceptions can crash your application.
- **Unstructured Concurrency:** Avoid creating tasks without a task group. This can lead to resource leaks and difficult-to-debug issues.
- **Spin Locks:** Do not use busy-waiting or spin locks in asynchronous code. Use synchronization primitives like `Lock` or `Condition` instead.
- **State Management:**
- Use immutable data structures whenever possible to avoid race conditions.
- Employ `Lock` or `Condition` objects to protect shared mutable state.
- Consider using atomic operations for simple state updates.
- **Error Handling:**
- Wrap code in `try...except` blocks to catch exceptions.
- Use `try...finally` blocks to ensure cleanup, even in case of exceptions.
- Leverage task groups to handle exceptions across multiple tasks.
- Implement retry mechanisms for transient errors.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Asynchronous I/O:** Utilize AnyIO's asynchronous I/O functions (e.g., `anyio.Path`, `anyio.open_file`) for optimal performance when dealing with I/O-bound operations.
- **Connection Pooling:** Implement connection pooling for database connections or other network resources to reduce overhead.
- **Caching:** Cache frequently accessed data to minimize I/O operations.
- **Minimize Context Switching:** Reduce unnecessary context switching by batching operations and avoiding excessive `await` calls.
- **Memory Management:**
- Avoid creating large, unnecessary data structures.
- Use generators or iterators to process large datasets in a memory-efficient manner.
- Properly close resources (e.g., sockets, files) to release memory.
- Use the `del` statement or `weakref` to break circular references and allow garbage collection.
- **Rendering Optimization:** N/A (AnyIO is not directly involved in rendering).
- **Bundle Size Optimization:** N/A (AnyIO itself is a dependency, not a frontend bundle).
- **Lazy Loading:**
- Use lazy loading to defer the initialization of components until they are needed.
- Implement code splitting to load modules on demand.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- **Denial of Service (DoS):** Protect against DoS attacks by limiting the number of concurrent connections or requests.
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks (e.g., SQL injection, command injection).
- **Cross-Site Scripting (XSS):** N/A (AnyIO is not directly involved in front-end development).
- **Input Validation:**
- Validate all user inputs to ensure they conform to expected formats and ranges.
- Use input validation libraries to simplify the process.
- Escape or sanitize user inputs before using them in database queries or system commands.
- **Authentication and Authorization:**
- Implement authentication to verify the identity of users.
- Implement authorization to control access to resources based on user roles.
- Use secure password hashing algorithms (e.g., bcrypt, Argon2).
- **Data Protection:**
- Use encryption to protect sensitive data at rest and in transit.
- Store cryptographic keys securely.
- Comply with relevant data privacy regulations (e.g., GDPR, CCPA).
- **Secure API Communication:**
- Use HTTPS for all API communication to encrypt data in transit.
- Implement proper authentication and authorization mechanisms for API endpoints.
- Protect against Cross-Site Request Forgery (CSRF) attacks if your API is used by web applications.
## 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for individual components to verify their functionality.
- Use mocking or stubbing to isolate components from their dependencies.
- Aim for high test coverage to ensure that all code paths are tested.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components.
- Test the integration with external services (e.g., databases, APIs).
- **End-to-End Testing:**
- Write end-to-end tests to verify the entire application flow.
- Simulate real user interactions to test the application from a user's perspective.
- **Test Organization:**
- Organize tests into separate modules based on the components or features they test.
- Use a consistent naming convention for test files and functions.
- Employ test fixtures to set up and tear down test environments.
- **Mocking and Stubbing:**
- Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to replace dependencies with mock objects.
- Stub external services or APIs to simulate different scenarios.
- Verify that mock objects are called with the expected arguments.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Not using `async with` for resources:** Forgetting to use `async with` for resources that require asynchronous cleanup can lead to resource leaks.
- **Mixing asyncio and Trio idioms:** Avoid mixing idioms from different asynchronous frameworks. Stick to AnyIO's API.
- **Incorrectly using `to_thread.run_sync`:** Ensure that the code passed to `to_thread.run_sync` is actually blocking.
- **Edge Cases:**
- **Cancellation:** Be aware of how cancellation works in AnyIO and handle it gracefully.
- **Timeouts:** Implement timeouts to prevent tasks from running indefinitely.
- **Signal Handling:** Properly handle signals (e.g., `SIGINT`, `SIGTERM`) to ensure graceful shutdown.
- **Version-Specific Issues:**
- Consult the AnyIO changelog for known issues and breaking changes in different versions.
- **Compatibility Concerns:**
- Ensure that AnyIO is compatible with the versions of asyncio or Trio you are using.
- Be aware of potential compatibility issues with other libraries that use asynchronous programming.
- **Debugging Strategies:**
- Use logging to trace the execution flow of your code.
- Employ debuggers (e.g., `pdb`, `ipdb`) to step through your code and inspect variables.
- Use asynchronous debugging tools to debug asynchronous code.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **Python:** Use the latest stable version of Python (3.10+ recommended).
- **Poetry/Pip:** Use Poetry or Pip for dependency management.
- **Pytest:** Use Pytest for testing.
- **Black/Ruff:** Use Black and Ruff for code formatting and linting.
- **VS Code/PyCharm:** Use VS Code or PyCharm as your IDE.
- **Build Configuration:**
- Use a `pyproject.toml` file to configure Poetry or Pip.
- Specify dependencies and build settings in the `pyproject.toml` file.
- Use a `setup.py` file for projects that need to be installed with `pip install -e .`
- **Linting and Formatting:**
- Configure Black and Ruff to enforce consistent code formatting and style.
- Use a pre-commit hook to automatically format and lint code before committing.
- **Deployment:**
- Package your application into a Docker container for easy deployment.
- Use a process manager (e.g., systemd, Supervisor) to manage your application.
- Deploy your application to a cloud platform (e.g., AWS, Azure, GCP).
- **CI/CD Integration:**
- Use a CI/CD pipeline to automate the build, test, and deployment process.
- Integrate your CI/CD pipeline with your version control system (e.g., GitHub, GitLab, Bitbucket).
- Use automated testing to ensure that code changes do not introduce regressions.
+217
View File
@@ -0,0 +1,217 @@
---
description: This rule provides comprehensive best practices and coding standards for developing with Apollo GraphQL. It covers schema design, security, performance, testing, and deployment.
globs: **/*.{js,jsx,ts,tsx,graphql}
---
- Always use UV when installing dependencies
- Always use python 3.12
- Always use classes instead of function
# Apollo GraphQL Best Practices
This document provides a comprehensive guide to best practices and coding standards for developing GraphQL APIs and applications using the Apollo ecosystem.
## Library Information:
- Name: apollo-graphql
- Tags: web, api, graphql, javascript
## 1. Schema Design
- **Clarity and Consistency:**
- Use descriptive naming conventions for types, fields, and arguments (e.g., `getUserById` instead of `getUser`).
- Maintain consistency across the schema in terms of naming and structure.
- Define a clear schema that reflects your business domain and data model.
- **Interfaces and Unions:**
- Implement interfaces and unions for shared features and common data structures.
- Use interfaces to define contracts for types that implement shared behaviors.
- Use unions when a field can return different object types that don't share a common interface.
- **Nullability:**
- Every field is nullable by default unless explicitly marked as non-null using `!`. Carefully consider nullability for each field.
- Use non-null types (`!`) only when you can guarantee that the field will always return a value.
- Handle potential errors gracefully and return `null` for nullable fields when appropriate.
- **Demand-Driven Schema Design:**
- Design your schema to serve client use cases and product requirements.
- Intentionally design your schema to serve client use cases and product requirements.
- **Avoid Autogenerated Schemas:**
- Avoid autogenerating schemas, especially the fields on the root operation types
## 2. Security
- **Disable Introspection in Production:**
- Disable introspection in production environments to prevent unauthorized access to your schema.
- Restrict access to staging environments where introspection is enabled.
- **Input Validation:**
- Validate all user inputs to prevent injection attacks and data corruption.
- Use custom scalars or directives to enforce validation rules on input types.
- Sanitize and escape user inputs before using them in resolvers.
- **Authentication and Authorization:**
- Implement robust authentication and authorization mechanisms to protect your API.
- Use industry-standard protocols like OAuth 2.0 or JWT for authentication.
- Implement fine-grained authorization checks at the field level.
- Enforcing authentication and authorization in the router protects your underlying APIs from malicious operations
- **Rate Limiting and Depth Limiting:**
- Implement rate limiting to prevent abuse and denial-of-service attacks.
- Limit query depth to prevent complex queries from overwhelming your server.
- **Whitelisting Queries:**
- Consider whitelisting queries to restrict the operations that can be executed against your API.
- **Obfuscate Error Details:**
- Remove verbose error details from API responses in your production graph.
- Only selectively expose error details to clients in production.
- **Data Validation and Sanitization:**
- As a schema design best practice, you should deliberately design your schema to serve client use cases and product requirements.
## 3. Performance Optimization
- **Batching and Caching:**
- Utilize batching techniques (e.g., DataLoader) to reduce the number of requests to backend data sources.
- Implement caching at different levels (e.g., server-side, client-side) to improve response times.
- **Pagination:**
- Implement pagination strategies to manage large datasets effectively.
- Use cursor-based pagination for efficient retrieval of paginated data.
- **N+1 Problem:**
- Use tools like DataLoader to address the N+1 query problem and ensure efficient data fetching.
- **Server-Side Batching &amp; Caching:**
- GraphQL is designed in a way that allows you to write clean code on the server, where every field on every type has a focused single-purpose function for resolving that value.
- **Automatic Persisted Queries (APQ):**
- Consider implementing automatic persisted queries (APQ) to optimize network usage and improve security
## 4. Code Organization and Structure
- **Directory Structure:**
src/
schema/
types/
*.graphql
resolvers/
*.js
dataSources/
*.js
utils/
*.js
index.js // Entry point
- **File Naming Conventions:**
- Use PascalCase for type definitions (e.g., `UserType.graphql`).
- Use camelCase for resolver functions (e.g., `getUserById.js`).
- **Module Organization:**
- Organize your code into reusable modules based on functionality (e.g., user management, product catalog).
- Create separate modules for schema definitions, resolvers, and data sources.
- **Component Architecture:**
- Follow a component-based architecture for building GraphQL applications.
- Create reusable components for common UI elements and data fetching logic.
- **Code Splitting:**
- Use code splitting to reduce the initial bundle size and improve page load times.
- Consider splitting your application into smaller chunks based on routes or features.
## 5. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Data Source Pattern:** Decouple data fetching logic from resolvers using data sources.
- **Schema Stitching:** Combine multiple GraphQL APIs into a single, unified schema.
- **Recommended Approaches:**
- Use a GraphQL client library (e.g., Apollo Client, Relay) for efficient data fetching and caching.
- Implement custom directives to add additional functionality to your schema.
- **Anti-patterns:**
- **Over-fetching/Under-fetching:** Avoid returning more or less data than required by the client.
- **Chatty APIs:** Reduce the number of round trips between the client and the server.
- **God Objects:** Avoid creating large, monolithic types with too many fields.
- **State Management:**
- Use a state management library (e.g., Redux, Zustand, Jotai) to manage client-side state.
- Consider using Apollo Client's local state management features for simple state requirements.
- **Error Handling:**
- Use a consistent error handling mechanism across your application.
- Return informative error messages to the client.
- Log errors on the server for debugging purposes.
## 6. Testing Approaches
- **Unit Testing:**
- Unit test individual resolvers and data sources.
- Mock external dependencies to isolate the code under test.
- **Integration Testing:**
- Integrate test your GraphQL API with your database and other backend services.
- Use a testing framework like Jest or Mocha for writing integration tests.
- **End-to-End Testing:**
- Use end-to-end testing to verify the entire application flow.
- Use a testing tool like Cypress or Puppeteer for writing end-to-end tests.
- **Test Organization:**
- Organize your tests into separate directories based on functionality.
- Use descriptive names for your test files and test cases.
- **Mocking and Stubbing:**
- Use mocking and stubbing techniques to isolate the code under test and simulate external dependencies.
## 7. Common Pitfalls and Gotchas
- **N+1 Problem:** Be aware of the N+1 query problem and use DataLoader or other batching techniques to solve it.
- **Schema Evolution:** Plan for schema evolution and use techniques like adding new fields and deprecating old ones to avoid breaking changes.
- **Performance Bottlenecks:** Monitor your API for performance bottlenecks and use profiling tools to identify slow resolvers.
- **Nullability:** Ensure that non-null fields never return `null` to avoid unexpected errors.
## 8. Tooling and Environment
- **Development Tools:**
- Use a GraphQL IDE like GraphiQL or Apollo Studio for exploring and testing your API.
- Use code generation tools to generate types and resolvers from your schema.
- **Build Configuration:**
- Use a build tool like Webpack or Parcel to bundle your code for production.
- Configure your build tool to optimize your code and reduce bundle size.
- **Linting and Formatting:**
- Use a linter like ESLint or Prettier to enforce code style and prevent errors.
- **Deployment:**
- Deploy your GraphQL API to a production environment like AWS Lambda, Google Cloud Functions, or a Node.js server.
- Use a serverless platform for easy scaling and management.
- **CI/CD Integration:**
- Integrate your GraphQL API with a CI/CD pipeline for automated testing and deployment.
## 9. Additional Best Practices
- **Versioning:** While GraphQL promotes continuous evolution, consider versioning your API if you need to make breaking changes.
- **Documentation:** Provide comprehensive documentation for your GraphQL API using tools like GraphQL Docs.
- **Monitoring:** Monitor your GraphQL API for performance and errors using tools like Apollo Studio or New Relic.
- **Error Messages and Notifications:** You can also opt for union types to represent an error and to prompt suggestions to users, though this is a more expensive choice.
## 10. Global Identification
- Another way to organize components, besides Pagination, is by using a global identification. Originally proposed on Relay and similar to URIs, this method has become a more general good practice though it is not considered mandatory — especially if you are not planning on supporting Relay in your application
## 11. Rate Limiting
- Like any other web API, setting limits is a good strategy to avoid, for example, an overload of requests per minute. There are a few ways this can be done in GraphQL
## 12. Authentication and Authorization
- Often interchanged in their meaning, authentication is the act of determining who a user is and whether they are logged in or not. Authorization, on the other hand, is the act of determining if a user is allowed to do an action or see something.
## 13. Safelisting with Persisted queries
- Beyond operation limits, GraphOS enables first-party apps to register trusted operations in a persisted query list ( PQL) or safelist.
+363
View File
@@ -0,0 +1,363 @@
---
description: This rule file provides best practices and coding standards for ASP.NET Core development, covering various aspects from code organization to security and performance optimization.
globs: **/*.cs
---
# ASP.NET Core Best Practices and Coding Standards
This document outlines recommended best practices and coding standards for developing ASP.NET Core applications. Following these guidelines will help ensure code clarity, maintainability, performance, and security.
## 1. Code Organization and Structure
### Directory Structure Best Practices:
A well-defined directory structure is crucial for maintaining a scalable and organized ASP.NET Core project. Here's a suggested structure:
ProjectName/
├── src/
│ ├── ProjectName.Web/
│ │ ├── Controllers/
│ │ ├── Models/
│ │ ├── Views/
│ │ ├── Pages/ (for Razor Pages)
│ │ ├── wwwroot/
│ │ ├── appsettings.json
│ │ ├── Program.cs
│ │ ├── Startup.cs
│ ├── ProjectName.Data/
│ │ ├── Models/
│ │ ├── Contexts/
│ │ ├── Repositories/
│ │ ├── Migrations/
│ ├── ProjectName.Services/
│ │ ├── Interfaces/
│ │ ├── Implementations/
│ ├── ProjectName.Models/ (if different from Data Models)
├── tests/
│ ├── ProjectName.UnitTests/
│ ├── ProjectName.IntegrationTests/
├── artifacts/
├── .editorconfig
├── .gitignore
├── ProjectName.sln
* **src:** Contains the source code of the application.
* **ProjectName.Web:** The main web application project. This can also be named `API` for web API projects.
* **Controllers:** Contains ASP.NET Core controllers.
* **Models:** Contains view models and other data transfer objects (DTOs) specific to the web layer.
* **Views:** Contains Razor views (.cshtml files).
* **Pages:** Contains Razor Pages (if using Razor Pages model).
* **wwwroot:** Contains static files like CSS, JavaScript, and images.
* **ProjectName.Data:** Contains data access logic, Entity Framework Core contexts, and models representing database entities.
* **Models (Data):** Defines entity models that correspond to database tables.
* **Contexts:** Contains the DbContext class.
* **Repositories:** Contains repositories for data access.
* **Migrations:** Contains Entity Framework Core migrations.
* **ProjectName.Services:** Contains business logic and application services.
* **Interfaces:** Defines interfaces for services.
* **Implementations:** Contains concrete implementations of service interfaces.
* **ProjectName.Models:** (Optional) Contains domain models that are shared across multiple layers. This layer promotes separation of concerns if your data layer models should not be exposed at the API or Web layer.
* **tests:** Contains unit and integration tests.
* **ProjectName.UnitTests:** Contains unit tests.
* **ProjectName.IntegrationTests:** Contains integration tests.
* **artifacts:** Contains build artifacts.
* **.editorconfig:** Defines code style rules.
* **.gitignore:** Specifies intentionally untracked files that Git should ignore.
* **ProjectName.sln:** The solution file.
### File Naming Conventions:
* **Classes:** PascalCase (e.g., `UserController`, `ProductService`)
* **Interfaces:** IPascalCase (e.g., `IProductService`, `IUserRepository`)
* **Methods:** PascalCase (e.g., `GetProduct`, `CreateUser`)
* **Variables (local):** camelCase (e.g., `productName`, `userId`)
* **Parameters:** camelCase (e.g., `productId`, `userName`)
* **Constants:** PascalCase (e.g., `DefaultPageSize`, `MaxRetries`)
* **Enums:** PascalCase (e.g., `OrderStatus`, `UserRole`)
* **Namespaces:** PascalCase, mirroring the directory structure (e.g., `ProjectName.Web.Controllers`, `ProjectName.Services.Implementations`)
* **Files:** Match the class/interface name (e.g., `UserController.cs`, `IProductService.cs`)
### Module Organization:
* **Feature-based Modules:** Group related functionality into modules based on features (e.g., `Authentication`, `Products`, `Orders`). Each feature can have its own folder within the `src` directory, containing its own controllers, models, services, and data access components. This enhances cohesion and reduces coupling.
* **Vertical Slices:** Organize modules around specific use cases or user stories. Each slice contains all the code necessary to implement a particular feature, from the UI to the data access layer. This promotes faster development and easier maintenance.
### Component Architecture:
* **Layered Architecture:** Divide the application into layers (e.g., Presentation, Application, Domain, Infrastructure) to separate concerns and promote testability. Each layer has a specific responsibility and interacts with other layers through well-defined interfaces.
* **Microservices:** For larger applications, consider breaking down the application into smaller, independent microservices. Each microservice handles a specific business capability and can be deployed and scaled independently.
### Code Splitting Strategies:
* **Feature-based Splitting:** Split code based on features, loading modules only when they are needed. This can improve initial load time and reduce memory consumption.
* **Route-based Splitting:** Load code only when a specific route is accessed. This is especially useful for large applications with many routes.
* **On-Demand Loading:** Load code dynamically when a user interacts with a specific component. This can improve perceived performance and reduce the initial download size.
## 2. Common Patterns and Anti-patterns
### Design Patterns:
* **Dependency Injection (DI):** Use the built-in DI container to manage dependencies and promote loose coupling.
* **Repository Pattern:** Abstract data access logic behind repositories to improve testability and maintainability. Avoid exposing EF Core `IQueryable` outside of the repository.
* **Unit of Work Pattern:** Encapsulate multiple operations into a single transaction to ensure data consistency.
* **CQRS (Command Query Responsibility Segregation):** Separate read and write operations into separate models to optimize performance and scalability.
* **Mediator Pattern:** Decouple components by routing messages through a central mediator. Libraries like MediatR are excellent for this.
* **Specification Pattern:** Encapsulate complex query logic into reusable specification objects.
* **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable.
### Recommended Approaches for Common Tasks:
* **Configuration:** Use the `IOptions<T>` pattern to access configuration settings in a strongly-typed manner.
* **Logging:** Use the `ILogger<T>` interface for logging. Configure logging providers in `appsettings.json` and leverage structured logging.
* **Exception Handling:** Implement global exception handling middleware to handle unhandled exceptions and return appropriate error responses.
* **Data Validation:** Use data annotations and the `ModelState` property for validating user input. Implement custom validation attributes for complex validation rules.
* **Asynchronous Programming:** Use `async` and `await` for I/O-bound operations to avoid blocking threads.
* **HTTP Requests:** Utilize `HttpClientFactory` for creating and managing `HttpClient` instances.
* **Background Tasks:** Use hosted services or background worker services for running long-running tasks asynchronously.
### Anti-patterns and Code Smells:
* **Tight Coupling:** Avoid tight coupling between components. Use interfaces and dependency injection to promote loose coupling.
* **God Classes:** Avoid creating large classes with too many responsibilities. Break down large classes into smaller, more manageable classes.
* **Shotgun Surgery:** Avoid making changes to multiple classes when a single responsibility changes. This indicates poor separation of concerns.
* **Primitive Obsession:** Avoid using primitive types to represent domain concepts. Create value objects to encapsulate domain logic and validation rules.
* **Feature Envy:** Avoid classes that access the data of another class more than their own. Move the method to the class where the data resides.
* **Sync-over-Async:** Avoid using `Task.Wait()` or `Task.Result` in asynchronous methods, as this can lead to thread pool starvation. Always use `await`.
* **Ignoring Exceptions:** Avoid catching exceptions and not logging or handling them appropriately.
* **Magic Strings/Numbers:** Avoid hardcoding values directly in the code. Use constants or configuration settings instead.
* **Returning raw Entities:** Do not expose EF Core entities directly to the client. Create DTOs or View Models to represent the data that needs to be returned.
### State Management Best Practices:
* **Stateless Controllers:** Design controllers to be stateless. Avoid storing state in controller fields.
* **Session State:** Use session state sparingly. Session state can impact scalability. Consider using a distributed cache for session state.
* **Cookies:** Use cookies for storing small amounts of non-sensitive data. Be mindful of cookie size limits and security concerns.
* **TempData:** Use TempData for passing data between redirects. TempData is stored in session or cookies.
* **Caching:** Use caching (memory cache, distributed cache, response caching) to improve performance and reduce database load. Cache aggressively, but invalidate appropriately.
### Error Handling Patterns:
* **Global Exception Handling:** Implement global exception handling middleware to catch unhandled exceptions and return consistent error responses.
* **Exception Filters:** Use exception filters to handle exceptions at the controller level.
* **Try-Catch Blocks:** Use try-catch blocks for handling expected exceptions.
* **Problem Details:** Return problem details (RFC 7807) in error responses to provide more detailed information about the error.
* **Idempotency:** Design APIs to be idempotent where possible, so that retries are safe.
## 3. Performance Considerations
### Optimization Techniques:
* **Asynchronous Programming:** Use `async` and `await` for I/O-bound operations.
* **Caching:** Implement caching strategies to reduce database load and improve response times.
* **Response Compression:** Enable response compression to reduce the size of HTTP responses.
* **Minification and Bundling:** Minify and bundle CSS and JavaScript files to reduce the number of HTTP requests and improve load times.
* **Image Optimization:** Optimize images to reduce their file size without sacrificing quality.
* **Database Optimization:** Optimize database queries and indexing to improve data access performance.
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead.
* **HTTP/2:** Use HTTP/2 for improved performance and reduced latency.
* **Precompiled Views:** Precompile Razor views to improve startup time.
* **Use Span<T> and Memory<T>:** Utilize these types for efficient memory manipulation, reducing allocations and copies.
* **Object Pooling:** Employ object pooling for frequently created and destroyed objects to reduce garbage collection overhead. `ArrayPool<T>` is especially effective for large arrays.
* **Optimize LINQ Usage:** Use LINQ effectively, avoiding unnecessary iterations and allocations. Utilize `AsNoTracking()` for read-only queries and be mindful of client-side evaluation.
* **Use System.Text.Json:** Prefer `System.Text.Json` over `Newtonsoft.Json` where possible, as it offers better performance and is designed for UTF-8 text.
### Memory Management:
* **Minimize Object Allocations:** Reduce object allocations, especially in hot code paths. Consider using object pooling and value types.
* **Avoid Large Objects:** Avoid allocating large objects (>= 85,000 bytes) as they are stored on the large object heap and can cause performance issues.
* **Dispose of Resources:** Dispose of disposable resources (e.g., database connections, file streams) properly to prevent memory leaks.
* **Garbage Collection:** Understand how the garbage collector works and avoid patterns that trigger frequent garbage collections.
### Rendering Optimization:
* **Partial Views:** Use partial views to reuse code and reduce code duplication.
* **View Components:** Use view components to encapsulate complex rendering logic.
* **Tag Helpers:** Use tag helpers to create reusable UI components.
* **Client-Side Rendering:** Consider using client-side rendering frameworks (e.g., React, Angular, Vue.js) for complex UI interactions.
* **Lazy Loading:** Implement lazy loading for images and other assets to improve initial load time.
### Bundle Size Optimization:
* **Tree Shaking:** Use tree shaking to remove unused code from JavaScript bundles.
* **Code Splitting:** Split code into smaller chunks that can be loaded on demand.
* **Compression:** Compress JavaScript and CSS files using gzip or Brotli.
* **Dead Code Elimination:** Remove unused code from the application.
### Lazy Loading Strategies:
* **Lazy Loading of Images:** Load images only when they are visible in the viewport.
* **Lazy Loading of Modules:** Load modules only when they are needed.
* **Lazy Loading of Data:** Load data only when it is requested.
## 4. Security Best Practices
### Common Vulnerabilities and Prevention:
* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks.
* **Cross-Site Scripting (XSS):** Sanitize user input and encode output to prevent XSS attacks.
* **Cross-Site Request Forgery (CSRF):** Use anti-forgery tokens to prevent CSRF attacks.
* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data and functionality.
* **Clickjacking:** Protect against clickjacking attacks by using the X-Frame-Options header.
* **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
* **Open Redirects:** Validate redirect URLs to prevent open redirect vulnerabilities.
* **Insecure Direct Object References (IDOR):** Implement proper authorization checks to prevent unauthorized access to resources.
### Input Validation:
* **Server-Side Validation:** Always validate user input on the server-side.
* **Whitelisting:** Use whitelisting to allow only valid characters and data formats.
* **Data Annotations:** Use data annotations to validate model properties.
* **Custom Validation:** Implement custom validation attributes for complex validation rules.
* **Sanitization:** Sanitize user input to remove potentially harmful characters.
### Authentication and Authorization:
* **Authentication Schemes:** Choose an appropriate authentication scheme (e.g., cookies, JWT, OAuth2) based on the application requirements.
* **Authorization Policies:** Use authorization policies to define access control rules.
* **Role-Based Access Control (RBAC):** Implement RBAC to grant users access to specific resources based on their roles.
* **Claims-Based Authorization:** Use claims-based authorization to grant users access to specific resources based on their claims.
* **Secure Password Storage:** Use strong password hashing algorithms (e.g., bcrypt, Argon2) to store passwords securely.
* **Multi-Factor Authentication (MFA):** Implement MFA to enhance security.
* **Implement OWASP Recommendations:** Follow the OWASP (Open Web Application Security Project) guidelines for secure authentication and authorization.
### Data Protection:
* **Encryption:** Encrypt sensitive data at rest and in transit.
* **Data Protection API:** Use the Data Protection API to protect sensitive data.
* **Key Management:** Implement proper key management practices to protect encryption keys.
* **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
### Secure API Communication:
* **API Keys:** Use API keys to authenticate API clients.
* **OAuth 2.0:** Use OAuth 2.0 to authorize API clients.
* **JWT (JSON Web Tokens):** Use JWT for secure API authentication and authorization.
* **Rate Limiting:** Implement rate limiting to prevent API abuse.
* **Input Validation:** Implement proper input validation on the server-side to prevent injection attacks.
* **Output Encoding:** Encode API responses to prevent XSS attacks.
* **CORS (Cross-Origin Resource Sharing):** Configure CORS to allow only authorized domains to access the API.
## 5. Testing Approaches
### Unit Testing:
* **Test-Driven Development (TDD):** Write unit tests before writing the code.
* **Arrange, Act, Assert (AAA):** Follow the AAA pattern in unit tests.
* **Mocking:** Use mocking frameworks (e.g., Moq, NSubstitute) to isolate the code being tested.
* **Code Coverage:** Aim for high code coverage.
* **Focus on Business Logic:** Unit test the business logic of the application.
### Integration Testing:
* **Test Data Access:** Test the interaction between the application and the database.
* **Test External Services:** Test the interaction between the application and external services.
* **Use a Test Database:** Use a separate test database for integration tests.
* **Seed the Database:** Seed the test database with test data before running integration tests.
### End-to-End Testing:
* **Test the Entire Application Flow:** Test the entire application flow from the user interface to the database.
* **Use Automation Tools:** Use automation tools (e.g., Selenium, Cypress) to automate end-to-end tests.
* **Test in a Production-Like Environment:** Test in a production-like environment to ensure that the application works as expected in production.
### Test Organization:
* **Separate Test Projects:** Create separate test projects for unit tests, integration tests, and end-to-end tests.
* **Organize Tests by Feature:** Organize tests by feature or module.
* **Use Naming Conventions:** Use consistent naming conventions for test classes and methods.
### Mocking and Stubbing:
* **Use Mocking Frameworks:** Use mocking frameworks to create mock objects and stubs.
* **Mock Dependencies:** Mock external dependencies to isolate the code being tested.
* **Verify Interactions:** Verify that the code being tested interacts with its dependencies as expected.
* **Avoid Over-Mocking:** Avoid mocking too many dependencies. Focus on mocking external dependencies and complex objects.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes:
* **Incorrect Dependency Injection Configuration:** Incorrectly configuring dependency injection can lead to runtime errors.
* **Not Handling Exceptions Properly:** Not handling exceptions properly can lead to application crashes.
* **Blocking Calls:** Making blocking calls in asynchronous methods can lead to thread pool starvation.
* **Incorrect Data Validation:** Incorrect data validation can lead to security vulnerabilities and data corruption.
* **Over-Engineering:** Over-engineering the application can lead to unnecessary complexity.
* **Premature Optimization:** Optimizing the application too early can lead to wasted effort and code that is difficult to maintain.
* **Ignoring Security Best Practices:** Ignoring security best practices can lead to security vulnerabilities.
* **Not Writing Tests:** Not writing tests can lead to code that is difficult to maintain and prone to errors.
* **Leaking Database Connections:** Failing to properly dispose of database connections can exhaust connection resources and cause performance issues.
* **Using Sync over Async:** Blocking asynchronous operations can lead to thread pool starvation and performance degradation.
* **Not using HttpClientFactory correctly:** Improper disposal of `HttpClient` instances leads to socket exhaustion. Always use `HttpClientFactory`.
### Edge Cases:
* **Handling Null Values:** Handle null values properly to prevent null reference exceptions.
* **Handling Empty Collections:** Handle empty collections properly to prevent unexpected behavior.
* **Handling Large Data Sets:** Handle large data sets efficiently to prevent performance issues.
* **Handling Time Zones:** Handle time zones correctly to prevent data inconsistencies.
### Version-Specific Issues:
* **Breaking Changes:** Be aware of breaking changes between different versions of ASP.NET Core.
* **Deprecated Features:** Be aware of deprecated features and plan to migrate to newer features.
* **Performance Improvements:** Take advantage of performance improvements in newer versions of ASP.NET Core.
* **Security Patches:** Stay up-to-date with security patches to protect against vulnerabilities.
### Compatibility Concerns:
* **.NET Framework vs .NET Core:** Be aware of the differences between .NET Framework and .NET Core and choose the appropriate framework for the application.
* **Operating System Compatibility:** Ensure that the application is compatible with the target operating system.
* **Browser Compatibility:** Ensure that the application is compatible with the target browsers.
### Debugging Strategies:
* **Logging:** Use logging to track down errors and unexpected behavior.
* **Debugging Tools:** Use debugging tools (e.g., Visual Studio debugger) to step through the code and examine variables.
* **Profiling Tools:** Use profiling tools to identify performance bottlenecks.
* **Remote Debugging:** Use remote debugging to debug applications running on remote servers.
* **Diagnostic Tools:** Use diagnostic tools (e.g., Application Insights) to monitor the health and performance of the application.
## 7. Tooling and Environment
### Recommended Development Tools:
* **Visual Studio:** A comprehensive IDE for developing ASP.NET Core applications.
* **Visual Studio Code:** A lightweight and versatile code editor for developing ASP.NET Core applications.
* **.NET CLI:** A command-line tool for creating, building, and running ASP.NET Core applications.
* **NuGet Package Manager:** A package manager for managing dependencies in ASP.NET Core applications.
* **Postman:** A tool for testing APIs.
* **Fiddler:** A tool for debugging HTTP traffic.
### Build Configuration:
* **Use a Build Server:** Use a build server (e.g., Azure DevOps, Jenkins) to automate the build process.
* **Configure Build Configurations:** Configure build configurations (e.g., Debug, Release) to optimize the application for different environments.
* **Use NuGet Package Restore:** Use NuGet package restore to automatically download dependencies during the build process.
* **Version Control:** Use version control (e.g., Git) to track changes to the code.
### Linting and Formatting:
* **.editorconfig:** Use an .editorconfig file to define code style rules.
* **Code Analyzers:** Use code analyzers to enforce code style rules and detect potential errors.
* **StyleCop:** Use StyleCop to enforce coding style guidelines.
* **ReSharper:** Use ReSharper to improve code quality and productivity.
* **Format on Save:** Configure the IDE to format code on save.
### Deployment Best Practices:
* **Choose a Hosting Environment:** Choose an appropriate hosting environment (e.g., Azure, AWS, on-premises server) based on the application requirements.
* **Configure Application Settings:** Configure application settings (e.g., connection strings, API keys) for the production environment.
* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server.
* **Enable Logging:** Enable logging to track errors and unexpected behavior in the production environment.
* **Monitor the Application:** Monitor the health and performance of the application in the production environment.
* **Use a Deployment Pipeline:** Automate the deployment process with a CI/CD pipeline.
* **Consider Containerization:** Deploy your application using containers (e.g., Docker) to ensure consistency across environments.
* **Implement Health Checks:** Use ASP.NET Core's built-in health checks endpoint to monitor the health of your application.
### CI/CD Integration:
* **Use a CI/CD Pipeline:** Use a CI/CD pipeline (e.g., Azure DevOps, GitHub Actions, GitLab CI) to automate the build, test, and deployment process.
* **Automate Testing:** Automate unit tests, integration tests, and end-to-end tests in the CI/CD pipeline.
* **Automate Deployment:** Automate the deployment process in the CI/CD pipeline.
* **Implement Rollbacks:** Implement rollbacks to quickly revert to a previous version of the application if there are problems with the new deployment.
+168
View File
@@ -0,0 +1,168 @@
---
description: Comprehensive best practices and coding standards for Astro projects, including code organization, performance considerations, security, and testing.
globs: **/*.astro
---
- # Code Organization and Structure
- ## Directory Structure Best Practices
- `src/`: This is the heart of your Astro project.
- `components/`: Reusable UI elements. Organize components into subdirectories based on functionality or feature.
- `layouts/`: Components that define the overall page structure. Use a `BaseLayout.astro` to provide common elements like `<head>` and `<footer>`.
- `pages/`: Special components that create routes. Each file here becomes a page. Use dynamic routes (`[param].astro`) for data-driven content.
- `content/`: (Required for content collections) Store content collections and an optional `config.ts` or `config.js` file.
- `styles/`: Global CSS or Sass files. Use Astro's CSS Modules for component-specific styles.
- `scripts/`: JavaScript modules or utilities. Consider using TypeScript for type safety.
- `utils/`: Helper functions and utilities.
- `types/`: TypeScript type definitions for your project.
- `public/`: Static assets like images, fonts, and favicons. These are copied directly to the `dist/` folder without processing.
- `dist/`: (Generated) The output directory containing the built website. Usually ignored in version control.
- `node_modules/`: (Generated) Project dependencies managed by npm, pnpm or yarn. Usually ignored in version control.
- `.astro/`: (Generated) Internal Astro files. Should not be manually modified.
- ## File Naming Conventions
- **Components:** `ComponentName.astro` (PascalCase).
- **Pages:** `page-name.astro` (kebab-case). Index pages should be named `index.astro`.
- **Layouts:** `LayoutName.astro` (PascalCase).
- **Styles:** `Component.module.css` (component-specific), `global.css` (global styles).
- **Scripts:** `script-name.js` or `script-name.ts` (kebab-case).
- ## Module Organization
- Favor modularity and reusability.
- Group related components and functions into modules within the appropriate directory (e.g., `components/ui/Button.astro`).
- Use clear and descriptive names for files and folders.
- Expose only the necessary parts of a module using `export` and `import` statements.
- ## Component Architecture Recommendations
- **Atomic Design:** Consider using Atomic Design principles to create a scalable and maintainable component library (Atoms, Molecules, Organisms, Templates, Pages).
- **Composition:** Favor composition over inheritance.
- **Slots:** Utilize Astro's slots to create flexible components that accept dynamic content.
- **Props:** Use TypeScript to define prop types for your components.
- **Keep Components Focused:** A component should ideally handle a single responsibility.
- ## Code Splitting Strategies
- **Automatic Code Splitting:** Astro automatically code-splits JavaScript and CSS, so generally you don't need to manually handle code splitting.
- **Dynamic Imports:** Use dynamic imports (`import('./Component.astro')`) for components or modules that are not immediately needed. This is useful for infrequently used components or large libraries.
- **View Transitions:** Astro's View Transitions API also helps with perceived performance, providing smoother navigation between pages instead of full reloads. Optimize assets for transitions by using the `<Image>` component.
- # Common Patterns and Anti-patterns
- ## Design Patterns
- **Container/Presentational:** Separate data fetching and logic (container components) from UI rendering (presentational components).
- **Higher-Order Components (HOCs):** Use HOCs or render props (though less common in Astro) to share logic between components.
- **Provider Pattern:** Utilize Astro's `<script context="module">` to provide context values to all components within a scope.
- ## Recommended Approaches
- **Data Fetching:** Fetch data in `<script>` tags inside Astro components using `fetch` or other HTTP libraries. Use `await` to handle asynchronous operations.
- **State Management:** Astro favors a simpler approach with props and events for most use cases. For complex state management, consider using tools like nanostores, zustand or redux if needed.
- **Component Communication:** Pass data down through props. For event handling, use standard JavaScript event listeners and dispatch custom events if needed.
- ## Anti-patterns
- **Mutating Props:** Avoid directly mutating props passed to a component.
- **Over-Complicated State Management:** Don't introduce complex state management libraries unless absolutely necessary.
- **Large Components:** Break down large components into smaller, more manageable pieces.
- **Inline Styles:** Avoid inline styles. Use CSS Modules or global CSS files instead.
- ## State Management Best Practices
- **Local Component State:** Use `Astro.props` for simple local state within a component.
- **Global State (If Needed):** For application-wide state, consider lightweight state management libraries such as nanostores.
- **Avoid Overusing State:** Not every value needs to be reactive state. Consider the complexity trade-off.
- ## Error Handling
- **Try/Catch:** Use `try...catch` blocks to handle errors during data fetching or other asynchronous operations.
- **Error Boundaries (Components):** Create dedicated components to catch errors and display fallback UI.
- **Centralized Logging:** Implement a centralized logging system to track errors in production.
- # Performance Considerations
- ## Optimization Techniques
- **Image Optimization:** Use Astro's `<Image>` component for automatic image optimization (resizing, format conversion, lazy loading).
- **Font Optimization:** Use `font-display: swap;` in your CSS to prevent blocking render when loading web fonts.
- **Minification and Bundling:** Astro automatically minifies and bundles CSS and JavaScript during the build process.
- **Remove Unused CSS:** Use tools like PurgeCSS to remove unused CSS from your stylesheets, improving performance.
- **Partial Hydration:** Use Astro's directives (e.g., `client:load`, `client:idle`) to control when components are hydrated, reducing JavaScript overhead.
- ## Memory Management
- **Avoid Memory Leaks:** Be mindful of memory leaks, especially in long-running applications. Properly clean up event listeners and resources when components unmount.
- **Efficient Data Structures:** Choose appropriate data structures for your application's needs.
- ## Rendering Optimization
- **Static Rendering:** Astro favors static rendering, which delivers the fastest possible performance.
- **Server-Side Rendering (SSR):** Use SSR only when necessary for dynamic content or features that require server-side processing.
- **Client-Side Rendering (CSR):** Minimize client-side rendering to improve initial page load time.
- ## Bundle Size Optimization
- **Lazy Loading:** Use lazy loading for images and other assets that are not immediately visible on the page.
- **Tree Shaking:** Astro's build process automatically performs tree shaking to remove unused code from your JavaScript bundles.
- **Code Splitting:** Astro automatically splits your code into smaller chunks, which can improve performance by reducing the amount of code that needs to be downloaded initially.
- ## Lazy Loading Strategies
- **Images:** Use the `loading="lazy"` attribute on `<img>` tags or use the Astro `<Image>` component to automatically lazy load images.
- **Components:** Use dynamic imports to lazy load components that are not immediately needed.
- **Libraries:** Import libraries only when they are needed, using dynamic imports if necessary.
- # Security Best Practices
- ## Common Vulnerabilities
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and escaping output.
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
- **SQL Injection:** Protect against SQL injection attacks by using parameterized queries or an ORM.
- **Man-in-the-Middle (MitM) Attacks:** Use HTTPS to encrypt communication between the client and server.
- ## Input Validation
- **Server-Side Validation:** Always validate user input on the server-side.
- **Client-Side Validation:** Use client-side validation for immediate feedback to the user, but never rely on it as the sole means of validation.
- **Escape Output:** Escape user-provided data when rendering it to prevent XSS.
- ## Authentication and Authorization
- **Use Secure Authentication:** Use a secure authentication mechanism, such as OAuth 2.0 or JWT.
- **Implement Role-Based Access Control (RBAC):** Restrict access to resources based on user roles.
- **Protect API Endpoints:** Require authentication for all API endpoints that require authorization.
- ## Data Protection
- **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
- **Use Strong Passwords:** Enforce strong password policies.
- **Regularly Back Up Data:** Regularly back up your data in case of data loss or corruption.
- ## Secure API Communication
- **Use HTTPS:** Always use HTTPS to encrypt communication between the client and server.
- **Validate API Responses:** Validate API responses to ensure that they are in the expected format.
- **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
- # Testing Approaches
- ## Unit Testing
- **Test Individual Components:** Test individual components in isolation to ensure that they are working correctly.
- **Mock Dependencies:** Use mocking to isolate components from their dependencies.
- **Assertion Libraries:** Use assertion libraries like Jest or Chai to assert that components are behaving as expected.
- ## Integration Testing
- **Test Component Interactions:** Test the interactions between components to ensure that they are working together correctly.
- **Test Data Flow:** Test the flow of data through your application to ensure that data is being passed correctly between components.
- ## End-to-End Testing
- **Test User Flows:** Test user flows to ensure that users can complete tasks successfully.
- **Automate Tests:** Automate end-to-end tests to ensure that your application is working correctly after changes are made.
- ## Test Organization
- **Locate tests near components:** Keep test files close to the components being tested (e.g. `src/components/MyComponent.test.astro`).
- **Consistent naming:** Use a consistent naming convention for test files (e.g., `MyComponent.test.astro` or `MyComponent.spec.astro`).
- ## Mocking and Stubbing
- **Mock API calls:** Mock API calls to isolate components from the backend.
- **Stub External Dependencies:** Stub external dependencies to control their behavior during testing.
- **Use testing libraries:** Utilize testing libraries such as `jest`, `vitest`, or `mocha` for mocking and stubbing.
- # Common Pitfalls and Gotchas
- ## Frequent Mistakes
- **Over-reliance on Client-Side JavaScript:** Remember Astro's focus on minimal JS. Avoid hydrating components unless necessary.
- **Incorrect Component Hydration Directives:** Double-check `client:` directives to make sure components are hydrated at the correct time.
- **Ignoring Performance Metrics:** Pay attention to performance metrics like Lighthouse scores and bundle sizes.
- ## Edge Cases
- **View Transitions with Complex Animations:** Complex animations may need special handling with Astro's View Transitions API.
- **Integrating with Third-Party Libraries:** Some third-party libraries may require custom integration due to Astro's build process.
- ## Version-Specific Issues
- Refer to the Astro documentation and release notes for any version-specific issues or breaking changes.
- ## Compatibility Concerns
- Be aware of compatibility concerns when integrating with other technologies, such as backend frameworks or CMS systems.
- ## Debugging Strategies
- **Browser Developer Tools:** Use browser developer tools to inspect HTML, CSS, and JavaScript.
- **Astro Dev Toolbar:** Take advantage of Astro's built-in Dev Toolbar for component inspection and debugging.
- **Console Logging:** Strategically use `console.log` statements to debug your code.
- **Debugging in VS Code:** Configure VS Code for debugging Astro applications.
- # Tooling and Environment
- ## Recommended Development Tools
- **VS Code:** Use VS Code with the official Astro extension for syntax highlighting, code completion, and other features.
- **ESLint:** Configure ESLint with the `eslint-plugin-astro` plugin to lint Astro components.
- **Prettier:** Use Prettier to automatically format your code.
- **EditorConfig:** Use EditorConfig to maintain consistent code style across different editors.
- ## Build Configuration
- **astro.config.mjs:** Configure your Astro project in the `astro.config.mjs` file.
- **Environment Variables:** Use environment variables to configure your application for different environments.
- ## Linting and Formatting
- **ESLint:** Configure ESLint with the recommended rules for Astro projects.
- **Prettier:** Configure Prettier with the recommended options for Astro projects.
- **Husky and Lint-Staged:** Use Husky and Lint-Staged to automatically lint and format your code before committing.
- ## Deployment Best Practices
- **Choose a Deployment Platform:** Choose a deployment platform that is compatible with Astro, such as Netlify, Vercel, or Cloudflare Pages.
- **Configure Build Settings:** Configure your build settings to optimize your application for production.
- **Use a CDN:** Use a CDN to serve your static assets.
- **Optimize Images:** Optimize images for web performance.
- ## CI/CD Integration
- **GitHub Actions:** Use GitHub Actions or other CI/CD tools to automate your build, test, and deployment processes.
- **Automated Testing:** Run automated tests during your CI/CD pipeline to ensure that your application is working correctly before it is deployed.
+371
View File
@@ -0,0 +1,371 @@
---
description: This rule provides comprehensive guidelines and best practices for utilizing the asyncio library in Python, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.py
---
# asyncio Best Practices and Coding Standards
This document outlines comprehensive best practices for using the `asyncio` library in Python. It covers various aspects of asyncio development, including code organization, common patterns, performance considerations, security, testing, common pitfalls, and tooling.
## Library Information:
- Name: asyncio
- Tags: python, async, standard-library
## 1. Code Organization and Structure
Effective code organization is crucial for maintainability and scalability when working with asyncio.
### 1.1 Directory Structure Best Practices
A well-defined directory structure helps in organizing different parts of your asyncio application.
project_root/
├── src/
│ ├── __init__.py
│ ├── main.py # Entry point of the application
│ ├── modules/
│ │ ├── __init__.py
│ │ ├── networking.py # Handles networking tasks
│ │ ├── processing.py # Data processing tasks
│ │ └── utils.py # Utility functions
│ ├── config.py # Configuration settings
├── tests/
│ ├── __init__.py
│ ├── test_networking.py
│ ├── test_processing.py
│ └── conftest.py # Fixtures and configuration for pytest
├── requirements.txt # Project dependencies
├── pyproject.toml # Project metadata and build system
├── README.md # Project documentation
### 1.2 File Naming Conventions
Consistent file naming conventions enhance readability and maintainability.
- Use descriptive names that reflect the module's purpose.
- Prefer lowercase with underscores (snake_case) for file names (e.g., `async_utils.py`, `data_handler.py`).
- Test files should follow the `test_*.py` pattern for pytest compatibility.
### 1.3 Module Organization
Divide your code into logical modules based on functionality.
- Group related functions and classes within the same module.
- Use `__init__.py` files to make directories into Python packages.
- Employ relative imports for internal modules (`from . import utils`).
- Use absolute imports for external libraries (`import aiohttp`).
python
# src/modules/networking.py
import asyncio
import aiohttp
async def fetch_data(url: str) -> str:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
### 1.4 Component Architecture Recommendations
Consider using a layered architecture to separate concerns.
- **Presentation Layer**: Handles user interface or API endpoints.
- **Service Layer**: Contains business logic and orchestrates tasks.
- **Data Access Layer**: Manages data persistence and retrieval.
- **Infrastructure Layer**: Provides supporting services like logging and configuration.
### 1.5 Code Splitting Strategies
Split large modules into smaller, more manageable files.
- Use functions and classes to encapsulate specific tasks.
- Consider splitting modules based on logical boundaries (e.g., one module for database interactions, another for API calls).
- Refactor complex coroutines into smaller, reusable coroutines.
## 2. Common Patterns and Anti-patterns
Understanding common patterns and anti-patterns helps in writing efficient and maintainable asyncio code.
### 2.1 Design Patterns Specific to asyncio
- **Producer-Consumer**: Use `asyncio.Queue` to manage tasks between producers and consumers.
- **Worker Pool**: Create a pool of worker coroutines to process tasks concurrently.
- **Pub-Sub**: Implement a publish-subscribe pattern using queues or custom event handling.
#### Producer-Consumer Example
python
import asyncio
async def producer(queue: asyncio.Queue, data: list):
for item in data:
await queue.put(item)
print(f"Produced: {item}")
await queue.put(None) # Signal end of production
async def consumer(queue: asyncio.Queue):
while True:
item = await queue.get()
if item is None:
break
print(f"Consumed: {item}")
queue.task_done()
async def main():
queue = asyncio.Queue()
data = [1, 2, 3, 4, 5]
producer_task = asyncio.create_task(producer(queue, data))
consumer_task = asyncio.create_task(consumer(queue))
await asyncio.gather(producer_task, consumer_task)
if __name__ == "__main__":
asyncio.run(main())
### 2.2 Recommended Approaches for Common Tasks
- **Making HTTP Requests**: Use `aiohttp` for non-blocking HTTP requests.
- **Reading/Writing Files**: Use `aiofiles` for asynchronous file I/O.
- **Database Operations**: Utilize async database drivers like `aiopg` or `asyncpg`.
- **Task Scheduling**: Use `asyncio.create_task` or `asyncio.gather` to manage concurrent tasks.
### 2.3 Anti-patterns and Code Smells to Avoid
- **Blocking Calls**: Avoid using blocking functions like `time.sleep` or `requests` in coroutines. Use `asyncio.sleep` and `aiohttp` instead.
- **Long-Running Coroutines**: Break down long-running coroutines into smaller, awaitable chunks to avoid blocking the event loop.
- **Ignoring Exceptions**: Always handle exceptions properly to prevent unexpected crashes.
- **Over-using Locks**: Excessive use of locks can reduce concurrency. Consider using queues or other synchronization primitives.
- **Unnecessary Context Switching**: Minimize context switches by optimizing code and reducing unnecessary `await` calls.
### 2.4 State Management Best Practices
- **Immutable Data**: Prefer immutable data structures to avoid race conditions.
- **Thread-Safe Data Structures**: Use thread-safe data structures from the `queue` or `collections` modules when sharing data between coroutines.
- **Avoid Global State**: Minimize the use of global state to reduce complexity and potential conflicts.
### 2.5 Error Handling Patterns
- **Try-Except Blocks**: Use `try-except` blocks to catch and handle exceptions within coroutines.
- **`asyncio.gather(..., return_exceptions=True)`**: Use `return_exceptions=True` in `asyncio.gather` to prevent one exception from canceling other tasks.
- **Logging Errors**: Log exceptions with detailed information for debugging purposes.
- **Graceful Shutdown**: Implement a mechanism to gracefully shut down the application and release resources.
python
import asyncio
import logging
async def my_coroutine(value):
try:
if value < 0:
raise ValueError("Value must be non-negative")
await asyncio.sleep(1)
return value * 2
except ValueError as e:
logging.error(f"Error processing {value}: {e}")
return None
async def main():
results = await asyncio.gather(
my_coroutine(5), my_coroutine(-1), my_coroutine(10), return_exceptions=True
)
print(f"Results: {results}")
if __name__ == "__main__":
logging.basicConfig(level=logging.ERROR)
asyncio.run(main())
## 3. Performance Considerations
Optimizing performance is critical for asyncio applications.
### 3.1 Optimization Techniques
- **Minimize I/O Operations**: Reduce the number of I/O operations by batching requests or caching data.
- **Use Efficient Data Structures**: Choose appropriate data structures for specific tasks (e.g., dictionaries for fast lookups).
- **Avoid Unnecessary Copying**: Minimize copying data to reduce memory usage and improve performance.
- **Profile Your Code**: Use profiling tools to identify performance bottlenecks.
- **Use `uvloop`**: Consider using `uvloop`, a fast, drop-in replacement for the default asyncio event loop.
python
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
print("Using uvloop")
except ImportError:
print("uvloop not installed, using default asyncio loop")
### 3.2 Memory Management
- **Resource Management**: Properly release resources (e.g., file handles, database connections) when they are no longer needed.
- **Use Generators**: Use generators to process large datasets in chunks.
- **Limit Object Creation**: Reduce the creation of unnecessary objects to minimize memory overhead.
### 3.3 Lazy Loading Strategies
- **Import on Demand**: Import modules only when they are needed to reduce startup time.
- **Load Data Lazily**: Load data only when it is accessed to reduce initial memory usage.
## 4. Security Best Practices
Securing asyncio applications is essential for protecting against vulnerabilities.
### 4.1 Common Vulnerabilities and Prevention
- **Injection Attacks**: Sanitize user inputs to prevent SQL injection, command injection, and other injection attacks.
- **Cross-Site Scripting (XSS)**: Encode user-generated content to prevent XSS attacks.
- **Denial of Service (DoS)**: Implement rate limiting and input validation to prevent DoS attacks.
- **Man-in-the-Middle (MitM) Attacks**: Use TLS/SSL for secure communication to prevent MitM attacks.
### 4.2 Input Validation
- **Validate All Inputs**: Validate all user inputs and data received from external sources.
- **Use Regular Expressions**: Use regular expressions to validate input formats.
- **Limit Input Length**: Restrict the length of input fields to prevent buffer overflows.
### 4.3 Authentication and Authorization
- **Use Strong Authentication**: Implement strong authentication mechanisms (e.g., multi-factor authentication).
- **Implement Authorization**: Implement authorization checks to ensure users only have access to authorized resources.
- **Store Passwords Securely**: Hash passwords using strong hashing algorithms (e.g., bcrypt or Argon2).
- **Use JWTs**: Employ JSON Web Tokens (JWTs) for stateless authentication.
### 4.4 Data Protection Strategies
- **Encrypt Sensitive Data**: Encrypt sensitive data at rest and in transit.
- **Use Secure Protocols**: Use secure protocols (e.g., HTTPS, SSH) for communication.
- **Regularly Audit Security**: Conduct regular security audits to identify and address vulnerabilities.
### 4.5 Secure API Communication
- **Use HTTPS**: Always use HTTPS for API communication.
- **Validate API Responses**: Validate API responses to ensure data integrity.
- **Implement Rate Limiting**: Implement rate limiting to prevent abuse.
## 5. Testing Approaches
Testing is crucial for ensuring the reliability of asyncio applications.
### 5.1 Unit Testing Strategies
- **Test Coroutines in Isolation**: Use `asyncio.run` or `pytest-asyncio` to test coroutines in isolation.
- **Mock External Dependencies**: Use mocking libraries like `unittest.mock` to mock external dependencies.
- **Assert Expected Outcomes**: Use assertions to verify expected outcomes and error conditions.
### 5.2 Integration Testing
- **Test Interactions Between Components**: Test interactions between different components of the application.
- **Use Real Dependencies**: Use real dependencies (e.g., databases, APIs) in a controlled environment.
### 5.3 End-to-End Testing
- **Simulate Real User Scenarios**: Simulate real user scenarios to test the entire application flow.
- **Use Test Automation Frameworks**: Use test automation frameworks like Selenium or Playwright.
### 5.4 Test Organization
- **Organize Tests by Module**: Organize tests into separate files that correspond to the application modules.
- **Use Descriptive Test Names**: Use descriptive test names that clearly indicate what is being tested.
### 5.5 Mocking and Stubbing Techniques
- **Mock Asynchronous Functions**: Use `asyncio.iscoroutinefunction` to check if a function is a coroutine before mocking it.
- **Patch External Dependencies**: Use `unittest.mock.patch` to replace external dependencies with mock objects.
- **Use Asynchronous Mocks**: Use asynchronous mocks to simulate asynchronous behavior.
python
import asyncio
import unittest.mock
import pytest
async def fetch_data(url: str) -> str:
# This is just a placeholder; in real code, it would use aiohttp
await asyncio.sleep(0.1) # Simulate I/O delay
return f"Data from {url}"
@pytest.mark.asyncio
async def test_fetch_data():
with unittest.mock.patch("__main__.fetch_data") as mock_fetch_data:
mock_fetch_data.return_value = "Mocked data"
result = await fetch_data("http://example.com")
assert result == "Mocked data"
mock_fetch_data.assert_called_once_with("http://example.com")
## 6. Common Pitfalls and Gotchas
Being aware of common pitfalls helps in avoiding mistakes when using asyncio.
### 6.1 Frequent Mistakes
- **Mixing Synchronous and Asynchronous Code**: Avoid mixing synchronous and asynchronous code in the same coroutine.
- **Forgetting to Await**: Ensure that you `await` all awaitable objects.
- **Blocking the Event Loop**: Avoid blocking the event loop with long-running synchronous operations.
- **Ignoring Task Cancellation**: Handle task cancellation properly to prevent resource leaks.
- **Not Handling Exceptions**: Always handle exceptions properly to prevent unexpected crashes.
### 6.2 Edge Cases
- **Task Timeouts**: Implement task timeouts to prevent tasks from running indefinitely.
- **Resource Limits**: Set resource limits (e.g., maximum number of connections) to prevent resource exhaustion.
- **Signal Handling**: Handle signals (e.g., SIGINT, SIGTERM) to gracefully shut down the application.
### 6.3 Version-Specific Issues
- **asyncio API Changes**: Be aware of API changes between different versions of asyncio.
- **Python 3.7+**: Use Python 3.7 or later to take advantage of the latest asyncio features (e.g., `asyncio.run`).
### 6.4 Compatibility Concerns
- **Third-Party Libraries**: Ensure that third-party libraries are compatible with asyncio.
- **Event Loop Implementations**: Be aware of compatibility issues between different event loop implementations (e.g., `uvloop`).
### 6.5 Debugging Strategies
- **Enable Debug Mode**: Enable asyncio debug mode to get more detailed information about tasks and coroutines.
- **Use Logging**: Use logging to track the execution flow and identify potential issues.
- **Use Debuggers**: Use debuggers like `pdb` or IDE-integrated debuggers to step through code and inspect variables.
- **Inspect Task State**: Inspect the state of tasks using `asyncio.Task.all_tasks()` to identify stuck or failing tasks.
## 7. Tooling and Environment
Using the right tools and environment can greatly improve the development experience.
### 7.1 Recommended Development Tools
- **IDE**: Use an IDE like VS Code, PyCharm, or Sublime Text with Python support.
- **Linters**: Use linters like `flake8` or `pylint` to enforce coding standards.
- **Formatters**: Use formatters like `black` or `autopep8` to automatically format code.
- **Debuggers**: Use debuggers like `pdb` or IDE-integrated debuggers to step through code and inspect variables.
### 7.2 Build Configuration
- **Use `pyproject.toml`**: Configure the project using a `pyproject.toml` file to specify build dependencies and settings.
- **Specify Dependencies**: Specify project dependencies in `requirements.txt` or `pyproject.toml`.
- **Use Virtual Environments**: Use virtual environments to isolate project dependencies.
### 7.3 Linting and Formatting
- **Configure Linters**: Configure linters to enforce coding standards (e.g., PEP 8).
- **Configure Formatters**: Configure formatters to automatically format code.
- **Use Pre-commit Hooks**: Use pre-commit hooks to automatically run linters and formatters before committing code.
### 7.4 Deployment Best Practices
- **Use a Production-Ready Event Loop**: Use a production-ready event loop like `uvloop`.
- **Use a Process Manager**: Use a process manager like systemd or Supervisor to manage the application process.
- **Use a Load Balancer**: Use a load balancer to distribute traffic across multiple instances of the application.
- **Monitor Application Health**: Monitor the application's health and performance using metrics and alerts.
### 7.5 CI/CD Integration
- **Automate Tests**: Automate unit, integration, and end-to-end tests in the CI/CD pipeline.
- **Automate Linting and Formatting**: Automate linting and formatting in the CI/CD pipeline.
- **Automate Deployment**: Automate deployment to production environments.
By adhering to these best practices, you can build robust, efficient, and maintainable asyncio applications in Python.
+195
View File
@@ -0,0 +1,195 @@
---
description: This rule provides comprehensive guidance for Auth0 library usage, covering code organization, security, performance, testing, and common pitfalls. Adhering to these guidelines ensures secure, efficient, and maintainable Auth0 integrations.
globs: **/*.{js,jsx,ts,tsx,html,css,scss,py,java,go}
---
---
# Auth0 Best Practices and Coding Standards
This document outlines best practices for working with Auth0 to ensure secure, efficient, and maintainable authentication and authorization in your applications.
## Library Information:
- Name: Auth0
- Tags: authentication, security, identity, SaaS
## 1. Code Organization and Structure:
- **Directory Structure:**
- Adopt a modular structure. For example:
src/
auth/
auth0.config.js # Auth0 configuration
auth0.service.js # Authentication and authorization logic
components/
login.jsx # Login component
profile.jsx # User profile component
utils/
auth.helper.js # Helper functions for authentication
components/
... other application components
- **File Naming Conventions:**
- Use descriptive names. Example: `auth0.config.js`, `AuthService.ts`, `LoginButton.jsx`.
- Follow a consistent naming convention (e.g., camelCase for JavaScript, PascalCase for React components).
- **Module Organization:**
- Group related Auth0 logic into modules. Avoid placing all Auth0-related code in a single, monolithic file.
- Use dependency injection to decouple Auth0 modules from other parts of your application.
- **Component Architecture (if applicable, e.g., React, Angular, Vue):**
- Create dedicated components for authentication-related UI elements (login buttons, profile displays, etc.).
- Separate concerns: keep UI components focused on rendering and delegate authentication logic to a separate service or module.
- **Code Splitting:**
- For large applications, consider lazy-loading Auth0-related code to improve initial load time.
- Implement code splitting at the route level, loading authentication modules only when necessary.
## 2. Common Patterns and Anti-patterns:
- **Design Patterns:**
- **Adapter Pattern:** Use an adapter to abstract the underlying Auth0 SDK and provide a consistent API for your application.
- **Singleton Pattern:** Ensure that only one instance of the Auth0 client is created.
- **Observer Pattern:** Use an observer pattern to notify components when the authentication state changes.
- **Recommended Approaches for Common Tasks:**
- **Authentication:** Use the Auth0 SDK to handle authentication flows (login, logout, password reset).
- **Authorization:** Implement role-based access control (RBAC) using Auth0's authorization features.
- **User Profile Management:** Leverage Auth0's user profile management features to store and retrieve user information.
- **Token Handling:** Securely store and manage access tokens and refresh tokens. Consider using HttpOnly cookies or secure storage mechanisms.
- **Anti-patterns and Code Smells:**
- **Hardcoding Credentials:** Never hardcode Auth0 credentials (Client ID, Client Secret) directly in your code. Use environment variables or secure configuration files.
- **Exposing Sensitive Data:** Avoid exposing sensitive user data (e.g., access tokens) in the client-side code or URLs.
- **Ignoring Error Handling:** Implement robust error handling to catch and handle authentication errors gracefully.
- **Overly Complex Rules/Actions:** Keep Auth0 Rules and Actions simple and focused. Delegate complex logic to external services.
- **Storing Secrets in Rules Code:** Don't store sensitive keys or credentials directly in the Rule code. Use the rule settings and the configuration object instead.
- **State Management:**
- Utilize context API, Redux, Zustand, or similar state management libraries to manage the user's authentication state (e.g., isLoggedIn, user profile).
- Ensure the authentication state is persisted across page reloads (e.g., using localStorage or sessionStorage).
- **Error Handling:**
- Use try-catch blocks to handle potential errors during authentication and authorization.
- Log errors to a central logging service for monitoring and debugging.
- Display user-friendly error messages to the user.
## 3. Performance Considerations:
- **Optimization Techniques:**
- **Caching:** Cache user profiles and access tokens to reduce the number of calls to Auth0.
- **Token Reuse:** Reuse existing access tokens whenever possible.
- **Minimize Data Transfer:** Only request the necessary user profile information from Auth0.
- **Memory Management:**
- Release resources (e.g., timers, event listeners) when they are no longer needed.
- Avoid creating unnecessary objects during authentication and authorization.
- **Rendering Optimization (if applicable):**
- Use techniques like memoization and virtualization to optimize the rendering of authentication-related UI components.
- **Bundle Size Optimization:**
- Use tree shaking to remove unused Auth0 code from the final bundle.
- Consider using a smaller alternative to the full Auth0 SDK if possible.
- **Lazy Loading:**
- Lazy load Auth0 modules and components to improve initial page load time.
## 4. Security Best Practices:
- **Common Vulnerabilities and Prevention:**
- **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens.
- **Token Theft:** Securely store and manage access tokens to prevent token theft.
- **Injection Attacks:** Prevent injection attacks by validating and sanitizing all user inputs.
- **Input Validation:**
- Validate all user inputs to prevent malicious data from being processed.
- Use a validation library to simplify the input validation process.
- **Authentication and Authorization:**
- Use the Auth0 SDK for authentication and authorization.
- Implement role-based access control (RBAC) using Auth0's authorization features.
- Enforce multi-factor authentication (MFA) to enhance security.
- Regularly review security settings, enable breach detection features, and utilize logging to monitor authentication events for any suspicious activities.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS for all communications.
- Protect API keys and other sensitive credentials.
- **Secure API Communication:**
- Always use HTTPS for all communications to protect sensitive data during transmission.
- Store sensitive information, like API keys, in the Auth0 rule settings instead of hardcoding them directly in your code to prevent exposure.
- Avoid sending the entire context object to external services. Send only a subset of the less sensitive attributes from the context object when and where necessary. In a similar fashion, avoid passing any aspect of the auth0 object outside of a rule.
## 5. Testing Approaches:
- **Unit Testing:**
- Write unit tests for Auth0-related modules and components.
- Mock the Auth0 SDK to isolate the code being tested.
- Test different authentication scenarios (successful login, failed login, password reset).
- **Integration Testing:**
- Integrate Auth0 with your application and test the entire authentication flow.
- Use a test Auth0 tenant for integration testing.
- Verify that authentication and authorization work as expected.
- **End-to-End Testing:**
- Use end-to-end testing frameworks (e.g., Cypress, Selenium) to test the entire application from the user's perspective.
- Simulate user interactions and verify that authentication works correctly.
- **Test Organization:**
- Organize tests into separate directories based on the modules or components being tested.
- Use descriptive test names to clearly indicate the purpose of each test.
- **Mocking and Stubbing:**
- Use mocking libraries (e.g., Jest, Mocha) to mock the Auth0 SDK and other external dependencies.
- Use stubbing to replace external dependencies with predefined values.
## 6. Common Pitfalls and Gotchas:
- **Frequent Mistakes:**
- Forgetting to configure the callback URL in the Auth0 dashboard.
- Incorrectly configuring the allowed logout URLs.
- Failing to handle authentication errors gracefully.
- Storing sensitive data in client-side code.
- Not enabling multi-factor authentication (MFA).
- **Edge Cases:**
- Handling expired access tokens.
- Dealing with network connectivity issues.
- Supporting different browsers and devices.
- Managing user sessions.
- **Version-Specific Issues:**
- Be aware of breaking changes in Auth0 SDK updates.
- Refer to the Auth0 documentation for migration guides.
- **Compatibility Concerns:**
- Ensure that the Auth0 SDK is compatible with the other technologies used in your application.
- Test the integration with different browsers and devices.
- **Debugging:**
- Use the Auth0 logs to troubleshoot authentication issues.
- Use browser developer tools to inspect network requests and responses.
- Set breakpoints in your code to debug authentication logic.
## 7. Tooling and Environment:
- **Recommended Tools:**
- Auth0 CLI: For managing Auth0 tenants and applications.
- Auth0 Management API: For programmatically managing Auth0 resources.
- Auth0 SDKs: For integrating Auth0 into your applications.
- Postman or Insomnia: For testing API endpoints.
- **Build Configuration:**
- Use a build tool (e.g., Webpack, Parcel, Rollup) to bundle your application.
- Configure the build tool to use tree shaking to remove unused Auth0 code.
- Minify the code to reduce the bundle size.
- **Linting and Formatting:**
- Use a linter (e.g., ESLint, JSHint) to enforce code style and prevent errors.
- Use a code formatter (e.g., Prettier) to automatically format your code.
- **Deployment:**
- Deploy your Auth0 configuration to production using the Auth0 CLI or Management API.
- Use environment variables to configure your application for different environments.
- Monitor the application for errors and performance issues.
- **CI/CD Integration:**
- Integrate Auth0 deployment into your CI/CD pipeline.
- Use automated tests to verify the integration before deploying to production.
## Additional Best Practices:
* **Use Identity Industry Standards:** Use OAuth 2.0 and OpenID Connect for interoperability and compliance.
* **Regularly Review Security Settings:** Enable breach detection and anomaly detection features. Configure rate limits to protect against brute force attacks.
* **Store Configuration Values in the Dashboard:** If your Actions, Rules, Hooks, custom database scripts, or Webtasks require configuration values (such as credentials or API keys), store them in the Auth0 Dashboard. This makes migrating configuration between tenants easier.
* **Add Auth0 Public IP Addresses to Allow List:** If your Actions, Rules, Hooks, custom database scripts, or Webtasks call a service in your intranet or behind another firewall, be sure to add the Auth0 public IP addresses to the Allow List. This lets requests from those IP addresses through.
* **Run Tenant Configuration Checks:** The Auth0 Support Center provides a configuration checker tool. Run the configuration checker periodically during development and again before you launch. To run the configuration check, go to Auth0 Support Center > Tenants, select the gear icon, and choose Run Production Check.
* **Contextual bypass for Multi-Factor Authentication (MFA):** As a recommended best practice, use of allowRememberBrowser or context.authentication should be the only options considered for contextual bypass when using out-of-box MFA.
* **Passwordless Connections:** Enable passwordless login using email or SMS for improved user experience.
* **Custom Domains:** Use a custom domain (example: auth.yourcompany.com) for branding and consistent user experience.
* **Regularly Review User Accounts and Roles:** Remove inactive accounts and update permissions as needed.
* **Software Updates:** Keep your Auth0 SDKs and libraries up to date to ensure you benefit from the latest security patches and features.
* **Continuous Monitoring:** Continuously monitor authentication logs and respond to any anomalies or security incidents.
* **Always use HTTPS:** Always use HTTPS, not HTTP, when making calls to external services or when executing redirect as part of your rule implementation.
* **Check if an email is verified:** Check to see if a user's email address is verified in a rule
* **Check for exact string matches:** For rules that determine access control based on a particular string, such as an email domain, check for an exact string match instead of checking for a substring match.
By following these best practices, you can build secure, scalable, and maintainable applications with Auth0.
+166
View File
@@ -0,0 +1,166 @@
---
description: Provides coding standards, best practices, and guidance specific to the AutoGen library, covering aspects from code structure to security and performance.
globs: **/*.py
---
- Best practice 1: Employ Modular Design. Utilize AutoGen's multi-agent framework to create modular agents with specific roles. This enhances code reusability and simplifies the orchestration of complex workflows. Example: Create separate agents for data fetching, code execution, and response formatting.
- Best practice 2: Define Customizable Workflows. Leverage AutoGen's capabilities to define customizable workflows that integrate LLMs, human inputs, and tools. This allows for flexible agent interactions and enhances the performance of LLM applications. Implement a workflow manager to define and control agent interactions.
- Best practice 3: Ensure Code Quality and Consistency. Implement automatic code formatting and linting features provided by AutoGen to ensure consistent coding styles and practices. This reduces human error in code generation and maintains high code quality. Integrate linters like `pylint` or `flake8` in your CI/CD pipeline.
- Best practice 4: Integrate Human Feedback. Incorporate a Human Proxy Agent to facilitate human feedback in the workflow, ensuring that the AI systems remain aligned with user expectations and can adapt based on real-world input. Use AutoGen's `HumanProxyAgent` to gather and incorporate human feedback in the loop.
- Best practice 5: Use UV for dependency management for faster and more reliable installations.
- Best practice 6: Always use the latest stable version of Python (currently 3.12) for better performance and security.
- Best practice 7: Prefer using classes over standalone functions to encapsulate state and behavior, particularly for agents and tools.
- Best practice 8: Separate configuration from code using environment variables and configuration files to allow easy modification without altering the code base
## Library Information:
- Name: autogen
- Tags: ai, ml, llm, python, agent-framework, multi-agent
## Comprehensive Guide to AutoGen Best Practices
### 1. Code Organization and Structure:
- **Directory Structure Best Practices:**
- `src/`: Contains the core AutoGen application code.
- `src/agents/`: Holds individual agent implementations (e.g., `code_writer_agent.py`, `data_analyst_agent.py`).
- `src/workflows/`: Defines workflows or agent interaction patterns (e.g., `code_generation_workflow.py`).
- `src/tools/`: Contains custom tools and utilities used by agents (e.g., `web_scraper.py`, `api_client.py`).
- `config/`: Stores configuration files (e.g., `agent_config.yaml`, `llm_config.json`).
- `tests/`: Contains unit and integration tests.
- `docs/`: Holds documentation.
- `examples/`: Example scripts and notebooks showcasing AutoGen's capabilities.
- **File Naming Conventions:**
- Use descriptive names with snake_case (e.g., `code_executor_agent.py`, `data_processing_tool.py`).
- Configuration files should use `.yaml` or `.json` extensions (e.g., `agent_config.yaml`).
- Test files should be named `test_<module_name>.py` (e.g., `test_code_executor.py`).
- **Module Organization Best Practices:**
- Group related functionalities into modules (e.g., `agents`, `workflows`, `tools`).
- Use `__init__.py` files to define packages and control imports.
- Implement clear and concise module-level documentation.
- **Component Architecture Recommendations:**
- Separate agents, tools, and workflows into distinct components.
- Use interfaces or abstract base classes to define contracts between components.
- Implement a central registry or dependency injection mechanism to manage component dependencies.
- **Code Splitting Strategies:**
- Split large agent implementations into smaller, more manageable classes or functions.
- Use lazy loading or dynamic imports to load components only when needed.
- Implement a plugin system to allow external components to be added to the application.
### 2. Common Patterns and Anti-patterns:
- **Design Patterns:**
- **Factory Pattern:** Create agents and tools dynamically based on configuration or user input.
- **Strategy Pattern:** Implement different agent behaviors or tool execution strategies based on the current context.
- **Observer Pattern:** Allow agents to subscribe to events or notifications from other agents or tools.
- **Recommended Approaches for Common Tasks:**
- **Code Generation:** Use AutoGen's code generation capabilities to automate boilerplate code creation or data transformation tasks. Example: Automatically generate data validation functions based on schema definitions.
- **Data Analysis:** Implement agents that can analyze data, generate visualizations, and extract insights. Example: Create an agent that analyzes website traffic data and identifies potential areas for improvement.
- **Workflow Orchestration:** Define workflows that automate complex multi-step tasks involving multiple agents and tools. Example: Implement a workflow that automatically generates, tests, and deploys code changes.
- **Anti-patterns and Code Smells:**
- **God Agent:** Avoid creating a single agent that performs too many tasks. Decompose complex tasks into smaller, more manageable agents.
- **Tight Coupling:** Minimize dependencies between agents and tools. Use interfaces or abstract base classes to decouple components.
- **Code Duplication:** Extract common functionalities into reusable functions or classes.
- **State Management Best Practices:**
- Use a central state management system to store and manage the application's state.
- Implement versioning or snapshotting to track state changes over time.
- Use immutable data structures to prevent unintended state modifications.
- **Error Handling Patterns:**
- Implement robust error handling mechanisms to catch and handle exceptions.
- Use logging to record errors and debug issues.
- Implement retry logic to handle transient errors.
### 3. Performance Considerations:
- **Optimization Techniques:**
- **Caching:** Cache frequently accessed data to reduce latency and improve throughput.
- **Parallelization:** Use asynchronous programming or multithreading to parallelize tasks and improve performance.
- **Code Optimization:** Profile and optimize code to reduce execution time.
- **Memory Management:**
- Use generators or iterators to process large datasets in chunks.
- Release resources as soon as they are no longer needed.
- Avoid creating unnecessary copies of data.
- **Bundle Size Optimization (if applicable):** N/A for a Python Library, but if creating web apps with autogen, use tree-shaking to remove unused code and minimize bundle size.
- **Lazy Loading:** Load modules and components only when needed to reduce startup time and memory usage.
### 4. Security Best Practices:
- **Common Vulnerabilities:**
- **Prompt Injection:** Sanitize user inputs to prevent malicious code from being injected into agent prompts.
- **Unauthorized Access:** Implement access controls to restrict access to sensitive data and functionalities.
- **Data Leaks:** Protect sensitive data from being exposed in logs or error messages.
- **Input Validation:**
- Validate all user inputs to ensure that they conform to the expected format and range.
- Use allow lists to restrict the types of inputs that are allowed.
- Sanitize inputs to remove potentially harmful characters or code.
- **Authentication and Authorization:**
- Implement authentication mechanisms to verify the identity of users or agents.
- Use authorization policies to control access to resources and functionalities.
- Use role-based access control (RBAC) to simplify access management.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms to protect data from unauthorized access.
- Implement data masking or anonymization techniques to protect sensitive data in logs or error messages.
- **Secure API Communication:**
- Use HTTPS to encrypt API communication.
- Authenticate and authorize API requests.
- Validate API responses to prevent data tampering.
### 5. Testing Approaches:
- **Unit Testing:**
- Write unit tests for individual agents, tools, and workflows.
- Use mocking or stubbing to isolate components during testing.
- Test different scenarios and edge cases.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components.
- Test the integration with external systems or APIs.
- Use test data that is representative of real-world data.
- **End-to-End Testing:**
- Write end-to-end tests to verify the overall functionality of the application.
- Simulate user interactions and verify that the application behaves as expected.
- Use automated testing frameworks to automate the testing process.
- **Test Organization:**
- Organize tests into separate directories or files based on the component being tested.
- Use descriptive names for test functions or classes.
- Follow a consistent testing convention.
- **Mocking and Stubbing:**
- Use mocking to replace external dependencies with mock objects.
- Use stubbing to replace complex functionalities with simple stubs.
- Use mocking frameworks to simplify the mocking process.
### 6. Common Pitfalls and Gotchas:
- **Frequent Mistakes:**
- Not properly configuring LLM parameters (e.g., temperature, max tokens).
- Overly complex prompts that confuse the LLM.
- Ignoring error messages and logs.
- Not validating user inputs.
- **Edge Cases:**
- Handling unexpected LLM responses.
- Dealing with rate limits or API outages.
- Handling large datasets or complex workflows.
- **Version-Specific Issues:**
- Be aware of breaking changes in AutoGen updates.
- Check the release notes for known issues or workarounds.
- **Compatibility Concerns:**
- Ensure that AutoGen is compatible with other libraries or frameworks being used in the project.
- Check for conflicts between different versions of AutoGen.
- **Debugging Strategies:**
- Use logging to track the execution flow and identify errors.
- Use a debugger to step through the code and inspect variables.
- Use print statements to output intermediate results.
### 7. Tooling and Environment:
- **Recommended Development Tools:**
- Python IDE (e.g., VS Code, PyCharm).
- Version control system (e.g., Git).
- Dependency management tool (e.g., pip, uv).
- **Build Configuration:**
- Use a build system to automate the build process.
- Configure the build system to run linters and tests.
- Use a virtual environment to isolate dependencies.
- **Linting and Formatting:**
- Use linters to enforce coding style guidelines.
- Use formatters to automatically format code.
- Integrate linters and formatters into the development workflow.
- **Deployment:**
- Use a deployment platform to deploy the application to a production environment.
- Configure the deployment platform to automatically scale the application.
- Use a monitoring system to track the application's performance.
- **CI/CD Integration:**
- Use a CI/CD pipeline to automate the build, test, and deployment process.
- Integrate the CI/CD pipeline with the version control system.
- Use automated testing to ensure code quality.
+286
View File
@@ -0,0 +1,286 @@
---
description: This rule provides best practices and coding standards for aws-amplify projects, covering code organization, common patterns, performance, security, testing, pitfalls, and tooling. It aims to guide developers in building robust, scalable, and maintainable aws-amplify applications.
globs: **/*.{js,jsx,ts,tsx}
---
- # aws-amplify Best Practices
This document outlines best practices and coding standards for developing applications using the aws-amplify library. It aims to guide developers in creating robust, scalable, and maintainable applications.
- ## 1. Code Organization and Structure
- ### Directory Structure
- **src/**: Contains all the application source code.
- **components/**: Reusable UI components.
- `ComponentName/`: Each component in its own directory.
- `ComponentName.tsx`: The component file.
- `ComponentName.module.css`: Component-specific styles (using CSS Modules).
- `ComponentName.test.tsx`: Unit tests for the component.
- `index.ts`: (Optional) Exports the component for easier imports.
- **pages/**: Defines the application's routes/pages (especially important for Next.js and similar frameworks).
- `index.tsx`: The home page.
- `[routeName].tsx`: Dynamic routes.
- **services/**: Contains business logic, data fetching, and interactions with aws-amplify services.
- `authService.ts`: Authentication-related functions.
- `dataService.ts`: Data fetching and manipulation (e.g., interacting with AppSync).
- `storageService.ts`: Storage-related functions (e.g., interacting with S3).
- **models/**: Defines data models used in the application. This often corresponds to your Amplify DataStore or GraphQL schema definitions.
- `Todo.ts`: Example data model for a `Todo` item.
- **utils/**: Utility functions and helpers.
- `apiClient.ts`: A wrapper around the `Amplify` object for making API requests.
- `dateUtils.ts`: Date formatting functions.
- **config/**: Application configuration files.
- `aws-exports.js`: Automatically generated aws-amplify configuration.
- **hooks/**: Custom React hooks for reusable logic.
- `useAuth.ts`: A hook for managing authentication state.
- **amplify/**: Generated directory by Amplify CLI, containing backend definitions.
- **backend/**: Code and configurations that define the AWS resources.
- `api/`: GraphQL API definitions (schema.graphql, resolvers, etc.).
- `auth/`: Authentication configuration (Cognito User Pool, Identity Pool).
- `storage/`: Storage configurations (S3 bucket).
- `function/`: Lambda functions.
- ### File Naming Conventions
- Components: `ComponentName.tsx`
- Styles: `ComponentName.module.css`
- Services: `serviceName.ts`
- Models: `ModelName.ts`
- Hooks: `useHookName.ts`
- Tests: `FileName.test.tsx` or `FileName.spec.tsx`
- ### Module Organization
- Group related functionalities into modules.
- Use clear and descriptive names for modules.
- Avoid circular dependencies between modules.
- Export only necessary functions and variables from each module.
- ### Component Architecture
- **Presentational Components:** Responsible for how things look. Receive data and callbacks via props.
- **Container Components:** Concerned with how things work. Fetch data, manage state, and pass data/callbacks to presentational components.
- Use composition over inheritance.
- Keep components small and focused on a single responsibility.
- Use React Hooks for managing state and side effects.
- ### Code Splitting
- Use dynamic imports (`React.lazy`) for components that are not immediately needed.
- Split routes into separate bundles.
- Leverage webpack, Parcel, or other bundlers to automatically split code.
- ## 2. Common Patterns and Anti-patterns
- ### Design Patterns
- **Provider Pattern:** Use React Context to provide aws-amplify client and authentication state to the entire application.
- **Hook Composition:** Create custom hooks that encapsulate aws-amplify logic for reusability.
- **Repository Pattern:** Abstract data access logic behind a repository interface.
- ### Recommended Approaches
- **Authentication:** Use `Amplify.configure` to initialize Amplify with the configuration from `aws-exports.js`.
- Implement sign-in, sign-up, sign-out using `Auth` API.
- Utilize Higher Order Components or custom Hooks to protect routes based on authentication status.
- **Data Fetching:** Use `DataStore` or GraphQL APIs for data fetching. Consider using pagination for large datasets.
- **Storage:** Use `Storage` API for uploading and retrieving files from S3.
- ### Anti-patterns and Code Smells
- **Tight Coupling:** Avoid directly using `Amplify` APIs in components. Abstract them into services or hooks.
- **Over-fetching:** Fetch only the necessary data from APIs. Use GraphQL fragments to specify required fields.
- **Ignoring Errors:** Always handle errors when interacting with aws-amplify services.
- **Storing Sensitive Data in Client:** Never store API keys or secrets in the client-side code. Use Lambda functions with environment variables.
- **Over-reliance on Amplify UI Components:** While useful for rapid prototyping, customize or replace Amplify UI components for complex designs and accessibility requirements.
- ### State Management
- **Component State:** Use `useState` or `useReducer` for local component state.
- **Context API:** Use React Context for application-wide state (e.g., authentication status, user data).
- **Redux/Zustand/Recoil:** Consider using a state management library for complex applications with global state dependencies.
- **Amplify DataStore:** Excellent solution for offline-first applications needing real-time data synchronization with the cloud. Use its built-in mechanisms for local persistence and conflict resolution.
- ### Error Handling
- Use `try...catch` blocks to handle errors when calling aws-amplify APIs.
- Display user-friendly error messages.
- Log errors for debugging purposes.
- Implement retry mechanisms for transient errors.
- ## 3. Performance Considerations
- ### Optimization Techniques
- **Caching:** Cache API responses to reduce network requests. Use `Cache` API for storing data in the browser.
- **Lazy Loading:** Load components and data only when needed.
- **Debouncing and Throttling:** Limit the rate at which functions are executed (e.g., event handlers).
- **Memoization:** Cache the results of expensive function calls using `useMemo` or `React.memo`.
- **Image Optimization:** Optimize images before uploading them to S3. Use responsive images with different sizes for different devices.
- ### Memory Management
- Avoid memory leaks by cleaning up subscriptions and timers in `useEffect` hooks.
- Release unused resources.
- ### Rendering Optimization
- Use `React.memo` to prevent unnecessary re-renders of components.
- Implement shouldComponentUpdate (if using class components) for fine-grained control over rendering.
- Virtualize long lists to render only visible items.
- ### Bundle Size Optimization
- Use code splitting to reduce the initial bundle size.
- Remove unused code and dependencies.
- Minify and compress code.
- Analyze bundle size with tools like `webpack-bundle-analyzer` or `Source Map Explorer`.
- ### Lazy Loading
- Use `React.lazy` and `Suspense` for lazy-loading components.
- Implement lazy loading for images and other assets.
- ## 4. Security Best Practices
- ### Common Vulnerabilities
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms.
- **Injection Attacks:** Protect against SQL injection, NoSQL injection, and command injection attacks.
- **Authentication and Authorization Flaws:** Secure authentication and authorization mechanisms.
- ### Input Validation
- Validate all user input on both the client and server sides.
- Use strong validation rules to prevent invalid data from being stored in the database.
- ### Authentication and Authorization
- Use Amazon Cognito for authentication and authorization.
- Implement role-based access control (RBAC) to restrict access to resources.
- Secure API endpoints with authentication and authorization checks.
- Follow the principle of least privilege when granting permissions.
- ### Data Protection
- Encrypt sensitive data at rest and in transit.
- Use HTTPS for all communication.
- Implement data masking and redaction techniques to protect sensitive data from unauthorized access.
- Regularly back up data.
- ### Secure API Communication
- Use HTTPS for all API requests.
- Validate API responses.
- Implement rate limiting to prevent abuse.
- ## 5. Testing Approaches
- ### Unit Testing
- Test individual components and functions in isolation.
- Use mocking and stubbing to isolate components from external dependencies.
- Write tests that cover all possible scenarios and edge cases.
- Use testing frameworks like Jest and React Testing Library.
- ### Integration Testing
- Test the interaction between different components and modules.
- Test the integration with aws-amplify services.
- Use integration testing frameworks like Cypress or Playwright.
- ### End-to-End Testing
- Test the entire application flow from start to finish.
- Simulate real user interactions.
- Use end-to-end testing frameworks like Cypress or Selenium.
- ### Test Organization
- Keep tests close to the code they are testing.
- Use descriptive names for tests.
- Organize tests into logical groups.
- ### Mocking and Stubbing
- Use mocking libraries like Jest to mock aws-amplify APIs and services.
- Use stubbing to replace complex dependencies with simple implementations for testing purposes.
- ## 6. Common Pitfalls and Gotchas
- ### Frequent Mistakes
- Misconfiguring aws-amplify.
- Ignoring error messages.
- Not handling edge cases.
- Over-complicating code.
- Not testing thoroughly.
- ### Edge Cases
- Handling offline scenarios.
- Dealing with slow network connections.
- Handling unexpected API responses.
- ### Version-Specific Issues
- Be aware of breaking changes between aws-amplify versions.
- Consult the aws-amplify documentation and release notes for migration guides.
- ### Compatibility Concerns
- Ensure compatibility between aws-amplify and other libraries and frameworks used in the project.
- Check for known compatibility issues and workarounds.
- ### Debugging Strategies
- Use browser developer tools for debugging client-side code.
- Use CloudWatch logs for debugging server-side code (Lambda functions).
- Use the aws-amplify CLI to diagnose configuration issues.
- ## 7. Tooling and Environment
- ### Recommended Tools
- Visual Studio Code (VS Code) or other preferred IDE
- aws-amplify CLI
- Node.js and npm or yarn
- Git for version control
- Jest and React Testing Library for unit testing
- Cypress or Playwright for end-to-end testing
- ### Build Configuration
- Use a build tool like webpack, Parcel, or esbuild.
- Configure the build tool to optimize code for production.
- Use environment variables for configuration settings.
- ### Linting and Formatting
- Use ESLint and Prettier to enforce code style and prevent errors.
- Configure ESLint and Prettier to automatically format code on save.
- ### Deployment
- Use aws-amplify Console for deploying the application.
- Configure CI/CD pipelines to automatically deploy changes to production.
- Use environment variables for configuration settings.
- ### CI/CD Integration
- Integrate with CI/CD tools like GitHub Actions, CircleCI, or Travis CI.
- Automate the build, test, and deployment processes.
- Use environment variables for configuration settings.
- **Code-First Approach with TypeScript:** Embrace the code-first approach with AWS Amplify Gen 2, using TypeScript for both frontend and backend development to improve developer productivity and catch errors early. Leverage AWS CDK for defining infrastructure as code.
- **Single Responsibility Principle:** Adhere to the Single Responsibility Principle for AWS Lambda functions to improve code maintainability and testability.
- **Avoid Function Chaining:** Reduce complexity and improve debugging by avoiding function chaining in Lambda functions. If code reuse is needed, utilize separate TypeScript files for shared logic.
- **Start with Templates:** Accelerate development by using pre-built templates instead of starting projects from scratch.
- **Utilize Cloud Sandboxes:** Leverage per-developer cloud sandbox environments for isolated testing and iteration without interfering with other team members.
- **Take advantage of Amplify's opinionated nature** When you read the docs, you will start to understand how opinionated Amplify is. Whether you choose Amplify or not should include this aspect of its design, and you shouldn't choose this tool if it doesn't align with the direction your team is taking with infrastructure. It is best used as 'Glue' for an All-AWS roadmap.
+349
View File
@@ -0,0 +1,349 @@
---
description: This rule provides comprehensive guidance on best practices for developing and managing AWS resources using the AWS CLI, covering code organization, security, performance, and testing.
globs: **/*.{sh,py,yml,yaml,tf,json,md}
---
# AWS CLI Best Practices and Coding Standards
This document provides guidelines and recommendations for developing and managing AWS resources using the AWS CLI. Following these practices enhances code quality, security, and operational efficiency.
## 1. Code Organization and Structure
### 1.1. Directory Structure
A well-organized directory structure promotes maintainability and readability.
project-root/
├── scripts/ # Shell scripts for common AWS CLI operations
│ ├── create-s3-bucket.sh
│ ├── deploy-lambda.sh
│ └── ...
├── modules/ # Reusable modules (e.g., Python scripts)
│ ├── s3_utils.py # S3 utility functions
│ ├── iam_utils.py # IAM utility functions
│ └── ...
├── config/ # Configuration files
│ ├── aws_config.yml # AWS CLI configuration
│ └── ...
├── terraform/ # Infrastructure as Code (IaC) using Terraform (optional)
│ ├── main.tf
│ ├── variables.tf
│ └── ...
├── tests/ # Test scripts
│ ├── test_s3_utils.py
│ └── ...
├── README.md # Project documentation
└── .gitignore # Git ignore file
### 1.2. File Naming Conventions
* **Scripts:** Use descriptive names (e.g., `create-ec2-instance.sh`). Suffix with `.sh` for shell scripts.
* **Modules:** Use descriptive names (e.g., `s3_utils.py`). Suffix with `.py` for Python modules.
* **Configuration:** Use `.yml` or `.yaml` for YAML configuration files (e.g., `aws_config.yml`).
* **Terraform:** Follow Terraform conventions (`main.tf`, `variables.tf`).
* **Tests:** Prefix test files with `test_` (e.g., `test_s3_utils.py`).
### 1.3. Module Organization
* **Purpose-Driven Modules:** Group related functionalities into modules (e.g., `s3_utils.py` for S3 operations).
* **Avoid Circular Dependencies:** Design modules to minimize inter-dependencies.
* **Clear Interfaces:** Define clear function signatures and API contracts for each module.
* **Documentation:** Include docstrings to explain the purpose and usage of each function within a module.
### 1.4. Component Architecture
For larger projects, consider a component-based architecture. Each component encapsulates specific AWS-related functionalities. This approach promotes modularity, testability, and reusability.
Example:
components/
├── s3/
│ ├── s3_component.py
│ ├── ...
├── iam/
│ ├── iam_component.py
│ ├── ...
└── ...
### 1.5. Code Splitting
* **Break Down Complex Scripts:** Split large, complex scripts into smaller, more manageable functions or modules.
* **Configuration-Driven Scripts:** Use configuration files to drive script behavior, making them more flexible and reusable.
* **Parameterization:** Parameterize scripts to accept input variables, reducing hardcoding and improving adaptability.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Facade:** Create a facade to simplify complex AWS CLI operations.
* **Adapter:** Use adapters to translate between different data formats (e.g., JSON and YAML).
* **Strategy:** Implement different strategies for error handling or retry mechanisms.
* **Command Pattern:** Encapsulate AWS CLI commands as objects, facilitating command queuing, logging, and undo operations.
### 2.2. Recommended Approaches
* **Configuration Management:** Use environment variables, configuration files, or AWS Systems Manager Parameter Store to manage AWS credentials and configurations.
* **Idempotent Scripts:** Design scripts to be idempotent, meaning that running them multiple times has the same effect as running them once.
* **Logging:** Implement comprehensive logging to track script execution and identify issues.
* **Error Handling:** Use appropriate error handling mechanisms to gracefully handle exceptions.
* **Progress Indicators:** Add progress indicators to provide feedback during long-running operations.
### 2.3. Anti-patterns
* **Hardcoding Credentials:** Avoid hardcoding AWS credentials directly in scripts.
* **Lack of Error Handling:** Failing to handle exceptions can lead to unexpected script termination.
* **Overly Complex Scripts:** Overly complex scripts are difficult to maintain and debug.
* **Ignoring Security Best Practices:** Neglecting security best practices can lead to vulnerabilities.
* **Not using IaC:** Managing infrastructure manually instead of using Infrastructure as Code (IaC) tools such as CloudFormation or Terraform.
### 2.4. State Management
* **AWS Systems Manager Parameter Store:** Use Parameter Store to store and manage configuration data and secrets.
* **DynamoDB:** Use DynamoDB to store application state data.
* **S3:** Store state data in S3 buckets, ensuring proper access control.
* **CloudFormation Stack Outputs:** If using CloudFormation, use stack outputs to manage state information.
* **Terraform State:** If using Terraform, properly manage the Terraform state file (e.g., using S3 backend with DynamoDB lock). Never commit the state file to version control.
### 2.5. Error Handling
* **Try-Except Blocks:** Use `try-except` blocks in Python to handle exceptions.
* **Error Codes:** Check for specific error codes returned by AWS CLI commands.
* **Retry Mechanisms:** Implement retry mechanisms with exponential backoff for transient errors.
* **Alerting:** Set up alerting to notify administrators of critical errors.
* **Consistent Error Messages:** Provide clear, informative error messages that help in debugging.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Parallel Execution:** Use parallel processing to execute multiple AWS CLI commands concurrently.
* **Caching:** Cache frequently accessed data to reduce API calls.
* **Pagination:** Use pagination to retrieve large datasets in smaller chunks.
* **Filtering:** Filter data on the server-side to reduce the amount of data transferred.
* **Asynchronous Operations:** Utilize asynchronous operations when possible to avoid blocking the main thread of execution.
### 3.2. Memory Management
* **Large Datasets:** Avoid loading large datasets into memory at once. Use iterators or generators to process data in chunks.
* **Resource Cleanup:** Ensure that resources are properly released after use to prevent memory leaks.
* **Efficient Data Structures:** Use efficient data structures to minimize memory consumption.
### 3.3. Rendering Optimization (If applicable)
N/A - The AWS CLI is not a rendering library.
### 3.4. Bundle Size Optimization (If applicable)
N/A - Bundle size optimization is not directly relevant to the AWS CLI itself, but it might be relevant for tools built on top of it that are distributed as standalone applications.
### 3.5. Lazy Loading
* **Import Modules on Demand:** Import modules only when they are needed to reduce startup time.
* **Load Configuration As Needed:** Load configuration data only when it is required.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Credential Exposure:** Exposing AWS credentials in code or configuration files.
* **Insufficient Access Control:** Granting excessive permissions to IAM roles or users.
* **SQL Injection (if applicable):** If constructing SQL queries dynamically, protect against SQL injection.
* **Cross-Site Scripting (XSS) (if applicable):** If the CLI interacts with web interfaces, sanitize inputs to prevent XSS.
* **Command Injection:** If constructing shell commands dynamically from user inputs, sanitize inputs to prevent command injection.
### 4.2. Input Validation
* **Sanitize Inputs:** Sanitize all user inputs to prevent malicious code injection.
* **Validate Data Types:** Validate that input data conforms to expected data types.
* **Limit Input Lengths:** Limit the length of input strings to prevent buffer overflows.
* **Regular Expressions:** Use regular expressions to validate input patterns.
* **Whitelist Allowed Values:** If applicable, use a whitelist of allowed values rather than a blacklist.
### 4.3. Authentication and Authorization
* **IAM Roles:** Use IAM roles to grant permissions to AWS resources.
* **Least Privilege:** Follow the principle of least privilege when granting permissions.
* **Multi-Factor Authentication (MFA):** Enable MFA for all IAM users.
* **Credential Rotation:** Rotate AWS credentials regularly.
* **IAM Policies:** Implement granular IAM policies to control access to resources.
### 4.4. Data Protection
* **Encryption:** Encrypt sensitive data at rest and in transit.
* **Access Control Lists (ACLs):** Use ACLs to control access to S3 buckets and objects.
* **Data Masking:** Mask sensitive data to prevent unauthorized access.
* **Regular Backups:** Create regular backups of critical data.
* **Secure Logging:** Ensure that logs do not contain sensitive information and are stored securely.
### 4.5. Secure API Communication
* **HTTPS:** Use HTTPS for all API communication.
* **TLS:** Enforce TLS 1.2 or higher for secure connections.
* **API Gateway:** Use API Gateway to secure and manage API endpoints.
* **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks.
* **WAF (Web Application Firewall):** Use WAF to protect against common web exploits.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Mock AWS CLI Calls:** Use mocking libraries to simulate AWS CLI calls and verify expected behavior.
* **Test Individual Functions:** Write unit tests for each function or module.
* **Boundary Conditions:** Test boundary conditions and edge cases.
* **Assertion Libraries:** Use assertion libraries to verify expected results.
### 5.2. Integration Testing
* **Test End-to-End Workflows:** Test complete workflows that involve multiple AWS services.
* **Use Real AWS Resources:** Use real AWS resources in a test environment.
* **Automated Test Execution:** Automate integration tests as part of the CI/CD pipeline.
* **Verify Resource Creation and Deletion:** Ensure that resources are created and deleted correctly during testing.
### 5.3. End-to-End Testing
* **Simulate Real-World Scenarios:** Simulate real-world scenarios to test the application's overall behavior.
* **Automated Test Scripts:** Create automated test scripts to verify functionality.
* **Monitor System Behavior:** Monitor system behavior during end-to-end tests.
### 5.4. Test Organization
* **Dedicated Test Directory:** Store test files in a dedicated directory (e.g., `tests/`).
* **Test Naming Conventions:** Follow consistent test naming conventions.
* **Test Suites:** Group related tests into test suites.
* **Test Reports:** Generate test reports to track test results.
### 5.5. Mocking and Stubbing
* **Mock AWS CLI:** Use mocking libraries to simulate AWS CLI behavior.
* **Stub External Dependencies:** Stub external dependencies to isolate components during testing.
* **Control Test Data:** Use controlled test data to ensure predictable test results.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Incorrect IAM Permissions:** Granting insufficient or excessive IAM permissions.
* **Missing Configuration:** Failing to configure the AWS CLI properly.
* **Hardcoding Values:** Hardcoding values instead of using configuration files or environment variables.
* **Ignoring Error Messages:** Ignoring error messages can lead to unexpected behavior.
* **Not Using Pagination:** Retrieving incomplete datasets due to lack of pagination.
### 6.2. Edge Cases
* **Rate Limiting:** Handling API rate limits gracefully.
* **Service Outages:** Handling service outages or transient errors.
* **Data Consistency:** Ensuring data consistency across multiple AWS services.
* **Concurrency Issues:** Managing concurrency issues when multiple scripts access the same resources.
### 6.3. Version-Specific Issues
* **API Changes:** Handling API changes across different AWS CLI versions.
* **Deprecated Features:** Avoiding deprecated features.
* **Compatibility Issues:** Addressing compatibility issues between different AWS CLI versions and AWS services.
### 6.4. Compatibility Concerns
* **Operating Systems:** Ensuring compatibility across different operating systems (e.g., Linux, Windows, macOS).
* **Programming Languages:** Addressing compatibility issues with different programming languages.
* **Third-Party Libraries:** Managing dependencies on third-party libraries.
### 6.5. Debugging Strategies
* **Logging:** Use comprehensive logging to track script execution.
* **Debugging Tools:** Use debugging tools to step through code and inspect variables.
* **Error Messages:** Analyze error messages carefully to identify the root cause of issues.
* **Verbose Mode:** Use verbose mode to print detailed information about AWS CLI commands.
* **AWS CloudTrail:** Use AWS CloudTrail to track API calls and identify potential issues.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **AWS CLI:** The core command-line interface for interacting with AWS services.
* **Text Editor/IDE:** A suitable text editor or IDE for writing scripts (e.g., VS Code, Sublime Text, PyCharm).
* **Version Control:** Git for version control.
* **Shell:** Bash, Zsh, or PowerShell for running scripts.
* **Python (if applicable):** Python for scripting and automation.
* **jq:** A command-line JSON processor.
* **yq:** A command-line YAML processor.
### 7.2. Build Configuration
* **Makefile:** Use Makefiles to automate common build tasks.
* **Build Scripts:** Create build scripts to package and deploy applications.
* **Dependency Management:** Use appropriate dependency management tools (e.g., pip for Python).
### 7.3. Linting and Formatting
* **Shellcheck:** Use Shellcheck to lint shell scripts.
* **Pylint:** Use Pylint to lint Python code.
* **Black:** Use Black to format Python code.
* **YAML Lint:** Use a YAML linter to validate YAML files.
### 7.4. Deployment
* **AWS CloudFormation:** Deploy infrastructure as code using AWS CloudFormation.
* **AWS CodeDeploy:** Automate application deployments using AWS CodeDeploy.
* **AWS Lambda:** Deploy serverless functions using AWS Lambda.
* **Docker:** Containerize applications using Docker.
### 7.5. CI/CD Integration
* **AWS CodePipeline:** Use AWS CodePipeline to automate the CI/CD process.
* **Jenkins:** Integrate with Jenkins for continuous integration.
* **GitHub Actions:** Use GitHub Actions for CI/CD.
* **Automated Testing:** Integrate automated testing into the CI/CD pipeline.
## Infrastructure as Code (IaC)
* Treat your infrastructure as code using tools like AWS CloudFormation or Terraform. This allows for version control, consistent deployments, and easier management of infrastructure changes.
## Continuous Integration/Continuous Deployment (CI/CD)
* Implement CI/CD pipelines using AWS CodePipeline, ensuring that all code changes are automatically tested and deployed. This includes defining clear stages for building, testing, and deploying applications, and incorporating security checks throughout the pipeline.
## Security
* Employ least-privilege access controls using IAM, enforce multi-factor authentication (MFA), and regularly review permissions. Security should be integrated at every stage of the development and deployment process.
## Automate tasks
* Automate repetitive tasks to increase efficiency and reduce errors.
## Version control
* Ensure robust version control for all code and configuration files.
## Prioritize testing
* Integrate comprehensive testing at every stage to ensure code quality.
## Maintain and adapt
* Regularly update and adapt the pipeline to evolving requirements.
## Monitor and analyze
* Continuously monitor and analyze pipeline performance and outcomes.
## IAM Best Practices:
* Require human users to use federation with an identity provider to access AWS using temporary credentials
* Require workloads to use temporary credentials with IAM roles to access AWS
* Require multi-factor authentication (MFA)
* Update access keys when needed for use cases that require long-term credentials
* Follow best practices to protect your root user credentials
* Apply least-privilege permissions
* Get started with AWS managed policies and move toward least-privilege permissions
* Use IAM Access Analyzer to generate least-privilege policies based on access activity
* Regularly review and remove unused users, roles, permissions, policies, and credentials
* Use conditions in IAM policies to further restrict access
* Verify public and cross-account access to resources with IAM Access Analyzer
* Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions
* Establish permissions guardrails across multiple accounts
* Use permissions boundaries to delegate permissions management within an account
By adhering to these best practices, you can develop robust, secure, and efficient AWS CLI applications.
+182
View File
@@ -0,0 +1,182 @@
---
description: This rule provides best practices and coding standards for developing applications using AWS DynamoDB. It covers aspects like schema design, performance optimization, security, and testing.
globs: **/*.{js,ts,jsx,tsx,py}
---
- **Minimize the number of tables; prefer single-table design.** Having fewer tables keeps things more scalable, requires less permissions management, and reduces overhead for your DynamoDB application. Consider using a single table with appropriate use of primary and secondary indexes.
- **Identify query patterns before schema design.** Understand the application's access patterns before designing the DynamoDB schema. Knowing how the data will be queried is crucial for optimizing performance and cost.
- **Use sort order for related items and distribute queries to avoid hot spots.** Group related items together by utilizing sort keys and design data keys to distribute traffic evenly across partitions.
- **Prefer queries over scans for efficiency.** DynamoDB queries are more efficient and less costly than scan operations. Always aim to use queries that filter based on partition and sort keys.
- **Use caching to reduce read/write costs.** Implement caching strategies, such as AWS ElastiCache or DynamoDB Accelerator (DAX), to minimize DynamoDB read/write costs. Use appropriate invalidation logic.
- **Validate data integrity in the application layer.** Since DynamoDB doesn't enforce relationship data or integrity constraints, it's essential to perform strict data validations in the application or business layer.
## 1. Code Organization and Structure
- **Directory Structure Best Practices:**
- `src/`: Contains the application's source code.
- `src/models/`: Defines data models representing DynamoDB entities.
- `src/services/`: Implements business logic and interacts with DynamoDB.
- `src/repositories/`: Handles DynamoDB data access operations.
- `src/utils/`: Contains utility functions (e.g., data validation, error handling).
- `tests/`: Includes unit, integration, and end-to-end tests.
- `config/`: Stores configuration files (e.g., DynamoDB table names, AWS region).
- **File Naming Conventions:**
- Use descriptive names for files and directories.
- Model files: `user.model.js` or `user.model.ts`
- Service files: `user.service.js` or `user.service.ts`
- Repository files: `user.repository.js` or `user.repository.ts`
- Test files: `user.service.test.js` or `user.service.test.ts`
- **Module Organization Best Practices:**
- Encapsulate DynamoDB interactions within dedicated modules (e.g., repositories).
- Use dependency injection to manage dependencies (e.g., DynamoDB client).
- Follow the single responsibility principle for modules.
- **Component Architecture Recommendations:**
- Adopt a layered architecture (e.g., presentation, application, domain, infrastructure).
- Decouple components to improve maintainability and testability.
- Use interfaces to define contracts between components.
- **Code Splitting Strategies:**
- Bundle only the necessary aws-sdk/client-dynamodb code by using tree shaking and only importing the necessary modules.
- Implement lazy loading for less frequently used features.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Repository Pattern:** Abstract DynamoDB data access logic.
- **Data Mapper Pattern:** Transform data between application and DynamoDB formats.
- **Single Table Design Pattern:** Minimize tables by using composite keys and attributes to represent different entity types and relationships.
- **Composite Keys Pattern:** Combine attributes to create partition and sort keys.
- **Recommended Approaches for Common Tasks:**
- **Creating Items:** Use the `PutItem` operation.
- **Reading Items:** Use the `GetItem` operation for single items and `Query` for sets.
- **Updating Items:** Use the `UpdateItem` operation for granular updates.
- **Deleting Items:** Use the `DeleteItem` operation.
- **Querying Data:** Utilize indexes (GSI/LSI) to optimize query performance. Use projection expressions to return only required attributes.
- **Scanning Data (Avoid when possible):** If scanning is unavoidable, use `Limit` and `ExclusiveStartKey` for pagination and consider parallel scans for large datasets.
- **Anti-patterns and Code Smells:**
- **Over-fetching Data:** Avoid retrieving unnecessary attributes.
- **Excessive Scanning:** Design schemas and queries to minimize scans.
- **Hardcoding Table Names:** Use configuration files or environment variables.
- **Ignoring Error Handling:** Implement robust error handling with retries and logging.
- **Insufficient Data Validation:** Validate data before writing to DynamoDB.
- **Hot Partitioning:** Design partitions to distribute data evenly and prevent overload of specific partitions.
- **State Management Best Practices:**
- Use DynamoDB to persist application state (e.g., user sessions, feature flags).
- Implement atomic counters and conditional updates to manage concurrent access.
- **Error Handling Patterns:**
- Use try-catch blocks to handle DynamoDB errors.
- Implement retry mechanisms for transient errors (e.g., throttling).
- Log errors with sufficient context for debugging.
- Use custom exception classes to categorize DynamoDB errors.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Minimize Read Capacity Units (RCUs) and Write Capacity Units (WCUs):** Optimize queries and writes to consume fewer RCUs and WCUs. Use projection expressions to return only the attributes you need.
- **Use Batch Operations:** Use `BatchGetItem` and `BatchWriteItem` for bulk operations.
- **Optimize Data Sizes:** Keep item sizes small to reduce storage costs and improve performance. If items exceed the size limit, consider storing larger attributes in S3 and referencing them in DynamoDB.
- **Use Parallel Scans (with caution):** Use parallel scans to speed up full table scans, but be aware of the increased RCUs consumption.
- **Optimize Index Usage:** Use indexes effectively to support query patterns. Be mindful of the cost implications of GSI writes.
- **Leverage DynamoDB Accelerator (DAX):** Use DAX for in-memory caching to reduce latency and RCU consumption.
- **Memory Management Considerations:**
- Avoid loading large datasets into memory.
- Use pagination to process data in chunks.
- Release resources promptly after use.
- **Bundle Size Optimization Strategies:**
- Use code splitting to reduce the initial bundle size.
- Remove unused dependencies.
- Optimize image sizes (if applicable).
- **Lazy Loading Strategies:**
- Load data on demand when needed.
- Use placeholders for content that is not immediately visible.
## 4. Security Best Practices
- **Common Vulnerabilities and Prevention:**
- **Injection Attacks:** Prevent NoSQL injection by validating and sanitizing user inputs.
- **Unauthorized Access:** Implement proper authentication and authorization mechanisms.
- **Data Exposure:** Encrypt sensitive data at rest and in transit.
- **Input Validation Best Practices:**
- Validate data types, formats, and ranges.
- Sanitize inputs to prevent injection attacks.
- Use input validation libraries (e.g., Joi, Validator.js).
- **Authentication and Authorization Patterns:**
- Use AWS Identity and Access Management (IAM) roles and policies to control access to DynamoDB resources.
- Implement fine-grained access control using conditional IAM policies.
- Consider using AWS Cognito for user authentication and authorization.
- **Data Protection Strategies:**
- Enable encryption at rest and in transit for DynamoDB tables.
- Use AWS Key Management Service (KMS) to manage encryption keys.
- Implement data masking and tokenization for sensitive data.
- Comply with data privacy regulations (e.g., GDPR, CCPA).
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Implement API authentication and authorization.
- Protect against cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.
## 5. Testing Approaches
- **Unit Testing Strategies:**
- Mock DynamoDB client using libraries like `aws-sdk-mock` or `jest-mock-extended`.
- Test individual functions and modules in isolation.
- Verify that functions correctly interact with the mocked DynamoDB client.
- **Integration Testing Approaches:**
- Test the integration between different modules and components.
- Use a local DynamoDB instance (e.g., DynamoDB Local, Docker image) for integration tests.
- Verify that data is correctly written to and read from DynamoDB.
- **End-to-end Testing Recommendations:**
- Test the entire application flow from the user interface to DynamoDB.
- Use a staging environment that mirrors the production environment.
- Verify that the application meets all functional and non-functional requirements.
- **Test Organization Best Practices:**
- Organize tests by module or component.
- Use descriptive names for test cases.
- Follow the AAA (Arrange, Act, Assert) pattern.
- **Mocking and Stubbing Techniques:**
- Use mocking libraries to create mock objects for DynamoDB client.
- Use stubbing to replace real dependencies with controlled test values.
- Verify that mocked methods are called with the expected parameters.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- Forgetting to handle pagination when querying large datasets.
- Not understanding DynamoDB capacity units (RCUs and WCUs) and throttling.
- Using inefficient query patterns.
- Neglecting to implement proper error handling.
- Designing schemas that lead to hot partitions.
- **Edge Cases:**
- Handling large item sizes exceeding DynamoDB's limits.
- Dealing with eventual consistency when reading data.
- Managing concurrent updates to the same item.
- **Version-Specific Issues:**
- Be aware of breaking changes in aws-sdk/client-dynamodb versions.
- Consult the AWS documentation and release notes for migration guides.
- **Compatibility Concerns:**
- Ensure compatibility between aws-sdk/client-dynamodb and other libraries.
- **Debugging Strategies:**
- Use AWS CloudWatch Logs to monitor DynamoDB operations.
- Enable DynamoDB Streams to capture changes to DynamoDB tables.
- Use the AWS X-Ray service for distributed tracing.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- AWS CLI
- AWS SDK for Javascript/Typescript
- DynamoDB Local (for local development)
- NoSQL Workbench for DynamoDB (for data modeling).
- **Build Configuration Best Practices:**
- Use a build tool (e.g., webpack, Parcel, esbuild) to bundle and optimize code.
- Configure environment variables for DynamoDB table names, AWS region, and credentials.
- Use `.env` files or AWS Systems Manager Parameter Store to manage configuration data.
- **Linting and Formatting Recommendations:**
- Use ESLint or TSLint for linting.
- Use Prettier for code formatting.
- Configure linting and formatting rules to enforce consistent code style.
- **Deployment Best Practices:**
- Use infrastructure-as-code tools (e.g., AWS CloudFormation, AWS CDK, Terraform) to provision DynamoDB resources.
- Implement blue/green deployments or canary deployments to minimize downtime.
- Automate deployments using CI/CD pipelines.
- **CI/CD Integration Strategies:**
- Use CI/CD tools (e.g., Jenkins, GitLab CI, CircleCI, AWS CodePipeline) to automate the build, test, and deployment process.
- Run unit and integration tests in the CI/CD pipeline.
- Deploy code to staging environments for testing and validation before deploying to production.
+210
View File
@@ -0,0 +1,210 @@
---
description: This rule covers best practices for developing, deploying, and maintaining applications using AWS Elastic Container Service (ECS). It includes guidance on code organization, performance, security, testing, and common pitfalls.
globs: **/*.{tf,yml,yaml,json,sh,dockerfile}
---
- **General Principles:**
- **Infrastructure as Code (IaC):** Treat your ECS infrastructure as code. Use tools like Terraform, AWS CloudFormation, or AWS CDK to define and manage your ECS clusters, task definitions, and services.
- **Configuration Management:** Externalize configuration from your application code. Use environment variables, AWS Secrets Manager, or AWS Systems Manager Parameter Store to manage configuration data.
- **Idempotency:** Ensure that your deployment scripts and automation are idempotent. This means that running the same script multiple times should have the same result as running it once.
- **Automation:** Automate all aspects of your ECS deployment, from building container images to deploying services and scaling resources.
- **1. Code Organization and Structure:**
- **1.1 Directory Structure:**
- **Project Root:** The base directory containing all project-related files.
- `infrastructure/`: Contains IaC code (Terraform, CloudFormation) for ECS clusters, task definitions, services, VPC, etc.
- `application/`: Contains source code for your containerized application.
- `src/`: Application source code.
- `tests/`: Unit, integration, and end-to-end tests.
- `Dockerfile`: Dockerfile for building the application container image.
- `scripts/`: Contains deployment, build, and other utility scripts.
- `docs/`: Documentation for the project.
- `README.md`: Project README file.
- **1.2 File Naming Conventions:**
- **Terraform:** `main.tf`, `variables.tf`, `outputs.tf`, `<module_name>.tf`
- **CloudFormation:** `<stack_name>.yml` or `<stack_name>.yaml`
- **Docker:** `Dockerfile` (no extension), `.dockerignore`
- **Scripts:** `<script_name>.sh` (Bash), `<script_name>.py` (Python)
- **Configuration:** `config.yml`, `config.json`, `.env`
- **1.3 Module Organization:**
- **Terraform Modules:** Create reusable Terraform modules for common ECS infrastructure components (e.g., ECS cluster, task definition, load balancer).
- **Application Modules:** Organize your application code into logical modules based on functionality (e.g., authentication, API, database access).
- Use separate git repositories for independent services/applications, and ECS services accordingly. This avoids monolithic deployments and allows independent scaling and versioning.
- **1.4 Component Architecture:**
- **Microservices:** Design your application as a collection of microservices, each deployed as an independent ECS service.
- **API Gateway:** Use an API gateway (e.g., Amazon API Gateway) to route requests to different ECS services.
- **Message Queue:** Use a message queue (e.g., Amazon SQS, Amazon MQ) for asynchronous communication between services.
- **Database:** Use a managed database service (e.g., Amazon RDS, Amazon DynamoDB) for data persistence. Ensure proper security and access control configurations.
- **1.5 Code Splitting:**
- Break down large applications or services into smaller, more manageable components that can be deployed independently.
- Optimize container images to only include code required for each specific component.
- Utilize ECS services to deploy each component separately, enabling independent scaling and upgrades.
- **2. Common Patterns and Anti-patterns:**
- **2.1 Design Patterns:**
- **Sidecar:** Use sidecar containers (e.g., for logging, monitoring, or service mesh) to add functionality to your main application container without modifying the application code. Use a separate container in the same task definition.
- **Backend for Frontend (BFF):** Create a BFF layer that provides a specific API for each client application, improving performance and security.
- **Strangler Fig:** Gradually migrate a legacy application to ECS by introducing new microservices and slowly replacing the old functionality.
- **Aggregator Pattern:** Use an aggregator service to combine data from multiple backend services into a single response.
- **2.2 Recommended Approaches:**
- **Health Checks:** Implement robust health checks for your containers and configure ECS to use them. Use both `HEALTHCHECK` in the `Dockerfile` for initial container health and ECS health checks (ELB health checks) for service availability.
- **Service Discovery:** Use service discovery (e.g., AWS Cloud Map) to enable services to find each other dynamically.
- **Load Balancing:** Use a load balancer (e.g., Application Load Balancer, Network Load Balancer) to distribute traffic across multiple ECS tasks.
- **Auto Scaling:** Configure auto scaling to automatically adjust the number of ECS tasks based on demand. Use CloudWatch metrics (CPU, memory, request count) as scaling triggers.
- **Immutable Infrastructure:** Avoid making changes to running containers. Instead, redeploy a new container image with the changes.
- **Use ECS Exec for debugging** avoid SSH into running EC2 instances
- **2.3 Anti-patterns:**
- **Hardcoding Configuration:** Avoid hardcoding configuration values in your application code.
- **Large Container Images:** Keep your container images small by using multi-stage builds and removing unnecessary dependencies.
- **Ignoring Security Best Practices:** Neglecting security best practices can lead to vulnerabilities. Always follow security best practices for container images, task definitions, and IAM roles.
- **Manual Scaling:** Manually scaling ECS tasks is inefficient and error-prone. Use auto scaling instead.
- **Monolithic Containers:** Avoid creating single containers that run multiple applications. Break them down into smaller, single-purpose containers.
- **2.4 State Management:**
- **Stateless Applications:** Design your applications to be stateless whenever possible. Store state in a database or other external storage service.
- **Persistent Storage:** Use persistent storage volumes (e.g., Amazon EFS, Amazon EBS) for stateful applications.
- **Container Lifecycle:** Understand the container lifecycle and how ECS manages container restarts and replacements.
- **2.5 Error Handling:**
- **Logging:** Implement comprehensive logging and monitoring for your applications. Log to stdout/stderr, and use a logging driver (e.g., FireLens) to ship logs to a central logging service (e.g., CloudWatch Logs, Splunk).
- **Exception Handling:** Implement proper exception handling in your application code.
- **Retry Logic:** Implement retry logic for transient errors.
- **Dead Letter Queues:** Use dead letter queues (DLQs) to handle messages that cannot be processed after multiple retries.
- **3. Performance Considerations:**
- **3.1 Optimization Techniques:**
- **Resource Allocation:** Properly size your ECS tasks based on the application's resource requirements (CPU, memory). Monitor resource utilization and adjust task sizes as needed.
- **Container Image Optimization:** Optimize container images by minimizing size, using efficient base images, and leveraging layer caching. Use tools like `docker image prune` to remove unused images.
- **Load Balancing:** Configure load balancing algorithms and connection draining to optimize traffic distribution and minimize downtime.
- **Caching:** Implement caching at various levels (e.g., application, CDN) to reduce latency and improve performance.
- **Connection Pooling:** Reuse database connections to minimize overhead.
- **3.2 Memory Management:**
- **Memory Limits:** Set appropriate memory limits for your containers. Monitor memory usage and adjust limits to prevent out-of-memory errors.
- **Garbage Collection:** Optimize garbage collection settings for your application's runtime environment.
- **Memory Leaks:** Identify and fix memory leaks in your application code.
- **3.3 Bundle Size Optimization:**
- **Code Splitting:** Split your application code into smaller bundles to reduce the initial load time. Utilize dynamic imports to only load code when it's needed.
- **Tree Shaking:** Remove unused code from your application bundle.
- **Minification:** Minify your application code to reduce its size.
- **Compression:** Compress your application code to reduce its size.
- **3.4 Lazy Loading:**
- Load resources (e.g., images, data) only when they are needed.
- Use lazy-loading techniques to improve the initial load time of your application.
- **4. Security Best Practices:**
- **4.1 Common Vulnerabilities:**
- **Container Image Vulnerabilities:** Unpatched vulnerabilities in container images can be exploited by attackers. Regularly scan container images for vulnerabilities and apply patches.
- **IAM Role Misconfiguration:** Overly permissive IAM roles can allow attackers to access sensitive resources. Follow the principle of least privilege and grant only the necessary permissions.
- **Network Security Misconfiguration:** Misconfigured network security can expose your ECS services to unauthorized access. Use security groups and network ACLs to restrict network access.
- **Secrets Management Vulnerabilities:** Storing secrets in plain text can expose them to attackers. Use a secrets management service (e.g., AWS Secrets Manager) to securely store and manage secrets.
- **4.2 Input Validation:**
- Validate all input data to prevent injection attacks (e.g., SQL injection, command injection).
- Use a framework or library to perform input validation.
- **4.3 Authentication and Authorization:**
- Implement authentication and authorization to control access to your ECS services.
- Use a standard authentication protocol (e.g., OAuth 2.0, OpenID Connect).
- Use fine-grained authorization policies to restrict access to specific resources.
- **4.4 Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to encrypt data in transit.
- Use AWS KMS to encrypt data at rest.
- Implement data masking and tokenization to protect sensitive data.
- **4.5 Secure API Communication:**
- Use HTTPS for all API communication.
- Implement authentication and authorization for all API endpoints.
- Validate all input data to prevent injection attacks.
- Protect against Cross-Site Request Forgery (CSRF) attacks.
- **5. Testing Approaches:**
- **5.1 Unit Testing:**
- Write unit tests for individual components of your application.
- Use a unit testing framework (e.g., JUnit, pytest).
- Mock external dependencies to isolate the component being tested.
- **5.2 Integration Testing:**
- Write integration tests to verify the interaction between different components of your application.
- Use a test environment that is similar to the production environment.
- Test the integration with external services (e.g., databases, message queues).
- **5.3 End-to-End Testing:**
- Write end-to-end tests to verify the functionality of the entire application.
- Use an end-to-end testing framework (e.g., Selenium, Cypress).
- Test the application from the user's perspective.
- **5.4 Test Organization:**
- Organize your tests into a logical directory structure.
- Use meaningful names for your test files and test methods.
- Use a test runner to execute your tests.
- **5.5 Mocking and Stubbing:**
- Use mocking and stubbing to isolate components during testing.
- Use a mocking framework (e.g., Mockito, EasyMock).
- Create mock objects that simulate the behavior of external dependencies.
- **6. Common Pitfalls and Gotchas:**
- **6.1 Frequent Mistakes:**
- **Incorrect IAM Permissions:** Granting insufficient or excessive IAM permissions can lead to security vulnerabilities or application failures.
- **Misconfigured Network Settings:** Misconfigured network settings can prevent containers from communicating with each other or with external services.
- **Insufficient Resource Limits:** Setting insufficient resource limits (CPU, memory) can cause containers to crash or become unresponsive.
- **Ignoring Health Checks:** Ignoring health checks can lead to ECS tasks being considered healthy even when they are not.
- **Failing to handle SIGTERM signals:** Applications in containers must gracefully handle SIGTERM signals to allow ECS to shutdown tasks cleanly.
- **6.2 Edge Cases:**
- **Task Placement Constraints:** Be aware of task placement constraints (e.g., availability zone, instance type) and how they can affect task scheduling.
- **Service Discovery Limitations:** Understand the limitations of service discovery and how it can affect service resolution.
- **Load Balancer Connection Draining:** Be aware of load balancer connection draining and how it can affect application availability during deployments.
- **6.3 Version-Specific Issues:**
- Stay up-to-date with the latest ECS agent and Docker versions to avoid known issues and security vulnerabilities.
- Check the AWS documentation for any version-specific issues or known bugs.
- **6.4 Compatibility Concerns:**
- Be aware of compatibility issues between ECS and other AWS services (e.g., VPC, IAM, CloudWatch).
- Test your application with different versions of these services to ensure compatibility.
- **6.5 Debugging Strategies:**
- **Logging:** Use comprehensive logging to track application behavior and identify errors.
- **Monitoring:** Use monitoring tools (e.g., CloudWatch) to track resource utilization and application performance.
- **Debugging Tools:** Use debugging tools (e.g., Docker exec, AWS Systems Manager Session Manager) to troubleshoot running containers.
- **ECS Exec:** Utilize the ECS Exec feature to directly connect to containers for debugging purposes.
- **7. Tooling and Environment:**
- **7.1 Recommended Tools:**
- **Terraform:** For infrastructure as code.
- **AWS CLI:** For interacting with AWS services from the command line.
- **Docker:** For building and managing container images.
- **AWS SAM CLI:** For local development of serverless applications.
- **Visual Studio Code (VS Code):** With AWS and Docker extensions for development and debugging.
- **cdk8s:** Define Kubernetes applications and ECS using general purpose programming languages.
- **7.2 Build Configuration:**
- **Makefile:** Use a Makefile to automate build, test, and deployment tasks.
- **Build Scripts:** Use build scripts to customize the build process.
- **CI/CD Pipeline:** Integrate your build process with a CI/CD pipeline (e.g., AWS CodePipeline, Jenkins).
- **7.3 Linting and Formatting:**
- **Linters:** Use linters (e.g., ESLint, Pylint) to enforce code style and identify potential errors.
- **Formatters:** Use formatters (e.g., Prettier, Black) to automatically format your code.
- **Editor Integration:** Integrate linters and formatters with your code editor.
- **7.4 Deployment:**
- **Blue/Green Deployments:** Use blue/green deployments to minimize downtime during deployments.
- **Canary Deployments:** Use canary deployments to gradually roll out new versions of your application.
- **Rolling Updates:** Use rolling updates to gradually update ECS tasks with the new version.
- **7.5 CI/CD Integration:**
- **Automated Builds:** Automate the build process using a CI/CD pipeline.
- **Automated Tests:** Run automated tests as part of the CI/CD pipeline.
- **Automated Deployments:** Automate the deployment process using a CI/CD pipeline.
+324
View File
@@ -0,0 +1,324 @@
---
description: This rule provides best practices and coding standards for developing applications that interact with AWS RDS. It covers code organization, security, performance, testing, and common pitfalls.
globs: **/*.{sql,js,py,java,tf,yaml,yml}
---
# AWS RDS Best Practices and Coding Standards
This document outlines best practices for developing applications interacting with AWS Relational Database Service (RDS). It covers code organization, common patterns, performance, security, testing, and deployment.
## Library Information:
- Name: aws-rds
- Tags: database, sql, aws, cloud
## 1. Code Organization and Structure
### 1.1 Directory Structure
Organize your project to promote maintainability and scalability. A suggested directory structure is:
project-root/
├── modules/ # Reusable components for RDS interactions
│ ├── db_config.py # Database connection configuration (e.g., using SQLAlchemy)
│ ├── rds_operations.py # CRUD operations (e.g., using boto3)
│ └── query_builder.py # Dynamic SQL query generation
├── models/ # Data models (e.g., SQLAlchemy models, Pydantic schemas)
│ ├── user.py # Example: User model definition
│ └── order.py # Example: Order model definition
├── services/ # Application logic interacting with RDS
│ ├── user_service.py # Example: User management service
│ └── reporting_service.py # Example: Reporting service
├── tests/ # Test suite
│ ├── unit/ # Unit tests for individual components
│ ├── integration/ # Integration tests for RDS interactions
│ └── e2e/ # End-to-end tests
├── config/ # Configuration files
│ ├── settings.py # Application settings (database credentials, etc.)
│ └── logging.yaml # Logging configuration
├── migrations/ # Database migration scripts (e.g., using Alembic)
├── infrastructure/ # Infrastructure-as-Code (IaC) using Terraform or CloudFormation
│ ├── rds.tf # RDS instance and security group definition (Terraform example)
│ └── security_group.tf # RDS Security Group definition (Terraform example)
├── scripts/ # Utility scripts for database management and deployment
├── README.md # Project documentation
├── requirements.txt # Python dependencies (example)
└── .env # Environment variables (for local development, never commit this file!)
### 1.2 File Naming Conventions
- **Python:** Use snake_case for file and variable names (e.g., `rds_operations.py`, `user_id`).
- **JavaScript/TypeScript:** Use camelCase for variable names and PascalCase for class and component names (e.g., `getUser`, `UserComponent`). Generally, kebab-case is recommended for component file names (e.g., `user-component.jsx`).
- **SQL:** Use snake_case for table and column names (e.g., `users`, `user_name`). Use `.sql` as the file extension and use uppercase for SQL keywords (e.g., `SELECT`, `FROM`, `WHERE`).
- **Terraform:** Use snake_case (e.g., `rds_instance.tf`).
### 1.3 Module Organization
- Break down large modules into smaller, more manageable files.
- Use clear and descriptive module names.
- Avoid circular dependencies between modules.
- Use dependency injection to decouple modules and improve testability.
### 1.4 Component Architecture
- **Layered Architecture:** Separate concerns into distinct layers (e.g., data access layer, business logic layer, presentation layer).
- **Microservices:** For larger applications, consider using a microservices architecture, with each service responsible for a specific domain and interacting with its own RDS instance.
- **Event-Driven Architecture:** Use an event-driven architecture to decouple components and improve scalability. For example, use AWS SNS or SQS to trigger actions based on database changes.
### 1.5 Code Splitting
- Split large files into smaller, more focused files.
- Organize files by feature or functionality.
- Use lazy loading for less frequently used modules.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
- **Repository Pattern:** Abstract data access logic behind a repository interface.
- **Unit of Work Pattern:** Track changes to entities and persist them as a single unit.
- **Factory Pattern:** Encapsulate object creation logic.
- **Observer Pattern:** React to database changes or events.
- **Singleton Pattern:** Use carefully for database connections. Connection pooling libraries often manage this internally; avoid creating your own Singleton unless necessary for custom connection management logic.
### 2.2 Recommended Approaches
- **Connection Pooling:** Use connection pooling to efficiently manage database connections. Popular libraries include SQLAlchemy (Python) and HikariCP (Java).
- **ORM (Object-Relational Mapping):** Use an ORM like SQLAlchemy, Django ORM (Python), Hibernate (Java), or Sequelize (JavaScript) to map database tables to objects and simplify data access.
- **Database Migrations:** Use a migration tool like Alembic (Python) or Flyway (Java) to manage database schema changes.
- **Asynchronous Operations:** Use asynchronous operations to avoid blocking the main thread when interacting with RDS, especially for long-running queries or large data transfers.
- **Parameterized Queries:** Always use parameterized queries to prevent SQL injection attacks.
### 2.3 Anti-patterns
- **Writing Raw SQL Directly in Application Code:** Avoid embedding raw SQL queries directly within the application code. This makes the code harder to maintain and more vulnerable to SQL injection attacks. Use an ORM or query builder instead.
- **Ignoring Connection Management:** Failing to properly open and close database connections can lead to resource exhaustion and performance issues. Always use connection pooling and ensure connections are closed promptly.
- **Over-fetching Data:** Avoid retrieving more data than necessary from the database. This can lead to performance problems, especially when dealing with large tables. Use appropriate `WHERE` clauses and select only the required columns.
- **Ignoring Error Handling:** Failing to handle database errors gracefully can lead to unexpected application behavior and data corruption. Implement robust error handling mechanisms and log errors appropriately.
- **Storing Secrets in Code:** Never store database credentials or other sensitive information directly in the application code or configuration files. Use environment variables or a secrets management service like AWS Secrets Manager.
- **Lack of Indexing:** Neglecting to add indexes to frequently queried columns can drastically reduce query performance. Analyze query execution plans to identify missing indexes.
### 2.4 State Management
- **Stateless Applications:** Design applications to be stateless to improve scalability and fault tolerance. Use RDS to store persistent data.
- **Caching:** Use caching to reduce the load on RDS. Implement caching at different levels (e.g., application-level caching, database-level caching using Redis or Memcached).
### 2.5 Error Handling
- **Try-Except Blocks:** Use `try-except` (Python), `try-catch` (Java/JavaScript) blocks to handle potential exceptions during RDS interactions.
- **Logging:** Log all database errors to a central location for monitoring and debugging.
- **Retry Mechanism:** Implement a retry mechanism with exponential backoff for transient errors (e.g., network connectivity issues).
- **Custom Exceptions:** Define custom exception classes for specific RDS-related errors.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Query Optimization:** Analyze query execution plans and optimize queries for performance. Use indexes, rewrite inefficient queries, and avoid using `SELECT *`.
- **Connection Pooling:** As mentioned earlier, use connection pooling to reuse database connections and reduce overhead.
- **Caching:** Implement caching strategies to reduce the number of database queries.
- **Read Replicas:** Use read replicas to offload read traffic from the primary RDS instance.
- **Provisioned IOPS:** Use provisioned IOPS (IOPS) for workloads that require consistent high performance.
- **Database Tuning:** Tune database parameters (e.g., buffer pool size, query cache size) based on workload characteristics.
- **Partitioning:** Use table partitioning for very large tables to improve query performance and manageability.
- **Stored Procedures:** Use stored procedures for complex operations to reduce network traffic and improve security.
### 3.2 Memory Management
- **Appropriate Instance Size:** Choose an RDS instance size that is appropriate for the workload. Consider memory requirements for the database server and application.
- **Monitor Memory Usage:** Monitor memory usage on the RDS instance using CloudWatch metrics and adjust the instance size or database parameters as needed.
- **Avoid Memory Leaks:** Be careful to avoid memory leaks in the application code, especially when dealing with large datasets or database connections.
### 3.3 Rendering Optimization (If Applicable)
- This is primarily relevant if you are directly rendering data retrieved from RDS in a user interface.
- **Pagination:** Implement pagination to load data in smaller chunks, improving initial load times.
- **Virtualization:** Use virtualization techniques (e.g., virtual scrolling) to render large lists of data efficiently.
- **Memoization:** Use memoization to cache the results of expensive rendering operations.
### 3.4 Bundle Size Optimization
- **Tree Shaking:** Use tree shaking to remove unused code from the JavaScript/TypeScript bundle.
- **Code Splitting:** Split the code into smaller chunks that can be loaded on demand.
- **Minification:** Minify the code to reduce the bundle size.
- **Compression:** Compress the bundle using gzip or Brotli.
### 3.5 Lazy Loading
- **Lazy Loading of Modules:** Load modules on demand to reduce the initial load time of the application.
- **Lazy Loading of Data:** Load data only when it is needed (e.g., when a user scrolls down a page).
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
- **SQL Injection:** Exploiting vulnerabilities in SQL queries to execute malicious code.
- **Cross-Site Scripting (XSS):** Injecting malicious scripts into web pages served from your application.
- **Cross-Site Request Forgery (CSRF):** Tricking users into performing actions they did not intend to perform.
- **Data Breach:** Unauthorized access to sensitive data stored in RDS.
- **Denial of Service (DoS):** Overwhelming the RDS instance with requests, making it unavailable to legitimate users.
### 4.2 Input Validation
- **Whitelist Validation:** Validate input against a whitelist of allowed characters or patterns.
- **Data Type Validation:** Ensure that input data is of the correct data type.
- **Length Validation:** Limit the length of input strings to prevent buffer overflows.
- **Encoding:** Encode input data to prevent HTML injection.
- **Parameterized Queries (again!):** Use parameterized queries to prevent SQL injection attacks.
### 4.3 Authentication and Authorization
- **IAM Roles:** Use IAM roles to grant permissions to applications to access RDS.
- **Database Usernames and Passwords:** Use strong database usernames and passwords and store them securely using AWS Secrets Manager. Avoid using the `admin` user for application access.
- **Least Privilege Principle:** Grant only the necessary permissions to database users.
- **Multi-Factor Authentication (MFA):** Enable MFA for database user accounts.
- **Row-Level Security (RLS):** Implement row-level security to restrict access to specific rows in a table.
- **VPC Security Groups:** Utilize VPC security groups to control network access to the RDS instance.
### 4.4 Data Protection
- **Encryption at Rest:** Enable encryption at rest for the RDS instance.
- **Encryption in Transit:** Use SSL/TLS to encrypt data in transit between the application and RDS.
- **Data Masking:** Mask sensitive data in the database to protect it from unauthorized access.
- **Data Backup and Recovery:** Implement a data backup and recovery plan to protect against data loss.
- **Regular Auditing:** Audit database activity regularly to identify and investigate suspicious behavior.
### 4.5 Secure API Communication
- **HTTPS:** Use HTTPS for all API communication with the application.
- **API Authentication:** Authenticate all API requests using API keys, JWT tokens, or other authentication mechanisms.
- **API Authorization:** Authorize all API requests to ensure that users only have access to the resources they are authorized to access.
- **Rate Limiting:** Implement rate limiting to prevent DoS attacks.
## 5. Testing Approaches
### 5.1 Unit Testing
- **Focus:** Test individual components in isolation (e.g., functions, classes).
- **Mocking:** Use mocking to isolate components from external dependencies, such as RDS.
- **Assertions:** Use assertions to verify that the components are behaving as expected.
- **Test Coverage:** Aim for high test coverage to ensure that all parts of the code are tested.
### 5.2 Integration Testing
- **Focus:** Test the interactions between different components, including RDS.
- **Test Databases:** Use test databases for integration tests to avoid affecting production data.
- **Data Setup and Teardown:** Set up test data before each test and tear down the data after each test to ensure that the tests are isolated.
- **Transaction Management:** Use transaction management to rollback changes made during tests.
### 5.3 End-to-End (E2E) Testing
- **Focus:** Test the entire application flow, from the user interface to the database.
- **Automated Testing:** Automate E2E tests to ensure that the application is working correctly.
- **Realistic Scenarios:** Use realistic scenarios to simulate user behavior.
- **Browser Automation:** Use browser automation tools (e.g., Selenium, Cypress) to automate E2E tests.
### 5.4 Test Organization
- **Separate Test Directory:** Store all tests in a separate directory.
- **Mirror Source Code Structure:** Mirror the source code structure in the test directory to make it easy to find the tests for a specific component.
- **Descriptive Test Names:** Use descriptive test names to make it clear what each test is testing.
### 5.5 Mocking and Stubbing
- **Mocking:** Replace external dependencies with mock objects that simulate their behavior.
- **Stubbing:** Replace specific methods or functions of external dependencies with stubs that return predefined values.
- **Mocking Libraries:** Use mocking libraries (e.g., Mockito (Java), pytest-mock (Python), Jest (JavaScript)) to simplify the creation of mock objects and stubs.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Not Using Connection Pooling:** Leading to excessive connection overhead and performance issues.
- **SQL Injection Vulnerabilities:** Due to improper input validation and not using parameterized queries.
- **Over-fetching Data:** Retrieving more data than necessary, leading to performance problems.
- **Ignoring Error Handling:** Leading to unexpected application behavior and data corruption.
- **Not Monitoring RDS Performance:** Failing to monitor RDS performance, leading to undetected performance issues.
- **Underestimating Database Growth:** Not planning for future database growth, leading to performance problems and storage limitations.
- **Using Default Security Settings:** Leaving the RDS instance with default security settings, making it vulnerable to attacks.
### 6.2 Edge Cases
- **Handling Large Datasets:** Optimizing queries and using pagination to handle large datasets efficiently.
- **Concurrent Access:** Handling concurrent access to the database using transactions and locking mechanisms.
- **Network Connectivity Issues:** Implementing retry mechanisms and handling network connectivity issues gracefully.
- **Database Failover:** Testing the application's ability to handle database failover seamlessly.
- **Time Zones:** Correctly handling time zones when storing and retrieving dates and times from RDS.
### 6.3 Version-Specific Issues
- **Check Release Notes:** Always review the release notes for each new version of the RDS engine to identify any breaking changes or known issues.
- **Compatibility Testing:** Perform compatibility testing to ensure that the application works correctly with the new version of the RDS engine.
- **Deprecation Warnings:** Pay attention to deprecation warnings and update the code accordingly.
### 6.4 Compatibility Concerns
- **ORM Compatibility:** Ensure that the ORM is compatible with the specific RDS engine being used.
- **Driver Compatibility:** Use the latest version of the database driver to ensure compatibility with the RDS engine.
- **API Compatibility:** Ensure that the application's API is compatible with the RDS API.
### 6.5 Debugging Strategies
- **Logging:** Use logging to trace the execution flow of the application and identify potential issues.
- **Remote Debugging:** Use remote debugging to debug the application running in a production environment.
- **Query Profiling:** Use query profiling tools to analyze the performance of SQL queries.
- **Database Monitoring:** Use database monitoring tools to monitor the health and performance of the RDS instance.
- **CloudWatch Metrics:** Use CloudWatch metrics to monitor CPU utilization, memory usage, disk I/O, and network traffic.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE (Integrated Development Environment):** VS Code, IntelliJ IDEA, PyCharm, Eclipse.
- **Database Client:** DBeaver, SQL Developer, pgAdmin.
- **Database Migration Tool:** Alembic, Flyway.
- **Testing Framework:** pytest, unittest (Python), JUnit (Java), Jest (JavaScript).
- **Mocking Library:** Mockito (Java), pytest-mock (Python), Jest (JavaScript).
- **AWS CLI:** The AWS Command Line Interface (CLI) is a unified tool to manage your AWS services.
- **Terraform/CloudFormation:** Infrastructure-as-Code tools to manage RDS infrastructure.
### 7.2 Build Configuration
- **Dependency Management:** Use a dependency management tool (e.g., pip (Python), Maven (Java), npm/yarn (JavaScript)) to manage project dependencies.
- **Build Automation:** Use a build automation tool (e.g., Make, Gradle, Maven, npm scripts) to automate the build process.
- **Environment Variables:** Use environment variables to configure the application for different environments (e.g., development, staging, production).
### 7.3 Linting and Formatting
- **Linters:** Use linters (e.g., pylint (Python), ESLint (JavaScript), Checkstyle (Java)) to enforce coding standards and identify potential issues.
- **Formatters:** Use formatters (e.g., black (Python), Prettier (JavaScript), Google Java Format (Java)) to automatically format the code.
### 7.4 Deployment
- **Infrastructure as Code:** Use Infrastructure as Code (IaC) tools (e.g., Terraform, CloudFormation) to automate the deployment of RDS infrastructure.
- **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies into a portable container.
- **Orchestration:** Use an orchestration tool (e.g., Kubernetes, ECS) to manage and scale the application.
- **Blue/Green Deployments:** Use blue/green deployments to minimize downtime during deployments.
- **Rolling Deployments:** Use rolling deployments to gradually update the application without disrupting service.
### 7.5 CI/CD Integration
- **Continuous Integration (CI):** Integrate the build, test, and linting processes into a CI pipeline to automatically run these checks whenever code is committed.
- **Continuous Deployment (CD):** Automate the deployment process to automatically deploy the application to production whenever code is committed.
- **CI/CD Tools:** Use CI/CD tools (e.g., Jenkins, GitHub Actions, CircleCI, GitLab CI) to manage the CI/CD pipeline.
## Additional RDS Best Practices (From Exa Search and Citations):
- **Monitoring Metrics:** Monitor RDS metrics like memory, CPU, storage usage using CloudWatch. Set up alarms for unusual activity.
- **Automatic Backups:** Enable automatic backups with a window during low IOPS periods.
- **Scaling DB Instances:** Scale DB instances vertically as needed to meet demand.
- **Optimize Queries:** Tune queries to minimize resource consumption.
- **AWS Database Drivers:** Use the AWS suite of drivers for faster failover and integration with AWS Secrets Manager and IAM.
- **Regular Updates:** Regularly update statistics and monitor performance metrics.
- **Enough RAM:** Allocate enough RAM so that your working set resides almost completely in memory to minimize disk I/O.
- **Client DNS Caching:** Set a time-to-live (TTL) value of less than 30 seconds if your client application is caching the Domain Name Service (DNS) data of your DB instances.
- **Test Failover:** Test failover for your DB instance to understand how long the process takes for your particular use case.
## References:
- [AWS RDS Documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_BestPractices.html)
- [AWS Database Blog](https://aws.amazon.com/blogs/database/best-practices-for-configuring-performance-parameters-for-amazon-rds-for-sql-server/)
- [AWS re:Invent Videos (Links as provided in search results)]
By adhering to these best practices, developers can build scalable, secure, and performant applications that leverage the power of AWS RDS.
+176
View File
@@ -0,0 +1,176 @@
---
description: Comprehensive guidelines for Azure Pipelines, covering code structure, security, performance, testing, and deployment. Provides actionable advice for developers working with Azure Pipelines YAML definitions to enhance code quality and CI/CD processes.
globs: **/*.{yml,yaml}
---
- # General Guidelines
- Utilize YAML pipelines for version control and ease of replication.
- Integrate security practices throughout the pipeline using Azure Key Vault for secret management.
- Implement role-based access controls (RBAC) to limit permissions.
- Establish monitoring and alerting mechanisms for maintaining pipeline health and addressing issues.
- Use Infrastructure as Code (IaC) for consistent deployments.
- # 1. Code Organization and Structure
- **Directory Structure Best Practices:**
- Organize pipeline definitions into a dedicated directory (e.g., `azure-pipelines`).
- Use subdirectories to categorize pipelines based on application, environment, or team (e.g., `azure-pipelines/app1/dev`, `azure-pipelines/app1/prod`).
- Store reusable templates and scripts in a separate `templates` or `scripts` directory.
- Consider using a `modules` directory for custom modules or extensions related to pipeline functionality.
- **File Naming Conventions:**
- Use descriptive names for pipeline definitions (e.g., `ci-cd-app1-dev.yml`, `deploy-to-staging.yml`).
- Prefix or suffix template files with `template` or `tmpl` (e.g., `build-template.yml`, `deploy-tmpl.yml`).
- Use consistent naming for variables, parameters, and stages within YAML files.
- **Module Organization Best Practices:**
- Break down complex pipelines into smaller, reusable modules using templates.
- Use parameters to configure templates for different scenarios.
- Store modules in a central repository for sharing across projects.
- **Component Architecture Recommendations:**
- Design pipelines with a clear separation of concerns (e.g., build, test, deploy).
- Use stages to represent distinct phases of the CI/CD process.
- Leverage tasks to perform specific actions within each stage.
- Define clear inputs and outputs for each component (stage/task).
- **Code Splitting Strategies:**
- Split large YAML files into smaller, more manageable files using the `extends` keyword.
- Use templates to define reusable pipeline components.
- Implement parameterization to customize pipeline behavior without duplicating code.
- # 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Template Pattern:** Define a base template with placeholders for customization, allowing for consistent pipeline structure with varying configurations.
- **Strategy Pattern:** Use parameters to select different deployment strategies (e.g., blue-green, canary) within a single pipeline.
- **Chain of Responsibility:** Implement a sequence of tasks or stages, where each component handles a specific aspect of the deployment process.
- **Recommended Approaches for Common Tasks:**
- **Secret Management:** Use Azure Key Vault to store sensitive information such as passwords, API keys, and connection strings. Reference secrets in pipelines using variables or tasks.
- **Environment Configuration:** Define environment-specific variables and settings using variable groups. Use conditional execution to apply different configurations based on the target environment.
- **Artifact Management:** Publish and consume artifacts using the `PublishBuildArtifacts` and `DownloadBuildArtifacts` tasks. Use artifact feeds to store and manage dependencies.
- **Rollback Strategies:** Implement rollback mechanisms to revert to a previous version in case of deployment failures. Use deployment slots or blue-green deployments for seamless rollbacks.
- **Anti-patterns and Code Smells:**
- Hardcoding secrets in pipeline definitions.
- Duplicating code across multiple pipelines.
- Overly complex and monolithic YAML files.
- Lack of error handling and logging.
- Insufficient testing and validation.
- **State Management Best Practices:**
- Use Azure DevOps variables or variable groups to store pipeline state.
- Consider using external storage (e.g., Azure Blob Storage, Azure Table Storage) for persistent state.
- Implement idempotency to ensure that pipeline operations can be safely retried.
- **Error Handling Patterns:**
- Use the `try...catch` construct to handle exceptions within pipeline tasks.
- Implement retry mechanisms for transient failures.
- Configure alerts and notifications for pipeline failures.
- # 3. Performance Considerations
- **Optimization Techniques:**
- **Parallel Execution:** Use parallel jobs to run multiple tasks concurrently, reducing overall pipeline execution time.
- **Caching:** Cache dependencies and build artifacts to speed up subsequent builds.
- **Agent Selection:** Choose the appropriate agent size and type based on the workload requirements.
- **Task Optimization:** Optimize individual tasks to minimize execution time (e.g., using efficient scripts, optimizing database queries).
- **Memory Management:**
- Monitor pipeline memory usage and identify potential memory leaks.
- Use appropriate data structures and algorithms to minimize memory consumption.
- Optimize image sizes for containerized applications.
- **Bundle Size Optimization:**
- Minimize the size of build artifacts by removing unnecessary files and dependencies.
- Use code splitting and tree shaking techniques to reduce bundle size.
- Compress artifacts before publishing.
- **Lazy Loading:**
- Implement lazy loading for large files or datasets to improve pipeline startup time.
- # 4. Security Best Practices
- **Common Vulnerabilities and Prevention:**
- **Credential Leaks:** Avoid storing secrets in pipeline definitions or source code. Use Azure Key Vault for secure secret management.
- **Command Injection:** Sanitize user inputs and avoid executing untrusted code. Use parameterized tasks and scripts to prevent command injection attacks.
- **Unauthorized Access:** Implement RBAC to restrict access to sensitive resources and operations.
- **Dependency Vulnerabilities:** Regularly scan dependencies for known vulnerabilities and update them to the latest versions.
- **Input Validation:**
- Validate all user inputs to prevent injection attacks and other security vulnerabilities.
- Use regular expressions or other validation techniques to ensure that inputs conform to expected formats.
- Implement input sanitization to remove or escape potentially malicious characters.
- **Authentication and Authorization:**
- Use service principals or managed identities for authentication with Azure resources.
- Implement RBAC to control access to pipelines, resources, and environments.
- Enforce multi-factor authentication (MFA) for privileged accounts.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure protocols (e.g., HTTPS, TLS) for API communication.
- Mask sensitive information in pipeline logs and outputs.
- **Secure API Communication:**
- Use API keys or access tokens for authentication.
- Implement rate limiting to prevent denial-of-service attacks.
- Validate API responses to prevent data corruption.
- # 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for individual pipeline tasks and components.
- Use mocking frameworks to isolate components and simulate dependencies.
- Ensure that unit tests cover all critical code paths.
- **Integration Testing:**
- Perform integration tests to verify the interaction between different pipeline stages and tasks.
- Test the integration with external services and resources.
- Use test environments that closely resemble production environments.
- **End-to-end Testing:**
- Conduct end-to-end tests to validate the entire CI/CD pipeline from code commit to deployment.
- Use automated testing frameworks to automate end-to-end tests.
- Test the deployed application in a production-like environment.
- **Test Organization:**
- Organize tests into a dedicated `tests` directory.
- Use a consistent naming convention for test files and methods.
- Group tests based on functionality or component.
- **Mocking and Stubbing:**
- Use mocking frameworks (e.g., Moq, NSubstitute) to create mock objects for dependencies.
- Use stubbing to replace complex dependencies with simple, predictable implementations.
- # 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- Using incorrect YAML syntax.
- Forgetting to parameterize reusable components.
- Neglecting error handling and logging.
- Insufficient testing.
- Ignoring security best practices.
- **Edge Cases:**
- Handling large files or datasets.
- Dealing with complex dependencies.
- Managing concurrency and race conditions.
- Recovering from catastrophic failures.
- **Version-Specific Issues:**
- Be aware of breaking changes in Azure DevOps updates.
- Test pipelines after upgrading Azure DevOps versions.
- Use version control to track changes to pipeline definitions.
- **Compatibility Concerns:**
- Ensure compatibility between pipeline tasks and agent versions.
- Verify compatibility with external services and resources.
- **Debugging Strategies:**
- Use pipeline logs to identify errors and warnings.
- Enable verbose logging for detailed troubleshooting.
- Use remote debugging to step through pipeline execution.
- # 7. Tooling and Environment
- **Recommended Development Tools:**
- Visual Studio Code with the Azure Pipelines extension.
- Azure CLI.
- PowerShell.
- YAML linters and validators.
- **Build Configuration Best Practices:**
- Use a consistent build configuration across environments.
- Store build configuration in version control.
- Use environment variables to customize build behavior.
- **Linting and Formatting:**
- Use YAML linters (e.g., yamllint) to enforce consistent formatting and syntax.
- Configure linters to automatically fix formatting issues.
- **Deployment Best Practices:**
- Use deployment slots for zero-downtime deployments.
- Implement rollback mechanisms for failed deployments.
- Monitor deployed applications for performance and errors.
- **CI/CD Integration:**
- Integrate Azure Pipelines with source control systems (e.g., Azure Repos, GitHub).
- Automate build, test, and deployment processes.
- Use triggers to automatically start pipelines on code changes.
- # Additional Best Practices
- **Infrastructure as Code (IaC):** Use tools like ARM templates or Terraform for consistent deployments.
- **Automated Testing:** Automate builds, run tests, and perform code quality checks with each commit.
- **Secret Management:** Securely manage secrets using Azure Key Vault.
- **Monitoring and Alerting:** Implement robust monitoring and alerting for pipeline health.
- **Role-Based Access Control (RBAC):** Enforce RBAC to limit access to sensitive resources.
- **Regular Audits:** Perform regular security audits to identify and address vulnerabilities.
By adhering to these guidelines, developers can create robust, secure, and efficient Azure Pipelines for continuous integration and continuous delivery.
+292
View File
@@ -0,0 +1,292 @@
---
description: This rule enforces best practices and coding standards for Bash scripting to improve code quality, maintainability, and security. It covers naming conventions, formatting, error handling, security, and performance considerations.
globs: **/*.sh
---
# Bash Best Practices and Coding Standards
This document outlines the best practices and coding standards for writing Bash scripts. Following these guidelines will lead to more maintainable, readable, and robust code.
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
For large Bash projects, a well-defined directory structure is crucial. Consider the following structure:
project_root/
├── bin/ # Executable scripts (main entry points)
├── lib/ # Library scripts (reusable functions and modules)
├── config/ # Configuration files (e.g., settings, environment variables)
├── data/ # Data files (e.g., CSV, JSON)
├── log/ # Log files generated by scripts
├── tmp/ # Temporary files used during script execution
├── tests/ # Unit and integration tests
├── docs/ # Documentation (e.g., README, design documents)
└── README.md # Project README
### 1.2. File Naming Conventions
* **Executable Scripts:** Use descriptive names without extensions (e.g., `process_data`, `backup_system`).
* **Library Scripts:** Use `.sh` extension (e.g., `string_utils.sh`, `database_functions.sh`). For bash-specific code use `.bash`.
* **Configuration Files:** Use `.conf` or `.cfg` extensions (e.g., `app.conf`, `settings.cfg`).
* **Test Files:** Use `_test.sh` suffix (e.g., `string_utils_test.sh`).
### 1.3. Module Organization
* **Separate Concerns:** Divide your code into logical modules, each responsible for a specific task (e.g., database interaction, string manipulation, system monitoring).
* **Reusable Functions:** Place reusable functions in library scripts (`lib/`) and source them in your main scripts using `source lib/string_utils.sh` or `. lib/string_utils.sh`.
* **Modular Design:** Aim for a modular design where each module can be easily tested and reused in other projects.
### 1.4. Component Architecture
* **Functions as Components:** Treat functions as components with well-defined inputs (parameters) and outputs (return values or side effects).
* **Configuration Management:** Use configuration files to store settings that can be easily modified without changing the script's code.
* **Logging:** Implement a consistent logging mechanism to track script execution and errors.
### 1.5. Code Splitting Strategies
* **Function Decomposition:** Break down complex tasks into smaller, more manageable functions.
* **File Inclusion:** Use `source` or `.` to include reusable code from other files.
* **External Commands:** Delegate tasks to external commands when appropriate (e.g., `grep`, `sed`, `awk`).
* **Consider a 'main' function:** Wrap the primary logic of the script into a `main` function to improve readability and maintainability. All scripts that are long enough to contain at least one other function should have a `main` function.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Facade:** Create a simplified interface to a complex set of functions or modules.
* **Strategy:** Define a family of algorithms and encapsulate each one in a separate function, making them interchangeable.
* **Template Method:** Define the skeleton of an algorithm in a function, deferring some steps to subfunctions.
* **Chain of Responsibility:** Pass a request along a chain of functions until one of them handles it.
* **Singleton (Carefully):** Use sparingly for global configuration, initialize only once.
### 2.2. Recommended Approaches for Common Tasks
* **String Manipulation:** Use Bash's built-in string manipulation features (e.g., parameter expansion, substring extraction) instead of external commands like `sed` or `awk` when possible.
* **File Handling:** Use Bash's built-in file handling commands (e.g., `read`, `write`, `mkdir`, `rm`) for basic operations. For more complex operations, consider `find` with `-exec` or `xargs`.
* **Looping:** Use `for` loops for iterating over lists of items and `while` loops for conditional execution.
* **Conditional Statements:** Use `if`, `elif`, and `else` statements for branching logic. Prefer `[[ ]]` over `[ ]` for string comparisons.
* **Exit Early:** Use `return` or `exit` to exit the script as soon as an error is detected.
### 2.3. Anti-patterns and Code Smells
* **Hardcoded Values:** Avoid hardcoding values directly in the script. Use constants or configuration files instead.
* **Unquoted Variables:** Always quote variables to prevent word splitting and globbing issues.
* **Eval:** Avoid using `eval` as it can introduce security vulnerabilities and make the code difficult to understand.
* **Backticks:** Use `$(command)` instead of backticks for command substitution.
* **Relying on Globals:** Minimize the use of global variables to avoid naming conflicts and unexpected side effects. Use `local` within functions.
* **Ignoring Errors:** Always check the return values of commands to handle errors gracefully. Use `set -e` to exit on errors automatically.
* **Over-commenting Obvious Code:** Comments should explain *why* the code is doing something, not *what* the code is doing.
* **Excessive Piping:** While powerful, long pipelines can become unreadable. Consider breaking down complex operations into smaller, more manageable steps with intermediate variables.
### 2.4. State Management Best Practices
* **Environment Variables:** Use environment variables to store global configuration settings that can be accessed by all scripts and functions.
* **Temporary Files:** Use temporary files to store intermediate data during script execution. Use `mktemp` to create unique temporary file names and remove them when finished. They should be created under `/tmp` or another location if needed.
* **Persistent Storage:** For persistent state, consider using a simple database (e.g., SQLite) or a key-value store (e.g., Redis).
* **Configuration Files:** Store persistent configuration options in configuration files.
### 2.5. Error Handling Patterns
* **`set -e`:** Exit immediately if a command exits with a non-zero status.
* **Check Return Values:** Use `$?` to check the return value of a command and handle errors accordingly.
* **Error Functions:** Create functions to handle common error scenarios (e.g., logging errors, displaying error messages, exiting the script).
* **Signal Handling:** Use `trap` to handle signals (e.g., `SIGINT`, `SIGTERM`) and perform cleanup actions.
* **Informative Error Messages:** Provide clear and informative error messages to help users diagnose problems. The error messages should explain the cause and possibly the recommended solution.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Built-in Commands:** Prefer built-in commands over external commands whenever possible, as they are generally faster.
* **String Operations:** Use Bash's built-in string manipulation features instead of external commands like `sed` or `awk` for simple operations.
* **Avoid Loops:** Minimize the use of loops, as they can be slow in Bash. Consider using `find` with `-exec` or `xargs` for file processing instead.
* **Command Substitution:** Avoid unnecessary command substitution, as it can be expensive.
* **Arrays:** Use arrays to store lists of items instead of strings, as they are more efficient for iteration and manipulation.
* **Parameter Expansion:** Use parameter expansion features like `${var:-default}` to provide default values for variables without using conditional statements.
* **`set -f`:** Disable globbing when not needed to prevent unintended file expansion.
### 3.2. Memory Management
* **Limit Data Size:** Avoid loading large files or data structures into memory.
* **Stream Processing:** Use stream processing techniques to process data incrementally instead of loading it all into memory at once.
* **Remove Variables:** Unset or reassign variables to release memory when they are no longer needed.
### 3.3. Rendering Optimization (If Applicable)
* **Minimize Output:** Reduce the amount of output generated by the script, as it can slow down execution.
* **Use `printf`:** Use `printf` for formatted output instead of `echo`, as it is generally faster and more portable.
### 3.4. Bundle Size Optimization (If Applicable)
* **N/A:** Bash scripts do not typically have bundle sizes in the same way that web applications do.
### 3.5. Lazy Loading
* **Source on Demand:** Only source library scripts when they are needed.
* **Conditional Execution:** Use conditional statements to execute code blocks only when certain conditions are met.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
* **Command Injection:** Avoid using `eval` and carefully sanitize any user input used in commands.
* **Path Injection:** Sanitize path names to prevent malicious users from manipulating file operations.
* **Denial of Service (DoS):** Implement resource limits to prevent scripts from consuming excessive CPU, memory, or disk space.
* **Information Disclosure:** Protect sensitive information (e.g., passwords, API keys) by storing them in environment variables or configuration files with appropriate permissions.
* **Shellshock:** Ensure your Bash version is patched against the Shellshock vulnerability.
### 4.2. Input Validation
* **Sanitize User Input:** Carefully sanitize any user input to prevent command injection and other vulnerabilities.
* **Regular Expressions:** Use regular expressions to validate input formats (e.g., email addresses, phone numbers).
* **Whitelist Validation:** Validate input against a whitelist of allowed values.
* **Length Limits:** Enforce length limits on input fields to prevent buffer overflows.
### 4.3. Authentication and Authorization
* **Avoid Storing Credentials:** Avoid storing credentials directly in scripts or configuration files. Use environment variables or a secure credential store instead.
* **Principle of Least Privilege:** Run scripts with the minimum necessary privileges.
* **User Authentication:** Implement user authentication using `sudo` or other authentication mechanisms.
* **Role-Based Access Control (RBAC):** Implement RBAC to restrict access to sensitive resources based on user roles.
### 4.4. Data Protection
* **Encryption:** Use encryption to protect sensitive data at rest and in transit.
* **Data Masking:** Mask sensitive data in log files and other output.
* **Access Control:** Restrict access to sensitive data to authorized users only.
### 4.5. Secure API Communication
* **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
* **API Keys:** Use API keys to authenticate requests to external APIs.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
* **Input Validation:** Validate all input from external APIs to prevent injection attacks.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Individual Functions:** Write unit tests to verify the behavior of individual functions.
* **Mock Dependencies:** Use mocking techniques to isolate functions from their dependencies.
* **Assert Statements:** Use assert statements to verify that the functions return the expected values.
* **Testing Frameworks:** Consider using a bash testing framework like Bats (Bash Automated Testing System).
### 5.2. Integration Testing
* **Test Interactions:** Write integration tests to verify the interactions between different modules or components.
* **Real Environments:** Run integration tests in a real or simulated environment.
* **End-to-End Testing:** Write end-to-end tests to verify the entire script from start to finish.
### 5.3. End-to-End Testing
* **Real Use Cases:** Emulate real-world use cases to test the script's overall functionality.
* **System-Level Testing:** Verify that the script interacts correctly with the underlying system.
### 5.4. Test Organization
* **Separate Test Directory:** Create a separate `tests/` directory to store test files.
* **Naming Convention:** Use a consistent naming convention for test files (e.g., `module_name_test.sh`).
* **Test Suites:** Organize tests into suites based on functionality or module.
### 5.5. Mocking and Stubbing
* **Mock External Commands:** Create mock versions of external commands to isolate functions from their dependencies.
* **Stub Functions:** Create stub versions of functions to control their behavior during testing.
* **Environment Variable Mocking:** Mock environment variables to test different configurations.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Forgetting `set -e`:** Not exiting on errors can lead to unexpected behavior.
* **Unquoted Variables:** Forgetting to quote variables can lead to word splitting and globbing issues.
* **Incorrect Variable Scope:** Using global variables when local variables are needed can lead to naming conflicts.
* **Not Checking Return Values:** Not checking return values can lead to errors being ignored.
* **Over-reliance on Globals** Using global variables when local variables are preferable can lead to unintended side effects.
* **Not using Functions** Code becomes difficult to maintain if its not broken into manageable functions.
### 6.2. Edge Cases
* **Empty Variables:** Handle empty variables gracefully.
* **Special Characters:** Handle special characters in file names and other input.
* **Large Files:** Handle large files efficiently to prevent memory issues.
* **Race Conditions:** Avoid race conditions when multiple scripts are running concurrently.
### 6.3. Version-Specific Issues
* **Bash 3 vs. Bash 4:** Be aware of compatibility issues between different versions of Bash.
* **POSIX Compliance:** If portability is a concern, stick to POSIX-compliant syntax.
### 6.4. Compatibility Concerns
* **Operating Systems:** Ensure your scripts are compatible with the target operating systems.
* **External Tools:** Be aware of the dependencies on external tools and ensure they are available on the target systems.
### 6.5. Debugging Strategies
* **`set -x`:** Enable tracing to see the commands being executed.
* **`echo` Statements:** Use `echo` statements to print variable values and debug messages.
* **Shellcheck:** Use Shellcheck to identify common errors and warnings.
* **Interactive Debugging:** Use an interactive debugger like `bashdb` to step through the code.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **Text Editor:** Use a text editor with syntax highlighting and code completion for Bash (e.g., VS Code, Sublime Text, Vim).
* **Shellcheck:** Use Shellcheck to lint your Bash code.
* **Bats:** Use Bats for unit testing.
* **Bashdb:** Use Bashdb for interactive debugging.
* **Git:** Use Git for version control.
### 7.2. Build Configuration
* **Makefile:** Use a Makefile to automate build and test processes.
* **Dependency Management:** Use a dependency management tool like `dep` to manage external dependencies.
### 7.3. Linting and Formatting
* **Shellcheck:** Use Shellcheck to lint your Bash code and enforce coding standards.
* **shfmt:** Use shfmt for automatic code formatting.
### 7.4. Deployment Best Practices
* **Package Scripts:** Package your scripts and dependencies into a deployable package (e.g., Debian package, RPM package).
* **Configuration Management:** Use configuration management tools (e.g., Ansible, Puppet, Chef) to deploy and configure your scripts on target systems.
* **Automated Deployment:** Use automated deployment pipelines to deploy your scripts quickly and reliably.
* **Idempotent Scripts:** Ensure your deployment scripts are idempotent, meaning they can be run multiple times without causing unintended side effects.
### 7.5. CI/CD Integration
* **Continuous Integration (CI):** Integrate your Bash scripts into a CI pipeline to automatically run tests and linting on every commit.
* **Continuous Deployment (CD):** Integrate your Bash scripts into a CD pipeline to automatically deploy your scripts to production.
## 8. Naming Conventions
Follow these naming conventions:
* **Function Names:** Lowercase, with underscores to separate words (e.g., `process_data`, `calculate_total`).
* **Variable Names:** Lowercase, with underscores to separate words (e.g., `input_file`, `output_directory`). Loop variables should be similarly named for the variable you're looping through.
* **Constant Names:** All caps, separated with underscores (e.g., `MAX_RETRIES`, `DEFAULT_TIMEOUT`). Declared at the top of the file.
* **File Names:** Lowercase, with underscores to separate words (e.g., `data_processing.sh`, `configuration_settings.conf`).
## 9. Style and Formatting
* **Indentation:** Use 2 spaces for indentation. No tabs.
* **Line Length:** Limit lines to 80 characters. Use line continuation characters (`\`) to break long lines.
* **Spacing:** Use spaces around operators and after commas.
* **Comments:** Write clear and concise comments to explain the purpose and logic of your code. Any function that is not both obvious and short must be commented. Any function in a library must be commented regardless of length or complexity. Use `TODO` comments to mark code that needs to be improved or completed.
* **Quoting:** Always quote variables unless careful unquoted expansion is required.
* **Braces:** Use `${variable}` instead of `$variable` for clarity.
* **Pipelines:** Format pipelines for maximum clarity. Break long pipelines into multiple lines with one pipeline element per line.
## 10. Exit Codes
* Ensure exit codes are consistent throughout the scripts.
* Use `exit 0` for successful completion.
* Use non-zero exit codes (e.g., 1, 2, 127, etc.) to indicate failure.
* Standardize exit codes for specific error conditions across your project.
* Include custom error messages with meaningful context.
Following these best practices and coding standards will help you write more maintainable, readable, secure, and efficient Bash scripts.
+5
View File
@@ -0,0 +1,5 @@
---
description: This rule file outlines best practices for using the beautifulsoup4 library in Python, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.py
---
By following these best practices, you can build robust, efficient, and secure web scrapers using beautifulsoup4.
+4
View File
@@ -0,0 +1,4 @@
---
description: This rule file provides comprehensive best practices for writing maintainable and effective Behave BDD tests, including code organization, common patterns, performance considerations, and security.
globs: **/*.feature
---
+134
View File
@@ -0,0 +1,134 @@
---
description: Enforces consistent code formatting using Black, the uncompromising Python code formatter, promoting readability and reducing diffs. Covers best practices related to Black's configuration, usage, and integrations.
globs: **/*.py
---
- Adopt Black as the primary code formatter for all Python projects.
- Adhere to Black's default style guide for consistent formatting across projects.
- Integrate Black into the development workflow using pre-commit hooks and CI/CD pipelines.
- Configure Black using `pyproject.toml` file for project-specific settings, if needed.
- Use Black's CLI or editor integrations for seamless formatting.
## Black Code Formatting Best Practices
Black is the uncompromising Python code formatter. By using it, you agree to cede control over minutiae of hand-formatting. In return, Black gives you speed, determinism, and freedom from `pycodestyle` nagging about formatting. You will save time and mental energy for more important matters.
### Key Principles
- **Consistency:** Black enforces a consistent code style, reducing ambiguity and promoting readability.
- **Automation:** Black automates the formatting process, eliminating manual effort and reducing formatting-related code review comments.
- **Integration:** Black integrates seamlessly with popular development tools and workflows.
- **Minimal Configuration:** Black provides sensible defaults and limits configuration options to ensure consistency.
### 1. Code Organization and Structure
Black primarily focuses on formatting within files, but it indirectly influences code organization by promoting readability and consistent style. Consider the following:
- **Directory Structure:** Black doesn't enforce a specific directory structure. However, a well-organized project with clear module boundaries will benefit more from consistent formatting.
- **File Naming Conventions:** Black uses the `.py` extension for python files. Adhering to PEP 8 naming conventions alongside Black is recommended for improved readability (`snake_case` for variables, functions, and modules; `PascalCase` for classes).
- **Module Organization:** Black formats code within modules. Break large modules into smaller, more manageable files to improve readability and maintainability. Organize related functions and classes within modules.
- **Component Architecture:** Black can be used with any component architecture. Focus on creating well-defined components with clear interfaces. Consistent formatting within each component enhances maintainability.
- **Code Splitting Strategies:** Black formats code regardless of the splitting strategy. Break code into smaller functions or classes to improve code readability and organization.
### 2. Common Patterns and Anti-patterns
- **Design Patterns:** Black doesn't impose any specific design patterns. However, it encourages clean, readable code that makes it easier to implement design patterns correctly. For example, consistent formatting makes it easier to identify and understand the structure of a Factory pattern.
- **Recommended Approaches:**
- Use Black on all Python files in your project.
- Integrate Black into your pre-commit hooks to automatically format code before committing.
- Use Black's CLI to format entire directories or specific files.
- Configure Black using `pyproject.toml` to customize settings like line length, if necessary.
- **Anti-patterns:**
- Manually formatting code instead of using Black.
- Ignoring Black's formatting suggestions.
- Disabling Black for specific files or sections of code without a strong reason.
- **State Management:** Black doesn't directly address state management, but its consistent formatting promotes code clarity, making state management strategies easier to implement and understand. Consider using established state management patterns like Redux or Context API (if applicable).
- **Error Handling:** Black encourages readable code, making it easier to implement and understand error handling mechanisms. Use `try...except` blocks to handle exceptions gracefully. Consistent formatting of exception handling code improves maintainability.
### 3. Performance Considerations
Black's formatting process itself has minimal performance overhead. The main performance considerations are related to the code being formatted, not Black itself.
- **Optimization Techniques:** Black-formatted code is easier to read and understand, which can help identify performance bottlenecks. Use profiling tools to identify slow code and optimize accordingly.
- **Memory Management:** Black doesn't directly affect memory management. Follow Python's memory management best practices, such as using generators for large datasets and avoiding circular references.
- **Rendering Optimization:** Not applicable as Black is primarily a code formatter and not directly involved in rendering.
- **Bundle Size Optimization:** Not applicable as Black is a code formatter. Bundle size optimization techniques are relevant to web applications or other deployments where code size impacts load times.
- **Lazy Loading:** Not applicable as Black is a code formatter.
### 4. Security Best Practices
Black improves code readability, which can help identify potential security vulnerabilities. However, Black itself doesn't directly address security. Focus on the following security best practices:
- **Common Vulnerabilities:** Black doesn't prevent common vulnerabilities like SQL injection or cross-site scripting (XSS). Use secure coding practices to avoid these vulnerabilities.
- **Input Validation:** Implement robust input validation to prevent injection attacks. Black's consistent formatting makes it easier to review input validation code.
- **Authentication and Authorization:** Use established authentication and authorization patterns to protect your application. Black's consistent formatting can improve the readability of authentication and authorization code.
- **Data Protection:** Use encryption to protect sensitive data. Follow data protection best practices, such as storing passwords securely.
- **Secure API Communication:** Use HTTPS to encrypt API communication. Implement API authentication and authorization to prevent unauthorized access.
### 5. Testing Approaches
Black promotes consistent code formatting, making tests easier to write, read, and maintain.
- **Unit Testing:** Write unit tests for individual functions and classes. Black's consistent formatting makes it easier to write clear and concise unit tests.
- **Integration Testing:** Write integration tests to verify that different components of your application work together correctly. Consistent formatting makes it easier to understand the interactions between components.
- **End-to-end Testing:** Write end-to-end tests to verify that your application works as expected from a user's perspective. Consistent formatting makes it easier to debug end-to-end tests.
- **Test Organization:** Organize your tests into a logical directory structure. Follow a consistent naming convention for test files and functions.
- **Mocking and Stubbing:** Use mocking and stubbing to isolate units of code during testing. Black's consistent formatting makes it easier to understand the code being tested and create appropriate mocks.
### 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- Not integrating Black into the development workflow.
- Ignoring Black's formatting suggestions.
- Over-configuring Black and deviating from its default style.
- **Edge Cases:**
- Black may have difficulty formatting very complex or deeply nested expressions.
- Black's formatting may not always be optimal for specific use cases.
- **Version-specific Issues:**
- Ensure that all developers are using the same version of Black to avoid formatting inconsistencies.
- **Compatibility Concerns:**
- Black may have compatibility issues with older versions of Python or other tools.
- **Debugging Strategies:**
- Use Black's CLI to format code and identify formatting issues.
- Use a debugger to step through code and understand its behavior.
### 7. Tooling and Environment
- **Recommended Tools:**
- Black: The primary code formatter.
- Pre-commit: A tool for managing pre-commit hooks.
- VS Code, PyCharm, or other Python IDEs with Black integration.
- **Build Configuration:**
- Configure Black in your project's `pyproject.toml` file.
- Integrate Black into your build process to automatically format code.
- **Linting and Formatting:**
- Use Black for formatting and other linters (e.g., Flake8, pylint) for code quality checks.
- Configure your linter to ignore formatting errors reported by Black.
- **Deployment:**
- Ensure that your deployment environment has Black installed.
- Run Black as part of your deployment process to ensure consistent formatting.
- **CI/CD Integration:**
- Integrate Black into your CI/CD pipeline to automatically format code and run tests.
### Example `.pre-commit-config.yaml`
repos:
- repo: https://github.com/psf/black
rev: 24.2.2 # Replace with the latest version
hooks:
- id: black
### Example `pyproject.toml`
toml
[tool.black]
line-length = 88
target-version = ['py38', 'py39', 'py310']
include = '\.pyi?$'
exclude = '''
/(\.(git|hg|mypy_cache|tox|venv)|_build|build|dist)/ # Removed: |/foo/bar/
'''
By following these best practices, you can leverage Black to improve code quality, enhance collaboration, and reduce development time.
+349
View File
@@ -0,0 +1,349 @@
---
description: This rule file outlines best practices for using the boto3 library, including code organization, security, performance, testing, and common pitfalls. It aims to ensure efficient, secure, and maintainable AWS integrations with boto3.
globs: **/*.py
---
---
# boto3 Best Practices
This document outlines best practices for using the boto3 library in Python for interacting with Amazon Web Services (AWS). Following these guidelines will help you write more efficient, secure, and maintainable code.
## 1. Project Setup and Authentication
- **Use Sessions**: Always use boto3 sessions for managing configurations and credentials effectively.
python
import boto3
session = boto3.Session()
s3 = session.client('s3')
- **Avoid Hard-coding Credentials**: Never hard-code AWS credentials in your code. Use environment variables, AWS CLI configuration, IAM roles, or AWS Secrets Manager.
- **Environment Variables**:
python
import os
aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID')
aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
- **AWS CLI Configuration**:
Configure your credentials using the AWS CLI (`aws configure`). Boto3 will automatically pick up the credentials.
- **IAM Roles**: Use IAM roles for EC2 instances or Lambda functions to grant permissions.
- **AWS Secrets Manager**: Securely store and retrieve secrets (like database passwords or API keys) using AWS Secrets Manager, accessible via boto3.
## 2. Code Organization and Structure
- **Directory Structure**: Organize your project with a clear directory structure.
my_project/
├── src/
│ ├── __init__.py
│ ├── aws/
│ │ ├── __init__.py
│ │ ├── s3_utils.py
│ │ ├── dynamodb_utils.py
│ ├── models/
│ │ ├── __init__.py
│ │ ├── user.py
│ ├── main.py
├── tests/
│ ├── __init__.py
│ ├── aws/
│ │ ├── test_s3_utils.py
│ │ ├── test_dynamodb_utils.py
├── requirements.txt
├── .env
└── README.md
- **File Naming Conventions**: Use descriptive and consistent file names.
- `s3_utils.py`: Contains S3-related utility functions.
- `dynamodb_utils.py`: Contains DynamoDB-related utility functions.
- `user.py`: Defines a User model or data structure.
- **Module Organization**: Break down your code into logical modules.
- `aws/`: Contains modules for interacting with different AWS services.
- `models/`: Contains data models representing your application's entities.
- **Component Architecture**: Design your application with reusable components.
- Create separate functions or classes for different AWS operations (e.g., uploading files, querying DynamoDB).
- **Code Splitting**: Split large files into smaller, more manageable files.
- Group related functions and classes into separate files.
- Use clear and concise names for your files and modules.
## 3. Common Patterns and Anti-patterns
- **Design Patterns**: Use appropriate design patterns for boto3 interactions.
- **Factory Pattern**: Create clients using a factory pattern to abstract client creation.
python
class AWSClientFactory:
def create_client(self, service_name, session=None):
if not session:
session = boto3.Session()
return session.client(service_name)
factory = AWSClientFactory()
s3 = factory.create_client('s3')
- **Strategy Pattern**: Implement different strategies for handling AWS operations (e.g., different retry mechanisms).
- **Recommended Approaches**: Follow recommended approaches for common tasks.
- **Uploading Files to S3**: Use `upload_file` or `upload_fileobj` for uploading files to S3.
python
s3.upload_file('my_local_file.txt', 'my_bucket', 'my_s3_key.txt')
- **Downloading Files from S3**: Use `download_file` or `download_fileobj` for downloading files from S3.
python
s3.download_file('my_bucket', 'my_s3_key.txt', 'my_local_file.txt')
- **Anti-patterns**: Avoid common anti-patterns.
- **Tight Coupling**: Don't tightly couple your application logic with boto3 code. Abstract AWS interactions behind interfaces.
- **Ignoring Errors**: Always handle exceptions when interacting with AWS services.
- **Over-permissioning**: Grant only the necessary permissions to IAM roles.
- **State Management**: Manage state effectively in your boto3 applications.
- **Stateless Functions**: Prefer stateless functions that don't rely on global variables.
- **DynamoDB Sessions**: Use DynamoDB for storing session data in web applications.
- **Error Handling**: Implement robust error handling.
python
from botocore.exceptions import ClientError
try:
response = s3.get_object(Bucket='my_bucket', Key='my_key')
print(response['Body'].read().decode('utf-8'))
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchKey':
print('The specified key does not exist.')
else:
print(f'An error occurred: {e}')
## 4. Performance Considerations
- **Optimization Techniques**: Optimize boto3 interactions for performance.
- **Pagination**: Use pagination to handle large datasets.
python
paginator = s3.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket='my_bucket')
for page in pages:
for obj in page['Contents']:
print(obj['Key'])
- **Batch Operations**: Use batch operations for efficient data processing.
python
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
delete_keys = [{'Key': 'file1.txt'}, {'Key': 'file2.txt'}]
response = bucket.delete_objects(Delete={'Objects': delete_keys})
print(response)
- **Transfer Acceleration**: For faster uploads over long distances, enable S3 Transfer Acceleration.
python
s3 = boto3.client('s3',
config=boto3.session.Config(
s3={'use_accelerate_endpoint': True}
)
)
- **Memory Management**: Be mindful of memory usage when working with large files or datasets.
- **Streaming**: Use streaming operations to process data in chunks.
- **Garbage Collection**: Ensure proper garbage collection to release unused memory.
- **Bundle Size Optimization**: Reduce bundle size by using only necessary boto3 modules.
- **Lazy Loading**: Load boto3 modules only when needed to reduce startup time.
## 5. Security Best Practices
- **Common Vulnerabilities**: Understand and prevent common vulnerabilities.
- **Credential Leakage**: Protect your AWS credentials from being exposed in code or logs.
- **Injection Attacks**: Sanitize inputs to prevent injection attacks.
- **Cross-Site Scripting (XSS)**: Protect against XSS attacks when displaying data from AWS.
- **Input Validation**: Validate all inputs to prevent security issues.
- **Sanitize Inputs**: Remove or escape potentially harmful characters from inputs.
- **Use Parameterized Queries**: Use parameterized queries to prevent SQL injection attacks when working with databases.
- **Authentication and Authorization**: Implement proper authentication and authorization mechanisms.
- **Principle of Least Privilege**: Grant only the necessary permissions to IAM roles and users.
- **Multi-Factor Authentication (MFA)**: Enable MFA for sensitive operations.
- **Data Protection**: Protect your data at rest and in transit.
- **Encryption**: Use server-side encryption (SSE-S3) for data security by default. For additional security using AWS Key Management Service (KMS) keys, include encryption parameters
python
response = boto3.client('s3').upload_file(
file_path,
bucket_name,
key,
ExtraArgs={
'ServerSideEncryption': 'aws:kms',
'SSEKMSKeyId': 'your-kms-key-id'
}
)
- **Secure Transport**: Enforce HTTPS-only access by applying a bucket policy.
- **Versioning**: Enable S3 Versioning for recovery.
- **Secure API Communication**: Ensure secure communication with AWS APIs.
- **HTTPS**: Always use HTTPS for communication with AWS services.
## 6. Testing Approaches
- **Unit Testing**: Write unit tests for your boto3 components.
- **Mocking**: Use mocking libraries like `moto` to simulate AWS services during testing.
- **Test Cases**: Create comprehensive test cases for different scenarios.
- **Integration Testing**: Test the integration of your boto3 components with AWS services.
- **LocalStack**: Use LocalStack to simulate AWS services locally for integration testing.
- **End-to-End Tests**: Write end-to-end tests to verify the complete application flow.
- **Test Organization**: Organize your tests in a clear and maintainable structure.
- **Separate Test Files**: Create separate test files for each module or component.
- **Descriptive Test Names**: Use descriptive names for your test functions and classes.
- **Mocking and Stubbing**: Use mocking and stubbing techniques to isolate components during testing.
- **Mock Boto3 Clients**: Mock boto3 clients to avoid making real API calls during unit tests.
python
import boto3
from moto import mock_aws
import unittest
class MyTestCase(unittest.TestCase):
@mock_aws
def test_s3_upload(self):
s3 = boto3.client('s3')
s3.create_bucket(Bucket='mybucket')
s3.put_object(Bucket='mybucket', Key='myfile', Body='my content')
response = s3.get_object(Bucket='mybucket', Key='myfile')
self.assertEqual(response['Body'].read().decode('utf-8'), 'my content')
if __name__ == '__main__':
unittest.main()
## 7. Common Pitfalls and Gotchas
- **Frequent Mistakes**: Be aware of common mistakes when using boto3.
- **Incorrect Region**: Specifying the wrong AWS region.
- **Missing Permissions**: Insufficient IAM permissions.
- **Not Handling Exceptions**: Ignoring exceptions raised by boto3.
- **Edge Cases**: Consider edge cases when designing your application.
- **Throttling**: Handle API throttling by implementing retry mechanisms.
- **Version-Specific Issues**: Be aware of version-specific issues with boto3.
- **API Changes**: Keep up with API changes and deprecations.
- **Compatibility**: Test your code with different boto3 versions.
- **Compatibility Concerns**: Address compatibility concerns between boto3 and other technologies.
- **Python Versions**: Ensure compatibility with different Python versions.
- **Dependency Conflicts**: Resolve dependency conflicts with other libraries.
- **Debugging**: Use effective debugging strategies for boto3 applications.
- **Logging**: Implement detailed logging to track API calls and errors.
- **Debugging Tools**: Use debugging tools like `pdb` or IDE debuggers.
## 8. Tooling and Environment
- **Recommended Development Tools**: Use recommended development tools.
- **IDE**: Use a Python IDE like VS Code, PyCharm, or Sublime Text.
- **AWS CLI**: Use the AWS CLI for managing AWS resources.
- **Build Configuration**: Configure your build process for boto3 projects.
- **Requirements File**: Use a `requirements.txt` file to manage dependencies.
- **Virtual Environments**: Use virtual environments to isolate dependencies.
- **Linting and Formatting**: Follow linting and formatting recommendations.
- **PEP 8**: Adhere to PEP 8 style guidelines.
- **Linters**: Use linters like `flake8` or `pylint` to enforce code quality.
- **Formatters**: Use formatters like `black` to automatically format your code.
- **Deployment**: Follow deployment best practices.
- **Infrastructure as Code (IaC)**: Use IaC tools like Terraform or CloudFormation to manage your infrastructure.
- **CI/CD**: Implement CI/CD pipelines for automated deployments.
- **CI/CD Integration**: Integrate your boto3 projects with CI/CD systems.
- **Automated Tests**: Run automated tests during the CI/CD process.
- **Deployment Pipelines**: Create deployment pipelines to automate the deployment process.
## 9. Advanced S3 features
- S3 Object Lambda: Process and transform the data returned by S3 GET requests on the fly without modifying the stored object.
- S3 Lifecycle policies: Automate the transition of objects to more cost-effective storage classes, or schedule their deletion based on defined rules.
- S3 Event Notifications: Monitor bucket events and trigger actions such as invoking Lambda functions, sending messages via SNS or SQS, when new objects are created.
For example, you can configure S3 Event Notifications with Boto3 as follows:
python
import boto3
s3_client = boto3.client('s3')
notification_configuration = {
'LambdaFunctionConfigurations': [
{
'LambdaFunctionArn': 'arn:aws:lambda:us-east-1:123456789012:function:ProcessS3Event',
'Events': ['s3:ObjectCreated:*'],
'Filter': {
'Key': {
'FilterRules': [
{'Name': 'suffix', 'Value': '.jpg'}
]
}
}
}
]
}
s3_client.put_bucket_notification_configuration(
Bucket='your-bucket-name',
NotificationConfiguration=notification_configuration
)
## 10. Best Practices Summary
- **Security**: Prioritize security by avoiding hard-coded credentials, enforcing the principle of least privilege, and using encryption.
- **Performance**: Optimize performance by using pagination, batch operations, and S3 Transfer Acceleration.
- **Error Handling**: Implement robust error handling with comprehensive logging.
- **Testing**: Write unit tests, integration tests, and end-to-end tests using mocking and LocalStack.
- **Code Organization**: Maintain a clear and modular code structure.
By following these best practices, you can ensure that your boto3 applications are efficient, secure, and maintainable.
+279
View File
@@ -0,0 +1,279 @@
---
description: Comprehensive coding standards, best practices, and architectural guidelines for Python backend development with the Bottle microframework, designed to improve code quality, maintainability, and security.
globs: **/*.py
---
# Bottle Framework Best Practices
This document provides comprehensive coding standards, best practices, and architectural guidelines for Python backend development using the Bottle microframework. Adhering to these guidelines will improve code quality, maintainability, security, and overall project success.
## 1. Code Organization and Structure
Effective code organization is crucial for maintainability and scalability. Here's how to structure your Bottle applications:
### 1.1. Directory Structure Best Practices
A well-organized directory structure makes it easier to navigate and understand the project.
my_bottle_app/
├── app.py # Main application entry point
├── routes/
│ ├── __init__.py # Make 'routes' a package
│ ├── home.py # Route definitions for the home page
│ ├── api.py # Route definitions for the API
│ └── users.py # Route definitions for user management
├── models/
│ ├── __init__.py
│ ├── user.py # User model definition
│ └── product.py # Product model definition
├── views/
│ ├── __init__.py
│ ├── home.tpl # Template for the home page
│ └── user_list.tpl # Template for listing users
├── config.py # Application configuration
├── db.py # Database connection and setup
├── utils/
│ ├── __init__.py
│ ├── auth.py # Authentication utilities
│ └── helpers.py # General helper functions
├── tests/
│ ├── __init__.py
│ ├── test_routes.py # Tests for route handlers
│ └── test_models.py # Tests for data models
├── requirements.txt # Project dependencies
└── README.md
### 1.2. File Naming Conventions
* **Python Files:** Use lowercase with underscores (snake_case) for Python file names (e.g., `user_model.py`, `api_routes.py`).
* **Template Files:** Use lowercase with underscores, and the `.tpl` extension (e.g., `product_details.tpl`).
* **Configuration Files:** Use a descriptive name like `config.py`.
* **Test Files:** Prefix test files with `test_` (e.g., `test_user_routes.py`).
### 1.3. Module Organization
* **Separate Concerns:** Group related functionality into separate modules (e.g., routes, models, utilities).
* **Use Packages:** Utilize Python packages (directories with `__init__.py` files) to further organize modules into logical groups.
* **Avoid Circular Imports:** Carefully manage dependencies between modules to prevent circular import errors. Structure your code so that lower-level modules (e.g., models, utilities) don't depend on higher-level modules (e.g., routes).
### 1.4. Component Architecture
* **MVC (Model-View-Controller):** While Bottle is simple, aim for an MVC-like structure:
* **Models:** Represent data and business logic (e.g., database interactions).
* **Views:** Render the user interface (using Bottle's templating or another engine).
* **Controllers (Routes):** Handle user requests, interact with models, and select the appropriate view.
* **Service Layer (Optional):** For more complex applications, introduce a service layer between routes and models to encapsulate business logic and improve testability.
### 1.5. Code Splitting Strategies
* **Functional Decomposition:** Break down complex functions into smaller, more manageable functions with single responsibilities.
* **Route Grouping:** Group related routes into separate modules or route blueprints for better organization.
* **Configuration Management:** Move configuration settings to a separate module for easy management and environment-specific configurations.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Singleton (Carefully):** Use sparingly for resources like database connections. Ensure thread safety if using a singleton in a multithreaded environment.
* **Factory:** Useful for creating model instances or other objects in a controlled manner.
* **Middleware (Plugins):** Bottle's plugin system allows you to create reusable middleware components for tasks like authentication, logging, and request processing.
### 2.2. Recommended Approaches for Common Tasks
* **Database Access:** Use an ORM (SQLAlchemy) for database interaction. This provides an abstraction layer, improves code readability, and helps prevent SQL injection vulnerabilities.
* **Templating:** Leverage Bottle's built-in templating engine for simple projects. For more complex templating needs, consider Jinja2 or Mako.
* **Request Handling:** Use Bottle's decorators (`@route`, `@get`, `@post`) for defining routes and handling HTTP requests.
* **Error Handling:** Implement custom error handlers for different HTTP status codes to provide informative error messages to the client.
### 2.3. Anti-patterns and Code Smells
* **Fat Routes:** Avoid putting too much logic directly in route handlers. Delegate complex tasks to models, services, or helper functions.
* **Global State:** Minimize the use of global variables. Prefer dependency injection or passing data as arguments.
* **Hardcoding Configuration:** Never hardcode sensitive information like API keys or database credentials. Use environment variables or a configuration file.
* **Ignoring Exceptions:** Don't catch exceptions and do nothing. Log the error and take appropriate action (e.g., return an error response to the client).
* **SQL Injection Vulnerabilities:** Avoid string concatenation when building SQL queries. Use parameterized queries provided by your ORM or database driver.
### 2.4. State Management
* **Stateless Architecture:** Prefer a stateless architecture where each request is independent and doesn't rely on server-side session state. This improves scalability.
* **Sessions (if needed):** If session state is required, use a session middleware (e.g., Beaker) or a token-based authentication system (JWT).
* **Cookies:** Use cookies for storing non-sensitive information on the client-side.
### 2.5. Error Handling
* **Specific Exception Handling:** Catch specific exceptions rather than generic `Exception` to handle different error scenarios appropriately.
* **Logging:** Use the `logging` module to log errors and other important events. Configure different logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) for different environments.
* **Custom Error Pages:** Create custom error pages for different HTTP status codes (404, 500, etc.) to provide a better user experience.
* **Return Informative Error Responses:** When an error occurs, return a JSON response with a clear error message and status code.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Caching:** Implement caching for frequently accessed data to reduce database load and improve response times. Use Bottle's caching mechanism or an external caching system like Redis or Memcached.
* **Database Optimization:** Optimize database queries by using indexes, avoiding unnecessary joins, and selecting only the required columns.
* **Gzip Compression:** Enable Gzip compression for HTTP responses to reduce the amount of data transferred to the client.
* **Asynchronous Operations:** Use asynchronous tasks (e.g., Celery) for long-running operations like sending emails or processing large datasets. This prevents blocking the main thread and improves responsiveness.
* **Profiling:** Use profiling tools to identify performance bottlenecks in your code.
### 3.2. Memory Management
* **Avoid Memory Leaks:** Be careful when dealing with large datasets or long-running processes to avoid memory leaks. Use generators or iterators to process data in chunks.
* **Resource Management:** Release resources (e.g., database connections, file handles) as soon as they are no longer needed. Use `try...finally` blocks or context managers (`with` statement) to ensure resources are released even if an exception occurs.
### 3.3. Rendering Optimization
* **Template Caching:** Enable template caching to improve rendering performance. Bottle's built-in templating engine supports caching.
* **Minify CSS and JavaScript:** Minify CSS and JavaScript files to reduce their size and improve loading times.
* **Optimize Images:** Optimize images for the web by using appropriate image formats, compression levels, and dimensions.
### 3.4. Bundle Size Optimization (Applicable if using Bottle to serve static assets)
* **Code Splitting (For Single Page Apps):** If building a SPA, consider code-splitting your javascript into smaller bundles.
* **Tree Shaking:** Use a bundler (like Webpack or Parcel) that supports tree shaking to remove unused code from your JavaScript bundles.
### 3.5. Lazy Loading
* **Lazy Imports:** Import modules only when they are needed. This can reduce startup time.
* **Database Connection on Demand:** Establish database connections only when they are required, rather than at application startup.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
* **SQL Injection:** Use parameterized queries with an ORM like SQLAlchemy to prevent SQL injection vulnerabilities.
* **Cross-Site Scripting (XSS):** Sanitize user input before displaying it in templates to prevent XSS attacks. Use Bottle's HTML escaping functions or a templating engine that automatically escapes HTML.
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by generating and validating CSRF tokens for state-changing requests. Bottle doesn't have built-in CSRF protection, so you'll need to use a library or implement it manually.
* **Authentication Bypass:** Ensure proper authentication and authorization mechanisms are in place to prevent unauthorized access to resources.
* **Denial of Service (DoS):** Implement rate limiting and input validation to prevent DoS attacks.
### 4.2. Input Validation
* **Validate All User Input:** Validate all user input on both the client-side and server-side.
* **Use Data Type Validation:** Ensure that input data matches the expected data types.
* **Sanitize Input:** Sanitize input data to remove potentially harmful characters or code.
* **Limit Input Length:** Limit the length of input fields to prevent buffer overflows.
### 4.3. Authentication and Authorization
* **Use a Strong Authentication Scheme:** Implement a secure authentication scheme like OAuth 2.0 or JWT.
* **Hash Passwords:** Hash passwords using a strong hashing algorithm (e.g., bcrypt or Argon2) before storing them in the database. Never store passwords in plain text.
* **Implement Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
* **Use HTTPS:** Always use HTTPS to encrypt communication between the client and server.
### 4.4. Data Protection
* **Encrypt Sensitive Data:** Encrypt sensitive data (e.g., credit card numbers, social security numbers) both in transit and at rest.
* **Use Environment Variables:** Store sensitive configuration data (e.g., API keys, database credentials) in environment variables rather than hardcoding them in the code.
* **Regularly Update Dependencies:** Keep your dependencies up to date to patch security vulnerabilities.
* **Secure File Uploads:** Validate file types and sizes during upload. Store uploaded files outside the web root and serve them through a controlled endpoint.
### 4.5. Secure API Communication
* **API Keys:** Use API keys for authentication and authorization of API clients.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
* **Input Validation:** Thoroughly validate all data received through the API.
* **HTTPS Only:** Require HTTPS for all API communication.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Individual Components:** Unit tests should focus on testing individual components (e.g., functions, classes) in isolation.
* **Use a Testing Framework:** Use a testing framework like `pytest` or `unittest` to write and run unit tests.
* **Mock Dependencies:** Mock external dependencies (e.g., database connections, API calls) to isolate the component being tested.
* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that the component handles unexpected input correctly.
* **Follow the Arrange-Act-Assert Pattern:** Structure your tests using the Arrange-Act-Assert pattern to make them more readable and maintainable.
### 5.2. Integration Testing
* **Test Interactions Between Components:** Integration tests should focus on testing the interactions between different components of the application.
* **Use a Test Database:** Use a separate test database to avoid affecting the production database.
* **Test API Endpoints:** Test API endpoints to ensure that they return the correct data and status codes.
### 5.3. End-to-End Testing
* **Simulate User Interactions:** End-to-end tests should simulate user interactions with the application to ensure that the entire system works correctly.
* **Use a Browser Automation Tool:** Use a browser automation tool like Selenium or Playwright to automate end-to-end tests.
* **Test Common User Flows:** Test common user flows to ensure that the application meets the needs of its users.
### 5.4. Test Organization
* **Separate Test Files:** Create separate test files for each module or component.
* **Organize Tests by Feature:** Organize tests into directories based on the feature they are testing.
* **Use Descriptive Test Names:** Use descriptive test names that clearly indicate what the test is verifying.
### 5.5. Mocking and Stubbing
* **Use Mocking for External Dependencies:** Use mocking to simulate the behavior of external dependencies (e.g., databases, APIs) in your tests.
* **Use Stubbing for Complex Calculations:** Use stubbing to replace complex calculations with precomputed values.
* **Use a Mocking Library:** Use a mocking library like `unittest.mock` or `pytest-mock` to simplify the process of creating mocks and stubs.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Not Sanitizing User Input:** Failing to sanitize user input can lead to XSS vulnerabilities.
* **Hardcoding Secrets:** Hardcoding sensitive information like API keys or database passwords directly in the code makes them vulnerable to exposure.
* **Incorrect Error Handling:** Improper exception handling can result in unhandled errors and application crashes.
* **Ignoring Security Updates:** Neglecting dependency updates leaves you exposed to known vulnerabilities.
### 6.2. Edge Cases
* **Unicode Handling:** Ensure your application handles Unicode characters correctly, especially when dealing with user input or data from external sources.
* **Time Zones:** Be mindful of time zones when dealing with dates and times. Store dates and times in UTC and convert them to the user's local time zone when displaying them.
* **Concurrency Issues:** If your application handles concurrent requests, be aware of potential race conditions and synchronization issues.
### 6.3. Version-Specific Issues
* **Bottle Versions:** Stay informed about changes and bug fixes of specific Bottle versions you are using. Check the Bottle changelog for changes that may impact your application.
### 6.4. Compatibility Concerns
* **Python Version Compatibility:** Ensure your application is compatible with the Python version you are using. Bottle supports Python 3.6+.
* **Dependency Conflicts:** Be aware of potential dependency conflicts between different libraries. Use a virtual environment to isolate your project's dependencies.
### 6.5. Debugging Strategies
* **Use a Debugger:** Use a debugger like `pdb` or the built-in debugger in your IDE to step through your code and inspect variables.
* **Logging:** Use the `logging` module to log errors and other important events. Configure different logging levels for different environments.
* **Error Handling:** Implement custom error handlers to catch exceptions and provide informative error messages.
* **Testing:** Write unit tests and integration tests to catch bugs early in the development process.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **IDE:** Use a powerful IDE like Visual Studio Code, PyCharm, or Sublime Text for code editing, debugging, and testing.
* **Virtual Environment Manager:** Use `venv`, `virtualenv`, or `conda` to create virtual environments for isolating project dependencies.
* **Package Manager:** Use `pip` or `conda` to install and manage Python packages.
* **Database Client:** Use a database client like DBeaver or pgAdmin to connect to and manage your databases.
### 7.2. Build Configuration
* **Use `requirements.txt`:** Use a `requirements.txt` file to specify your project's dependencies. Generate this file using `pip freeze > requirements.txt`.
* **Specify Versions:** Specify exact versions of your dependencies in `requirements.txt` to ensure consistent builds across different environments.
* **Use a Build Tool (Optional):** For more complex projects, consider using a build tool like Make or Invoke to automate build tasks.
### 7.3. Linting and Formatting
* **Use a Linter:** Use a linter like `flake8` or `pylint` to enforce coding style and identify potential errors.
* **Use a Formatter:** Use a code formatter like `black` or `autopep8` to automatically format your code according to PEP 8.
* **Configure Your IDE:** Configure your IDE to automatically run the linter and formatter when you save a file.
### 7.4. Deployment Best Practices
* **Use a Production Web Server:** Use a production-ready web server like Gunicorn or uWSGI to serve your application.
* **Use a Reverse Proxy:** Use a reverse proxy like Nginx or Apache to handle static assets, SSL termination, and load balancing.
* **Use a Process Manager:** Use a process manager like Supervisor or systemd to ensure that your application is always running.
* **Monitor Your Application:** Use a monitoring tool like Prometheus or Grafana to monitor your application's performance and identify potential issues.
### 7.5. CI/CD Integration
* **Use a CI/CD Pipeline:** Use a CI/CD pipeline to automate the process of building, testing, and deploying your application.
* **Use a CI/CD Tool:** Use a CI/CD tool like Jenkins, GitLab CI, GitHub Actions, or CircleCI to create your CI/CD pipeline.
* **Run Tests Automatically:** Configure your CI/CD pipeline to run tests automatically on every commit.
* **Automate Deployment:** Automate the deployment process so that new versions of your application are deployed automatically when the tests pass.
By following these best practices, you can build robust, maintainable, and secure Bottle applications that meet the needs of your users and your organization.
+368
View File
@@ -0,0 +1,368 @@
---
description: This rule file provides a comprehensive guide to C# best practices, coding standards, and common patterns for writing maintainable, performant, and secure code.
globs: **/*.cs
---
# C# Best Practices and Coding Standards
This document provides a comprehensive guide to C# best practices, coding standards, and common patterns for writing maintainable, performant, and secure code. It covers various aspects of C# development, including code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling.
**Library Information:**
- Name: c-sharp
- Tags: language, microsoft, dotnet, backend
## 1. Code Organization and Structure
A well-organized codebase is crucial for maintainability, scalability, and collaboration. Here are some best practices for organizing your C# code:
### 1.1. Directory Structure Best Practices
* **Project Root:** Contains the solution file (.sln) and project directories.
* **Project Directory:** Contains the project file (.csproj), source code, and other project-related files.
* `src/`: Contains the main source code.
* `Models/`: Data models and DTOs (Data Transfer Objects).
* `Services/`: Business logic and service classes.
* `Controllers/`: API controllers (if applicable).
* `Repositories/`: Data access logic.
* `Utilities/`: Helper classes and utility functions.
* `Exceptions/`: Custom exception definitions.
* `Interfaces/`: Interface definitions for abstraction.
* `Configuration/`: Configuration-related classes.
* `tests/`: Contains unit tests, integration tests, and end-to-end tests.
* `docs/`: Documentation for the project.
* `build/`: Build scripts and configuration files.
* `Properties/`: Assembly information and project settings.
Example:
MyProject/
├── MyProject.sln
├── MyProject/
│ ├── MyProject.csproj
│ ├── src/
│ │ ├── Models/
│ │ ├── Services/
│ │ ├── Controllers/
│ │ ├── Repositories/
│ │ ├── Utilities/
│ │ ├── Exceptions/
│ │ ├── Interfaces/
│ │ └── Configuration/
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ └── appsettings.json
├── MyProject.Tests/
│ ├── MyProject.Tests.csproj
│ └── UnitTests/
└── README.md
### 1.2. File Naming Conventions
* **Classes:** PascalCase (e.g., `MyClass.cs`)
* **Interfaces:** IPascalCase (e.g., `IMyInterface.cs`)
* **Enums:** PascalCase (e.g., `MyEnum.cs`)
* **Structs:** PascalCase (e.g., `MyStruct.cs`)
* **Delegates:** PascalCase (e.g., `MyDelegate.cs`)
* **Configuration Files:** appsettings.json, config.xml
* **Test Files:** `MyClassTests.cs`
### 1.3. Module Organization
* **Namespaces:** Use namespaces to group related classes and interfaces. Follow a consistent naming convention for namespaces (e.g., `CompanyName.ProjectName.ModuleName`).
* **Assemblies:** Divide large projects into multiple assemblies to improve build times, reduce dependencies, and enable code reuse. Consider functional or domain boundaries when creating assemblies.
* **NuGet Packages:** Use NuGet packages to manage dependencies and share code across projects.
### 1.4. Component Architecture
* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access) to promote separation of concerns and testability.
* **Microservices Architecture:** For large and complex applications, consider a microservices architecture where the application is composed of small, independent services.
* **Dependency Injection (DI):** Use DI to manage dependencies between components and improve testability and maintainability. Popular DI containers include Autofac, Ninject, and Microsoft.Extensions.DependencyInjection.
### 1.5. Code Splitting Strategies
* **By Feature:** Group code related to a specific feature into a separate module or assembly.
* **By Layer:** Separate code based on the architectural layer (e.g., presentation, business logic, data access).
* **By Responsibility:** Split classes and methods into smaller, more focused units of work.
* **Partial Classes:** Use partial classes to split a large class into multiple files for better organization (use sparingly).
## 2. Common Patterns and Anti-patterns
Understanding common design patterns and anti-patterns is essential for writing effective and maintainable C# code.
### 2.1. Design Patterns
* **Singleton:** Ensures that a class has only one instance and provides a global point of access to it.
* **Factory:** Provides an interface for creating objects without specifying their concrete classes.
* **Abstract Factory:** Provides an interface for creating families of related objects without specifying their concrete classes.
* **Builder:** Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
* **Observer:** Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
* **Strategy:** Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
* **Dependency Injection (DI):** A technique whereby one object (or static method) supplies the dependencies of another object. This helps to decouple components.
* **Repository:** Mediates between the domain and data mapping layers, acting like an in-memory domain object collection.
* **Unit of Work:** Maintains a list of objects affected by a business transaction and coordinates the writing out of changes.
* **Asynchronous Programming Patterns (TAP, EAP, APM):** Handle asynchronous operations efficiently using async/await.
### 2.2. Recommended Approaches for Common Tasks
* **String Manipulation:** Use `StringBuilder` for efficient string concatenation in loops.
* **File I/O:** Use `using` statements or `try-finally` blocks to ensure proper disposal of file resources.
* **Data Access:** Use ORMs like Entity Framework Core or Dapper for simplified data access.
* **Asynchronous Operations:** Use `async` and `await` for non-blocking asynchronous operations.
* **Configuration Management:** Use `Microsoft.Extensions.Configuration` for managing application configuration.
* **Logging:** Use logging frameworks like Serilog or NLog for structured logging.
### 2.3. Anti-patterns and Code Smells
* **God Class:** A class that does too much and has too many responsibilities.
* **Long Method:** A method that is too long and complex.
* **Feature Envy:** A method that accesses data from another object more than its own.
* **Shotgun Surgery:** Changes to one part of the code require changes to many other parts.
* **Data Clump:** Groups of data that appear together in multiple places.
* **Primitive Obsession:** Using primitive types instead of creating custom classes for domain concepts.
* **Switch Statements (over Polymorphism):** Using large switch statements instead of leveraging polymorphism.
* **Magic Numbers/Strings:** Hardcoding values directly in the code instead of using constants or configuration settings.
* **Ignoring Exceptions:** Catching exceptions without handling them properly.
* **Empty Catch Blocks:** Catching exceptions and doing nothing.
* **Over-commenting:** Writing excessive comments that are obvious from the code itself.
* **Dead Code:** Code that is never executed.
### 2.4. State Management Best Practices
* **Stateless Services:** Design services to be stateless whenever possible to improve scalability and reliability.
* **Session State:** Use session state sparingly and only when necessary. Consider using distributed caching for session state in web applications.
* **Caching:** Use caching to improve performance by storing frequently accessed data in memory.
* **Redux/Flux:** For complex UI applications, consider using a state management library like Redux or Flux.
* **Immutable Data Structures:** Use immutable data structures to simplify state management and prevent unintended side effects.
### 2.5. Error Handling Patterns
* **Try-Catch-Finally:** Use `try-catch-finally` blocks to handle exceptions and ensure proper resource cleanup.
* **Exception Filters:** Use exception filters to catch specific exceptions based on certain conditions.
* **Custom Exceptions:** Create custom exception types for specific error conditions in your application.
* **Logging Exceptions:** Log exceptions with sufficient context to aid in debugging.
* **Graceful Degradation:** Handle errors gracefully and provide informative error messages to the user.
* **Throw Early, Catch Late:** Detect errors as early as possible and handle exceptions at a higher level.
## 3. Performance Considerations
Optimizing C# code for performance is crucial for creating responsive and efficient applications.
### 3.1. Optimization Techniques
* **Avoid Boxing and Unboxing:** Boxing and unboxing value types can be expensive. Use generics to avoid boxing and unboxing.
* **Use Value Types When Appropriate:** Value types (structs) can be more efficient than reference types (classes) for small, immutable data structures.
* **Minimize Object Allocation:** Object allocation can be expensive. Reuse objects whenever possible.
* **Use `StringBuilder` for String Concatenation:** `StringBuilder` is more efficient than string concatenation using the `+` operator, especially in loops.
* **Optimize LINQ Queries:** Use LINQ carefully and avoid unnecessary iterations or computations. Consider using `AsParallel()` for parallel processing of large collections (with caution, as parallelism introduces complexity).
* **Use Asynchronous Programming:** Use `async` and `await` to avoid blocking the main thread and improve responsiveness.
* **Avoid Excessive Locking:** Minimize the use of locks to prevent contention and improve concurrency.
* **Use Lazy Initialization:** Initialize objects only when they are needed to avoid unnecessary initialization overhead.
* **Profile Your Code:** Use profiling tools to identify performance bottlenecks and optimize accordingly. Visual Studio Profiler, dotTrace, and PerfView are good options.
### 3.2. Memory Management Considerations
* **Garbage Collection:** Understand how the garbage collector works and avoid creating excessive garbage.
* **Dispose of Resources:** Implement the `IDisposable` interface and use `using` statements to ensure proper disposal of resources (e.g., file streams, database connections).
* **Weak References:** Use weak references to hold references to objects without preventing them from being garbage collected.
* **Object Pooling:** Use object pooling to reuse objects and reduce allocation overhead.
* **Large Object Heap (LOH):** Be aware of the Large Object Heap and avoid allocating large objects unnecessarily.
### 3.3. Rendering Optimization (If Applicable)
* **UI Virtualization:** Use UI virtualization to render only the visible items in a large list or grid.
* **Reduce Overdraw:** Minimize the number of times pixels are drawn on top of each other.
* **Batch Rendering:** Batch rendering operations to reduce the number of draw calls.
* **Use Hardware Acceleration:** Use hardware acceleration to offload rendering tasks to the GPU.
### 3.4. Bundle Size Optimization (If Applicable)
* **Tree Shaking:** Remove unused code from the bundle.
* **Code Minification:** Minify code to reduce its size.
* **Code Compression:** Compress code using Gzip or Brotli.
* **Image Optimization:** Optimize images to reduce their size without sacrificing quality.
### 3.5. Lazy Loading Strategies
* **Lazy Initialization:** Use `Lazy<T>` to initialize objects only when they are accessed.
* **Virtual Proxy:** Use a virtual proxy to load related data only when it is needed.
* **Explicit Loading:** Load related data explicitly using methods like `Include` in Entity Framework Core.
## 4. Security Best Practices
Security should be a primary concern in C# development to protect against vulnerabilities and attacks.
### 4.1. Common Vulnerabilities and Prevention
* **SQL Injection:** Parameterize database queries to prevent SQL injection attacks.
* **Cross-Site Scripting (XSS):** Encode user input to prevent XSS attacks.
* **Cross-Site Request Forgery (CSRF):** Use anti-forgery tokens to prevent CSRF attacks.
* **Authentication and Authorization Vulnerabilities:** Implement secure authentication and authorization mechanisms.
* **Insecure Direct Object References (IDOR):** Validate user access to objects to prevent IDOR attacks.
* **File Upload Vulnerabilities:** Validate file types and sizes to prevent malicious file uploads.
* **Denial-of-Service (DoS) Attacks:** Implement rate limiting and other measures to prevent DoS attacks.
* **Deserialization Vulnerabilities:** Avoid deserializing untrusted data.
* **Dependency Vulnerabilities:** Regularly update dependencies to patch security vulnerabilities.
### 4.2. Input Validation
* **Validate All User Input:** Validate all user input on both the client and server side.
* **Use Regular Expressions:** Use regular expressions to validate input formats.
* **Sanitize Input:** Sanitize input to remove or escape potentially malicious characters.
* **Use Whitelisting:** Use whitelisting to allow only known good input values.
* **Limit Input Length:** Limit the length of input fields to prevent buffer overflows.
### 4.3. Authentication and Authorization
* **Use Strong Passwords:** Enforce strong password policies and use password hashing algorithms like bcrypt.
* **Implement Multi-Factor Authentication (MFA):** Use MFA to add an extra layer of security to the authentication process.
* **Use Role-Based Access Control (RBAC):** Use RBAC to control user access to resources based on their roles.
* **Use Claims-Based Authentication:** Use claims-based authentication to represent user identities and permissions.
* **Implement Proper Session Management:** Implement secure session management practices, including session timeouts and secure cookies.
* **OAuth 2.0 and OpenID Connect:** Leverage industry-standard protocols for authentication and authorization.
### 4.4. Data Protection
* **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
* **Use Key Management:** Use a secure key management system to store and manage encryption keys.
* **Protect Connection Strings:** Protect connection strings and other sensitive configuration data.
* **Implement Auditing:** Implement auditing to track user actions and detect security breaches.
### 4.5. Secure API Communication
* **Use HTTPS:** Use HTTPS to encrypt communication between the client and server.
* **Implement API Authentication:** Use API keys, JWTs, or other authentication mechanisms to secure API endpoints.
* **Rate Limiting:** Implement rate limiting to prevent API abuse.
* **Input Validation:** Validate all API input to prevent injection attacks.
* **Output Encoding:** Encode API output to prevent XSS attacks.
## 5. Testing Approaches
Testing is a critical part of the software development process and helps ensure the quality and reliability of C# applications.
### 5.1. Unit Testing
* **Test Individual Units of Code:** Unit tests should focus on testing individual classes, methods, or functions in isolation.
* **Use Mocking Frameworks:** Use mocking frameworks like Moq or NSubstitute to isolate units of code and simulate dependencies.
* **Follow the Arrange-Act-Assert Pattern:** Arrange the test data, act on the code under test, and assert the expected results.
* **Write Clear and Concise Tests:** Write tests that are easy to read and understand.
* **Test Edge Cases and Error Conditions:** Test edge cases and error conditions to ensure that the code handles them properly.
* **Aim for High Code Coverage:** Aim for high code coverage to ensure that most of the code is tested.
### 5.2. Integration Testing
* **Test Interactions Between Components:** Integration tests should focus on testing the interactions between different components or modules of the application.
* **Use Real Dependencies or Test Doubles:** Use real dependencies or test doubles to simulate the environment in which the components will operate.
* **Test Data Access Logic:** Test data access logic to ensure that it interacts correctly with the database.
* **Test API Endpoints:** Test API endpoints to ensure that they handle requests and responses correctly.
### 5.3. End-to-End Testing
* **Test the Entire Application Flow:** End-to-end tests should focus on testing the entire application flow from start to finish.
* **Use Automation Frameworks:** Use automation frameworks like Selenium or Playwright to automate end-to-end tests.
* **Test User Interfaces:** Test user interfaces to ensure that they are functional and user-friendly.
* **Test Performance and Scalability:** Test performance and scalability to ensure that the application can handle the expected load.
### 5.4. Test Organization
* **Create Separate Test Projects:** Create separate test projects for unit tests, integration tests, and end-to-end tests.
* **Organize Tests by Feature or Module:** Organize tests by feature or module to improve maintainability.
* **Use Descriptive Test Names:** Use descriptive test names that clearly indicate what the test is verifying.
* **Use Test Categories:** Use test categories to group related tests together.
### 5.5. Mocking and Stubbing
* **Use Mocking Frameworks:** Use mocking frameworks like Moq or NSubstitute to create mock objects and stub dependencies.
* **Create Mock Objects for Dependencies:** Create mock objects for dependencies that are difficult or time-consuming to set up.
* **Stub Method Calls:** Stub method calls to return specific values or throw exceptions.
* **Verify Method Calls:** Verify that methods are called with the expected arguments.
## 6. Common Pitfalls and Gotchas
Being aware of common pitfalls and gotchas can help developers avoid mistakes and write more robust C# code.
### 6.1. Frequent Mistakes
* **NullReferenceException:** Not handling null values properly.
* **Incorrect Use of Asynchronous Programming:** Blocking the main thread with synchronous operations.
* **Memory Leaks:** Not disposing of resources properly.
* **Concurrency Issues:** Race conditions, deadlocks, and other concurrency issues.
* **Unhandled Exceptions:** Not catching or logging exceptions properly.
* **SQL Injection:** Not parameterizing database queries.
* **XSS Attacks:** Not encoding user input properly.
* **CSRF Attacks:** Not using anti-forgery tokens.
* **Ignoring Code Analysis Warnings:** Ignoring warnings from the compiler or code analysis tools.
### 6.2. Edge Cases
* **Empty Collections:** Handling empty collections properly.
* **Zero Values:** Handling zero values properly.
* **Maximum and Minimum Values:** Handling maximum and minimum values properly.
* **Date and Time Zones:** Handling date and time zones correctly.
* **Unicode Characters:** Handling Unicode characters correctly.
### 6.3. Version-Specific Issues
* **C# Language Features:** Being aware of new language features and how they affect existing code.
* **.NET Framework vs. .NET Core vs. .NET:** Understanding the differences between the different .NET platforms.
* **Breaking Changes:** Being aware of breaking changes in new versions of the .NET framework.
### 6.4. Compatibility Concerns
* **Cross-Platform Compatibility:** Ensuring that the code works correctly on different operating systems.
* **Backward Compatibility:** Ensuring that the code is compatible with older versions of the .NET framework.
* **Interoperability with Other Languages:** Ensuring that the code can interoperate with other languages like C++ or Java.
### 6.5. Debugging Strategies
* **Use the Visual Studio Debugger:** Use the Visual Studio debugger to step through code, inspect variables, and set breakpoints.
* **Use Logging:** Use logging to track the execution flow of the code and log important information.
* **Use Unit Tests:** Use unit tests to isolate and debug individual units of code.
* **Use Code Analysis Tools:** Use code analysis tools to identify potential problems in the code.
* **Use Profiling Tools:** Use profiling tools to identify performance bottlenecks.
## 7. Tooling and Environment
Choosing the right tools and configuring the development environment properly can significantly improve productivity and code quality.
### 7.1. Recommended Development Tools
* **Visual Studio:** The primary IDE for C# development.
* **Visual Studio Code:** A lightweight code editor with C# support.
* **JetBrains Rider:** A cross-platform .NET IDE.
* **NuGet Package Manager:** For managing dependencies.
* **Git:** For version control.
* **Resharper:** Powerful Visual Studio extension for code analysis, refactoring, and navigation.
### 7.2. Build Configuration
* **Use MSBuild or dotnet CLI:** Use MSBuild or the dotnet CLI to build the project.
* **Configure Build Configurations:** Configure different build configurations for debug and release builds.
* **Use NuGet Package Restore:** Use NuGet package restore to automatically download dependencies during the build process.
* **Sign Assemblies:** Sign assemblies to prevent tampering.
* **Generate Documentation:** Generate documentation from XML comments.
* **Enable deterministic builds:** Ensure builds are reproducible by enabling deterministic builds in the project file.
### 7.3. Linting and Formatting
* **Use StyleCop Analyzers:** Use StyleCop Analyzers to enforce coding style rules.
* **Use Roslyn Analyzers:** Use Roslyn analyzers to detect potential problems in the code.
* **Configure EditorConfig:** Use EditorConfig to define coding style rules for the project.
* **Use Code Formatters:** Use code formatters like the Visual Studio code formatter to automatically format code.
### 7.4. Deployment Best Practices
* **Choose a Deployment Target:** Choose a deployment target based on the application's requirements (e.g., Azure App Service, AWS Elastic Beanstalk, Docker).
* **Use a Deployment Pipeline:** Use a deployment pipeline to automate the deployment process.
* **Configure Application Settings:** Configure application settings properly for the deployment environment.
* **Monitor Application Health:** Monitor application health to detect and resolve issues.
### 7.5. CI/CD Integration
* **Use a CI/CD Platform:** Use a CI/CD platform like Azure DevOps, GitHub Actions, or Jenkins to automate the build, test, and deployment process.
* **Configure Build Triggers:** Configure build triggers to automatically start builds when code is committed.
* **Run Unit Tests and Integration Tests:** Run unit tests and integration tests as part of the build process.
* **Deploy to Different Environments:** Deploy the application to different environments (e.g., development, staging, production) as part of the deployment pipeline.
* **Automated Code Reviews:** Integrate with code review tools to automate aspects of code review.
By following these best practices and coding standards, developers can write C# code that is maintainable, performant, secure, and reliable.
+265
View File
@@ -0,0 +1,265 @@
---
description: This rule provides best practices for using Cheerio for web scraping and HTML parsing in JavaScript, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.js
---
# Cheerio Best Practices
This document outlines the best practices for using Cheerio, a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It focuses on efficient and ethical web scraping, robust code organization, and secure data handling.
## Library Information:
- Name: cheerio
- Tags: web-scraping, javascript, html-parsing, nodejs
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
Adopt a structured directory to enhance maintainability and scalability:
project-root/
├── src/
│ ├── scrapers/
│ │ ├── amazon_scraper.js # Specific website scrapers
│ │ ├── generic_scraper.js # Reusable scraping logic
│ ├── utils/
│ │ ├── helpers.js # Utility functions
│ │ ├── request.js # HTTP request handling (Axios wrapper)
│ ├── models/
│ │ ├── product.js # Data models
│ ├── config/
│ │ ├── config.js # Configuration settings
│ ├── index.js # Main application entry point
├── tests/
│ ├── scrapers/
│ │ ├── amazon_scraper.test.js
│ ├── utils/
│ │ ├── helpers.test.js
├── .env # Environment variables
├── package.json
├── package-lock.json
├── README.md
### 1.2. File Naming Conventions
Use descriptive names:
- **Scrapers:** `[website]_scraper.js` (e.g., `amazon_scraper.js`, `ebay_scraper.js`)
- **Utilities:** `[module_name].js` (e.g., `request.js`, `data_formatter.js`)
- **Tests:** `[module_name].test.js` (e.g., `amazon_scraper.test.js`)
### 1.3. Module Organization
- **Encapsulation:** Group related functionalities into modules (e.g., scraper functions, utility functions).
- **Separation of Concerns:** Isolate scraping logic, data processing, and storage functionalities.
- **Reusability:** Design modules for reuse across different scrapers.
### 1.4. Component Architecture Recommendations
For complex scraping applications, consider a component-based architecture:
- **Scraper Components:** Components that handle scraping data from specific websites. Should handle request logic and initial parsing of HTML
- **Parser Components:** Responsible for extracting relevant data from the scraped HTML using cheerio.
- **Data Model Components:** Define the structure of the data to be extracted.
- **Storage Components:** Save scraped data to files, databases, etc.
### 1.5. Code Splitting Strategies
- **Scraper-Specific Logic:** Separate logic for each website into individual modules.
- **Reusable Utilities:** Move common functions into utility modules.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Strategy Pattern:** Implement different scraping strategies based on website structure or anti-scraping measures.
- **Factory Pattern:** Dynamically create scraper instances based on website configuration.
- **Observer Pattern:** Notify subscribers when new data is scraped.
### 2.2. Recommended Approaches for Common Tasks
- **Making HTTP Requests:** Use Axios for making HTTP requests. Handle retries and timeouts gracefully.
- **Loading HTML:** Load HTML into Cheerio using `cheerio.load()`. Handle loading large HTML documents efficiently.
- **Selecting Elements:** Use CSS selectors effectively to target desired elements. Consider specificity and performance.
- **Extracting Data:** Extract data from selected elements using `.text()`, `.attr()`, `.val()`, etc.
### 2.3. Anti-patterns and Code Smells
- **Overly Complex Selectors:** Avoid overly long or complex CSS selectors that can be difficult to maintain and may impact performance. Refactor into smaller, more manageable selectors.
- **Ignoring Errors:** Always handle errors and exceptions gracefully. Log errors and provide meaningful error messages.
- **Hardcoding Values:** Avoid hardcoding URLs, selectors, or configuration values. Use configuration files or environment variables.
- **Lack of Rate Limiting:** Always implement rate limiting to avoid overloading target websites and getting IP-blocked.
- **Lack of Respect for `robots.txt`:** Always check and respect the `robots.txt` file to avoid scraping restricted content.
- **Not handling dynamic content**: If the site uses JavaScript to render content, Cheerio alone won't work. Integrate with Puppeteer or Playwright to render the page before parsing it.
### 2.4. State Management Best Practices
- For simple scripts, use local variables to store scraped data.
- For complex applications, consider using state management libraries like Redux or Zustand (although these are usually overkill for typical cheerio use cases). These are needed more for front-end state management.
- For managing concurrency and scheduling, use task queues (see below).
### 2.5. Error Handling Patterns
- **Try-Catch Blocks:** Wrap scraping logic in `try-catch` blocks to handle exceptions.
- **Custom Error Classes:** Define custom error classes to represent specific scraping errors.
- **Logging:** Log errors and exceptions to a file or logging service.
- **Retry Logic:** Implement retry logic for failed HTTP requests.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Efficient Selectors:** Use the most efficient CSS selectors possible. Avoid overly complex selectors and prioritize ID selectors or class selectors over attribute selectors.
- **Caching:** Cache frequently accessed data to reduce the number of HTTP requests.
- **Rate Limiting:** Implement rate limiting to avoid overloading target websites. Space out requests to be respectful and avoid getting blocked.
- **Asynchronous Operations:** Use asynchronous operations (e.g., `async/await`) to avoid blocking the main thread.
- **Connection Pooling:** Reuse HTTP connections to reduce overhead. Axios handles connection pooling automatically.
- **Parallel Scraping:** Use concurrent scraping (e.g. `Promise.all`) to speed up data collection. Implement carefully to avoid overwhelming the target server.
- **Use streams for large files:** When processing very large scraped files (e.g. JSON), use Node.js streams to avoid loading the entire file into memory at once.
### 3.2. Memory Management
- **Minimize Data Retention:** Only store the data you need. Discard unnecessary data as soon as possible.
- **Garbage Collection:** Ensure that unused objects are properly garbage collected.
- **Avoid Memory Leaks:** Be careful to avoid memory leaks, especially when using callbacks or closures.
### 3.3. Rendering Optimization
- Cheerio doesn't render content; it parses existing HTML. If dynamic content is required, use Puppeteer or Playwright to render the page first.
### 3.4. Bundle Size Optimization
- Cheerio itself is very lightweight. However, using too many utility libraries can increase bundle size.
- Use tools like Webpack or Parcel to bundle your code and optimize bundle size.
### 3.5. Lazy Loading
- Lazy load images or other resources that are not immediately visible.
- However, this is often not relevant for server-side scraping with Cheerio.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
- **Cross-Site Scripting (XSS):** Cheerio itself does not directly introduce XSS vulnerabilities. However, if you are displaying scraped data in a web browser, be sure to sanitize the data properly to prevent XSS attacks.
- **Denial of Service (DoS):** Implement rate limiting and request timeouts to prevent DoS attacks on target websites.
- **Data Injection:** Sanitize and validate scraped data before storing it in a database to prevent data injection attacks.
### 4.2. Input Validation
- Validate all input data to prevent malicious input from corrupting your application or data.
- Validate URLs to prevent scraping unintended websites.
### 4.3. Authentication and Authorization
- For accessing password-protected websites, implement proper authentication and authorization mechanisms.
- Store credentials securely using environment variables or configuration files.
- Avoid storing credentials directly in your code.
### 4.4. Data Protection
- Encrypt sensitive data at rest and in transit.
- Use secure protocols (e.g., HTTPS) for all network communication.
### 4.5. Secure API Communication
- If your scraping application interacts with APIs, use secure API keys and tokens.
- Implement proper authentication and authorization mechanisms for API access.
## 5. Testing Approaches
### 5.1. Unit Testing
- Unit test individual functions and components.
- Use mocking and stubbing to isolate units of code.
- Test edge cases and error conditions.
### 5.2. Integration Testing
- Integrate test different components of your application to ensure that they work together correctly.
- Test the interaction between scrapers, parsers, and data storage components.
### 5.3. End-to-End Testing
- End-to-end test the entire scraping process from start to finish.
- Simulate real-world scenarios to ensure that your application works as expected.
### 5.4. Test Organization
- Organize your tests in a clear and consistent manner.
- Use descriptive test names.
- Keep your tests small and focused.
### 5.5. Mocking and Stubbing
- Use mocking and stubbing to isolate units of code during testing.
- Mock HTTP requests to avoid making real requests to target websites during testing.
- Tools: Jest, Mocha, Sinon.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Ignoring `robots.txt`:** Always respect the `robots.txt` file.
- **Not Handling Dynamic Content:** Cheerio cannot render JavaScript. Use Puppeteer or Playwright for dynamic content.
- **Overloading Target Websites:** Implement rate limiting to avoid overloading target websites.
- **Not Handling Errors:** Always handle errors and exceptions gracefully.
- **Using Incorrect Selectors:** Ensure that your CSS selectors are correct and target the desired elements.
- **Not Validating Data:** Validate scraped data to prevent data corruption.
### 6.2. Edge Cases
- Websites with infinite scroll: These sites load content dynamically as you scroll. Use Puppeteer or Playwright to simulate scrolling and load all the content before parsing.
- Websites that require JavaScript to function: As stated before, use a headless browser like Puppeteer or Playwright.
- Websites with anti-scraping techniques: Websites may use techniques like IP blocking, CAPTCHAs, or dynamic content to prevent scraping. You'll need to implement strategies to avoid these, such as using proxies, solving CAPTCHAs, or rendering JavaScript.
- Websites that change their structure frequently: Websites may change their HTML structure, which can break your scraper. You'll need to monitor your scraper and update it as needed.
### 6.3. Version-Specific Issues
- Be aware of version-specific issues and breaking changes in Cheerio.
- Check the Cheerio documentation and release notes for information on known issues.
### 6.4. Compatibility Concerns
- Ensure that Cheerio is compatible with your version of Node.js.
- Be aware of potential compatibility issues with other libraries.
### 6.5. Debugging Strategies
- Use `console.log()` to print out the values of variables and expressions.
- Use a debugger to step through your code and inspect the state of your application.
- Use try-catch blocks to catch exceptions and log error messages.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **IDE:** Visual Studio Code, WebStorm
- **HTTP Client:** Postman, Insomnia
- **Debugging Tools:** Node.js Inspector, Chrome DevTools
### 7.2. Build Configuration
- Use a build tool like Webpack or Parcel to bundle your code and optimize bundle size.
- Configure your build tool to handle different environments (e.g., development, production).
### 7.3. Linting and Formatting
- Use a linter like ESLint to enforce code style and prevent errors.
- Use a formatter like Prettier to automatically format your code.
- Configure your linter and formatter to work with Cheerio code.
### 7.4. Deployment Best Practices
- Deploy your scraping application to a reliable hosting provider.
- Use a process manager like PM2 to ensure that your application is always running.
- Monitor your application for errors and performance issues.
### 7.5. CI/CD Integration
- Use a CI/CD tool like Jenkins, Travis CI, or CircleCI to automate the build, test, and deployment process.
- Configure your CI/CD pipeline to run your unit tests, integration tests, and end-to-end tests.
By following these best practices, you can build robust, efficient, and secure web scraping applications using Cheerio.
+231
View File
@@ -0,0 +1,231 @@
---
description: This rule provides comprehensive best practices for configuring and optimizing CircleCI workflows, covering code organization, security, performance, and testing to ensure efficient and reliable CI/CD pipelines.
globs: .circleci/config.yml
---
# CircleCI Best Practices: A Comprehensive Guide
This document provides a comprehensive guide to CircleCI best practices, covering various aspects of workflow configuration, optimization, security, and testing.
## 1. Code Organization and Structure
While CircleCI primarily focuses on workflow orchestration rather than code structure, adhering to a well-organized project structure significantly benefits CI/CD pipeline maintainability and efficiency. Here are some key recommendations:
### 1.1 Directory Structure
* **Root Level:**
* `.circleci/`: Contains the `config.yml` file defining the CircleCI workflow.
* `scripts/`: (Optional) Houses custom scripts used within the CI/CD pipeline (e.g., deployment scripts, database setup).
* `docker/`: (Optional) Contains Dockerfiles and related files for containerizing applications.
* `README.md`: Project documentation.
* `LICENSE`: Project license.
* `.gitignore`: Specifies intentionally untracked files that Git should ignore.
* **Application Code:** Follow a consistent structure based on the project's technology stack (e.g., `src/`, `app/`, `lib/`).
### 1.2 File Naming Conventions
* `config.yml`: The primary CircleCI configuration file. Use descriptive comments within this file.
* Shell Scripts: Use `.sh` extension for shell scripts in the `scripts/` directory (e.g., `deploy.sh`, `setup_database.sh`).
* Dockerfiles: Use `Dockerfile` (without extension) or a descriptive name like `Dockerfile.dev` or `Dockerfile.prod`.
### 1.3 Module Organization
* For larger projects, break down complex workflows into reusable modules or Orbs. Orbs allow you to encapsulate and share common configuration snippets across multiple projects.
* Utilize private Orbs within your organization to share proprietary configurations securely.
### 1.4 Component Architecture
* Consider a modular design for your application, making it easier to test and deploy individual components. This approach aligns well with microservices architectures.
* Use environment variables to configure different components based on the deployment environment (e.g., development, staging, production).
### 1.5 Code Splitting
* For large applications, consider splitting your code into smaller modules or packages to reduce build times and improve parallelism in your CI/CD pipeline.
* Use caching strategies to avoid rebuilding unchanged modules.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Configuration as Code (CaC):** Manage CircleCI configurations (and application configurations) as code, stored in version control. This ensures traceability, auditability, and reproducibility.
* **Infrastructure as Code (IaC):** Use tools like Terraform or CloudFormation to provision and manage infrastructure in a consistent and automated way.
* **GitOps:** Use Git as the single source of truth for infrastructure and application configurations. Changes are applied through pull requests, ensuring a controlled and auditable process.
### 2.2 Recommended Approaches
* **Automated Testing:** Integrate comprehensive automated testing into your pipeline, including unit tests, integration tests, and end-to-end tests. Fail the build if any tests fail.
* **Parallel Execution:** Leverage CircleCI's parallelism feature to run tests and other tasks concurrently, significantly reducing pipeline execution time.
* **Caching:** Use caching to store dependencies and build artifacts between jobs, avoiding redundant downloads and builds.
* **Orbs:** Utilize community or custom Orbs to simplify common tasks and promote code reuse.
### 2.3 Anti-patterns
* **Hardcoding Secrets:** Never hardcode sensitive information (API keys, passwords) directly in the `config.yml` file. Use environment variables or a secrets management tool.
* **Ignoring Test Failures:** Do not proceed with deployment if tests fail. Fix the underlying issues first.
* **Large, Monolithic Configurations:** Avoid creating a single, massive `config.yml` file. Break down the workflow into smaller, reusable jobs and Orbs.
* **Lack of Caching:** Failing to utilize caching can significantly increase build times.
* **Manual Deployments:** Avoid manual deployments. Automate the entire deployment process.
### 2.4 State Management
* CircleCI itself is stateless. For stateful applications, manage state using external databases, caches (e.g., Redis, Memcached), or cloud storage services (e.g., AWS S3, Azure Blob Storage).
* Use environment variables to configure the connection to stateful services based on the environment.
### 2.5 Error Handling
* Implement robust error handling in your scripts and application code.
* Use CircleCI's notification features to alert developers when builds fail or errors occur.
* Log detailed error messages to aid in debugging.
* Consider using tools like Sentry or Rollbar for centralized error tracking.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Parallelism:** As mentioned earlier, parallelize jobs to reduce overall pipeline execution time.
* **Caching:** Cache dependencies, build artifacts, and Docker layers.
* **Resource Classes:** Use appropriate resource classes for your jobs. Larger resource classes provide more CPU and memory, but also consume more credits.
* **Docker Layer Caching:** Optimize Dockerfiles to leverage layer caching effectively. Arrange commands from least to most frequently changed to maximize cache hits.
* **Optimize Docker Image Size:** Reduce the size of Docker images by using multi-stage builds and removing unnecessary dependencies.
### 3.2 Memory Management
* Monitor memory usage during builds, especially when running resource-intensive tasks (e.g., large test suites).
* Adjust resource classes if jobs are running out of memory.
* Optimize your application code to reduce memory consumption.
### 3.3 Bundle Size Optimization (If Applicable)
* For web applications, optimize JavaScript bundle sizes using techniques like code splitting, tree shaking, and minification.
* Use tools like Webpack Bundle Analyzer to identify large dependencies.
### 3.4 Lazy Loading (If Applicable)
* For web applications, implement lazy loading to load resources only when they are needed.
* Use dynamic imports in JavaScript to load modules on demand.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
* **Exposed Secrets:** Storing sensitive information in the codebase or configuration files.
* **Insecure Dependencies:** Using outdated or vulnerable dependencies.
* **Lack of Access Control:** Granting excessive permissions to users or services.
* **Man-in-the-Middle Attacks:** Failing to use HTTPS for secure communication.
### 4.2 Input Validation
* Validate all input data in your application to prevent injection attacks.
* Use parameterized queries to prevent SQL injection.
* Escape user-provided data when rendering HTML to prevent cross-site scripting (XSS) attacks.
### 4.3 Authentication and Authorization
* Use strong authentication mechanisms to protect your application.
* Implement role-based access control (RBAC) to restrict access to sensitive resources.
* Use secure tokens (e.g., JWT) for authentication and authorization.
### 4.4 Data Protection
* Encrypt sensitive data at rest and in transit.
* Use HTTPS for all API communication.
* Regularly back up your data.
### 4.5 Secure API Communication
* Use API keys or tokens to authenticate API requests.
* Implement rate limiting to prevent abuse.
* Use HTTPS for all API communication.
* Validate API requests and responses.
## 5. Testing Approaches
### 5.1 Unit Testing
* Write unit tests for all critical components of your application.
* Use a mocking framework to isolate components during unit testing.
* Aim for high test coverage (ideally > 80%).
### 5.2 Integration Testing
* Write integration tests to verify that different components of your application work together correctly.
* Test the interaction between your application and external services (e.g., databases, APIs).
### 5.3 End-to-End Testing
* Write end-to-end tests to simulate user interactions and verify that the entire application works as expected.
* Use a browser automation tool like Selenium or Cypress for end-to-end testing.
### 5.4 Test Organization
* Organize your tests in a logical directory structure (e.g., `tests/unit/`, `tests/integration/`, `tests/e2e/`).
* Use descriptive names for your test files and test cases.
### 5.5 Mocking and Stubbing
* Use mocking to replace external dependencies with controlled test doubles.
* Use stubbing to provide pre-defined responses for specific function calls or API requests.
* Choose a mocking framework that is appropriate for your programming language and testing framework.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Incorrect YAML Syntax:** YAML is sensitive to indentation. Use a YAML linter to validate your `config.yml` file.
* **Misconfigured Caching:** Using incorrect cache keys or not invalidating caches when dependencies change.
* **Not Using Environment Variables:** Hardcoding secrets or configuration values instead of using environment variables.
* **Ignoring Resource Limits:** Exceeding resource limits (CPU, memory, disk space) can lead to job failures.
### 6.2 Edge Cases
* **Network Connectivity Issues:** Handle transient network connectivity issues gracefully in your scripts.
* **API Rate Limiting:** Implement retry logic with exponential backoff to handle API rate limiting.
* **Concurrency Issues:** Be aware of potential concurrency issues when running parallel jobs.
### 6.3 Version-Specific Issues
* Be aware of breaking changes between CircleCI versions. Refer to the CircleCI documentation for upgrade instructions.
### 6.4 Compatibility Concerns
* Ensure that your CircleCI configuration is compatible with the versions of the tools and libraries you are using.
### 6.5 Debugging Strategies
* Use CircleCI's debugging features to inspect the state of your jobs.
* Add logging statements to your scripts to track the execution flow and identify errors.
* Use a remote debugger to step through your code interactively.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **IDE:** Visual Studio Code, IntelliJ IDEA, or other IDEs with YAML support.
* **YAML Linter:** Use a YAML linter to validate your `config.yml` file.
* **Docker:** Docker for local container development and testing.
* **CircleCI CLI:** CircleCI command-line interface for interacting with the CircleCI API.
### 7.2 Build Configuration
* Use a consistent build process across all environments.
* Automate build tasks using build tools like Make, Gradle, or npm.
* Configure your build environment using environment variables.
### 7.3 Linting and Formatting
* Use a linter to enforce code style and identify potential errors.
* Use a code formatter to automatically format your code.
* Integrate linting and formatting into your CI/CD pipeline.
### 7.4 Deployment
* Automate the deployment process using deployment tools like Ansible, Chef, or Puppet.
* Use a blue-green deployment strategy to minimize downtime during deployments.
* Monitor your application after deployment to ensure that it is functioning correctly.
### 7.5 CI/CD Integration
* Integrate CircleCI with your version control system (e.g., GitHub, Bitbucket).
* Configure CircleCI to trigger builds automatically when code is pushed to the repository.
* Use CircleCI's notification features to alert developers when builds succeed or fail.
By following these best practices, you can ensure that your CircleCI workflows are efficient, reliable, and secure. This guide provides a strong foundation for building robust CI/CD pipelines and optimizing your software development process.
+236
View File
@@ -0,0 +1,236 @@
---
description: This rule file outlines comprehensive best practices for developing applications using the Clerk library, focusing on security, performance, code organization, and testing to ensure robust and maintainable authentication implementations.
globs: **/*.{js,jsx,ts,tsx}
---
---
## Clerk Library Best Practices
This document provides comprehensive guidelines for developing applications using the Clerk library. It covers various aspects, including code organization, common patterns, performance considerations, security, testing, common pitfalls, and tooling, aiming to help developers build robust, secure, and maintainable applications.
### 1. Code Organization and Structure
* **Directory Structure:**
* `src/`: Contains the main source code of your application.
* `src/components/`: Reusable UI components. Further categorize components based on their functionality (e.g., `src/components/auth/`, `src/components/profile/`).
* `src/pages/`: (If using a framework like Next.js or Remix) Defines the application's routes.
* `src/lib/clerk/`: Clerk-specific utilities and customizations. This isolates Clerk configuration and extension logic.
* `src/lib/clerk/hooks.ts`: Custom hooks related to Clerk for reusability.
* `src/lib/clerk/utils.ts`: Utility functions for common Clerk tasks (e.g., formatting user data).
* `src/middleware.ts` (or similar): Middleware for authentication checks and redirects.
* `tests/`: Unit, integration, and end-to-end tests.
* `config/`: Configuration files (e.g., Clerk API keys, environment variables).
* **File Naming Conventions:**
* Components: Use PascalCase (e.g., `UserProfile.jsx`, `SignInForm.tsx`).
* Utilities: Use camelCase (e.g., `formatUserData.js`, `clerkApi.ts`).
* Pages/Routes: Follow the framework's conventions (e.g., `index.js` for the homepage).
* Configuration files: `clerk.config.js`, `environment.config.ts`
* **Module Organization:**
* Group related functionality into modules. For example, all Clerk-related functions and components could be placed within a `src/lib/clerk/` module.
* Use clear and descriptive names for modules and files.
* Favor small, focused modules over large, monolithic ones.
* **Component Architecture:**
* **Presentational Components:** Focus on UI rendering and receive data and callbacks as props.
* **Container Components:** Handle data fetching, state management, and pass data to presentational components.
* Use Higher-Order Components (HOCs) or render props for cross-cutting concerns like authentication checks.
* Utilize custom hooks to abstract Clerk logic and enhance reusability.
* **Code Splitting:**
* **Route-Based Splitting:** Leverage dynamic imports or framework features to split the application bundle based on routes. This ensures users only download the code necessary for the initial page load.
* **Component-Based Splitting:** Use `React.lazy` or similar techniques to lazy-load components that are not immediately visible or essential.
* Consider using tools like Webpack Bundle Analyzer to identify large dependencies and optimize bundle size.
### 2. Common Patterns and Anti-patterns
* **Design Patterns:**
* **Provider Pattern:** Use the Clerk provider to wrap your application and make Clerk's functionality accessible to all components.
* **Hook Pattern:** Create custom hooks to abstract Clerk logic (e.g., a `useUser` hook to fetch user data).
* **Strategy Pattern:** Implement different authentication strategies (e.g., email/password, social login) using a common interface.
* **Recommended Approaches:**
* Use Clerk's pre-built UI components for common authentication flows (sign-in, sign-up, user profile) to save development time and ensure a consistent user experience.
* Leverage Clerk's middleware for authentication checks on protected routes.
* Use environment variables to store Clerk API keys and other sensitive configuration data.
* Implement role-based access control (RBAC) to manage user permissions.
* **Anti-patterns:**
* **Directly Manipulating Clerk's State:** Avoid modifying Clerk's internal state directly. Use the provided API methods and hooks.
* **Storing Sensitive Data in the Client:** Never store Clerk API keys or user credentials in the client-side code.
* **Ignoring Error Handling:** Always handle errors that may occur during authentication flows.
* **Over-Customizing UI Components:** While customization is possible, avoid making excessive changes to Clerk's UI components, as this can lead to maintenance issues and compatibility problems during upgrades.
* **Performing complex operations in middleware:** Keep middleware logic lean and focused on authentication checks and redirects to avoid performance bottlenecks.
* **State Management:**
* For simple applications, Clerk's built-in state management may suffice. Avoid mixing it with external state if possible. It can lead to unpredictable behavior.
* For complex applications, consider using a state management library like Redux, Zustand or React Context in conjunction with Clerk, making sure to keep the Clerk state separate, and sync the user object to your state manager after Clerk authenticates the user.
* Use appropriate selectors to access user data from the state.
* **Error Handling:**
* Use `try...catch` blocks to handle errors that may occur during authentication flows.
* Display user-friendly error messages to the user.
* Log errors to a server-side logging service for debugging and monitoring.
* Implement retry mechanisms for transient errors.
* Centralize error handling logic in a dedicated module for consistency.
### 3. Performance Considerations
* **Optimization Techniques:**
* **Caching:** Cache user data and API responses to reduce the number of requests to Clerk's servers.
* **Code Splitting:** Implement code splitting to reduce the initial bundle size.
* **Lazy Loading:** Lazy-load components and resources that are not immediately needed.
* **Prefetching:** Prefetch data for routes that the user is likely to visit next.
* **Memory Management:**
* Avoid creating unnecessary objects or data structures.
* Release resources when they are no longer needed.
* Use memory profiling tools to identify and fix memory leaks.
* Be mindful of the size of user objects stored in the state. Avoid storing unnecessary data.
* **Rendering Optimization:** (If applicable, depends on the UI framework used with Clerk)
* Use memoization techniques to prevent unnecessary re-renders.
* Optimize rendering performance with tools like React Profiler.
* Use virtualization for large lists of data.
* **Bundle Size Optimization:**
* Use a bundler like Webpack or Parcel to optimize the bundle size.
* Remove unused code and dependencies.
* Use tree shaking to remove dead code.
* Minimize the use of large libraries, use alternative smaller ones.
* **Lazy Loading:**
* Lazy-load components using `React.lazy` or dynamic imports.
* Lazy-load images and other assets using a library like `react-lazyload`.
### 4. Security Best Practices
* **Common Vulnerabilities:**
* **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and using a Content Security Policy (CSP).
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection using tokens.
* **Authentication and Authorization Flaws:** Ensure that authentication and authorization are implemented correctly.
* **Sensitive Data Exposure:** Protect sensitive data by encrypting it and storing it securely.
* **Input Validation:**
* Validate all user input on both the client and server sides.
* Use a library like `joi` or `yup` to define and enforce validation schemas.
* Escape user input before rendering it to prevent XSS attacks.
* **Authentication and Authorization:**
* Use Clerk's built-in authentication and authorization features.
* Implement role-based access control (RBAC) to manage user permissions.
* Use multi-factor authentication (MFA) to enhance security.
* Enforce strong password policies.
* **Data Protection:**
* Encrypt sensitive data at rest and in transit.
* Use HTTPS to secure communication between the client and server.
* Store API keys and other sensitive data in environment variables.
* Regularly audit your application for security vulnerabilities.
* **Secure API Communication:**
* Use HTTPS for all API requests.
* Validate API responses to prevent data injection attacks.
* Implement rate limiting to prevent denial-of-service attacks.
* Use a secure API gateway to manage API access and security.
### 5. Testing Approaches
* **Unit Testing:**
* Write unit tests for individual components and functions.
* Use a testing framework like Jest or Mocha.
* Mock dependencies to isolate units under test.
* Focus on testing the logic within components, not the rendering details (if applicable).
* Test edge cases and error conditions.
* **Integration Testing:**
* Write integration tests to verify the interaction between different components and modules.
* Test the integration between Clerk and your application's backend.
* Use a testing library like React Testing Library to test component interactions.
* **End-to-End Testing:**
* Write end-to-end tests to verify the entire application flow.
* Use a testing framework like Cypress or Puppeteer.
* Test common user scenarios, such as signing up, signing in, and accessing protected resources.
* Run end-to-end tests in a CI/CD pipeline.
* **Test Organization:**
* Organize tests into separate directories based on the type of test (unit, integration, end-to-end).
* Use clear and descriptive names for test files and test cases.
* Follow a consistent testing style.
* Run tests automatically on every commit.
* **Mocking and Stubbing:**
* Use mocking libraries like Jest's `jest.mock` to mock Clerk's API and dependencies during testing.
* Create stubbed Clerk responses to simulate different scenarios.
* Avoid mocking implementation details. Mock the API calls and return known responses.
### 6. Common Pitfalls and Gotchas
* **Frequent Mistakes:**
* **Misconfiguring Clerk's API Keys:** Ensure that Clerk's API keys are configured correctly in your environment.
* **Incorrectly Implementing Authentication Checks:** Double-check that authentication checks are implemented correctly on protected routes.
* **Failing to Handle Errors:** Always handle errors that may occur during authentication flows.
* **Not Using Environment Variables:** Avoid hardcoding sensitive data in the code. Use environment variables instead.
* **Mixing server-side and client-side rendering approaches:** Understand which components are rendered where, and the impact on auth state.
* **Edge Cases:**
* **Handling Expired Sessions:** Implement a mechanism to handle expired sessions gracefully.
* **Dealing with Network Errors:** Handle network errors that may occur during API requests.
* **Supporting Different Browsers:** Test your application in different browsers to ensure compatibility.
* **Handling User Deletion:** Handle user deletion and associated data appropriately.
* **Implementing account recovery flows**: Consider how users will reset passwords or regain access to accounts
* **Version-Specific Issues:**
* Check the Clerk's changelog for breaking changes and migration guides when upgrading to a new version.
* Be aware of deprecated features and plan for their removal.
* Consult Clerk's documentation for version-specific instructions.
* **Compatibility Concerns:**
* Ensure that Clerk is compatible with the other technologies used in your application (e.g., React, Next.js, Node.js).
* Check for compatibility issues when upgrading dependencies.
* **Debugging Strategies:**
* Use browser developer tools to inspect network requests and console logs.
* Use a debugger to step through the code and identify issues.
* Check Clerk's server logs for error messages.
* Enable verbose logging in Clerk's configuration to get more detailed information.
* Use remote debugging tools when debugging on mobile devices.
### 7. Tooling and Environment
* **Recommended Development Tools:**
* **IDE:** VS Code, WebStorm
* **Bundler:** Webpack, Parcel
* **Testing Framework:** Jest, Mocha
* **Linting:** ESLint
* **Formatting:** Prettier
* **Version Control:** Git
* **Package Manager:** npm, yarn, pnpm
* **Build Configuration:**
* Use a build tool to automate the build process.
* Configure the build tool to optimize the bundle size.
* Use environment variables to configure the build process.
* Generate sourcemaps for debugging production code.
* Automate deployments using CI/CD pipelines.
* **Linting and Formatting:**
* Use ESLint to enforce code style and identify potential errors.
* Use Prettier to automatically format code.
* Integrate ESLint and Prettier into your IDE and build process.
* Use consistent code style rules across the entire project.
* **Deployment:**
* Deploy your application to a reliable hosting provider (e.g., Vercel, Netlify, AWS).
* Use a CDN to serve static assets.
* Configure HTTPS to secure communication between the client and server.
* Monitor your application for performance and security issues.
* **CI/CD Integration:**
* Use a CI/CD tool (e.g., GitHub Actions, GitLab CI, Jenkins) to automate the build, test, and deployment process.
* Run unit tests, integration tests, and end-to-end tests in the CI/CD pipeline.
* Automate deployments to staging and production environments.
* Use code review processes to ensure code quality.
By adhering to these best practices, developers can build robust, secure, and maintainable applications using the Clerk library.
+356
View File
@@ -0,0 +1,356 @@
---
description: Comprehensive best practices for developing robust and maintainable command-line interfaces using the Click library in Python. Covers code structure, patterns, performance, security, testing, and common pitfalls.
globs: **/*.py
---
# Click CLI Library Best Practices
This document outlines best practices and coding standards for developing command-line interfaces (CLIs) in Python using the Click library. Click is a powerful and user-friendly library that simplifies the creation of beautiful and functional CLIs.
## 1. Code Organization and Structure
### 1.1. Directory Structure
Adopt a well-organized directory structure to enhance maintainability and scalability.
mycli/
├── mycli.py # Main application entry point (click command group)
├── commands/
│ ├── __init__.py # Makes 'commands' a Python package
│ ├── cmd_foo.py # Implementation of 'foo' command
│ ├── cmd_bar.py # Implementation of 'bar' command
│ └── ...
├── utils/
│ ├── __init__.py # Utility functions (e.g., file I/O, API calls)
│ ├── helper.py # Helper functions
│ └── ...
├── models/
│ ├── __init__.py # Data models (e.g., classes, data structures)
│ ├── data_model.py # Data models
│ └── ...
├── tests/
│ ├── __init__.py # Test suite directory
│ ├── test_mycli.py # Tests for main application
│ ├── test_commands/
│ │ ├── test_cmd_foo.py # Tests for 'foo' command
│ │ └── ...
│ └── ...
├── README.md # Project documentation
├── LICENSE # License information
├── pyproject.toml # Project configuration (dependencies, build)
└── .gitignore # Specifies intentionally untracked files that Git should ignore
### 1.2. File Naming Conventions
* Use descriptive and consistent file names.
* Main application file: `mycli.py` (or a similar name reflecting the application's purpose).
* Command modules: `cmd_<command_name>.py` (e.g., `cmd_create.py`, `cmd_update.py`).
* Utility modules: `helper.py`, `file_utils.py`, etc.
* Test files: `test_<module_name>.py` (e.g., `test_mycli.py`, `test_cmd_create.py`).
### 1.3. Module Organization
* **Main Application Module (`mycli.py`):**
* Define the main `click.group()` that serves as the entry point for the CLI.
* Import and register subcommands from the `commands` package.
* Handle global options and context management.
* **Command Modules (`commands` package):**
* Each command module should define a single `click.command()` decorated function.
* Command functions should encapsulate the logic for that specific command.
* Import necessary utility functions and data models from the `utils` and `models` packages.
* **Utility Modules (`utils` package):**
* Provide reusable functions for common tasks, such as file I/O, API calls, data validation, etc.
* Keep utility functions generic and independent of specific commands.
* **Data Models (`models` package):**
* Define classes and data structures to represent the data used by the CLI application.
* Use dataclasses or attrs for creating data models with less boilerplate.
### 1.4. Component Architecture
* **Separation of Concerns:** Clearly separate the CLI interface from the application logic.
* **Command Layer:** Click commands handle user input, argument parsing, and invoking the underlying application logic.
* **Service Layer:** Implement the core application logic in separate modules or classes (services).
* **Data Access Layer:** Encapsulate data access and persistence logic in dedicated modules or classes.
### 1.5. Code Splitting Strategies
* **Command-Based Splitting:** Split the application into separate modules based on the CLI commands.
* **Feature-Based Splitting:** Group related commands and utilities into feature-specific modules.
* **Layered Splitting:** Divide the application into layers (CLI, service, data access) and organize modules accordingly.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Command Pattern:** Each CLI command is represented by a separate class or function, making it easy to add, remove, or modify commands.
* **Factory Pattern:** Use factories to create objects based on CLI arguments (e.g., creating different types of data exporters based on the `--format` option).
* **Dependency Injection:** Inject dependencies (e.g., API clients, database connections) into command functions to improve testability and flexibility.
* **Context Object:** Use Click's context object to store and share data across commands (see examples in the Click documentation).
### 2.2. Recommended Approaches
* **Configuration Management:** Use environment variables or configuration files to manage application settings.
* **Logging:** Implement comprehensive logging using the `logging` module to track application behavior and diagnose issues.
* **Progress Bars:** Use Click's progress bar (`click.progressbar`) to provide visual feedback for long-running tasks.
* **Interactive Prompts:** Use Click's prompts (`click.prompt`) to gather user input interactively.
* **File Handling:** Use `click.File` to handle file I/O with automatic error checking and encoding support.
* **Exception Handling:** Use try-except blocks to gracefully handle exceptions and provide informative error messages to the user.
* **Testing:** Implement a comprehensive test suite to ensure the CLI application's correctness and reliability.
### 2.3. Anti-patterns and Code Smells
* **Tight Coupling:** Avoid tight coupling between the CLI interface and the application logic.
* **Global State:** Minimize the use of global variables and mutable global state.
* **Hardcoded Values:** Avoid hardcoding values in the code; use configuration files or environment variables instead.
* **Duplicated Code:** Refactor duplicated code into reusable functions or classes.
* **Lack of Error Handling:** Neglecting to handle exceptions can lead to unexpected crashes and poor user experience.
* **Inadequate Testing:** Insufficient testing can result in undetected bugs and regressions.
* **Overly Complex Commands:** Break down overly complex commands into smaller, more manageable subcommands.
### 2.4. State Management
* **Context Object:** Use `click.Context.obj` to store and share state between commands. This is the recommended approach for passing data between different parts of your application within a single CLI invocation.
* **Environment Variables:** Use environment variables for global configuration settings that rarely change.
* **Files:** Store persistent state (e.g., user preferences, cached data) in files.
* **Databases:** For more complex state management, use a database.
### 2.5. Error Handling
* **`try...except` Blocks:** Wrap potentially failing operations in `try...except` blocks to catch exceptions.
* **Click's `click.ClickException`:** Raise `click.ClickException` to display user-friendly error messages. This will ensure that the error message is formatted correctly and displayed to the user in a consistent manner.
* **Custom Exception Classes:** Define custom exception classes for specific error conditions.
* **Logging:** Log all errors to aid in debugging and troubleshooting.
* **Exit Codes:** Use appropriate exit codes to indicate the success or failure of a command.
python
import click
@click.command()
@click.option('--input', '-i', required=True, type=click.Path(exists=True, dir_okay=False, readable=True))
def process_file(input):
try:
with open(input, 'r') as f:
# Process the file content
content = f.read()
click.echo(f'Processing file: {input}')
except FileNotFoundError:
raise click.ClickException(f'File not found: {input}')
except IOError:
raise click.ClickException(f'Could not read file: {input}')
except Exception as e:
click.echo(f'An unexpected error occurred: {e}', err=True)
raise # Re-raise the exception for higher-level handling or logging
if __name__ == '__main__':
try:
process_file()
except click.ClickException as e:
click.echo(f'Error: {e}', err=True)
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Minimize I/O Operations:** Reduce the number of file I/O and network operations.
* **Use Efficient Data Structures:** Choose appropriate data structures (e.g., sets, dictionaries) for optimal performance.
* **Caching:** Cache frequently accessed data to reduce redundant computations.
* **Profiling:** Use profiling tools to identify performance bottlenecks.
### 3.2. Memory Management
* **Large Datasets:** When dealing with large datasets, use generators or iterators to process data in chunks.
* **Object Creation:** Avoid creating unnecessary objects.
* **Resource Management:** Release resources (e.g., file handles, network connections) when they are no longer needed.
### 3.3. Bundle Size Optimization
* **Dependency Management:** Use a virtual environment to isolate project dependencies.
* **Tree Shaking:** Use tools like `pyinstaller` to remove unused code from the final executable.
### 3.4. Lazy Loading
* **Import on Demand:** Import modules only when they are needed.
* **Command Loading:** Load command modules only when the corresponding command is invoked.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Command Injection:** Prevent command injection by carefully validating user input.
* **Path Traversal:** Avoid path traversal vulnerabilities by sanitizing file paths.
* **Sensitive Data Exposure:** Protect sensitive data (e.g., passwords, API keys) by storing them securely and avoiding logging them.
### 4.2. Input Validation
* **Type Checking:** Use Click's type system to validate the type of user input.
* **Range Checking:** Validate that numerical inputs fall within acceptable ranges.
* **Regular Expressions:** Use regular expressions to validate string inputs.
* **Whitelist:** Validate inputs against a whitelist of allowed values.
* **Sanitization:** Sanitize user inputs to remove potentially harmful characters.
python
import click
import re
@click.command()
@click.option('--email', '-e', required=True)
def send_email(email):
# Input validation using regex
if not re.match(r"^[\w\.-]+@([\w-]+\.)+[\w-]{2,4}$", email):
raise click.ClickException("Invalid email format.")
click.echo(f"Sending email to {email}")
if __name__ == '__main__':
send_email()
### 4.3. Authentication and Authorization
* **API Keys:** Use API keys to authenticate users and authorize access to resources.
* **OAuth:** Implement OAuth 2.0 for secure API authentication.
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to commands and resources based on user roles.
### 4.4. Data Protection
* **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 outputs.
### 4.5. Secure API Communication
* **HTTPS:** Use HTTPS for all API communication.
* **TLS/SSL:** Use TLS/SSL certificates to encrypt data in transit.
* **API Rate Limiting:** Implement API rate limiting to prevent abuse.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Individual Functions:** Write unit tests for individual functions and classes.
* **Mock Dependencies:** Mock external dependencies (e.g., API calls, database connections) to isolate the code under test.
* **Test Edge Cases:** Test edge cases and boundary conditions to ensure code robustness.
* **Use `click.testing.CliRunner`:** Use `click.testing.CliRunner` to simulate CLI invocations and verify the output.
### 5.2. Integration Testing
* **Test Command Combinations:** Test combinations of commands and options to ensure they work together correctly.
* **Test Real Dependencies:** Test with real dependencies (e.g., a test database) to ensure the application integrates properly.
### 5.3. End-to-End Testing
* **Test Full Workflow:** Test the entire CLI application workflow from start to finish.
* **Automate Tests:** Automate end-to-end tests to ensure continuous integration and continuous delivery.
### 5.4. Test Organization
* **Separate Test Directory:** Create a separate `tests` directory for all tests.
* **Mirror Source Structure:** Mirror the source code structure in the test directory.
* **Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is verifying.
### 5.5. Mocking and Stubbing
* **`unittest.mock`:** Use the `unittest.mock` module to create mock objects and stubs.
* **Mock External Dependencies:** Mock external dependencies to isolate the code under test.
* **Stub Return Values:** Stub return values to control the behavior of mocked objects.
python
import unittest
from unittest.mock import patch
from click.testing import CliRunner
from mycli import cli # Assuming your main script is named mycli.py
class TestMyCLI(unittest.TestCase):
def test_hello_world(self):
runner = CliRunner()
result = runner.invoke(cli, ['hello', '--name', 'TestUser'])
self.assertEqual(result.exit_code, 0)
self.assertEqual(result.output.strip(), 'Hello, TestUser!')
@patch('mycli.commands.cmd_foo.get_data') # Assuming cmd_foo.py has a function get_data to mock
def test_foo_command(self, mock_get_data):
mock_get_data.return_value = ['data1', 'data2']
runner = CliRunner()
result = runner.invoke(cli, ['foo'])
self.assertEqual(result.exit_code, 0)
self.assertIn('data1', result.output)
self.assertIn('data2', result.output)
if __name__ == '__main__':
unittest.main()
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Forgetting `@click.command()` or `@click.group()`:** Commands will not be registered without these decorators.
* **Incorrect Argument Types:** Using the wrong type for a `click.argument` or `click.option` can lead to unexpected behavior.
* **Missing `required=True`:** Forgetting to specify `required=True` for mandatory arguments or options.
* **Not Handling Exceptions:** Failing to handle exceptions can cause the CLI to crash.
* **Incorrect File Paths:** Providing incorrect file paths to `click.Path` can lead to errors.
### 6.2. Edge Cases
* **Unicode Handling:** Ensure proper handling of Unicode characters in input and output.
* **Large Input Files:** Handle large input files efficiently to avoid memory issues.
* **Concurrent Access:** Handle concurrent access to shared resources (e.g., files, databases) properly.
### 6.3. Version-Specific Issues
* **Compatibility:** Check for compatibility issues between Click and other libraries.
* **Deprecated Features:** Be aware of deprecated features and plan for migration.
### 6.4. Compatibility Concerns
* **Python Versions:** Ensure compatibility with supported Python versions.
* **Operating Systems:** Test the CLI application on different operating systems (Windows, macOS, Linux).
* **Terminal Emulators:** Be aware of potential compatibility issues with different terminal emulators.
### 6.5. Debugging Strategies
* **`print()` Statements:** Use `print()` statements for basic debugging.
* **Debuggers:** Use debuggers (e.g., `pdb`, `ipdb`) for more advanced debugging.
* **Logging:** Use logging to track application behavior and diagnose issues.
* **Click's `echo()` Function:** Use Click's `echo()` to ensure consistent output across different platforms and terminal configurations. Also, use `err=True` to distinguish error messages clearly.
## 7. Tooling and Environment
### 7.1. Recommended Tools
* **Virtual Environments:** Use virtual environments (e.g., `venv`, `virtualenv`) to isolate project dependencies.
* **Package Manager:** Use `pip` for installing and managing Python packages.
* **Text Editor/IDE:** Use a text editor or IDE with Python support (e.g., VS Code, PyCharm).
* **Linting Tools:** Use linting tools (e.g., `flake8`, `pylint`) to enforce coding style and identify potential errors.
* **Formatting Tools:** Use formatting tools (e.g., `black`, `autopep8`) to automatically format code.
* **Testing Frameworks:** Use testing frameworks (e.g., `unittest`, `pytest`) to write and run tests.
### 7.2. Build Configuration
* **`pyproject.toml`:** Use `pyproject.toml` to specify project dependencies and build configuration.
* **`setup.py`:** Use `setup.py` to define the project's metadata and entry points.
* **Build Tools:** Use build tools (e.g., `setuptools`, `poetry`) to package and distribute the CLI application.
### 7.3. Linting and Formatting
* **`flake8`:** Use `flake8` to check for PEP 8 violations and other coding style issues.
* **`pylint`:** Use `pylint` for more comprehensive code analysis.
* **`black`:** Use `black` to automatically format code according to PEP 8.
* **Pre-commit Hooks:** Use pre-commit hooks to automatically run linting and formatting tools before committing code.
### 7.4. Deployment
* **Package Managers:** Deploy the CLI application using package managers (e.g., `pip`, `conda`).
* **Executable Bundles:** Create standalone executable bundles using tools like `pyinstaller` or `cx_Freeze`.
* **Containers:** Deploy the CLI application in containers (e.g., Docker) for portability and scalability.
### 7.5. CI/CD Integration
* **Continuous Integration:** Integrate the CLI application into a CI/CD pipeline (e.g., Jenkins, GitLab CI, GitHub Actions).
* **Automated Testing:** Automate testing as part of the CI/CD pipeline.
* **Automated Deployment:** Automate deployment to staging and production environments.
By following these best practices, developers can create robust, maintainable, and user-friendly CLI applications using the Click library.
+240
View File
@@ -0,0 +1,240 @@
---
description: This rule provides guidelines for using CodeMirror effectively, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure robust and maintainable code editor implementations.
globs: **/*.{js,ts,html,css,vue,svelte,jsx,tsx}
---
# CodeMirror Best Practices and Coding Standards
This document outlines best practices and coding standards for developing text editors and code-related applications using CodeMirror. Adhering to these guidelines will help ensure maintainability, performance, and a positive user experience.
## 1. Code Organization and Structure
### 1.1. Directory Structure
* **Project Root:**
* `.cursor/rules/`: (if using cursor rules) stores project-specific rules. Each rule should correspond to a specific aspect of the project or library.
* `src/`: Contains the main source code for your CodeMirror integration.
* `dist/`: Stores the built or compiled output.
* `node_modules/`: Contains project dependencies (managed by npm or yarn).
* `package.json`: Defines project metadata and dependencies.
* `webpack.config.js` or `vite.config.js`: Configuration file for the bundler (if using one).
* `.eslintrc.js`, `.prettierrc.js`: Configuration files for linting and formatting.
* `tests/`: Contains unit, integration, and end-to-end tests.
* `README.md`: Project documentation.
* **`src/` directory:**
* `components/`: Reusable CodeMirror components (e.g., custom toolbars, panels).
* `modes/`: Custom language modes (if any).
* `addons/`: Custom CodeMirror addons.
* `utils/` or `helpers/`: Utility functions.
* `config/`: Configuration files (e.g., CodeMirror options).
* `styles/`: Custom CSS or styling modules for CodeMirror.
* `index.js` or `index.ts`: Entry point for the CodeMirror integration.
### 1.2. File Naming Conventions
* **Components:** Use PascalCase (e.g., `EditorToolbar.js`, `SyntaxHighlightingAddon.ts`).
* **Modules:** Use camelCase (e.g., `editorConfig.js`, `stringUtils.ts`).
* **Styles:** Use kebab-case (e.g., `editor-styles.css`, `toolbar-theme.scss`).
* **Test Files:** Append `.test.js` or `.spec.ts` to the corresponding component/module name (e.g., `EditorToolbar.test.js`).
### 1.3. Module Organization
* **Modular Design:** Break down CodeMirror-related functionality into small, reusable modules.
* **Single Responsibility Principle:** Each module should have a clear and specific purpose.
* **Dependency Management:** Explicitly declare dependencies within each module. Use ES modules (`import`/`export`) or CommonJS (`require`/`module.exports`).
* **Avoid Global State:** Minimize the use of global variables or shared mutable state. Pass data and configuration options explicitly to functions and components.
### 1.4. Component Architecture
* **Presentational and Container Components:** Separate concerns by creating presentational components (responsible for rendering UI) and container components (responsible for data fetching and state management).
* **Component Composition:** Build complex UIs by composing smaller, reusable components.
* **Props and Events:** Use props to pass data down to components and events to communicate actions up to parent components.
### 1.5. Code Splitting
* **Dynamic Imports:** Use dynamic imports (`import()`) to load CodeMirror modes and addons on demand.
* **Route-Based Splitting:** If the CodeMirror editor is only used on specific routes in your application, load it only when those routes are visited.
* **Webpack or Vite Configuration:** Configure your bundler to automatically split your code into smaller chunks.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Observer Pattern:** Use the Observer pattern to notify other parts of the application when the editor's content changes.
* **Strategy Pattern:** Implement different editing strategies based on the selected language mode.
* **Factory Pattern:** Use a factory function to create CodeMirror instances with specific configurations.
### 2.2. Recommended Approaches
* **Configuration Objects:** Encapsulate CodeMirror options in a configuration object to improve readability and maintainability.
* **Custom Addons:** Create custom CodeMirror addons to extend the editor's functionality.
* **Event Handling:** Use CodeMirror's event system to respond to user interactions and editor changes.
### 2.3. Anti-patterns
* **Direct DOM Manipulation:** Avoid directly manipulating the CodeMirror DOM elements. Use the CodeMirror API instead.
* **Overly Complex Modes:** Keep language modes focused and well-structured. Delegate complex parsing logic to external libraries if necessary.
* **Ignoring Performance:** Be mindful of performance implications when adding new features or customizations.
### 2.4. State Management
* **Local State:** Use component state for simple, editor-specific data.
* **Redux or Context API:** For larger applications, consider using a state management library like Redux or the React Context API to manage the editor's state centrally.
* **Immutability:** Treat the editor's state as immutable to simplify debugging and improve performance.
### 2.5. Error Handling
* **Try-Catch Blocks:** Use try-catch blocks to handle potential errors when interacting with the CodeMirror API.
* **Error Boundaries:** In React applications, use error boundaries to catch errors that occur during rendering.
* **Logging:** Log errors and warnings to aid in debugging.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Lazy Loading:** Load CodeMirror modes and addons only when they are needed.
* **Debouncing:** Debounce event handlers to prevent excessive updates.
* **Virtualization:** If you are displaying a large number of lines, consider using a virtualization technique to render only the visible lines.
* **Minimize DOM Updates:** Reduce the number of DOM updates by batching changes and using efficient rendering techniques.
### 3.2. Memory Management
* **Remove Event Listeners:** Remove event listeners when components are unmounted to prevent memory leaks.
* **Clear Intervals and Timeouts:** Clear any intervals or timeouts that are no longer needed.
* **Object Reuse:** Reuse objects and data structures whenever possible to reduce memory allocation.
### 3.3. Rendering Optimization
* **ShouldComponentUpdate:** In React applications, use `shouldComponentUpdate` or `React.memo` to prevent unnecessary re-renders.
* **Immutable Data Structures:** Use immutable data structures to efficiently detect changes and trigger re-renders.
### 3.4. Bundle Size Optimization
* **Tree Shaking:** Configure your bundler to remove unused code (tree shaking).
* **Minification:** Minify your code to reduce its size.
* **Gzip Compression:** Use Gzip compression to reduce the size of your assets during transfer.
### 3.5. Lazy Loading Strategies
* **Mode-Specific Loading:** Only load the language mode when the user opens a file of that type.
* **Addon-Specific Loading:** Load addons only when the user needs their functionality.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Cross-Site Scripting (XSS):** Be careful when displaying user-generated content in the editor. Sanitize the input to prevent XSS attacks.
* **Code Injection:** Avoid using `eval()` or `Function()` to execute untrusted code.
### 4.2. Input Validation
* **Sanitize Input:** Sanitize user input before displaying it in the editor.
* **Validate Data:** Validate data received from external sources before using it in the editor.
### 4.3. Authentication and Authorization
* **Secure APIs:** Use secure APIs for data access and authentication.
* **Role-Based Access Control:** Implement role-based access control to restrict access to sensitive features.
### 4.4. Data Protection
* **Encryption:** Encrypt sensitive data at rest and in transit.
* **Secure Storage:** Store data in a secure location with appropriate access controls.
### 4.5. Secure API Communication
* **HTTPS:** Use HTTPS for all API communication.
* **API Keys:** Protect API keys and prevent them from being exposed in the client-side code.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Components:** Unit test individual CodeMirror components and modules.
* **Mock Dependencies:** Mock external dependencies to isolate the components being tested.
* **Assertion Libraries:** Use assertion libraries like Jest or Chai to write expressive tests.
### 5.2. Integration Testing
* **Test Interactions:** Test the interactions between different CodeMirror components and modules.
* **Real DOM:** Use a real DOM environment for integration testing.
### 5.3. End-to-End Testing
* **Simulate User Actions:** Simulate user actions to test the entire CodeMirror workflow.
* **Automated Testing:** Use end-to-end testing frameworks like Cypress or Puppeteer to automate the testing process.
### 5.4. Test Organization
* **Test Directory:** Create a dedicated `tests/` directory for all tests.
* **Test Files:** Place test files alongside the corresponding components/modules.
* **Test Suites:** Organize tests into logical suites based on functionality.
### 5.5. Mocking and Stubbing
* **Mock CodeMirror Instances:** Mock CodeMirror instances to control their behavior during testing.
* **Stub API Calls:** Stub API calls to prevent external dependencies from interfering with the tests.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Not Sanitizing User Input:** Failing to sanitize user input can lead to XSS vulnerabilities.
* **Ignoring Performance Issues:** Neglecting performance considerations can result in a slow and unresponsive editor.
* **Direct DOM Manipulation:** Directly manipulating CodeMirror's DOM can break its internal workings.
### 6.2. Edge Cases
* **Handling Large Files:** CodeMirror can struggle with extremely large files. Consider using virtualization or other optimization techniques.
* **Internationalization (i18n):** Ensure that the editor supports different languages and character sets.
* **Accessibility (a11y):** Make the editor accessible to users with disabilities by providing keyboard navigation, screen reader support, and appropriate ARIA attributes.
### 6.3. Version-Specific Issues
* **Check Release Notes:** Review the CodeMirror release notes for any breaking changes or known issues.
* **Test Upgrades:** Thoroughly test CodeMirror upgrades to ensure compatibility with your existing code.
### 6.4. Compatibility Concerns
* **Browser Compatibility:** Test the editor in different browsers to ensure compatibility.
* **Framework Compatibility:** Ensure that CodeMirror integrates correctly with your chosen framework (e.g., React, Vue, Angular).
### 6.5. Debugging Strategies
* **Browser Developer Tools:** Use the browser developer tools to inspect the CodeMirror DOM, network requests, and console output.
* **Logging:** Add logging statements to your code to track the flow of execution and identify potential issues.
* **Debugging Tools:** Use a debugger to step through your code and examine variables.
## 7. Tooling and Environment
### 7.1. Recommended Tools
* **Code Editor:** VS Code, Sublime Text, or Atom with CodeMirror-specific plugins.
* **Bundler:** Webpack, Vite, or Parcel.
* **Linter:** ESLint or JSHint.
* **Formatter:** Prettier.
* **Testing Framework:** Jest, Mocha, or Jasmine.
* **End-to-End Testing Framework:** Cypress or Puppeteer.
### 7.2. Build Configuration
* **Module Bundling:** Use a module bundler to combine your code and dependencies into optimized bundles.
* **Source Maps:** Generate source maps to aid in debugging.
* **Code Optimization:** Configure your build process to optimize code for production (e.g., minification, tree shaking).
### 7.3. Linting and Formatting
* **Consistent Style:** Use a linter and formatter to enforce a consistent coding style.
* **Code Quality:** Configure the linter to catch potential code quality issues (e.g., unused variables, syntax errors).
### 7.4. Deployment Best Practices
* **Optimize Assets:** Optimize your assets (e.g., images, CSS, JavaScript) for production.
* **Content Delivery Network (CDN):** Use a CDN to deliver CodeMirror assets to users from geographically distributed servers.
* **Caching:** Configure browser caching to reduce the number of requests to your server.
### 7.5. CI/CD Integration
* **Automated Builds:** Automate the build process using a CI/CD pipeline.
* **Automated Tests:** Run automated tests as part of the CI/CD pipeline.
* **Deployment Automation:** Automate the deployment process to reduce the risk of errors.
+179
View File
@@ -0,0 +1,179 @@
---
description: This rule provides comprehensive best practices for developing with the CrewAI library, covering code organization, performance, security, testing, and common pitfalls. It serves as a guide for building robust and scalable AI applications using CrewAI.
globs: **/*.py
---
- **General Best Practices**:
- Leverage structured responses from LLM calls using Pydantic for output validation.
- Maintain a modular architecture for flexibility and scalability.
- Regularly validate outputs from agents and tasks.
- Use UV for dependency management and Python 3.12.
- Prioritize classes over functions for better organization and maintainability.
- **Code Organization and Structure**:
- **Directory Structure:**
- `crewai_project/` (Root directory)
- `agents/`: Contains agent definitions (e.g., `research_agent.py`, `writer_agent.py`).
- `tasks/`: Contains task definitions (e.g., `research_task.py`, `writing_task.py`).
- `tools/`: Contains custom tools for agents (e.g., `web_search.py`, `data_analysis.py`).
- `models/`: Contains Pydantic models for structured LLM responses (e.g., `article_summary.py`).
- `utils/`: Contains utility functions and helper classes (e.g., `api_utils.py`, `string_formatter.py`).
- `config/`: Configuration files (e.g., `config.yaml`, `api_keys.json`). **Important:** Never commit API keys directly to the repo. Use environment variables or secure vault.
- `tests/`: Unit and integration tests.
- `main.py`: Entry point for the CrewAI application.
- `requirements.txt` or `pyproject.toml`: Project dependencies.
- **File Naming Conventions:**
- Use descriptive, lowercase names with underscores (e.g., `data_processing_agent.py`).
- Pydantic models should be singular (e.g., `ArticleSummary.py` -> `article_summary.py` and class `ArticleSummary`)
- Tests should mirror the source file name with a `_test` suffix (e.g., `data_processing_agent_test.py`).
- **Module Organization:**
- Group related agents, tasks, and tools into separate modules.
- Use clear and concise module names.
- Avoid circular dependencies between modules.
- **Component Architecture:**
- Follow a layered architecture (e.g., agent layer, task layer, tool layer).
- Design components with single responsibilities (Single Responsibility Principle).
- Prefer composition over inheritance for agent and task configurations.
- **Code Splitting:**
- Break down complex tasks into smaller, manageable subtasks.
- Use helper functions and classes to encapsulate reusable logic.
- Consider using a task orchestration framework (e.g., Celery, Dask) for asynchronous task execution if you have long running tasks.
- **Common Patterns and Anti-patterns**:
- **Design Patterns:**
- **Hierarchical Task Delegation:** Implement a manager agent to oversee task execution and validate outcomes.
- **Tool Abstraction:** Create a tool abstraction layer to allow agents to interact with different tools seamlessly.
- **Observer Pattern:** Implement an observer pattern to monitor task progress and trigger events.
- **Recommended Approaches:**
- Define clear roles for each agent.
- Utilize advanced CrewAI features for task delegation.
- Ensure efficient communication among agents through well-defined task interfaces.
- **Anti-patterns:**
- Hardcoding API keys or sensitive information in the code.
- Creating overly complex or tightly coupled agents.
- Ignoring error handling and validation.
- Neglecting proper logging and monitoring.
- Allowing agents unrestricted access to tools and resources.
- **State Management:**
- Use agent's memory (the `memory` attribute) to persist state between tasks.
- Consider using a dedicated state management library (e.g., Redis, Memcached) for complex applications.
- Ensure that state is properly serialized and deserialized.
- **Error Handling:**
- Implement try-except blocks to handle exceptions gracefully.
- Log errors with detailed information for debugging.
- Define custom exception types for specific error scenarios.
- Use retry mechanisms for transient errors (e.g., network timeouts).
- **Performance Considerations:**
- **Optimization Techniques:**
- Optimize LLM calls by using smaller context windows where possible.
- Cache LLM responses to avoid redundant calls.
- Use asynchronous operations for I/O-bound tasks.
- Optimize tools and utilities for performance.
- Implement rate limiting for API calls to avoid exceeding limits.
- **Memory Management:**
- Be mindful of the memory footprint of agents and tasks.
- Avoid storing large amounts of data in agent memory.
- Use generators for processing large datasets.
- Release resources promptly after use.
- **Bundle Size Optimization:** Not directly applicable to CrewAI but important for related web apps or interfaces.
- **Lazy Loading:** Not directly applicable to CrewAI but important for related web apps or interfaces.
- **Security Best Practices**:
- **Common Vulnerabilities:**
- Prompt injection attacks.
- Data breaches due to insecure storage of sensitive information.
- Unauthorized access to tools and resources.
- **Input Validation:**
- Validate all inputs from users and external sources.
- Sanitize inputs to prevent code injection attacks.
- Use regular expressions or validation libraries to enforce input constraints.
- **Authentication and Authorization:**
- Implement authentication to verify the identity of users and agents.
- Use authorization to control access to tools and resources.
- Follow the principle of least privilege: grant agents only the necessary permissions.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms for API keys and credentials.
- Implement data masking to protect sensitive information.
- Comply with relevant data privacy regulations (e.g., GDPR, CCPA).
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Implement API rate limiting to prevent abuse.
- Validate API responses to prevent data corruption.
- Use secure authentication mechanisms for API access.
- **Testing Approaches:**
- **Unit Testing:**
- Write unit tests for individual agents, tasks, and tools.
- Use mocking and stubbing to isolate components during testing.
- Assert that components behave as expected under different conditions.
- **Integration Testing:**
- Write integration tests to verify the interactions between different components.
- Test the end-to-end flow of a CrewAI application.
- Use realistic test data to simulate real-world scenarios.
- **End-to-end Testing:**
- Use tools like Selenium or Playwright to test the entire application flow.
- Verify that the application meets the specified requirements.
- Test the application in different environments.
- **Test Organization:**
- Organize tests into separate modules that mirror the source code structure.
- Use descriptive test names.
- Follow a consistent testing style.
- **Mocking and Stubbing:**
- Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to replace external dependencies with mock objects.
- Use stubbing to provide canned responses for external dependencies.
- Verify that mock objects are called as expected.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:**
- Using overly complex prompts that are difficult to understand and maintain.
- Failing to handle errors and exceptions gracefully.
- Neglecting to validate inputs and outputs.
- Not monitoring and logging application behavior.
- **Edge Cases:**
- Handling unexpected LLM responses.
- Dealing with rate limits and API errors.
- Managing long-running tasks.
- **Version-Specific Issues:**
- Be aware of breaking changes between CrewAI versions.
- Consult the CrewAI changelog for information about new features and bug fixes.
- Test your application with different CrewAI versions to ensure compatibility.
- **Compatibility Concerns:**
- Ensure that CrewAI is compatible with the other libraries and frameworks used in your application.
- Be aware of potential conflicts between different versions of dependencies.
- **Debugging Strategies:**
- Use logging to track application behavior.
- Use a debugger to step through the code and inspect variables.
- Use print statements to debug simple issues.
- Use the CrewAI debugger and introspection tools.
- **Tooling and Environment**:
- **Recommended Tools:**
- VS Code, PyCharm
- Debugger: pdb, ipdb
- Profiler: cProfile
- **Build Configuration:**
- Use `pyproject.toml` for managing dependencies and build settings.
- Use Poetry or pip-tools for dependency management.
- **Linting and Formatting:**
- Use Black for code formatting.
- Use Pylint or Flake8 for code linting.
- Configure pre-commit hooks to automatically format and lint code before committing.
- **Deployment:**
- Containerize your CrewAI application using Docker.
- Deploy your application to a cloud platform (e.g., AWS, Google Cloud, Azure).
- Use a deployment framework (e.g., Docker Compose, Kubernetes) to manage your application.
- **CI/CD Integration:**
- Use a CI/CD platform (e.g., GitHub Actions, GitLab CI, Jenkins) to automate the build, test, and deployment process.
- Write automated tests for your application.
- Configure CI/CD pipelines to run tests and deploy your application on every commit.
- **LLMs and CrewAI**
- CrewAI uses LLMs to provide context, enable decision-making, and generate human-like responses in the agents.
- Configure LLMs with environment variables or advanced features for optimization.
- Available Models and Capabilities:
- GPT-4: High-accuracy tasks, complex reasoning, 8,192 tokens
- GPT-4 Turbo: Long-form content, document analysis, 128,000 tokens
- GPT-4o & GPT-4o-mini: Cost-effective large context processing, 128,000 tokens
- o3-mini: Fast reasoning, complex reasoning, 200,000 tokens
- Structured LLM calls can be used for defining response formats using Pydantic models.
+230
View File
@@ -0,0 +1,230 @@
---
description: This rule provides best practices for developing efficient, maintainable, and scalable GUI applications with CustomTkinter. It covers code organization, performance, security, testing, and common pitfalls.
globs: **/*.py
---
- **Always use UV when installing dependencies.**
- **Always use Python 3.10 or higher.** CustomTkinter requires a modern Python version for compatibility and feature support.
- **Prefer an object-oriented approach.** Encapsulate UI elements and logic within classes for better organization, maintainability, and scalability. Avoid procedural coding for complex applications.
- **Use virtual environments.** Create isolated environments for each project to manage dependencies and avoid conflicts.
- **Use descriptive variable and function names.** Clear and concise names improve code readability.
## 1. Code Organization and Structure
- **Directory Structure:**
- Project Root
- `src/` (Source code)
- `gui/` (CustomTkinter-related modules)
- `__init__.py`
- `main_window.py` (Main application window)
- `components/` (Reusable UI components)
- `__init__.py`
- `button.py`
- `label.py`
- `models/` (Data models if applicable)
- `__init__.py`
- `user.py`
- `utils/` (Utility functions and helpers)
- `__init__.py`
- `config.py`
- `helpers.py`
- `services/` (API interaction services)
- `__init__.py`
- `api_service.py`
- `tests/` (Tests)
- `__init__.py`
- `gui/`
- `test_main_window.py`
- `utils/`
- `test_helpers.py`
- `data/` (Data files, configuration files)
- `requirements.txt` (Dependencies)
- `README.md` (Project documentation)
- `.gitignore`
- `LICENSE`
- `pyproject.toml` or `setup.py`
- **File Naming Conventions:**
- Python files: `lowercase_with_underscores.py`
- Class names: `PascalCase` (e.g., `MainWindow`, `CustomButton`)
- Variable names: `lowercase_with_underscores` (e.g., `main_window`, `button_text`)
- Constants: `UPPERCASE_WITH_UNDERSCORES` (e.g., `DEFAULT_FONT`, `API_KEY`)
- **Module Organization:**
- Group related functionalities into separate modules.
- Use `__init__.py` files to define packages and control namespace imports.
- Keep modules focused on a single responsibility.
- **Component Architecture:**
- Divide the UI into reusable components (e.g., buttons, labels, forms).
- Create custom widget classes by inheriting from `customtkinter.CTkBaseClass` or other appropriate customtkinter base classes.
- Utilize the Model-View-Controller (MVC) or Model-View-ViewModel (MVVM) design pattern to separate UI logic from data and presentation.
- **Code Splitting:**
- Break down large UI components into smaller, manageable parts.
- Use functions and methods to encapsulate specific actions.
- Consider creating separate modules for complex features.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **MVC (Model-View-Controller):** Separate data (Model), UI (View), and user input handling (Controller).
- **MVVM (Model-View-ViewModel):** Similar to MVC, but uses a ViewModel to mediate between the Model and View.
- **Observer:** Implement event handling and notifications between components.
- **Factory:** Create UI elements dynamically based on configuration or user input.
- **Singleton:** Ensures a class only has one instance.
- **Recommended Approaches:**
- **Dynamic UI updates:** Use `configure()` to modify widget properties instead of recreating widgets.
- **Data binding:** Link UI elements to data models for automatic updates.
- **Theming:** Create reusable themes with consistent styles for your application.
- **Asynchronous Operations:** Use `after()` or `threading` module to handle long-running tasks without blocking the main event loop.
- **Use `CTkFont`**: Use this to ensure that the correct font family is used, that is appropriate across all operating systems.
- **Anti-patterns and Code Smells:**
- **God object:** Avoid creating a single class that handles too many responsibilities.
- **Global variables:** Minimize the use of global variables; use instance variables or dependency injection instead.
- **Deeply nested code:** Refactor complex conditional statements and loops into smaller, more readable functions.
- **Mixing grid() and pack() layout managers**: Stick to one layout manager per container to avoid unexpected behavior.
- **State Management:**
- **Centralized state:** Use a dedicated state management class or library to store and manage application state (e.g., using the observer pattern). This can be a simple class for smaller apps, or something like RxPY for more complex state handling.
- **Immutable data:** Treat state data as immutable and create new copies when modifying it to prevent unexpected side effects.
- **Observable state:** Use observable patterns to notify components when the state changes.
- **Error Handling:**
- **Try-except blocks:** Wrap potentially failing code with `try-except` blocks to handle exceptions gracefully.
- **Logging:** Use the `logging` module to record errors and debug information.
- **User feedback:** Provide informative error messages to the user.
- **Specific exception handling:** Handle exceptions in specific branches of your application, rather than catching all errors in a single block.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Minimize UI redraws:** Use `update_idletasks()` to refresh the UI without a full redraw, especially when making multiple changes to widgets. Only update relevant portions of the UI.
- **Efficient layout management:** Choose the appropriate layout manager (grid or pack) and use it consistently.
- **Widget caching:** Reuse existing widgets instead of creating new ones whenever possible.
- **Batch updates:** Group multiple UI updates into a single operation to reduce the number of redraws.
- **Efficient image handling**: Use optimized image formats (e.g., WebP) and resize images appropriately for the UI.
- **Memory Management:**
- **Avoid memory leaks:** Be careful with circular references and ensure that objects are properly released when they are no longer needed.
- **Resource cleanup:** Close files, release database connections, and other resources when they are no longer needed.
- **Rendering Optimization:**
- **Reduce widget complexity:** Avoid using overly complex widgets or layouts.
- **Use hardware acceleration:** Enable hardware acceleration if available to improve rendering performance. This is typically handled by Tkinter itself, but ensure your system supports it.
- **Lazy Loading:**
- **Load UI elements on demand:** Load UI elements only when they are needed to reduce the initial load time.
- **Virtual scrolling:** Implement virtual scrolling for large lists or grids to render only the visible items.
- **Use `after()` wisely:** Delegate intensive tasks to run in the background using `after()` to prevent freezing.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- **Code injection:** Prevent code injection by validating and sanitizing user inputs.
- **Cross-site scripting (XSS):** Escape user-generated content to prevent XSS attacks.
- **Data exposure:** Protect sensitive data by encrypting it and storing it securely.
- **Denial of Service (DoS):** Prevent DoS attacks by limiting the rate of requests and validating input sizes.
- **Input Validation:**
- **Validate all user inputs:** Check data types, formats, and ranges to prevent invalid data from entering the system.
- **Sanitize inputs:** Remove or escape potentially harmful characters from user inputs.
- **Use parameterized queries:** Avoid SQL injection by using parameterized queries when interacting with databases.
- **Authentication and Authorization:**
- **Secure password storage:** Use strong hashing algorithms (e.g., bcrypt, Argon2) to store passwords.
- **Two-factor authentication (2FA):** Implement 2FA to enhance account security.
- **Role-based access control (RBAC):** Control access to resources based on user roles.
- **Use HTTPS:** Always use HTTPS for secure communication between the client and server.
- **Data Protection:**
- **Encryption:** Encrypt sensitive data both in transit and at rest.
- **Data masking:** Mask or redact sensitive data when displaying it to users.
- **Regular backups:** Create regular backups of your data to prevent data loss.
- **Secure API Communication:**
- **API keys:** Store API keys securely and protect them from unauthorized access.
- **Rate limiting:** Limit the rate of API requests to prevent abuse.
- **Input validation:** Validate all data received from APIs.
- **HTTPS:** Always use HTTPS when communicating with APIs.
## 5. Testing Approaches
- **Unit Testing:**
- **Test individual components:** Write unit tests for each component to ensure that it functions correctly.
- **Mock dependencies:** Use mocking to isolate the component being tested from its dependencies.
- **Test edge cases:** Test edge cases and boundary conditions to identify potential issues.
- **Use a testing framework:** Use pytest or unittest.
- **Integration Testing:**
- **Test interactions between components:** Write integration tests to ensure that components work together correctly.
- **Test API interactions:** Test the interaction between the UI and the backend API.
- **Use a testing framework:** Use pytest or unittest.
- **End-to-End Testing:**
- **Test the entire application workflow:** Write end-to-end tests to simulate user interactions and ensure that the application functions correctly from start to finish.
- **Use a testing framework:** Use playwright or selenium.
- **Test Organization:**
- **Separate test files:** Create separate test files for each module or component.
- **Follow a consistent naming convention:** Use a consistent naming convention for test files and functions (e.g., `test_<module_name>.py`, `test_<function_name>`).
- **Mocking and Stubbing:**
- **Use mocking libraries:** Use libraries like `unittest.mock` or `pytest-mock` to create mock objects for dependencies.
- **Stub external services:** Use stubs to replace external services with predictable responses during testing.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Forgetting `self`:** Forgetting to use `self` when accessing instance variables.
- **Incorrect layout management:** Mixing `grid` and `pack` in the same container or not specifying proper row/column configurations.
- **Blocking the main loop:** Performing long-running operations in the main thread, causing the UI to freeze. Use `after()` or `threading` for background tasks.
- **Incorrect event handling:** Not properly binding events to UI elements.
- **Using the same variable name for Tkinter elements**: Tkinter elements should be named descriptively so that they are not confused with other local variables.
- **Edge Cases:**
- **Handling different screen resolutions:** Test the UI on different screen resolutions to ensure that it looks correct.
- **Handling different operating systems:** Test the UI on different operating systems to ensure that it functions correctly.
- **Handling different font sizes:** Test the UI with different font sizes to ensure that the layout remains consistent.
- **Version-Specific Issues:**
- **Check compatibility:** Consult the CustomTkinter documentation for version-specific issues and compatibility information.
- **Compatibility Concerns:**
- **Tkinter versions:** Ensure compatibility between CustomTkinter and the underlying Tkinter version.
- **Operating system:** Test the application on different operating systems to identify potential compatibility issues.
- **Python versions:** Ensure that the application is compatible with the target Python versions.
- **Debugging Strategies:**
- **Use print statements:** Insert `print` statements to debug code and inspect variable values.
- **Use a debugger:** Use a debugger to step through code and inspect the execution flow.
- **Read error messages:** Carefully read error messages to understand the root cause of the problem.
## 7. Tooling and Environment
- **Recommended Tools:**
- **Text editor:** VS Code with Python extension.
- **Virtual environment manager:** `venv` or `conda`.
- **Package manager:** `pip` or `poetry`.
- **Testing framework:** `pytest`.
- **Linting and formatting:** `pylint` or `flake8` and `black` or `autopep8`.
- **Build Configuration:**
- **Use `pyproject.toml` or `setup.py`:** Define project metadata, dependencies, and build instructions in `pyproject.toml` or `setup.py`.
- **Specify dependencies:** List all dependencies in `requirements.txt` or `pyproject.toml`.
- **Linting and Formatting:**
- **Configure linting rules:** Configure linting tools to enforce code style and identify potential issues.
- **Use a formatter:** Use a code formatter to automatically format code according to a consistent style guide.
- **Integrate with CI/CD:** Integrate linting and formatting checks into the CI/CD pipeline.
- **Deployment:**
- **Package the application:** Package the application into an executable or installer using tools like `pyinstaller` or `cx_Freeze`.
- **Create a virtual environment:** Create a virtual environment for the application and include all dependencies.
- **Follow platform-specific guidelines:** Follow platform-specific guidelines for deploying applications.
- **CI/CD Integration:**
- **Automate testing:** Automate unit, integration, and end-to-end tests in the CI/CD pipeline.
- **Automate linting and formatting:** Automate linting and formatting checks in the CI/CD pipeline.
- **Automate deployment:** Automate the deployment process in the CI/CD pipeline.
+345
View File
@@ -0,0 +1,345 @@
---
description: This rule provides a comprehensive guide to Cypress best practices, covering code organization, performance, security, testing strategies, and tooling to ensure robust and maintainable end-to-end tests.
globs: **/*.{cy.js,cy.ts,spec.js,spec.ts}
---
# Cypress Best Practices: A Comprehensive Guide
This guide provides a comprehensive set of best practices for using Cypress, a popular end-to-end testing framework for web applications. Following these guidelines will help you write more robust, maintainable, and efficient tests.
## 1. Code Organization and Structure
Good code organization is crucial for maintaining large Cypress test suites. Here are recommendations for structuring your project:
### Directory Structure
cypress/
├── e2e/ # End-to-end tests
│ ├── example.cy.js # Example test file
│ └── ...
├── fixtures/ # Test data
│ ├── example.json # Example fixture file
│ └── ...
├── support/ # Custom commands and utility functions
│ ├── commands.js # Custom Cypress commands
│ ├── e2e.js # Runs before each test file
│ └── ...
├── downloads/ # Directory for downloaded files from tests
├── screenshots/ # Directory for screenshots of test failures
├── videos/ # Directory for test execution videos
cypress.config.js # Cypress configuration file
package.json # Node.js package file
**Explanation:**
* `e2e/`: Contains your end-to-end tests. Organize tests by feature or component.
* `fixtures/`: Stores static test data (JSON files). Use fixtures to avoid hardcoding data in your tests.
* `support/`: Holds custom commands and utility functions. This promotes code reuse and keeps tests concise.
* `downloads/`, `screenshots/`, `videos/`: Cypress automatically manages these directories for test artifacts.
* `cypress.config.js`: The main configuration file for Cypress.
* `package.json`: Standard Node.js package definition.
### File Naming Conventions
* Test files: `[feature].cy.js` or `[component].spec.js` (e.g., `login.cy.js`, `userProfile.spec.js`).
* Fixture files: `[data_description].json` (e.g., `valid_user.json`, `product_details.json`).
* Custom command files: `[command_name].js` (if multiple command files are created in support/).
### Module Organization
* **Custom Commands:** Place custom commands in `cypress/support/commands.js`. Create separate files for related commands and import them into `commands.js` to improve organization.
* **Page Objects:** If using the Page Object Model (see below), create separate files for each page object and store them in a dedicated directory (e.g., `cypress/page_objects/`).
* **Utility Functions:** Create utility functions for common tasks (e.g., data generation, API calls) and store them in `cypress/support/utils.js` or a similar named file/directory.
### Component Architecture
While Cypress is primarily for end-to-end testing, thinking in terms of components can help structure your tests:
* **Page Object Model (POM):** A design pattern where each page or section of the application is represented as a class. The class contains selectors for elements on the page and methods for interacting with those elements. This centralizes element selection and reduces code duplication. **Example:**
javascript
// cypress/page_objects/loginPage.js
class LoginPage {
getEmailField() {
return cy.get('[data-cy="email"]');
}
getPasswordField() {
return cy.get('[data-cy="password"]');
}
getSubmitButton() {
return cy.get('[data-cy="submit"]');
}
login(email, password) {
this.getEmailField().type(email);
this.getPasswordField().type(password);
this.getSubmitButton().click();
}
}
export default new LoginPage();
// cypress/e2e/login.cy.js
import loginPage from '../page_objects/loginPage';
describe('Login', () => {
it('should log in successfully', () => {
cy.visit('/login');
loginPage.login('test@example.com', 'password');
cy.url().should('include', '/dashboard');
});
});
### Code Splitting
* Cypress doesn't directly support code splitting in the same way as a frontend application. However, you can still organize your code into smaller, manageable files to improve maintainability and readability. Use `require()` or ES module imports (`import/export`) to split your code into modules.
## 2. Common Patterns and Anti-patterns
### Design Patterns
* **Page Object Model (POM):** See above. Encapsulates page-specific logic.
* **Custom Commands:** Create custom commands for frequently used actions. This makes tests more readable and reduces code duplication. **Example:**
javascript
// cypress/support/commands.js
Cypress.Commands.add('login', (email, password) => {
cy.request('POST', '/api/login', { email, password }).then((response) => {
cy.setCookie('auth_token', response.body.token);
cy.visit('/dashboard'); // Or however the app navigates
});
});
// cypress/e2e/dashboard.cy.js
describe('Dashboard', () => {
it('should display user information', () => {
cy.login('user@example.com', 'password');
cy.contains('Welcome, User');
});
});
* **Fixtures:** Load test data from fixture files to keep tests data-driven and avoid hardcoding values. **Example:**
javascript
// cypress/fixtures/user.json
{
"email": "test@example.com",
"password": "password"
}
// cypress/e2e/login.cy.js
describe('Login', () => {
it('should log in with valid credentials', () => {
cy.fixture('user').then((user) => {
cy.visit('/login');
cy.get('[data-cy="email"]').type(user.email);
cy.get('[data-cy="password"]').type(user.password);
cy.get('[data-cy="submit"]').click();
cy.url().should('include', '/dashboard');
});
});
});
### Recommended Approaches for Common Tasks
* **Logging in:** Use `cy.request()` to programmatically log in (as shown in the examples above). This is faster and more reliable than logging in through the UI.
* **Selecting elements:** Use `data-*` attributes for selecting elements. This makes tests more resilient to changes in CSS or JavaScript.
* **Waiting for API calls:** Use `cy.intercept()` to wait for specific API calls before proceeding with the test. Avoid using `cy.wait()` with fixed timeouts.
* **Handling asynchronous operations:** Cypress automatically waits for elements to become available, so avoid using manual timeouts.
### Anti-patterns and Code Smells
* **Hardcoding data:** Avoid hardcoding data directly in your tests. Use fixtures instead.
* **Using brittle selectors:** Avoid using CSS classes or IDs that are likely to change.
* **Relying on fixed timeouts:** Avoid using `cy.wait()` with fixed timeouts. Use `cy.intercept()` or Cypress's built-in waiting mechanisms.
* **Chaining too many commands:** While command chaining is powerful, excessive chaining can make tests harder to read and debug. Break down complex chains into smaller, more manageable chunks.
* **Sharing state between tests:** Each test should be independent and not rely on the state left by other tests. Use `beforeEach()` to set up a clean state for each test.
* **Testing implementation details:** Tests should focus on the user's perspective and not test implementation details that are likely to change.
* **Ignoring error messages:** Pay attention to error messages and use them to debug your tests.
* **Over-reliance on UI for setup:** Where possible, programmatically set up the application state using `cy.request` to seed data or log in users directly rather than navigating through the UI for every test.
### State Management
* Cypress tests should be independent and self-contained. Each test should set up its own initial state. Use `beforeEach()` hooks to reset the state before each test.
* Use `cy.request()` to seed data or log in users directly to set up the application state.
* Avoid sharing state between tests, as this can lead to unreliable and unpredictable results. Use `cy.clearCookies()`, `cy.clearLocalStorage()`, and `cy.clearSessionStorage()` to clear data between tests.
### Error Handling
* Cypress provides detailed error messages that can help you debug your tests. Pay attention to these messages and use them to identify the root cause of the problem.
* Use `try...catch` blocks to handle errors in custom commands or utility functions.
* Use `Cypress.on('uncaught:exception', (err, runnable) => { ... })` to handle uncaught exceptions in the application.
## 3. Performance Considerations
### Optimization Techniques
* **Minimize UI interactions:** Use `cy.request()` to set up the application state instead of interacting with the UI.
* **Use `cy.intercept()` for waiting:** Wait for specific API calls instead of using fixed timeouts.
* **Run tests in parallel:** Cypress Cloud enables parallel test execution to reduce overall test time.
* **Optimize selectors:** Use efficient selectors that quickly locate elements.
* **Filter tests using tags:** Use tags to selectively run tests based on feature or component.
### Memory Management
* Cypress runs in the browser, so memory management is generally handled by the browser. However, it's important to be aware of potential memory leaks in your application.
* Avoid creating large data structures in your tests.
* Use `cy.clearCookies()`, `cy.clearLocalStorage()`, and `cy.clearSessionStorage()` to clear data between tests.
### Rendering Optimization
* N/A - Cypress doesn't directly handle rendering. Rendering is handled by the application being tested.
### Bundle Size Optimization
* The size of your test files can affect the performance of your tests. Keep your test files as small as possible.
* Remove unused code from your test files.
* Use a bundler (e.g., Webpack, Parcel) to bundle your test files.
### Lazy Loading
* N/A - Cypress doesn't directly support lazy loading. Lazy loading is a feature of the application being tested.
## 4. Security Best Practices
### Common Vulnerabilities and How to Prevent Them
* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by properly escaping user input in your application. Cypress can be used to test for XSS vulnerabilities by injecting malicious code into input fields and verifying that it is properly escaped.
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF vulnerabilities by using CSRF tokens in your application. Cypress can be used to test for CSRF vulnerabilities by attempting to submit forms without a valid CSRF token.
* **SQL Injection:** Prevent SQL injection vulnerabilities by using parameterized queries or an ORM. Cypress can be used to test for SQL injection vulnerabilities by injecting malicious SQL code into input fields and verifying that it is properly escaped.
### Input Validation
* Validate all user input on both the client-side and server-side.
* Use strong input validation to prevent malicious input from reaching your application.
* Cypress can be used to test input validation by providing invalid input and verifying that the application properly handles it.
### Authentication and Authorization
* Use a secure authentication and authorization system.
* Use strong passwords and enforce password complexity requirements.
* Use multi-factor authentication for added security.
* Cypress can be used to test authentication and authorization by attempting to access protected resources without proper credentials.
### Data Protection
* Protect sensitive data by encrypting it at rest and in transit.
* Use HTTPS to encrypt data in transit.
* Store sensitive data in a secure location.
* Cypress can be used to test data protection by verifying that sensitive data is properly encrypted.
### Secure API Communication
* Use HTTPS for all API communication.
* Use API keys or other authentication mechanisms to protect your APIs.
* Validate all data received from APIs.
* Cypress can be used to test API security by attempting to access APIs without proper credentials or by sending invalid data.
## 5. Testing Approaches
### Unit Testing
* While Cypress excels at end-to-end testing, unit testing is still important for testing individual components in isolation. Use a unit testing framework like Mocha or Jest for unit testing.
* For components that interact heavily with the UI, consider using Cypress Component Testing.
### Integration Testing
* Integration tests verify that different parts of the application work together correctly. Cypress can be used to write integration tests by testing the interactions between different components or services.
### End-to-End Testing
* End-to-end tests verify that the entire application works correctly from the user's perspective. Cypress is ideal for writing end-to-end tests.
* Focus on testing key user flows and critical functionality.
### Test Organization
* Organize your tests by feature or component.
* Use descriptive names for your test files and test cases.
* Use tags to categorize your tests.
* Create a clear and consistent testing strategy.
### Mocking and Stubbing
* **Mocking:** Replace a dependency with a mock object that simulates the behavior of the dependency. Use `cy.stub()` to mock functions and `cy.intercept()` to mock API calls.
* **Stubbing:** Override the behavior of a function or API call with a predefined response. Use `cy.stub()` to stub functions and `cy.intercept()` to stub API calls.
* Use mocking and stubbing to isolate your tests and control the behavior of external dependencies. This makes tests more predictable and reliable.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes
* Using brittle selectors.
* Relying on fixed timeouts.
* Sharing state between tests.
* Testing implementation details.
* Ignoring error messages.
* Not using custom commands.
* Not using fixtures.
* Trying to test across different domains (Cypress has limitations here).
### Edge Cases
* Handling complex UI interactions (e.g., drag-and-drop, file uploads).
* Testing asynchronous operations.
* Testing WebSockets.
* Testing iframes.
* Testing third-party integrations.
### Version-Specific Issues
* Be aware of breaking changes in new versions of Cypress. Refer to the Cypress changelog for details.
* Test your tests after upgrading Cypress.
### Compatibility Concerns
* Cypress primarily supports Chromium-based browsers (Chrome, Edge). Limited support for Firefox and experimental support for Safari.
* Be aware of compatibility issues between Cypress and other technologies (e.g., React, Angular, Vue.js).
### Debugging Strategies
* Use the Cypress Test Runner to step through your tests and inspect the application state.
* Use the browser's developer tools to debug your tests.
* Use `console.log()` statements to log data to the console.
* Use `cy.pause()` to pause test execution and inspect the application state.
* Use Cypress Cloud for advanced debugging features such as time travel and video recording.
## 7. Tooling and Environment
### Recommended Development Tools
* **IDE:** Visual Studio Code with the Cypress extension.
* **Browser:** Chrome or Edge.
* **Node.js:** Latest LTS version.
* **NPM or Yarn:** Package managers.
### Build Configuration
* Use a bundler (e.g., Webpack, Parcel) to bundle your test files.
* Configure your bundler to optimize your test files for performance.
* Use environment variables to configure your tests for different environments.
### Linting and Formatting
* Use ESLint and Prettier to lint and format your code.
* Configure ESLint and Prettier to enforce consistent coding style.
* Use the Cypress ESLint plugin to catch common Cypress-specific errors.
### Deployment
* Run your Cypress tests as part of your CI/CD pipeline.
* Use Cypress Cloud to run your tests in parallel and get detailed test results.
* Deploy your Cypress tests to a staging environment before deploying to production.
### CI/CD Integration
* Integrate Cypress with your CI/CD pipeline (e.g., GitHub Actions, Jenkins, CircleCI).
* Run your Cypress tests automatically on every commit or pull request.
* Use Cypress Cloud to store your test results and track test history.
* Configure your CI/CD pipeline to fail if your Cypress tests fail.
By adhering to these best practices, you can create a robust and maintainable Cypress test suite that ensures the quality of your web application.
+5
View File
@@ -0,0 +1,5 @@
---
description: Comprehensive best practices and coding standards for D3.js projects, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.js
---
By following these best practices and coding standards, developers can create robust, maintainable, and performant data visualizations using the D3.js library.
+268
View File
@@ -0,0 +1,268 @@
---
description: Comprehensive best practices and coding standards for using Dask in Python, focusing on performance, code organization, and common pitfalls. Provides actionable guidance for developers using Dask for parallel and distributed computing.
globs: **/*.{py,ipynb}
---
# Dask Best Practices and Coding Standards
This document outlines best practices and coding standards for developing with Dask, focusing on code organization, performance optimization, security considerations, testing strategies, and common pitfalls to avoid. Following these guidelines will help ensure efficient, maintainable, and robust Dask applications.
## Library Information:
- Name: dask
- Tags: ai, ml, data-science, python, parallel-computing, big-data
## 1. Code Organization and Structure
A well-organized codebase is crucial for maintainability and collaboration. Here are best practices for structuring Dask projects:
### 1.1 Directory Structure
Adopt a logical directory structure that reflects the project's functionality. A common structure might look like this:
project_root/
├── data/ # Input datasets, sample data, etc.
├── src/ # Source code
│ ├── __init__.py
│ ├── data_loading/ # Modules for data input and output
│ │ ├── __init__.py
│ │ ├── loaders.py # Functions to load data from different formats (CSV, Parquet, etc.)
│ │ └── writers.py # Functions to write data
│ ├── processing/ # Modules for data processing pipelines
│ │ ├── __init__.py
│ │ ├── transformations.py # Dask DataFrame transformations
│ │ ├── aggregations.py # Dask DataFrame aggregations and reductions
│ │ └── utils.py # Utility functions for processing
│ ├── models/ # Modules for machine learning models and related code
│ │ ├── __init__.py
│ │ ├── train.py # Training scripts
│ │ ├── predict.py # Prediction scripts
│ │ └── evaluate.py # Evaluation scripts
│ ├── utils/ # General utility functions
│ │ ├── __init__.py
│ │ └── helpers.py # Various helper functions
│ └── visualization/ # Modules for visualization
│ ├── __init__.py
│ └── plots.py # Plotting functions
├── tests/ # Unit and integration tests
│ ├── __init__.py
│ ├── data_loading/ # Tests for data loading modules
│ ├── processing/ # Tests for processing modules
│ ├── models/ # Tests for machine learning models
│ └── utils/ # Tests for utility modules
├── notebooks/ # Jupyter notebooks for exploration and experimentation
├── docs/ # Project documentation
├── requirements.txt # Python dependencies
├── pyproject.toml # Project configuration
└── dask.yaml # Dask configuration
### 1.2 File Naming Conventions
* **Python files:** Use lowercase with underscores (e.g., `data_loader.py`, `processing_utils.py`).
* **Jupyter Notebooks:** Descriptive names that clearly indicate the notebook's purpose (e.g., `exploratory_data_analysis.ipynb`, `model_training.ipynb`).
* **Configuration Files:** Use standard names like `dask.yaml` for Dask configuration, and `requirements.txt` or `pyproject.toml` for dependencies.
### 1.3 Module Organization
* **Keep modules focused:** Each module should have a clear and specific purpose. Avoid creating monolithic modules with unrelated functionality.
* **Use `__init__.py`:** Include `__init__.py` files in subdirectories to make them importable as packages.
* **Relative imports:** Use relative imports within packages to avoid ambiguity and improve maintainability (e.g., `from . import utils` instead of `from project.src.utils import utils`).
### 1.4 Component Architecture
* **Layered architecture:** Separate concerns into distinct layers (e.g., data loading, processing, modeling, visualization). This promotes modularity and testability.
* **Microservices (optional):** For larger applications, consider breaking down the application into smaller, independent microservices that communicate with each other. Dask can be used within each microservice for parallel processing.
* **Dask Delayed:** Use Dask Delayed to create a graph of computations, enabling parallel execution. Define functions using `@dask.delayed` and build up a workflow.
### 1.5 Code Splitting
* **Functional decomposition:** Break down complex tasks into smaller, well-defined functions.
* **Lazy evaluation:** Leverage Dask's lazy evaluation to defer computation until necessary. This allows you to build complex workflows without immediately executing them.
* **Chunking:** Divide large datasets into smaller chunks that can be processed independently. Dask automatically handles the parallel processing of these chunks.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **MapReduce:** Dask excels at implementing the MapReduce pattern. Use `dask.dataframe.map_partitions` and `dask.array.map_blocks` to apply functions to individual partitions or blocks, followed by aggregations.
* **Data pipelines:** Design data processing workflows as pipelines of Dask operations. This allows for efficient execution and easy modification.
* **Scatter/Gather:** Distribute data to workers using `client.scatter` and then collect the results using `client.gather`. This pattern is useful for distributing data that is needed by multiple tasks.
### 2.2 Recommended Approaches
* **Start with Pandas/NumPy:** Prototype your code using Pandas and NumPy to ensure it works correctly before scaling up with Dask.
* **Use Dask collections:** Prefer using Dask DataFrames and Arrays over Dask Delayed when working with tabular or numerical data. Dask collections provide optimized implementations for common operations.
* **Leverage the Dask Dashboard:** Use the Dask Dashboard to monitor task execution, resource usage, and identify performance bottlenecks. The dashboard provides valuable insights into the behavior of your Dask application.
### 2.3 Anti-patterns
* **Creating large Python objects outside of Dask:** Avoid creating large Pandas DataFrames or NumPy arrays outside of Dask and then passing them to Dask. Instead, let Dask load the data directly. Use `dd.read_csv` or `da.from_array` instead of loading data with Pandas/NumPy and then converting to Dask.
* **Repeatedly calling `compute()`:** Calling `compute()` multiple times on independent parts of a Dask graph forces Dask to recompute shared dependencies. Instead, use `dask.compute()` to compute multiple results in a single call.
* **Over-partitioning:** Creating too many small partitions can lead to excessive overhead. Choose chunk sizes that are large enough to minimize overhead, but small enough to fit in memory.
* **Ignoring the Index:** If your DataFrame will be queried often on specific columns, setting those columns as the index can drastically improve performance.
### 2.4 State Management
* **Minimize global state:** Avoid using global variables within Dask tasks. Instead, pass data explicitly as arguments to the tasks.
* **Immutable data:** Treat data as immutable whenever possible. This simplifies reasoning about the code and avoids unexpected side effects.
* **Dask futures for stateful computations:** For stateful computations, use Dask futures to manage the state of individual tasks. This allows you to track the progress of each task and access its results.
### 2.5 Error Handling
* **Try-except blocks:** Use `try-except` blocks to handle exceptions that may occur within Dask tasks. Log the exceptions and consider retrying the task.
* **Dask futures for exception handling:** Dask futures will propagate exceptions from tasks to the main thread. Handle these exceptions appropriately.
* **Task retries:** Use the `retries` argument in `client.submit` to automatically retry failed tasks. This can be useful for handling transient errors.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Chunk Size Selection:** Choosing appropriate chunk sizes for your Dask arrays or DataFrames. Aim for sizes that allow multiple chunks to fit in memory without causing excessive overhead. A good rule of thumb is to keep chunks around 100 MB, which balances memory use and processing efficiency.
* **Persisting Data:** For large datasets, persist intermediate results in memory after initial processing steps to speed up subsequent computations. This reduces the need for repeated data loading and processing.
* **Minimizing Task Graph Size:** Minimize the number of tasks by fusing operations where possible and avoiding excessive partitioning. Large task graphs can lead to significant overhead that impacts performance.
* **Fusing operations:** Fuse multiple operations into a single task using `dask.delayed` or `dask.dataframe.map_partitions`. This reduces overhead and improves performance.
* **Data locality:** Try to keep data close to the workers that are processing it. This minimizes data transfer and improves performance. Use `client.scatter` to distribute data to specific workers.
* **Using the right scheduler:** The threaded scheduler works well for computations that are mostly CPU-bound. The process scheduler works well for computations that are I/O-bound or involve GIL-releasing operations. The distributed scheduler is best for large-scale deployments.
* **Avoid Oversubscribing Threads:** Explicitly set the number of threads used by NumPy's linear algebra routines to 1. Export the following environment variables before starting your python process: `export OMP_NUM_THREADS=1`, `export MKL_NUM_THREADS=1`, `export OPENBLAS_NUM_THREADS=1`
### 3.2 Memory Management
* **Monitor memory usage:** Use the Dask Dashboard to monitor memory usage and identify memory leaks.
* **Garbage collection:** Explicitly call `gc.collect()` to free up memory that is no longer being used.
* **Avoid creating unnecessary copies of data:** Use in-place operations whenever possible to avoid creating unnecessary copies of data.
* **Use `dask.cache` for caching intermediate results:** Cache intermediate results to avoid recomputing them. This can significantly improve performance for iterative algorithms.
### 3.3 Rendering Optimization
* **Optimize data transfer:** Reduce the amount of data that needs to be transferred for visualization. This can be done by downsampling the data or by aggregating it before transferring it.
* **Use efficient plotting libraries:** Use plotting libraries that are optimized for large datasets, such as Datashader or HoloViews.
### 3.4 Bundle Size Optimization
* **Only import necessary Dask modules:** Only import the Dask modules that are needed by your application. This reduces the size of the application's dependencies.
* **Use tree shaking:** Use a build tool that supports tree shaking to remove unused code from the application's bundle.
### 3.5 Lazy Loading
* **Dask Delayed:** Dask Delayed allows lazy evaluation of computations by building a graph of tasks that are executed only when the result is needed.
* **Dask DataFrames and Arrays:** These collections are lazily evaluated. Operations are not performed until `compute()` is called.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
* **Arbitrary code execution:** If Dask workers are exposed to untrusted networks, attackers may be able to execute arbitrary code on the workers.
* **Data leakage:** Sensitive data may be leaked if Dask workers are not properly secured.
### 4.2 Input Validation
* **Validate data types:** Ensure that input data conforms to the expected types. Use schema validation libraries to enforce data quality.
* **Sanitize input data:** Sanitize input data to prevent injection attacks.
### 4.3 Authentication and Authorization
* **Use Dask's authentication mechanisms:** Use Dask's authentication mechanisms to secure access to the Dask cluster. Dask supports various authentication methods, including password-based authentication and Kerberos authentication.
* **Implement authorization policies:** Implement authorization policies to restrict access to sensitive data and resources.
### 4.4 Data Protection
* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit.
* **Use secure storage:** Store data in secure storage systems with appropriate access controls.
* **Regularly back up data:** Regularly back up data to protect against data loss.
### 4.5 Secure API Communication
* **Use HTTPS:** Use HTTPS to encrypt communication between clients and the Dask cluster.
* **Use strong TLS ciphers:** Configure the Dask cluster to use strong TLS ciphers.
## 5. Testing Approaches
### 5.1 Unit Testing
* **Test individual functions and classes:** Write unit tests for individual functions and classes to ensure they behave as expected.
* **Use a testing framework:** Use a testing framework such as pytest or unittest to organize and run tests.
* **Mock external dependencies:** Mock external dependencies to isolate the code being tested.
### 5.2 Integration Testing
* **Test interactions between components:** Write integration tests to verify that different components of the Dask application work together correctly.
* **Test end-to-end workflows:** Write end-to-end tests to verify that the entire Dask application works as expected.
### 5.3 End-to-End Testing
* **Simulate real-world scenarios:** Design end-to-end tests that simulate real-world scenarios to ensure the Dask application can handle complex data and workloads.
* **Test performance:** Include performance tests to verify that the Dask application meets performance requirements.
### 5.4 Test Organization
* **Separate test directory:** Create a separate `tests` directory to store all tests.
* **Mirror the source code structure:** Organize tests in a way that mirrors the source code structure. This makes it easier to find the tests for a particular module.
### 5.5 Mocking and Stubbing
* **Use the `unittest.mock` module:** Use the `unittest.mock` module to create mock objects for testing.
* **Mock Dask collections:** Mock Dask DataFrames and Arrays to isolate the code being tested.
* **Use dependency injection:** Use dependency injection to make it easier to mock dependencies.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Not understanding lazy evaluation:** Dask operations are lazy, meaning they are not executed until `compute()` is called. This can lead to unexpected behavior if you are not aware of it.
* **Incorrect chunk size selection:** Choosing the wrong chunk size can significantly impact performance. Experiment with different chunk sizes to find the optimal value for your workload.
* **Not persisting intermediate results:** Not persisting intermediate results can lead to repeated computations and poor performance.
* **Not using the Dask Dashboard:** The Dask Dashboard provides valuable insights into the behavior of your Dask application. Use it to monitor task execution, resource usage, and identify performance bottlenecks.
### 6.2 Edge Cases
* **Empty DataFrames:** Be aware of how Dask handles empty DataFrames. Operations on empty DataFrames may return unexpected results.
* **Missing data:** Be aware of how Dask handles missing data (NaN values). Operations on DataFrames and Arrays with missing data may return unexpected results.
### 6.3 Version-Specific Issues
* **API changes:** Dask's API may change between versions. Be sure to consult the Dask documentation for the version you are using.
* **Bug fixes:** New versions of Dask may include bug fixes that address issues you are experiencing. Consider upgrading to the latest version of Dask.
### 6.4 Compatibility Concerns
* **Pandas and NumPy versions:** Dask is compatible with specific versions of Pandas and NumPy. Be sure to use compatible versions of these libraries.
* **Other libraries:** Dask may have compatibility issues with other libraries. Consult the Dask documentation for compatibility information.
### 6.5 Debugging Strategies
* **Use the Dask Dashboard:** Use the Dask Dashboard to monitor task execution and identify errors.
* **Set breakpoints:** Set breakpoints in your code to debug it using a debugger such as pdb or ipdb.
* **Log messages:** Add log messages to your code to track the execution flow and identify errors.
* **Use `dask.visualize()`:** Use `dask.visualize()` to visualize the Dask task graph. This can help you understand how Dask is executing your code and identify potential problems.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **IDE:** VS Code, PyCharm, or other Python IDE.
* **Dask Dashboard:** The Dask Dashboard is an essential tool for monitoring Dask applications.
* **Debugging tools:** pdb, ipdb, or other Python debuggers.
* **Profiling tools:** cProfile or other Python profiling tools.
### 7.2 Build Configuration
* **Use `pyproject.toml`:** Use `pyproject.toml` to specify the project's build dependencies and configuration.
* **Use a virtual environment:** Use a virtual environment to isolate the project's dependencies.
### 7.3 Linting and Formatting
* **Use a linter:** Use a linter such as pylint or flake8 to check the code for style errors and potential problems.
* **Use a formatter:** Use a formatter such as black or autopep8 to automatically format the code.
### 7.4 Deployment Best Practices
* **Choose the right Dask scheduler:** Choose the appropriate Dask scheduler for your deployment environment. The distributed scheduler is best for large-scale deployments.
* **Configure the Dask cluster:** Configure the Dask cluster to meet the needs of your application. Consider factors such as the number of workers, the amount of memory per worker, and the network bandwidth.
* **Monitor the Dask cluster:** Monitor the Dask cluster to ensure it is running correctly and meeting performance requirements.
### 7.5 CI/CD Integration
* **Automate testing:** Automate the testing process using a CI/CD system such as Jenkins or GitLab CI.
* **Automate deployment:** Automate the deployment process using a CI/CD system.
By adhering to these comprehensive guidelines, you can develop robust, efficient, and maintainable Dask applications that leverage the full power of parallel and distributed computing.
+180
View File
@@ -0,0 +1,180 @@
---
description: This rule outlines best practices for coding standards, observability, and effective use of the Datadog library in Python projects. It covers coding style, metric/tag naming, dashboard design, security, and performance optimization.
globs: **/*.py
---
- **Coding Standards**
- Use `black` for code formatting to ensure consistent style.
- Use `isort` to sort imports lexicographically.
- Employ `flake8` for style checks and to maintain code quality.
- Utilize `bugbear` plugin for `flake8` to identify potential bugs and design issues. Enable the following checks:
- `B001`: Avoid bare `except:` clauses; prefer `except Exception:`. Catches unexpected events.
- `B003`: Avoid direct assignment to `os.environ`. Use `os.environ.clear()` or `env=` argument to `Popen`.
- `B006`: Do not use mutable data structures for argument defaults.
- `B007`: Loop control variable should be used within the loop body.
- `B301`: Use Python 3 `.iter*` methods on dictionaries.
- `B305`: Use `next()` builtin instead of `.next()`.
- `B306`: Use `str(e)` or `e.args` to access exception messages.
- `B902`: Use `self` for instance methods, and `cls` for class methods.
- Enforce consistent logging format with `logging-format` `flake8` plugin. Enable the following checks:
- `G001`: Logging statements should not use `string.format()`.
- `G002`: Logging statements should not use `%` formatting.
- `G003`: Logging statements should not use `+` concatenation.
- `G004`: Logging statements should not use f-strings (Python 3.6+).
- `G010`: Logging statements should not use `warn`; use `warning` instead.
- `G100`: Logging statements should not use extra arguments unless whitelisted.
- `G201`: Logging statements should not use `error(..., exc_info=True)`; use `exception(...)` instead.
- `G202`: Logging statements should not use redundant `exc_info=True` in `exception`.
- Use type checking with `mypy` for improved code quality. Configure `mypy` in `hatch.toml`:
toml
[env.collectors.datadog-checks]
check-types: true
mypy-args = [
"--py2",
"--install-types",
"--non-interactive",
"datadog_checks/",
"tests/",
]
mypy-deps = [
"types-mock==0.1.5",
]
- Consider using flags like `--check-untyped-defs` and `--disallow-untyped-defs` for stricter type checking. Configure the files to be checked with mypy.ini file.
- **Metric and Tag Naming Conventions**
- Use descriptive and meaningful names for metrics and tags.
- Avoid abbreviations that might have multiple meanings.
- Maintain consistency in naming across all teams, apps, and services.
- Avoid reserved keywords.
- Prefix metrics with a namespace depicting the application or service generating the data (e.g., `http.nginx.response_time`).
- Metric names must start with a letter.
- Metric names can only contain ASCII alphanumerics, underscores, and periods. Other characters are converted to underscores.
- Metric names should not exceed 200 characters (preferably less than 100).
- Tag names must start with a letter.
- Tag names may contain alphanumerics, underscores, minuses, colons, periods, and slashes. Other characters are converted to underscores.
- Tags can be up to 200 characters long (including both key and value) and support Unicode, but are converted to lowercase.
- Use the `key:value` syntax for tags for optimal functionality. Commonly used metric tag keys are `instance`, `name`, and `role`.
- Implement unified service tagging using `env`, `service`, and `version` tags.
- **Effective Dashboard Design**
- Design dashboards carefully for effective visualization and correlation.
- Utilize out-of-the-box dashboards provided by Datadog.
- Contribute to community-curated dashboards to enhance visibility and correlation of observability data.
- Follow integration dashboard best practices when contributing.
- Consult the "Effective Dashboards" repository for dashboard design guidelines.
- **Code Organization and Structure**
- **Directory Structure:**
- Organize code into modules based on functionality (e.g., `metrics`, `logs`, `tracing`).
- Use a `common` directory for shared utilities and helper functions.
- **File Naming Conventions:**
- Use descriptive file names that reflect the module's purpose (e.g., `metrics_collector.py`, `log_processor.py`).
- **Module Organization:**
- Keep modules small and focused on a single responsibility.
- Use `__init__.py` files to define package structure and expose necessary functionality.
- **Component Architecture:**
- Design components with clear interfaces and separation of concerns.
- Use dependency injection to manage dependencies between components.
- **Code Splitting:**
- Consider splitting large modules into smaller files to improve maintainability.
- Use lazy loading for infrequently used modules.
- **Common Patterns and Anti-patterns**
- **Design Patterns:**
- Use the Observer pattern for subscribing to Datadog events.
- Implement the Decorator pattern for adding custom functionality to Datadog integrations.
- **Recommended Approaches:**
- Use Datadog's API client libraries for interacting with the Datadog API.
- Implement custom checks using Datadog's check framework.
- **Anti-patterns:**
- Avoid hardcoding API keys or other sensitive information in the code.
- Avoid excessive logging, which can impact performance.
- **State Management:**
- Use appropriate data structures for storing state (e.g., dictionaries, lists).
- Consider using a dedicated state management library for complex state management needs.
- **Error Handling:**
- Implement robust error handling to prevent application crashes.
- Use try-except blocks to catch and handle exceptions.
- Log errors to Datadog for monitoring and analysis.
- **Performance Considerations**
- **Optimization Techniques:**
- Use efficient data structures and algorithms.
- Minimize network requests to the Datadog API.
- Use caching to reduce database load.
- **Memory Management:**
- Avoid memory leaks by properly releasing resources.
- Use garbage collection to clean up unused objects.
- **Bundle Size Optimization:**
- Remove unused dependencies from the project.
- Use code minification to reduce bundle size.
- **Lazy Loading:**
- Load infrequently used modules or components on demand.
- **Security Best Practices**
- **Vulnerabilities:**
- Prevent injection attacks by validating user inputs.
- Protect against cross-site scripting (XSS) attacks by encoding outputs.
- **Input Validation:**
- Validate all user inputs to prevent malicious data from entering the system.
- Use regular expressions or other validation techniques to enforce input constraints.
- **Authentication and Authorization:**
- Use strong authentication mechanisms to verify user identities.
- Implement authorization policies to control access to resources.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure communication protocols (e.g., HTTPS) for API communication.
- **Secure API Communication:**
- Use TLS/SSL for secure communication with the Datadog API.
- Store API keys securely and do not expose them in the code.
- **Testing Approaches**
- **Unit Testing:**
- Write unit tests for individual components to verify their functionality.
- Use mocking to isolate components from external dependencies.
- **Integration Testing:**
- Write integration tests to verify interactions between components.
- Use a testing framework like pytest for writing and running tests.
- **End-to-end Testing:**
- Write end-to-end tests to verify the entire application workflow.
- Use a tool like Selenium or Cypress for automating browser tests.
- **Test Organization:**
- Organize tests into separate directories based on component or functionality.
- Use descriptive test names to clearly indicate the purpose of each test.
- **Mocking and Stubbing:**
- Use mocking to simulate external dependencies during testing.
- Use stubbing to replace complex components with simplified versions.
- **Common Pitfalls and Gotchas**
- **Frequent Mistakes:**
- Incorrectly configuring Datadog integrations.
- Not properly handling errors or exceptions.
- Overusing logging, which can impact performance.
- **Edge Cases:**
- Handling large volumes of data.
- Dealing with intermittent network connectivity issues.
- **Version-specific Issues:**
- Be aware of compatibility issues between different versions of Datadog and its dependencies.
- **Compatibility Concerns:**
- Ensure compatibility between Datadog and other technologies used in the project.
- **Debugging Strategies:**
- Use Datadog's monitoring tools to track down performance bottlenecks and errors.
- Use logging to trace the execution flow of the application.
- **Tooling and Environment**
- **Recommended Tools:**
- Use an IDE like VS Code or PyCharm for development.
- Use a version control system like Git for managing code.
- Use a build tool like Make or Poetry for building and deploying the application.
- **Build Configuration:**
- Use a build tool to automate the build process.
- Configure the build tool to generate optimized bundles.
- **Linting and Formatting:**
- Use a linter like Flake8 to enforce coding standards.
- Use a formatter like Black to automatically format code.
- **Deployment:**
- Use a deployment tool like Docker or Kubernetes for deploying the application.
- Use a CI/CD pipeline to automate the deployment process.
- **CI/CD Integration:**
- Integrate Datadog into the CI/CD pipeline to automatically monitor and analyze application performance.
- Use Datadog's API to create custom dashboards and alerts.
+268
View File
@@ -0,0 +1,268 @@
---
description: This rule file provides comprehensive guidelines for Deno development, covering best practices for code organization, security, performance, testing, and documentation. Adhering to these standards ensures maintainable, efficient, and secure Deno applications.
globs: **/*.{ts,tsx,js,jsx,md}
---
- **Use TypeScript**: Always prefer TypeScript for its strong typing, which enhances code quality and maintainability. Provide clear type annotations and use interfaces for better structure.
- **Documentation with JSDoc**: Utilize JSDoc for documenting all exported symbols. Include concise summaries, type information, and examples. Keep documentation up-to-date with code changes.
- **Consistent Naming Conventions**: Follow established naming conventions such as camelCase for variables and functions, PascalCase for classes, and UPPER_SNAKE_CASE for constants. This consistency aids readability and maintainability.
- **Limit Function Parameters**: Functions should ideally take no more than two parameters, using options objects for additional parameters. This makes functions easier to use and test.
## 1. Code Organization and Structure
- **Directory Structure Best Practices**:
- `src/`: Contains the main source code of the application.
- `src/components/`: Reusable UI components (if applicable).
- `src/services/`: Business logic and API interactions.
- `src/utils/`: Utility functions and helpers.
- `tests/`: Unit and integration tests.
- `mod.ts`: The main entry point for the module or application.
- `deps.ts`: Centralized dependency management file (more details below).
- `dev_deps.ts`: Centralized development dependency management file (more details below).
- `deno.json`: Deno configuration file.
- **File Naming Conventions**:
- Use descriptive names with `.ts`, `.tsx`, `.js`, or `.jsx` extensions.
- Component files: `ComponentName.tsx` or `component-name.tsx`
- Service files: `service-name.ts`
- Utility files: `utils.ts` or `string_utils.ts`
- Test files: `file_name_test.ts`
- **Module Organization Best Practices**:
- Favor small, focused modules with clear responsibilities.
- Avoid circular dependencies.
- Use `deps.ts` to manage dependencies centrally. This file exports all external dependencies used in the project, allowing for easy version management and updates. Example:
typescript
// deps.ts
export * as log from "https://deno.land/std@0.224.0/log/mod.ts";
export { assertEquals } from "https://deno.land/std@0.224.0/assert/mod.ts";
export { serve } from "https://deno.land/std@0.224.0/http/server.ts";
- Use `dev_deps.ts` to manage development dependencies centrally. Example:
typescript
// dev_deps.ts
export {
assert,
assertEquals,
assertExists,
assertNotEquals,
assertRejects,
assertStringIncludes,
} from "https://deno.land/std@0.224.0/assert/mod.ts";
export {
FakeTime,
} from "https://deno.land/std@0.224.0/testing/time.ts";
- Import dependencies using the `deps.ts` file in other modules:
typescript
// my_module.ts
import { log, assertEquals } from "./deps.ts";
log.info("Hello, Deno!");
- **Component Architecture Recommendations**:
- Follow a component-based architecture for UI development (if applicable).
- Each component should be self-contained and reusable.
- Consider using a state management library like `nano-states` or `unstate` for complex applications.
- **Code Splitting Strategies**:
- Use dynamic imports (`import()`) to load modules on demand.
- Split code based on routes or features.
- Leverage Deno's built-in module caching for efficient loading.
- Use `deno bundle` to create optimized bundles for deployment, but be mindful of over-bundling.
## 2. Common Patterns and Anti-patterns
- **Design Patterns**:
- **Module Pattern**: Encapsulating code within a module to control access and prevent global scope pollution.
- **Factory Pattern**: Creating objects without specifying the exact class to instantiate.
- **Observer Pattern**: Defining a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
- **Dependency Injection**: Making components loosely coupled. Useful with Deno's module system because you can easily swap out dependencies in tests without relying on complex mocking frameworks.
- **Recommended Approaches for Common Tasks**:
- **HTTP Server**: Use Deno's built-in `Deno.serve` for creating HTTP servers.
- **File System Access**: Use `Deno.readTextFile`, `Deno.writeTextFile`, etc., for file system operations.
- **Environment Variables**: Access environment variables using `Deno.env.get()`.
- **Process Management**: Use `Deno.run` for executing external commands.
- **Anti-patterns and Code Smells**:
- **Global Scope Pollution**: Avoid declaring variables in the global scope.
- **Deeply Nested Callbacks**: Refactor code to use async/await for better readability.
- **Ignoring Errors**: Always handle potential errors using try/catch blocks or `Result` types.
- **Over-Engineering**: Keep code simple and avoid unnecessary complexity.
- **Not Using `deps.ts`**: Failing to centralize and version control your dependencies will make maintenance difficult.
- **State Management Best Practices**:
- For simple applications, use local component state.
- For complex applications, consider using a lightweight state management library or a more robust solution like Redux (via a compatible Deno port).
- Centralize application state and manage it predictably.
- Avoid mutating state directly; use immutable updates.
- **Error Handling Patterns**:
- Use try/catch blocks for synchronous error handling.
- Use `.catch()` for handling errors in Promises.
- Create custom error types for specific scenarios.
- Log errors with sufficient context for debugging.
- Consider using a `Result` type to explicitly handle success or failure cases.
## 3. Performance Considerations
- **Optimization Techniques**:
- **Minimize I/O Operations**: Batch file reads/writes when possible.
- **Efficient Data Structures**: Use appropriate data structures for your use case (e.g., `Map` vs. `Object`).
- **Asynchronous Operations**: Leverage async/await for non-blocking operations.
- **WebAssembly**: Utilize WebAssembly modules for performance-critical tasks.
- **`Deno.bench`**: Use Deno's built-in benchmarking tool to identify performance bottlenecks. Run with `deno bench`. Write benchmarks adjacent to the files you are testing.
- **Memory Management Considerations**:
- Be mindful of memory leaks, especially when working with streams and resources.
- Use `finally` blocks to ensure resources are properly closed.
- Avoid creating unnecessary objects and variables.
- Profile your application to identify memory usage patterns.
- **Rendering Optimization (if applicable)**:
- Use virtual DOM techniques for efficient UI updates.
- Optimize images and other assets.
- Implement lazy loading for offscreen content.
- **Bundle Size Optimization**:
- Use `deno bundle` to create optimized bundles for deployment.
- Remove unused code with tree shaking.
- Minify JavaScript and CSS files.
- Compress assets with gzip or Brotli.
- **Lazy Loading Strategies**:
- Use dynamic imports (`import()`) to load modules on demand.
- Implement lazy loading for images and other assets.
- Split code based on routes or features.
## 4. Security Best Practices
- **Common Vulnerabilities and Prevention**:
- **Remote Code Execution**: Be extremely cautious with `Deno.run`, validate inputs, and never execute untrusted code.
- **Cross-Site Scripting (XSS)**: Sanitize user inputs to prevent XSS attacks (if applicable).
- **SQL Injection**: Use parameterized queries or an ORM to prevent SQL injection (if applicable).
- **Denial of Service (DoS)**: Implement rate limiting and other measures to prevent DoS attacks.
- **Supply Chain Attacks**: Carefully review and pin dependencies in `deps.ts` and `deno.lock`.
- **Input Validation**:
- Validate all user inputs to prevent injection attacks and data corruption.
- Use regular expressions or dedicated validation libraries to enforce input formats.
- Sanitize inputs to remove potentially malicious characters.
- **Authentication and Authorization**:
- Use secure authentication mechanisms like OAuth 2.0 or JWT.
- Implement role-based access control (RBAC) or attribute-based access control (ABAC) for authorization.
- Store passwords securely using bcrypt or Argon2.
- **Data Protection**:
- Encrypt sensitive data at rest and in transit.
- Use HTTPS for all communication.
- Implement proper access controls to protect data from unauthorized access.
- Regularly back up data and test recovery procedures.
- **Secure API Communication**:
- Use HTTPS for all API communication.
- Validate API requests and responses.
- Implement rate limiting to prevent abuse.
- Use API keys or JWT for authentication.
## 5. Testing Approaches
- **Unit Testing**:
- Write unit tests for individual components and functions.
- Use Deno's built-in testing framework (`Deno.test`).
- Mock dependencies to isolate units under test.
- Aim for high test coverage.
- **Integration Testing**:
- Write integration tests to verify interactions between different modules.
- Test API endpoints and data flows.
- Use a test database or mock API for integration tests.
- **End-to-End Testing**:
- Write end-to-end tests to verify the entire application flow.
- Use a testing framework like Playwright or Puppeteer.
- Test user interactions and UI elements (if applicable).
- **Test Organization**:
- Create a `tests/` directory to store all tests.
- Organize tests into subdirectories based on module or feature.
- Use descriptive test names.
- Run tests using `deno test`.
- **Mocking and Stubbing**:
- Use Deno's built-in mocking capabilities or a mocking library like `sinon`.
- Mock external dependencies and API calls.
- Use stubs to replace complex functions with simplified versions.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes**:
- **Incorrect Permissions**: Not requesting necessary permissions (e.g., `--allow-read`, `--allow-net`).
- **Uncaught Exceptions**: Not handling errors properly.
- **Global Variable Pollution**: Accidentally declaring variables in the global scope.
- **Missing `await`**: Forgetting to `await` asynchronous operations.
- **Inconsistent Dependency Versions**: Not managing dependency versions using `deps.ts`.
- **Edge Cases**:
- **Handling large files**: Efficiently stream large files to avoid memory issues.
- **Cross-platform compatibility**: Test your application on different operating systems.
- **Time zone differences**: Handle time zone conversions carefully.
- **Version-Specific Issues**:
- Be aware of breaking changes in Deno releases.
- Consult the Deno release notes for migration guidance.
- **Compatibility Concerns**:
- Ensure compatibility with different browsers and Deno versions (if applicable).
- Be mindful of differences between Deno and Node.js APIs.
- **Debugging Strategies**:
- Use Deno's built-in debugger (`deno inspect`).
- Use `console.log` statements for basic debugging.
- Use a code editor with Deno support for advanced debugging features.
- Inspect network requests and responses using browser developer tools.
## 7. Tooling and Environment
- **Recommended Development Tools**:
- **VS Code** with the Deno extension.
- **IntelliJ IDEA** with the Deno plugin.
- **Deno CLI**.
- **Build Configuration**:
- Use `deno.json` to configure Deno settings, like import maps, linting rules, and formatting options. Example:
json
{
"imports": {
"*": "./src/",
"std/": "https://deno.land/std@0.224.0/"
},
"lint": {
"rules": {
"no-explicit-any": true
}
},
"fmt": {
"lineWidth": 120,
"indentWidth": 2
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "react"
}
}
- **Linting and Formatting**:
- Use `deno lint` to check for code style and potential errors. Configure linting rules in `deno.json`.
- Use `deno fmt` to format code according to the configured style. Configure formatting options in `deno.json`.
- Integrate linting and formatting into your workflow using pre-commit hooks or CI/CD pipelines.
- **Deployment**:
- **Deno Deploy**: For easy serverless hosting of Deno applications. Requires no configuration files to start.
- **Docker**: Containerize your Deno app for consistent deployments.
- **Cloud Providers**: Deploy to AWS, Google Cloud, or Azure using standard deployment methods.
- **CI/CD Integration**:
- Use GitHub Actions, GitLab CI, or other CI/CD platforms to automate testing, linting, formatting, and deployment.
- Configure CI/CD pipelines to run tests on every commit or pull request.
- Automate deployments to production environments.
## Additional Best Practices
- **Use Underscores in Filenames**: Use `file_server.ts` instead of `file-server.ts`.
- **Write Tests for New Features**: Each module should contain or be accompanied by tests for its public functionality.
- **TODO Comments**: TODO comments should include an issue or the author's GitHub username in parentheses. Example: `// TODO(ry): Add tests.`
- **Be Explicit**: Be explicit, even when it means more code.
- **Inclusive Code**: Follow the guidelines for inclusive code.
- **Minimize Dependencies**: Do not make circular imports.
- **JSDoc**: Provide excellent JSDoc coverage for all exported symbols.
- **Resolve Linting Problems**: Use `// deno-lint-ignore <rule>` to suppress warnings when necessary, but use sparingly.
- **Test Module**: Every module with public functionality `foo.ts` should have a test module `foo_test.ts`.
- **Explicit Unit Tests**: Name unit tests clearly.
- **Top-Level Functions**: Use the `function` keyword for top-level functions, not arrow syntax.
- **std Library**: Do not depend on external code in the standard library.
- **Browser Compatibility**: Document and maintain browser compatibility where appropriate.
- **Prefer `#` over `private`**: Prefer `#` (private class fields) over the `private` keyword.
- **Naming Conventions**: Use camelCase, PascalCase, and UPPER_SNAKE_CASE consistently for variables, functions, classes, types, and constants.
By adhering to these best practices, you can create maintainable, efficient, and secure Deno applications.
+278
View File
@@ -0,0 +1,278 @@
---
description: This rule provides comprehensive guidelines for DigitalOcean infrastructure and application development, covering code organization, security, performance, and deployment best practices. It aims to ensure consistent, scalable, and secure cloud solutions on the DigitalOcean platform.
globs: **/*.{tf,yml,yaml,sh,py}
---
# DigitalOcean Development Best Practices
This document provides comprehensive guidelines for developing infrastructure and applications on DigitalOcean. It covers various aspects, including code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and recommended tooling.
## 1. Code Organization and Structure
### Directory Structure
A well-defined directory structure is crucial for maintainability and scalability. Consider these patterns:
project-root/
├── modules/ # Reusable Terraform modules
│ ├── droplet/ # Module for creating Droplets
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── ...
│ ├── database/ # Module for creating Managed Databases
│ │ └── ...
│ └── ...
├── environments/ # Environment-specific configurations
│ ├── dev/ # Development environment
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── terraform.tfvars # Environment-specific variables
│ │ └── ...
│ ├── staging/
│ │ └── ...
│ ├── prod/
│ │ └── ...
│ └── ...
├── scripts/ # Utility scripts (e.g., deployment, backup)
│ ├── deploy.sh
│ ├── backup.sh
│ └── ...
├── tests/ # Infrastructure tests
│ ├── integration/
│ │ └── ...
│ ├── unit/
│ │ └── ...
│ └── ...
├── README.md
├── LICENSE
└── ...
* **`modules/`**: Contains reusable Terraform modules. Each module encapsulates a specific DigitalOcean resource or set of resources (e.g., Droplet, Load Balancer, Database). This promotes code reuse and reduces duplication.
* **`environments/`**: Defines configurations specific to each environment (development, staging, production). This allows for environment-specific settings without modifying the core module code. Use `terraform.tfvars` files to store environment-specific variable values.
* **`scripts/`**: Includes utility scripts for tasks such as deployment, backups, and monitoring. Use descriptive names for scripts and include comments explaining their purpose.
* **`tests/`**: Contains automated tests to verify the infrastructure. Separate integration tests (testing the interaction between resources) from unit tests (testing individual modules).
### File Naming Conventions
* **Terraform files:** Use `.tf` extension. Name files descriptively (e.g., `main.tf`, `variables.tf`, `outputs.tf`). For environment-specific variables, use `terraform.tfvars`.
* **YAML/YML files:** Use `.yml` or `.yaml` extensions for configuration files (e.g., Docker Compose, Kubernetes manifests). Choose one consistently within the project.
* **Shell scripts:** Use `.sh` extension. Name scripts according to their function (e.g., `deploy.sh`, `backup.sh`).
* **Python scripts:** Use `.py` extension. Follow PEP 8 guidelines for naming variables, functions, and classes.
### Module Organization
* **Single Responsibility Principle:** Each module should have a single, well-defined purpose (e.g., creating a Droplet, configuring a firewall).
* **Abstraction:** Modules should abstract away the complexity of underlying DigitalOcean resources, providing a simple and consistent interface for users.
* **Versioning:** Use Terraform module registry to version and share reusable modules. This allows you to track changes and ensure consistent deployments across environments.
* **Input Validation:** Validate input variables to ensure they meet expected criteria (e.g., data type, allowed values). This helps prevent errors and improves the reliability of your infrastructure.
### Component Architecture
* **Microservices:** For complex applications, consider a microservices architecture. Each microservice can be deployed as a separate Droplet or containerized application within a DigitalOcean Kubernetes cluster.
* **Stateless Applications:** Design applications to be stateless whenever possible. This simplifies scaling and improves resilience. Store persistent data in Managed Databases or Object Storage.
* **API Gateway:** Use an API gateway to manage external access to your microservices. This provides a single point of entry and allows you to implement security policies, rate limiting, and other features.
### Code Splitting
* **Terraform workspaces:** Use Terraform workspaces to manage different environments within the same Terraform configuration. This avoids code duplication and simplifies environment management.
* **Modular design:** Follow a modular design approach for your application code. Break down complex functionalities into smaller, manageable modules.
* **Lazy loading:** Implement lazy loading for non-critical components to improve initial load time. This can be particularly useful for web applications.
## 2. Common Patterns and Anti-patterns
### Design Patterns
* **Infrastructure as Code (IaC):** Use Terraform, Pulumi, or other IaC tools to manage your DigitalOcean infrastructure programmatically. This ensures consistency, repeatability, and version control.
* **Twelve-Factor App:** Follow the principles of the Twelve-Factor App methodology for building cloud-native applications. This promotes portability, scalability, and maintainability.
* **Containerization:** Use Docker to containerize your applications. This provides a consistent runtime environment and simplifies deployment to DigitalOcean Kubernetes or Droplets.
* **Service Discovery:** Implement service discovery to allow your microservices to locate each other dynamically. Tools like Consul or etcd can be used for this purpose.
### Recommended Approaches
* **Automated Backups:** Regularly back up your Managed Databases and Droplet volumes. Use DigitalOcean's backup features or implement a custom backup solution using scripts and Object Storage.
* **Monitoring:** Set up monitoring for your DigitalOcean resources using DigitalOcean Monitoring or third-party tools like Prometheus and Grafana. This allows you to track performance, identify issues, and receive alerts.
* **Load Balancing:** Use DigitalOcean Load Balancers to distribute traffic across multiple Droplets. This improves performance and availability.
* **CDN:** Use DigitalOcean CDN to cache static assets and improve website performance for users around the world.
### Anti-patterns
* **Manual Infrastructure Management:** Avoid manually creating or modifying DigitalOcean resources through the web interface. This can lead to inconsistencies and makes it difficult to track changes.
* **Hardcoding Credentials:** Never hardcode API keys, passwords, or other sensitive information in your code. Store them in environment variables or use a secrets management tool like HashiCorp Vault.
* **Ignoring Security Updates:** Keep your Droplet operating systems and application dependencies up-to-date with the latest security patches. Use automated tools like `unattended-upgrades` to apply security updates automatically.
* **Lack of Monitoring:** Failing to monitor your DigitalOcean resources can lead to undetected performance issues and outages.
### State Management
* **Terraform State:** Store Terraform state remotely in DigitalOcean Spaces or other supported backends. This ensures that your Terraform state is stored securely and can be accessed by multiple team members.
* **Application State:** For stateful applications, use Managed Databases or Object Storage to store persistent data. Avoid storing state directly on Droplets.
### Error Handling
* **Comprehensive Logging:** Implement comprehensive logging throughout your application. Include enough information to diagnose issues but avoid logging sensitive data.
* **Centralized Logging:** Use a centralized logging system to collect and analyze logs from all your DigitalOcean resources. Tools like ELK stack (Elasticsearch, Logstash, Kibana) can be used for this purpose.
* **Alerting:** Set up alerting to notify you of errors, performance issues, and other critical events.
* **Retry Logic:** Implement retry logic for transient errors, such as network timeouts. This can improve the resilience of your application.
## 3. Performance Considerations
### Optimization Techniques
* **Resource Selection:** Choose the appropriate Droplet size and Managed Database tier for your workload. Start with a smaller instance and scale up as needed.
* **Caching:** Implement caching at various levels, including CDN, HTTP caching, and application-level caching. Use Redis or Memcached for in-memory caching.
* **Database Optimization:** Optimize your database queries and schema. Use indexes to improve query performance. Consider using a connection pool to reduce database connection overhead.
* **Code Profiling:** Profile your application code to identify performance bottlenecks. Use profiling tools to identify slow-running functions and optimize them.
### Memory Management
* **Memory Leaks:** Be aware of memory leaks in your application code. Use memory profiling tools to identify and fix memory leaks.
* **Garbage Collection:** Understand how garbage collection works in your programming language. Tune garbage collection settings to optimize performance.
### Rendering Optimization
* **Frontend Optimization:** Optimize your frontend code by minimizing HTTP requests, compressing images, and using a CDN.
* **Lazy Loading:** Implement lazy loading for images and other non-critical resources.
### Bundle Size Optimization
* **Code Minification:** Minify your JavaScript and CSS code to reduce bundle size.
* **Tree Shaking:** Use tree shaking to remove unused code from your JavaScript bundles.
* **Code Splitting:** Split your code into smaller bundles that can be loaded on demand.
### Lazy Loading
* **Dynamic Imports:** Use dynamic imports to load modules on demand. This can significantly reduce initial load time.
* **Intersection Observer:** Use the Intersection Observer API to lazy load images and other resources when they become visible in the viewport.
## 4. Security Best Practices
### Common Vulnerabilities
* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
* **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input and using a Content Security Policy (CSP).
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using anti-CSRF tokens.
* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect your application.
### Input Validation
* **Whitelisting:** Use whitelisting to validate user input. Only allow specific characters, data types, and formats.
* **Escaping:** Escape user input before displaying it to prevent XSS attacks.
* **Sanitization:** Sanitize user input to remove potentially harmful characters or code.
### Authentication and Authorization
* **Strong Passwords:** Enforce strong password policies and use a secure password hashing algorithm like bcrypt or Argon2.
* **Multi-Factor Authentication (MFA):** Implement MFA for all users.
* **Role-Based Access Control (RBAC):** Use RBAC to control access to resources based on user roles.
* **Least Privilege:** Grant users only the minimum necessary privileges.
### Data Protection
* **Encryption at Rest:** Encrypt sensitive data at rest using DigitalOcean's encryption features or a third-party encryption solution.
* **Encryption in Transit:** Use HTTPS to encrypt data in transit between your application and users.
* **Data Masking:** Mask sensitive data when displaying it to users.
* **Data Retention Policies:** Implement data retention policies to ensure that data is only stored for as long as necessary.
### Secure API Communication
* **API Keys:** Use API keys to authenticate requests to your APIs.
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your APIs.
* **API Versioning:** Use API versioning to allow you to make changes to your APIs without breaking existing clients.
## 5. Testing Approaches
### Unit Testing
* **Test-Driven Development (TDD):** Consider using TDD to write unit tests before writing your application code.
* **Mocking:** Use mocking to isolate components and test them in isolation.
* **Test Coverage:** Aim for high test coverage to ensure that your code is thoroughly tested.
### Integration Testing
* **Real DigitalOcean Resources:** Use real DigitalOcean resources for integration tests. This ensures that your code works correctly with the DigitalOcean platform.
* **Automated Setup and Teardown:** Automate the setup and teardown of your test environment.
### End-to-End Testing
* **Browser Automation:** Use browser automation tools like Selenium or Cypress to test your application from end to end.
* **Realistic Scenarios:** Test realistic user scenarios to ensure that your application works as expected.
### Test Organization
* **Separate Test Directory:** Create a separate directory for your tests.
* **Descriptive Test Names:** Use descriptive names for your test files and test functions.
### Mocking and Stubbing
* **Mock DigitalOcean API:** Mock the DigitalOcean API to test your code without making actual API calls. This is particularly useful for unit tests.
* **Stub External Dependencies:** Stub external dependencies to isolate your code and make tests more reliable.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes
* **Not Using IaC:** Manually managing infrastructure is error-prone and time-consuming. Use Terraform or other IaC tools.
* **Hardcoding Secrets:** Storing secrets in code is a major security risk. Use environment variables or a secrets management tool.
* **Ignoring Security Updates:** Failing to apply security updates can leave your systems vulnerable to attack.
* **Lack of Monitoring:** Not monitoring your systems can lead to undetected problems.
### Edge Cases
* **API Rate Limits:** Be aware of DigitalOcean API rate limits and implement retry logic to handle rate limit errors.
* **Resource Limits:** Be aware of DigitalOcean resource limits (e.g., number of Droplets, volumes, databases) and plan accordingly.
### Version-Specific Issues
* **Terraform Provider Versions:** Use specific versions of the DigitalOcean Terraform provider to avoid compatibility issues.
* **API Versioning:** Be aware of changes in the DigitalOcean API and update your code accordingly.
### Compatibility Concerns
* **Operating System Compatibility:** Ensure that your application is compatible with the operating system running on your Droplets.
* **Database Compatibility:** Ensure that your application is compatible with the version of Managed Databases you are using.
### Debugging Strategies
* **Logging:** Use comprehensive logging to diagnose issues.
* **Remote Debugging:** Use remote debugging to debug your application code running on a Droplet.
* **Terraform Debugging:** Use Terraform's debugging features to troubleshoot Terraform configurations.
## 7. Tooling and Environment
### Recommended Tools
* **Terraform:** For Infrastructure as Code.
* **Pulumi:** Alternative Infrastructure as Code using familiar programming languages.
* **Docker:** For containerization.
* **DigitalOcean CLI (doctl):** For managing DigitalOcean resources from the command line.
* **Visual Studio Code (VS Code):** Code editor with extensions for Terraform, Docker, and other technologies.
* **Git:** Version control system.
* **GitHub/GitLab/Bitbucket:** Code hosting and collaboration platforms.
### Build Configuration
* **Terraform Modules:** Structure your Terraform code into reusable modules.
* **Terraform Workspaces:** Use Terraform workspaces to manage different environments.
### Linting and Formatting
* **Terraform fmt:** Use `terraform fmt` to format your Terraform code.
* **Shellcheck:** Use Shellcheck to lint your shell scripts.
* **Pylint:** Use Pylint to lint your Python code.
* **Prettier:** Use Prettier to format your JavaScript and CSS code.
### Deployment Best Practices
* **CI/CD Pipelines:** Use CI/CD pipelines to automate the deployment process.
* **Blue/Green Deployments:** Use blue/green deployments to minimize downtime during deployments.
* **Canary Deployments:** Use canary deployments to test new versions of your application with a small subset of users before rolling them out to everyone.
### CI/CD Integration
* **GitHub Actions:** Use GitHub Actions to automate your CI/CD pipelines.
* **GitLab CI/CD:** Use GitLab CI/CD to automate your CI/CD pipelines.
* **Jenkins:** Use Jenkins to automate your CI/CD pipelines.
By following these best practices, you can build scalable, secure, and reliable applications on the DigitalOcean platform.
+190
View File
@@ -0,0 +1,190 @@
---
description: This rule provides best practices and coding standards for developing applications with the discord-api library. It covers code organization, performance, security, testing, and common pitfalls to ensure robust and maintainable Discord integrations.
globs: **/*.{js,ts,jsx,tsx,py,cs}
---
## 1. Code Organization and Structure
- **Directory Structure:**
- `src/`: Contains the main source code of your bot or application.
- `commands/`: Houses individual command modules, each in its own file or subdirectory.
- `events/`: Stores event handlers for Discord events (e.g., message creation, member join).
- `models/`: Defines data models and schemas (if applicable).
- `services/`: Contains reusable services or utilities (e.g., database connections, API wrappers).
- `config/`: Configuration files (e.g., API keys, bot token).
- `utils/`: Utility functions and helper modules.
- `tests/`: Unit and integration tests.
- `docs/`: Documentation for your bot or application.
- `scripts/`: Automation scripts (e.g., deployment, database setup).
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- Commands: `command_name.js`, `command_name.ts` or `command_name/index.js` for command directories.
- Events: `event_name.js`, `event_name.ts`.
- Models: `model_name.js`, `model_name.ts`.
- Services: `service_name.js`, `service_name.ts`.
- Configuration files: `config.json`, `config.js`, `config.ts`.
- **Module Organization:**
- Break down your bot logic into smaller, reusable modules.
- Use ES modules ( `import/export` in JavaScript/TypeScript) or equivalent module systems in other languages to manage dependencies.
- Avoid circular dependencies between modules.
- **Component Architecture:**
- **Command Handlers:** Create a dedicated module to handle command parsing, validation, and execution.
- **Event Emitters:** Use event emitters to decouple event handling logic from the core bot logic.
- **Service Layer:** Abstract external services (e.g., databases, APIs) behind a service layer.
- **Configuration Management:** Use a configuration management library to handle application settings.
- **Code Splitting:**
- Use dynamic imports to load command modules or event handlers on demand, reducing startup time.
- Bundle your code using tools like Webpack, Parcel, or Rollup to optimize bundle size.
- If applicable, use lazy loading for components or modules that are not immediately needed.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Command Pattern:** Encapsulate commands as objects, allowing for flexible command management.
- **Observer Pattern:** Use event emitters to decouple event sources from event listeners.
- **Singleton Pattern:** Implement singleton instances for database connections or other shared resources.
- **Factory Pattern:** Create factories for creating Discord API objects (e.g., messages, embeds).
- **Recommended Approaches:**
- Use a command framework (e.g., discord.js commands) to streamline command creation and handling.
- Utilize Discord's rate limiting mechanisms effectively.
- Implement robust error handling and logging.
- Store sensitive information (e.g., API keys, bot token) in environment variables.
- **Anti-patterns and Code Smells:**
- **Global State:** Avoid using global variables to store bot state, as it can lead to unexpected behavior.
- **Hardcoding:** Do not hardcode configuration values or API keys in your code.
- **Nested Callbacks:** Avoid deeply nested callbacks, which can make your code difficult to read and maintain. Use async/await or promises instead.
- **Ignoring Errors:** Always handle errors properly and log them for debugging.
- **Over-Complicating:** Keep your code as simple as possible while still meeting the requirements.
- **State Management:**
- Use a dedicated state management library (e.g., Redux, Zustand) for complex bot state.
- Store persistent data in a database (e.g., MongoDB, PostgreSQL).
- Implement caching to improve performance.
- **Error Handling:**
- Use try-catch blocks to handle potential errors.
- Log errors to a file or service for debugging.
- Implement retry mechanisms for transient errors.
- Use Discord's error events to catch API errors.
- Send user-friendly error messages to users in the Discord channel.
## 3. Performance Considerations
- **Optimization Techniques:**
- Use efficient data structures and algorithms.
- Cache frequently accessed data.
- Optimize database queries.
- Use asynchronous operations to avoid blocking the main thread.
- Shard your bot to distribute the load across multiple processes.
- **Memory Management:**
- Avoid memory leaks by properly releasing resources.
- Use garbage collection to reclaim unused memory.
- Be mindful of large data structures that can consume a lot of memory.
- **Rendering Optimization:**
- Optimize image sizes and formats.
- Use lazy loading for images and other media.
- Consider using optimized libraries for generating images or videos.
- **Bundle Size Optimization:**
- Use tree shaking to remove unused code from your bundle.
- Minify your code to reduce bundle size.
- Compress your bundle using Gzip or Brotli.
- **Lazy Loading:**
- Load command modules and event handlers on demand.
- Load images and other media only when they are needed.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- **Code Injection:** Prevent code injection vulnerabilities by validating user input and avoiding the use of `eval()` or similar functions.
- **Cross-Site Scripting (XSS):** If your bot interacts with websites or web applications, prevent XSS vulnerabilities by sanitizing user input and escaping output.
- **SQL Injection:** If your bot interacts with a database, prevent SQL injection vulnerabilities by using parameterized queries or an ORM.
- **Denial of Service (DoS):** Protect your bot from DoS attacks by implementing rate limiting and input validation.
- **Unauthorized Access:** Secure your bot's API endpoints and data by implementing authentication and authorization.
- **Input Validation:**
- Validate all user input to prevent malicious or invalid data from being processed.
- Use regular expressions or other validation techniques to enforce data types and formats.
- Sanitize user input to remove potentially harmful characters or code.
- **Authentication and Authorization:**
- Use a secure authentication mechanism to verify the identity of users.
- Implement authorization policies to control access to resources and functionality.
- Use role-based access control (RBAC) to manage user permissions.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms to protect API keys, bot tokens, and other credentials.
- Implement data loss prevention (DLP) measures to prevent sensitive data from being leaked.
- **Secure API Communication:**
- Use HTTPS to encrypt communication with the Discord API.
- Verify the server certificate to prevent man-in-the-middle attacks.
- Use secure API keys or tokens to authenticate with the Discord API.
## 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for individual components and modules.
- Use mocking or stubbing to isolate components from external dependencies.
- Test edge cases and error conditions.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components.
- Test the bot's integration with the Discord API.
- Use a test Discord server to run integration tests.
- **End-to-End Testing:**
- Write end-to-end tests to verify the entire bot workflow.
- Simulate user interactions to test the bot's functionality.
- Use a testing framework to automate end-to-end tests.
- **Test Organization:**
- Organize your tests into separate directories for unit tests, integration tests, and end-to-end tests.
- Use descriptive test names to indicate the purpose of each test.
- Follow a consistent naming convention for test files.
- **Mocking and Stubbing:**
- Use mocking libraries to create mock objects that simulate the behavior of external dependencies.
- Use stubbing to replace real dependencies with simplified versions for testing purposes.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Rate Limiting:** Failing to handle Discord API rate limits properly.
- **Incorrect Intents:** Not specifying the correct gateway intents for your bot.
- **Asynchronous Operations:** Not properly handling asynchronous operations, leading to race conditions or unexpected behavior.
- **Data Serialization:** Incorrectly serializing or deserializing data when interacting with the API.
- **Privileged Intents:** Not understanding the requirements for using privileged intents (e.g., presence, guild members, message content).
- **Edge Cases:**
- Handling large guilds with many members or channels.
- Dealing with unexpected API errors or outages.
- Handling different user locales and languages.
- Managing concurrency and race conditions.
- **Version-Specific Issues:**
- Being aware of breaking changes between different versions of the discord-api library.
- Using deprecated features or APIs.
- Ensuring compatibility with different versions of Node.js or other dependencies.
- **Compatibility Concerns:**
- Ensuring compatibility with different operating systems and platforms.
- Avoiding conflicts with other libraries or dependencies.
- Testing the bot on different Discord clients (e.g., web, desktop, mobile).
- **Debugging Strategies:**
- Use logging to track the bot's execution flow and identify errors.
- Use a debugger to step through the code and inspect variables.
- Use Discord's developer tools to inspect API requests and responses.
- Test your code thoroughly and write unit tests to catch errors early.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **IDE:** Visual Studio Code, IntelliJ IDEA, or other IDE with support for JavaScript/TypeScript.
- **Package Manager:** npm or yarn for managing dependencies.
- **Debugging Tools:** Node.js debugger or Chrome DevTools.
- **Linting Tools:** ESLint or JSHint for enforcing coding standards.
- **Formatting Tools:** Prettier for automatically formatting code.
- **Build Configuration:**
- Use a build tool like Webpack, Parcel, or Rollup to bundle your code.
- Configure your build process to minify and compress your code.
- Use environment variables to configure your build process.
- **Linting and Formatting:**
- Use ESLint or JSHint to enforce coding standards.
- Use Prettier to automatically format your code.
- Configure your editor to automatically run linters and formatters on save.
- **Deployment Best Practices:**
- Use a process manager like PM2 or systemd to keep your bot running.
- Deploy your bot to a cloud platform like Heroku, AWS, or Google Cloud.
- Use a reverse proxy like Nginx or Apache to handle incoming requests.
- Monitor your bot's performance and health.
- **CI/CD Integration:**
- Use a CI/CD platform like GitHub Actions, GitLab CI, or CircleCI to automate your build, test, and deployment process.
- Run unit tests and integration tests as part of your CI/CD pipeline.
- Automate the deployment process to reduce manual effort and errors.
+306
View File
@@ -0,0 +1,306 @@
---
description: This rule file provides comprehensive best practices for Django's Object-Relational Mapper (ORM), covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers in building efficient, maintainable, and secure Django applications.
globs: **/*.py
---
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
- **Application-Centric Structure:** Organize your Django project around applications (apps), where each app represents a specific feature or module.
- **Dedicated 'models' Module:** Keep all model definitions within the `models.py` file of each app.
- **Separate Queries:** For complex queries, consider creating a `queries.py` or `managers.py` file within your app to house custom querysets and managers.
- **Consistent Naming:** Use consistent naming conventions for app and model names.
myproject/
├── myproject/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── app1/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── managers.py # Custom managers and querysets
│ ├── views.py
│ ├── urls.py
│ ├── forms.py
│ ├── tests.py
│ └── migrations/
├── app2/
│ └── ...
└── manage.py
### 1.2. File Naming Conventions
- **Models:** Use singular nouns and CamelCase (e.g., `UserProfile`, `BlogPost`).
- **Fields:** Use lowercase with underscores (snake_case, e.g., `first_name`, `date_joined`).
- **Managers/Querysets:** Use descriptive names related to their functionality (e.g., `ActiveUsersManager`, `PublishedPostsQuerySet`).
- **Files:** Use lowercase with underscores (snake_case, e.g., `models.py`, `forms.py`, `urls.py`).
### 1.3. Module Organization
- **Keep Models Concise:** Limit the number of models in each app to a manageable amount (ideally under 10). If an app becomes too large, refactor it into smaller, more focused apps.
- **Avoid Circular Imports:** Be mindful of circular dependencies between models and other modules within the same app or across apps. Use string references in `ForeignKey` and `ManyToManyField` definitions to avoid immediate import requirements.
- **Utilize Abstract Base Classes:** For common fields across multiple models, define an abstract base class and inherit from it. This promotes code reuse and reduces redundancy. Don't forget to set `abstract = True` in the `Meta` class.
- **Consider Proxy Models:** Use proxy models (`proxy = True` in `Meta`) to change a model's behavior without altering the database schema. This is useful for adding methods or changing the default ordering.
### 1.4. Component Architecture
- **DRY (Don't Repeat Yourself):** Create reusable components such as custom model fields, managers, and querysets.
- **Model Mixins:** Use model mixins to add common functionality to multiple models (e.g., a mixin for soft deletion or timestamping).
- **Form Abstraction:** Create reusable form classes and widgets for data input and validation.
- **Template Tags and Filters:** Develop custom template tags and filters to simplify common tasks in templates related to model data.
### 1.5. Code Splitting Strategies
- **App-Based Splitting:** Organize models and related code within distinct Django apps.
- **Manager-Based Splitting:** Divide complex queries into custom managers and querysets.
- **Mixin-Based Splitting:** Utilize mixins to compartmentalize functionality across models.
- **Signal-Based Splitting:** Implement signals for decoupling operations, such as triggering tasks when a model is saved or deleted.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Repository Pattern:** Abstract data access logic behind a repository interface, allowing you to switch between different data sources without modifying the rest of your application.
- **Unit of Work Pattern:** Group multiple database operations into a single transaction to ensure atomicity and consistency.
- **Specification Pattern:** Encapsulate query logic into reusable specification objects, allowing you to combine and reuse queries across different parts of your application.
- **Model Decorators:** Use decorators to add functionality to models without modifying the original model class. Useful for things like caching calculated properties.
### 2.2. Recommended Approaches for Common Tasks
- **Filtering Data:** Use `filter()` and `exclude()` for efficient data retrieval.
- **Ordering Data:** Utilize `order_by()` to specify the order of results.
- **Aggregating Data:** Employ `aggregate()` to calculate summary statistics.
- **Creating and Updating Objects:** Use `create()` and `save()` for object manipulation.
- **Deleting Objects:** Use `delete()` for removing objects.
- **Prefetch Related:** Use `select_related` for ForeignKey and OneToOneField relationships, and `prefetch_related` for ManyToManyField and reverse ForeignKey relationships.
### 2.3. Anti-patterns and Code Smells
- **Overusing `raw()` Queries:** Prefer Django ORM methods over raw SQL queries to maintain database abstraction and security.
- **Ignoring Database Indexes:** Neglecting to add indexes to frequently queried columns can lead to significant performance bottlenecks. Use `db_index = True` and `Index` in Meta to specify indices.
- **Using `null=True` for String-Based Fields:** Avoid `null=True` for `CharField` and `TextField` fields. Use `blank=True` and an empty string (`''`) instead.
- **Creating Large Querysets without Pagination:** Avoid retrieving large datasets without pagination. Use Django's `Paginator` to break results into manageable chunks.
- **Performing Logic in Templates:** Keep templates focused on presentation. Move complex logic to views or custom template tags.
- **N+1 Query Problem:** Accessing related objects in a loop can cause the N+1 query problem. Use `select_related()` and `prefetch_related()` to mitigate this.
- **Inefficient Use of Exists/Count:** Prefer `exists()` over `count()` when simply checking for the existence of objects.
- **Unnecessary Database Hits:** Optimize data access patterns to minimize the number of database queries.
### 2.4. State Management
- **Database as Primary State:** Rely on the database as the single source of truth for application state.
- **Session Management:** Utilize Django's session framework for storing user-specific state.
- **Caching:** Implement caching strategies to reduce database load and improve response times.
- **Avoid Global Mutable State:** Minimize the use of global mutable state, as it can lead to unexpected behavior and concurrency issues.
### 2.5. Error Handling
- **Catch Database Exceptions:** Handle database exceptions (e.g., `IntegrityError`, `OperationalError`) gracefully.
- **Use Transactions:** Wrap multiple database operations in a transaction to ensure atomicity.
- **Log Errors:** Log errors and exceptions for debugging and monitoring purposes. Use `logger.exception()` to capture the traceback.
- **Custom Exception Handling Middleware:** Consider writing custom middleware to catch and handle database errors at a global level, providing user-friendly error messages.
- **Validate Data Before Saving:** Always validate data before saving it to the database to prevent errors and data inconsistencies. Use Django's built-in validators or create custom validators.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Query Optimization:** Use `select_related` and `prefetch_related` to reduce the number of database queries.
- **Indexing:** Add indexes to frequently queried columns.
- **Caching:** Implement caching strategies for frequently accessed data.
- **Pagination:** Use pagination for large datasets.
- **Batch Operations:** Use `bulk_create`, `bulk_update` and `bulk_delete` for bulk operations.
- **Defer/Only:** use `defer` to exclude fields from the query or `only` to only include specific fields in the query.
- **Conditional Expressions:** Use `Case`, `When`, and `Value` within queries to perform conditional logic directly in the database.
### 3.2. Memory Management
- **Limit Queryset Size:** Avoid retrieving large datasets into memory. Use pagination or generators.
- **Use Generators:** For processing large datasets, use generators to process data in chunks.
- **Garbage Collection:** Understand Python's garbage collection mechanisms and how they affect memory usage.
- **Profiling:** Use profiling tools to identify memory leaks and optimize memory usage.
### 3.3. Rendering Optimization
- **Template Caching:** Cache frequently used templates to reduce rendering time.
- **Context Processors:** Minimize the data passed to templates via context processors.
- **Lazy Loading:** Use lazy loading for images and other resources to improve initial page load time. Consider using template tags like `{% static %}` and `{% get_static_prefix %}` effectively.
### 3.4. Bundle Size Optimization
- **Remove Unused Code:** Eliminate unused models, fields, and queries.
- **Optimize Static Files:** Minify and compress static files (CSS, JavaScript, images).
- **Code Splitting:** Split JavaScript and CSS into smaller chunks for efficient loading.
### 3.5. Lazy Loading
- **Load Related Data on Demand:** Use lazy loading for related data to improve initial performance. Consider using Django Rest Framework serializers with `depth=0` and selectively increasing the depth when needed.
- **Database Views:** Create database views for complex queries to improve performance.
- **QuerySet Iterators:** Instead of converting large querysets into lists, iterate over them using `.iterator()` for memory efficiency.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
- **SQL Injection:** Prevent SQL injection by using Django ORM methods instead of raw SQL queries. Always parameterize your queries.
- **Cross-Site Scripting (XSS):** Sanitize user input and escape output in templates.
- **Cross-Site Request Forgery (CSRF):** Use Django's CSRF protection mechanisms.
- **Authentication and Authorization:** Implement robust authentication and authorization mechanisms.
- **Session Hijacking:** Secure sessions using HTTPS and appropriate session settings.
### 4.2. Input Validation
- **Use Django Forms:** Employ Django Forms for validating user input.
- **Sanitize User Input:** Sanitize user input to prevent XSS attacks.
- **Validate Data Types:** Validate data types to prevent database errors.
- **Limit Input Length:** Restrict input length to prevent buffer overflows.
- **Custom Validators:** Create custom validators for complex validation logic.
- **Consider using DRF Serializers:** Use Django Rest Framework Serializers to add an extra layer of validation to your models and data.
### 4.3. Authentication and Authorization
- **Use Django's Built-in Authentication:** Leverage Django's built-in authentication framework.
- **Implement Role-Based Access Control (RBAC):** Define roles and permissions for different user types.
- **Enforce Password Policies:** Enforce strong password policies.
- **Use Multi-Factor Authentication (MFA):** Implement MFA for sensitive accounts.
- **Rate Limiting:** Implement rate limiting to prevent brute-force attacks.
### 4.4. Data Protection
- **Use HTTPS:** Use HTTPS to encrypt data in transit.
- **Encrypt Sensitive Data:** Encrypt sensitive data at rest.
- **Store Passwords Securely:** Store passwords using a strong hashing algorithm (e.g., bcrypt, Argon2).
- **Regularly Back Up Data:** Regularly back up your database.
- **Audit Logging:** Implement audit logging to track user activity and data changes.
### 4.5. Secure API Communication
- **Use API Keys:** Use API keys for authenticating API requests.
- **Implement OAuth 2.0:** Implement OAuth 2.0 for secure API authorization.
- **Validate API Input:** Validate API input to prevent injection attacks.
- **Rate Limiting:** Implement rate limiting to prevent API abuse.
- **API Versioning:** Use API versioning to manage changes to your API.
## 5. Testing Approaches
### 5.1. Unit Testing
- **Test Model Methods:** Unit test model methods to ensure they behave as expected.
- **Test Custom Managers:** Unit test custom managers to verify their query logic.
- **Test Validators:** Unit test validators to ensure they correctly validate data.
- **Mock Database Dependencies:** Use mocking to isolate model tests from the database.
### 5.2. Integration Testing
- **Test Views and Models:** Integrate test views and models to ensure they work together correctly.
- **Test Forms and Models:** Integrate test forms and models to verify data validation and persistence.
- **Use Test Fixtures:** Use test fixtures to create consistent test data.
- **Test Database Interactions:** Test database interactions to ensure they are efficient and correct.
### 5.3. End-to-End Testing
- **Test User Workflows:** End-to-end test user workflows to ensure they are functional and user-friendly.
- **Test API Endpoints:** End-to-end test API endpoints to ensure they are secure and functional.
- **Use Selenium or Similar Tools:** Use Selenium or similar tools for automating end-to-end tests.
- **Test Across Different Browsers:** Test across different browsers to ensure compatibility.
### 5.4. Test Organization
- **Organize Tests by App:** Organize tests by app to improve maintainability.
- **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what is being tested.
- **Follow a Consistent Test Structure:** Follow a consistent test structure to improve readability.
- **Use Test Runners:** Use test runners to automate test execution.
### 5.5. Mocking and Stubbing
- **Mock Database Queries:** Mock database queries to isolate tests from the database.
- **Stub External Dependencies:** Stub external dependencies to control test environments.
- **Use Django's `override_settings` Decorator:** Use Django's `override_settings` decorator to modify settings during tests.
- **Use `patch` for Mocking:** Use `unittest.mock.patch` for mocking objects and functions.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Not Using Indexes:** Forgetting to add indexes to frequently queried columns.
- **Overusing `null=True`:** Using `null=True` for string-based fields.
- **Ignoring Database Transactions:** Not using database transactions for critical operations.
- **Creating Large Querysets:** Creating large querysets without pagination.
- **Performing Logic in Templates:** Performing logic in templates instead of views.
- **N+1 Query Problem:** Not addressing the N+1 query problem.
### 6.2. Edge Cases
- **Unicode Handling:** Handling Unicode characters correctly.
- **Time Zones:** Dealing with time zones accurately.
- **Concurrency Issues:** Managing concurrency issues in multi-threaded environments.
- **Database-Specific Differences:** Handling database-specific differences.
### 6.3. Version-Specific Issues
- **Deprecated Features:** Being aware of deprecated features and migrating to newer alternatives.
- **Compatibility Changes:** Handling compatibility changes between Django versions.
### 6.4. Compatibility Concerns
- **Python Version:** Ensuring compatibility with the supported Python versions.
- **Database Compatibility:** Ensuring compatibility with the chosen database.
- **Third-Party Libraries:** Ensuring compatibility with third-party libraries.
### 6.5. Debugging
- **Use Django's Debug Toolbar:** Use Django's Debug Toolbar for profiling and debugging.
- **Inspect Database Queries:** Inspect database queries to identify performance bottlenecks.
- **Log Errors and Exceptions:** Log errors and exceptions for debugging purposes.
- **Use a Debugger:** Use a debugger to step through code and inspect variables.
- **Read Stack Traces Carefully:** Read stack traces carefully to understand the source of errors.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **IDE:** PyCharm, VS Code with Python extension.
- **Database Client:** pgAdmin, MySQL Workbench, DB Browser for SQLite.
- **Virtual Environment Manager:** virtualenv, pipenv, conda.
- **Debug Toolbar:** Django Debug Toolbar.
- **Profiling Tools:** cProfile, line_profiler.
### 7.2. Build Configuration
- **Use a Virtual Environment:** Use a virtual environment to isolate project dependencies.
- **Specify Dependencies:** Specify dependencies in a `requirements.txt` or `Pipfile`.
- **Use a Build System:** Use a build system (e.g., Make, Fabric) to automate build tasks.
- **Configure Static File Handling:** Configure static file handling correctly for production.
### 7.3. Linting and Formatting
- **Use a Linter:** Use a linter (e.g., pylint, flake8) to enforce code style.
- **Use a Formatter:** Use a formatter (e.g., black, autopep8) to automatically format code.
- **Configure Editor Integration:** Configure editor integration to automatically lint and format code on save.
- **Follow PEP 8:** Adhere to PEP 8 style guidelines.
### 7.4. Deployment
- **Use a Production-Ready Web Server:** Use a production-ready web server (e.g., Gunicorn, uWSGI).
- **Use a Reverse Proxy:** Use a reverse proxy (e.g., Nginx, Apache) to handle static files and load balancing.
- **Use a Database Server:** Use a dedicated database server (e.g., PostgreSQL, MySQL).
- **Configure Caching:** Configure caching to improve performance.
- **Secure Deployment:** Secure the deployment environment with appropriate firewalls and security settings.
- **Use Environment Variables:** Store sensitive configuration data (e.g., database passwords, API keys) in environment variables.
### 7.5. CI/CD Integration
- **Use a CI/CD System:** Use a CI/CD system (e.g., Jenkins, Travis CI, GitLab CI) to automate testing and deployment.
- **Run Tests Automatically:** Run tests automatically on every commit.
- **Deploy Automatically:** Deploy automatically on successful builds.
- **Use Infrastructure as Code:** Use infrastructure as code (e.g., Terraform, Ansible) to automate infrastructure provisioning.
---
By consistently applying these best practices, you'll establish a robust foundation for building high-quality Django applications that are performant, maintainable, and secure.
+336
View File
@@ -0,0 +1,336 @@
---
description: A comprehensive guide to best practices for developing REST APIs using Django REST Framework (DRF), covering code structure, design patterns, security, performance, and testing.
globs: **/*.py
---
---
# django-rest-framework Best Practices
This document provides a comprehensive guide to best practices for developing robust, scalable, and maintainable REST APIs using the Django REST Framework (DRF). It covers various aspects of DRF development, including code organization, design patterns, security considerations, performance optimization, testing strategies, and common pitfalls.
## 1. Code Organization and Structure
### 1.1. Directory Structure
A well-structured project layout is crucial for maintainability and scalability. Here's a recommended directory structure:
myproject/
manage.py
myproject/
__init__.py
settings/
__init__.py
base.py # Base settings for all environments
development.py # Settings for development environment
production.py # Settings for production environment
urls.py # Root URL configuration
asgi.py
wsgi.py
api/ # Top-level for all apps interacting via REST API
__init__.py
app1/
__init__.py
models.py # Database models
serializers.py# DRF serializers
views.py # DRF viewsets and API views
urls.py # App-specific URL configuration
permissions.py # Custom permissions
filters.py # Custom filters
tasks.py # Celery tasks (if applicable)
tests.py # Unit and integration tests
app2/...
core/ # Core app for user management, etc.
utils/ # General utility functions and modules
docs/ # API documentation (e.g., OpenAPI specification)
### 1.2. File Naming Conventions
* `models.py`: Contains database models.
* `serializers.py`: Contains DRF serializers.
* `views.py`: Contains DRF viewsets and API views.
* `urls.py`: Contains app-specific URL configurations.
* `permissions.py`: Contains custom permissions.
* `filters.py`: Contains custom filters.
* `tasks.py`: Contains Celery tasks (if applicable).
* `tests.py`: Contains unit and integration tests.
* Descriptive names for custom serializers, views, permissions, and filters (e.g., `UserSerializer`, `ProductListView`, `IsAdminOrReadOnly`, `ProductFilter`).
### 1.3. Module Organization
* **Keep apps focused:** Each app should represent a distinct feature or domain within your API.
* **Abstract common logic:** Move reusable code into utility modules within each app or in a shared `utils` directory.
* **Separate concerns:** Ensure that models, serializers, views, and other components are logically separated within their respective modules.
### 1.4. Component Architecture
* **Models:** Define the data structure and relationships using Django's ORM.
* **Serializers:** Convert model instances to JSON and vice versa, handling data validation.
* **Viewsets:** Group related API endpoints (CRUD operations) for a model. Use Generic Views for simpler endpoints.
* **Permissions:** Control access to API endpoints based on user roles or other criteria.
* **Filters:** Allow clients to filter and sort data.
* **Pagination:** Manage large datasets by returning results in pages.
### 1.5. Code Splitting
* **Break down large viewsets:** Decompose complex viewsets into smaller, more manageable classes or functions.
* **Use mixins:** Employ DRF's mixins to reuse common viewset logic.
* **Custom methods for complex logic:** Move complex logic out of views and into helper functions or service classes.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Serializer Pattern:** Encapsulates the conversion of model instances to and from JSON. Enforces data validation rules.
* **Service Layer Pattern:** Encapsulates business logic and data access. Decouples views from models.
* **Repository Pattern:** An abstraction layer between data access logic and the rest of the application. (Less common in Django, but can be helpful for complex scenarios)
* **Factory Pattern:** Creates objects in a centralized location. Simplifies object creation logic.
* **Decorator Pattern:** Adds behavior to existing functions or classes. Enhances functionality without modifying core code.
### 2.2. Recommended Approaches
* **CRUD operations:** Use DRF's ModelViewSet for standard CRUD operations on a model.
* **Custom API endpoints:** Create custom views using `APIView` or generic views for specialized functionality.
* **Data validation:** Leverage DRF's serializers for robust data validation.
* **Authentication:** Use token authentication, session authentication, or OAuth for secure access.
* **Authorization:** Implement permission classes to control access to resources.
* **Filtering and sorting:** Use DRF's filtering and ordering capabilities.
* **Pagination:** Implement pagination for list endpoints with large datasets.
* **Versioning:** Implement API versioning to support evolving APIs.
### 2.3. Anti-patterns and Code Smells
* **Fat models:** Avoid putting business logic directly into models.
* **Fat views:** Keep views thin and delegate business logic to service classes.
* **Inconsistent naming:** Use consistent naming conventions throughout the project.
* **Lack of documentation:** Document all API endpoints and code components.
* **Ignoring errors:** Handle errors gracefully and provide meaningful error messages.
* **Over-engineering:** Don't overcomplicate solutions for simple problems.
* **Duplicated code:** Identify and refactor duplicated code into reusable functions or components.
* **Hardcoded values:** Avoid hardcoding configuration values in the code.
### 2.4. State Management
* **Stateless API:** DRF is inherently stateless, relying on tokens, sessions, or other mechanisms for authentication rather than server-side state. Each request should contain all the necessary information for processing.
* **Client-side state:** State management should primarily be handled on the client-side using libraries like Redux, Vuex, or React Context.
* **Avoid server-side sessions for API state:** Server-side sessions are less scalable and can introduce complexity.
### 2.5. Error Handling
* **Use DRF's exception handling:** DRF provides built-in exception handling that returns appropriate HTTP status codes and error messages.
* **Custom exception handling:** Extend DRF's exception handling to customize error responses.
* **Logging:** Log errors and warnings for debugging and monitoring.
* **Meaningful error messages:** Provide clear and helpful error messages to clients.
* **Centralized error handling:** Create middleware to catch exceptions and log/report.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Database query optimization:** Use Django's ORM efficiently, using `select_related` and `prefetch_related` to reduce database queries. Analyze queries with Django Debug Toolbar.
* **Caching:** Implement caching (using Django's caching framework or Redis) for frequently accessed data.
* **Pagination:** Use pagination for list endpoints with large datasets.
* **Filtering:** Implement efficient filtering mechanisms to reduce the amount of data processed.
* **Gzip compression:** Enable Gzip compression to reduce the size of API responses.
* **Throttling:** Implement API throttling to prevent abuse.
* **Use `defer()` and `only()`:** Retrieve only the necessary fields from the database.
* **Raw SQL Queries:** For very specific and highly optimized queries where the ORM becomes inefficient, consider using raw SQL queries.
* **Asynchronous tasks:** Use Celery to offload long-running tasks to background workers.
* **Read-only serializers:** Use `read_only=True` for fields that should not be updated by clients.
* **Caching Serialized Data:** Cache the results of serializers when appropriate.
### 3.2. Memory Management
* **Avoid loading large datasets into memory:** Use iterators or generators to process data in chunks.
* **Close database connections:** Ensure that database connections are closed properly after use.
* **Garbage collection:** Understand Python's garbage collection mechanisms and avoid creating circular references.
### 3.3. Rendering Optimization
* **Use DRF's built-in renderers:** DRF provides renderers for JSON, XML, and other formats. Use the appropriate renderer for your API.
* **Custom renderers:** Create custom renderers for specialized output formats.
* **Streaming responses:** Use streaming responses for large datasets.
### 3.4. Bundle Size Optimization (If applicable - primarily for client-side rendering)
* **Tree shaking:** Remove unused code from JavaScript bundles.
* **Code splitting:** Split JavaScript bundles into smaller chunks that can be loaded on demand.
* **Minification:** Minify JavaScript and CSS files to reduce their size.
### 3.5. Lazy Loading
* **Lazy load related data:** Load related data only when it is needed.
* **Use DRF's `depth` option:** Control the depth of nested serialization.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **SQL injection:** Prevent SQL injection by using Django's ORM and parameterized queries.
* **Cross-site scripting (XSS):** Sanitize user input to prevent XSS attacks (more relevant for templates, but consider it for any user-provided data).
* **Cross-site request forgery (CSRF):** Protect against CSRF attacks by using Django's CSRF protection mechanisms.
* **Authentication bypass:** Ensure that authentication is properly enforced for all API endpoints.
* **Authorization flaws:** Implement fine-grained authorization to restrict access to resources.
* **Data leakage:** Avoid exposing sensitive data in API responses.
* **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
### 4.2. Input Validation
* **Use DRF's serializers for input validation:** Serializers provide a convenient way to validate incoming data.
* **Validate data types:** Ensure that data types match the expected types.
* **Validate data ranges:** Ensure that data values fall within the allowed ranges.
* **Sanitize user input:** Sanitize user input to prevent XSS attacks.
* **Escape output:** Escape data when rendering it in templates to prevent XSS attacks.
* **Custom Validation:** Implement custom validation logic in serializers to enforce complex business rules.
### 4.3. Authentication and Authorization
* **Choose the appropriate authentication scheme:** Use token authentication, session authentication, or OAuth based on your requirements.
* **Implement permission classes:** Use permission classes to control access to resources based on user roles or other criteria.
* **Use JWT (JSON Web Tokens) for stateless authentication:** JWTs are a popular choice for stateless authentication in REST APIs.
* **Role-Based Access Control (RBAC):** Implement RBAC to manage user permissions based on roles.
* **Principle of Least Privilege:** Grant users only the minimum necessary permissions.
* **Multi-Factor Authentication (MFA):** Implement MFA for enhanced security.
* **Regularly rotate API keys:** Rotate API keys regularly to reduce the risk of compromise.
### 4.4. Data Protection
* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit.
* **Use HTTPS:** Use HTTPS for all API communication.
* **Store passwords securely:** Use Django's password hashing mechanisms to store passwords securely.
* **Data masking:** Mask sensitive data when displaying it to users.
* **Data retention policies:** Implement data retention policies to ensure that data is not stored longer than necessary.
* **Audit logging:** Implement audit logging to track access to sensitive data.
### 4.5. Secure API Communication
* **Use HTTPS:** Use HTTPS for all API communication.
* **Implement CORS:** Configure CORS (Cross-Origin Resource Sharing) to allow requests from specific domains.
* **Rate limiting:** Implement API throttling to prevent abuse.
* **Input Validation:** Implement robust data validation and sanitization.
* **Secure Headers:** Use secure HTTP headers like `X-Content-Type-Options`, `Strict-Transport-Security`, and `X-Frame-Options`.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test serializers:** Test that serializers correctly serialize and deserialize data, and that validation rules are enforced.
* **Test views:** Test that views return the expected responses for different requests, and that permissions are enforced.
* **Test models:** Test model methods and data integrity.
* **Isolate units of code:** Use mocking and stubbing to isolate units of code during testing.
* **Follow Arrange-Act-Assert pattern:** Arrange test data, act on the code, and assert the expected result.
### 5.2. Integration Testing
* **Test API endpoints:** Test that API endpoints work correctly when integrated with other components.
* **Test database interactions:** Test that database interactions are performed correctly.
* **Test authentication and authorization:** Test that authentication and authorization mechanisms work as expected.
* **Use Django's test client:** Use Django's test client to send HTTP requests to API endpoints.
* **Test with real database:** Use a separate test database for integration tests.
### 5.3. End-to-End Testing
* **Test the entire API workflow:** Test the entire API workflow from end to end.
* **Use tools like Selenium or Cypress:** Use tools like Selenium or Cypress to automate end-to-end tests.
* **Test with a production-like environment:** Test with a production-like environment to ensure that the API works correctly in a real-world setting.
### 5.4. Test Organization
* **Create a separate `tests.py` file for each app:** This promotes modularity and makes it easier to find tests for a specific app.
* **Organize tests within `tests.py` by component:** Group tests for serializers, views, models, and other components.
* **Use descriptive test names:** Use descriptive test names that clearly indicate what each test is testing.
* **Follow a consistent naming convention:** Use a consistent naming convention for test functions and classes.
### 5.5. Mocking and Stubbing
* **Use mocking to isolate units of code:** Mock external dependencies to isolate units of code during testing.
* **Use stubbing to provide controlled responses:** Stub external dependencies to provide controlled responses during testing.
* **Use libraries like `unittest.mock`:** Use libraries like `unittest.mock` for mocking and stubbing.
* **Avoid over-mocking:** Only mock the necessary dependencies to keep tests realistic.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Not using serializers for validation:** Skipping serializer validation can lead to data integrity issues and security vulnerabilities.
* **Incorrectly configuring permissions:** Misconfigured permissions can expose resources to unauthorized users.
* **Over-fetching data:** Fetching more data than necessary can impact performance.
* **Ignoring database query optimization:** Inefficient database queries can lead to slow API responses.
* **Not handling errors gracefully:** Unhandled exceptions can cause the API to crash or return unhelpful error messages.
* **Using `CharField` without `max_length`**: Can lead to unexpected database errors or vulnerabilities.
### 6.2. Edge Cases
* **Handling null values:** Ensure that null values are handled correctly in serializers and views.
* **Handling empty lists:** Ensure that empty lists are handled correctly in serializers and views.
* **Handling unicode characters:** Ensure that unicode characters are handled correctly in serializers and views.
* **Concurrency issues:** Be aware of potential concurrency issues when handling data updates.
* **Timezones:** Be aware of timezone issues and use timezone-aware datetime objects.
### 6.3. Version-Specific Issues
* **Consult DRF's release notes:** Refer to DRF's release notes for information on version-specific issues and breaking changes.
* **Test with different DRF versions:** Test your API with different DRF versions to ensure compatibility.
### 6.4. Compatibility Concerns
* **Django version compatibility:** Ensure that your DRF version is compatible with your Django version.
* **Python version compatibility:** Ensure that your DRF version is compatible with your Python version.
* **Third-party library compatibility:** Ensure that your DRF version is compatible with any third-party libraries that you are using.
### 6.5. Debugging Strategies
* **Use Django Debug Toolbar:** Use Django Debug Toolbar to inspect database queries, template rendering, and other performance metrics.
* **Use logging:** Use logging to track the flow of execution and identify errors.
* **Use a debugger:** Use a debugger to step through code and inspect variables.
* **Test API endpoints with a tool like Postman:** Use Postman or a similar tool to test API endpoints and inspect responses.
* **Read traceback carefully**: Python tracebacks are extremely helpful in locating the origin of an error.
## 7. Tooling and Environment
### 7.1. Recommended Tools
* **Virtual environment:** Use a virtual environment to isolate project dependencies.
* **Pip:** Use pip to manage Python packages.
* **Django:** Use Django as the web framework.
* **Django REST Framework:** Use DRF for building REST APIs.
* **Django Debug Toolbar:** Use Django Debug Toolbar for debugging and performance analysis.
* **Postman or Insomnia:** Use Postman or Insomnia to test API endpoints.
* **Git:** Use Git for version control.
* **EditorConfig:** Use EditorConfig to maintain consistent coding styles across different editors.
* **Black, isort, flake8**: For code formatting and linting
* **drf-yasg or Spectacular OpenAPI:** For automatic OpenAPI schema generation.
### 7.2. Build Configuration
* **Use a `requirements.txt` file:** Use a `requirements.txt` file to specify project dependencies.
* **Use a `setup.py` file:** Use a `setup.py` file to package and distribute your API.
* **Use environment variables:** Use environment variables to store configuration values.
* **Use Docker:** Use Docker to containerize your API for consistent deployment.
### 7.3. Linting and Formatting
* **Use PEP 8:** Follow PEP 8 guidelines for Python code.
* **Use Black:** Use Black for code formatting.
* **Use flake8:** Use flake8 for code linting.
* **Use isort:** Use isort for import sorting.
* **Configure pre-commit hooks:** Set up pre-commit hooks to automatically format and lint code before committing.
### 7.4. Deployment
* **Use a production-ready web server:** Use a production-ready web server like Gunicorn or uWSGI.
* **Use a load balancer:** Use a load balancer to distribute traffic across multiple servers.
* **Use a database server:** Use a database server like PostgreSQL or MySQL.
* **Use a caching server:** Use a caching server like Redis or Memcached.
* **Use a content delivery network (CDN):** Use a CDN to serve static assets.
* **Monitor API performance:** Monitor API performance to identify and address 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.
* **Use a CI/CD tool like Jenkins, GitLab CI, or CircleCI:** Use a CI/CD tool to manage your CI/CD pipeline.
* **Automate testing:** Automate unit, integration, and end-to-end tests as part of the CI/CD pipeline.
* **Automate code formatting and linting:** Automate code formatting and linting as part of the CI/CD pipeline.
* **Automate deployment:** Automate deployment to production as part of the CI/CD pipeline.
By following these best practices, you can create robust, scalable, maintainable, and secure REST APIs using the Django REST Framework.
+274
View File
@@ -0,0 +1,274 @@
---
description: This rule outlines best practices for using Drizzle ORM in TypeScript and JavaScript projects. It covers code organization, performance, security, testing, and common pitfalls.
globs: **/*.ts,**/*.tsx,**/*.js,**/*.jsx
---
# Drizzle ORM Best Practices and Coding Standards
This document provides a comprehensive guide to best practices for using Drizzle ORM in your TypeScript and JavaScript projects. It covers various aspects, including code organization, common patterns, performance considerations, security, testing, common pitfalls, and tooling.
## Library Information:
- Name: Drizzle ORM
- Tags: database, orm, typescript, javascript, sql
## 1. Code Organization and Structure
A well-organized project structure is crucial for maintainability and scalability. Here are some recommendations for organizing your Drizzle ORM projects:
### 1.1 Directory Structure
project-root/
├── src/
│ ├── db/
│ │ ├── schema.ts # Database schema definitions
│ │ ├── migrations/ # Migration files
│ │ ├── index.ts # Database connection and initialization
│ │ └── utils.ts # Utility functions for database operations
│ ├── models/ # Business logic models (if needed)
│ ├── services/ # Services interacting with the database
│ ├── utils/ # General utility functions
│ └── ...
├── drizzle.config.ts # Drizzle Kit configuration
├── package.json
├── tsconfig.json
└── ...
* **`src/db/schema.ts`**: This file contains your database schema definitions using Drizzle's table functions (e.g., `pgTable`, `mysqlTable`, `sqliteTable`).
* **`src/db/migrations/`**: This directory stores your database migration files, generated by Drizzle Kit.
* **`src/db/index.ts`**: This file handles the database connection and exports the Drizzle database instance.
* **`src/models/`**: (Optional) If you need to represent database entities with more complex business logic, create model classes or interfaces here.
* **`src/services/`**: This directory contains services that interact with the database, abstracting away the data access logic from your application's core.
### 1.2 File Naming Conventions
* Schema files: `schema.ts`
* Migration files: Use a timestamp-based naming convention (e.g., `0001_initial_schema.sql`). Drizzle Kit will typically handle this automatically.
* Service files: Use descriptive names based on the entity they manage (e.g., `userService.ts`, `productService.ts`).
* Utility files: `utils.ts` or more specific names like `dbUtils.ts`.
### 1.3 Module Organization
* Group related database operations into separate modules within the `src/db/` directory.
* Export the database instance and schema definitions from `src/db/index.ts`.
* Use ES module syntax (`import`/`export`) for clear dependency management.
### 1.4 Component Architecture (If Applicable)
If you are using Drizzle ORM in a frontend application with a component-based architecture (e.g., React, Vue, Angular), consider the following:
* Create reusable data access components or hooks that encapsulate Drizzle queries.
* Separate data fetching logic from UI rendering logic.
* Use state management libraries (e.g., Redux, Zustand, React Context) to manage the application's state and efficiently update components when data changes.
### 1.5 Code Splitting
* For large applications, use code splitting to reduce the initial bundle size.
* Consider lazy-loading database-related modules and components that are not immediately needed on initial page load.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Repository Pattern:** Create repository classes or functions to abstract data access logic. This promotes separation of concerns and makes your code more testable.
* **Unit of Work:** (If needed for complex transactions) Implement a Unit of Work pattern to manage multiple database operations within a single transaction.
### 2.2 Recommended Approaches for Common Tasks
* **Fetching Data:** Use Drizzle's `select` query builder for type-safe data retrieval. Leverage `where`, `orderBy`, `limit`, and `offset` clauses for efficient querying.
* **Inserting Data:** Use the `insert` query builder for inserting new records. Define TypeScript types for your data to ensure type safety.
* **Updating Data:** Use the `update` query builder for updating existing records. Use `where` clauses to target specific records for updates.
* **Deleting Data:** Use the `delete` query builder for deleting records. Use `where` clauses to prevent accidental data loss.
* **Migrations:** Use Drizzle Kit to manage database schema migrations. Create migration files for each schema change and apply them in a controlled manner.
### 2.3 Anti-patterns and Code Smells
* **Writing raw SQL directly in components:** Avoid embedding raw SQL queries directly within UI components or other parts of your application. Use service functions or repositories to abstract data access.
* **Ignoring type safety:** Take advantage of TypeScript's type system to define types for your database schema and data models. This will help catch errors at compile time and improve code maintainability.
* **Over-fetching data:** Avoid selecting unnecessary columns or related data when fetching records. This can lead to performance issues, especially for large tables.
* **Not using transactions:** Wrap multiple related database operations within a transaction to ensure data consistency. This is especially important when updating multiple tables.
* **Hardcoding database credentials:** Store database credentials securely using environment variables and avoid committing them to your codebase.
### 2.4 State Management
* Choose a state management solution that fits your application's complexity (e.g., Redux, Zustand, React Context).
* Use state management to store and manage data fetched from the database.
* Consider using caching strategies to reduce the number of database queries.
### 2.5 Error Handling
* Use try-catch blocks to handle potential database errors.
* Log errors appropriately, including relevant information such as the query and parameters.
* Provide informative error messages to the user (if applicable).
* Consider implementing a centralized error handling mechanism.
## 3. Performance Considerations
Optimizing performance is crucial for ensuring a smooth user experience. Here are some performance considerations when using Drizzle ORM:
### 3.1 Optimization Techniques
* **Indexing:** Create indexes on frequently queried columns to improve query performance.
* **Query optimization:** Analyze your queries and optimize them for performance. Use `EXPLAIN` to understand how the database is executing your queries.
* **Connection pooling:** Use a connection pool to reuse database connections and reduce connection overhead.
* **Caching:** Implement caching strategies to reduce the number of database queries. Consider using server-side caching (e.g., Redis, Memcached) or client-side caching (e.g., browser cache).
* **Prepared statements:** Use prepared statements to precompile SQL queries and improve performance for frequently executed queries.
* **Batch operations:** Use batch operations to insert, update, or delete multiple records in a single query.
### 3.2 Memory Management
* Be mindful of the amount of data you are fetching from the database. Avoid fetching unnecessary columns or related data.
* Use streaming or pagination to process large datasets in smaller chunks.
* Release database connections when they are no longer needed.
### 3.3 Rendering Optimization (If Applicable)
* Optimize UI rendering performance by using techniques such as virtualization, memoization, and lazy loading.
* Avoid performing expensive database queries in the UI rendering thread.
### 3.4 Bundle Size Optimization
* Use tree shaking to remove unused code from your bundle.
* Minify your code to reduce the bundle size.
* Compress your bundle using gzip or Brotli.
### 3.5 Lazy Loading
* Lazy load database-related modules and components that are not immediately needed on initial page load.
## 4. Security Best Practices
Securing your application is paramount. Here are some security best practices to follow when using Drizzle ORM:
### 4.1 Common Vulnerabilities and Prevention
* **SQL Injection:** Drizzle helps prevent SQL injection by using parameterized queries. Always use the built-in query builders and avoid concatenating user input directly into SQL strings. The `sql` template literal function also provides protection when used correctly.
* **Cross-Site Scripting (XSS):** Sanitize user input before displaying it in the UI to prevent XSS attacks. This is more of a frontend concern, but important to remember when displaying data from the database.
* **Cross-Site Request Forgery (CSRF):** Protect your application against CSRF attacks by implementing CSRF tokens.
* **Unauthorized Access:** Implement proper authentication and authorization mechanisms to restrict access to sensitive data.
### 4.2 Input Validation
* Validate all user input before using it in database queries. Use server-side validation to ensure data integrity.
* Use TypeScript types to enforce data types and constraints.
### 4.3 Authentication and Authorization
* Use a robust authentication system to verify user identities.
* Implement authorization rules to control access to resources based on user roles or permissions.
* Consider using a well-established authentication and authorization library (e.g., Passport.js, Auth0, Firebase Authentication).
### 4.4 Data Protection
* Encrypt sensitive data at rest and in transit.
* Use HTTPS to secure communication between the client and server.
* Regularly back up your database to prevent data loss.
### 4.5 Secure API Communication
* Use secure API endpoints (HTTPS).
* Implement rate limiting to prevent abuse.
* Validate API requests and responses.
## 5. Testing Approaches
Thorough testing is essential for ensuring the quality and reliability of your application. Here are some testing approaches for Drizzle ORM projects:
### 5.1 Unit Testing
* Write unit tests for your services, repositories, and utility functions.
* Mock the database connection to isolate your code and improve test performance.
* Use a testing framework such as Jest or Mocha.
### 5.2 Integration Testing
* Write integration tests to verify the interaction between your application and the database.
* Use a test database or in-memory database (e.g., SQLite) for integration tests.
* Ensure that your integration tests cover the most important database operations.
### 5.3 End-to-End Testing
* Write end-to-end tests to verify the complete application flow, including the UI and the database.
* Use a testing framework such as Cypress or Puppeteer.
### 5.4 Test Organization
* Organize your tests into separate directories based on the component or module they are testing.
* Use descriptive names for your test files and test cases.
### 5.5 Mocking and Stubbing
* Use mocking and stubbing techniques to isolate your code and control the behavior of dependencies during testing.
* Consider using a mocking library such as Jest's built-in mocking capabilities.
* Mock the Drizzle database instance to simulate database operations.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Incorrectly defining schema types:** Pay close attention to defining the correct TypeScript types for your database schema columns. Mismatched types can lead to runtime errors.
* **Forgetting to migrate the database:** After making schema changes, remember to generate and apply migrations using Drizzle Kit. Failing to do so will result in inconsistencies between your application and the database.
* **Not handling errors properly:** Implement proper error handling to catch potential database errors and prevent application crashes.
* **Ignoring performance considerations:** Be mindful of query performance and optimize your queries as needed. Avoid fetching unnecessary data or performing expensive operations.
### 6.2 Edge Cases
* **Concurrency issues:** Be aware of potential concurrency issues when multiple users or processes are accessing the database simultaneously. Use transactions to ensure data consistency.
* **Large datasets:** Handle large datasets efficiently by using pagination, streaming, or other optimization techniques.
* **Database-specific features:** Be aware of database-specific features and limitations. Drizzle aims to provide a consistent API across different databases, but some features may not be available or may behave differently.
### 6.3 Version-Specific Issues
* Refer to the Drizzle ORM documentation and release notes for information on version-specific issues and breaking changes.
* Keep your Drizzle ORM dependencies up to date to benefit from bug fixes and performance improvements.
### 6.4 Compatibility Concerns
* Ensure that your Drizzle ORM version is compatible with your database driver and other dependencies.
* Test your application thoroughly after upgrading Drizzle ORM or other dependencies.
### 6.5 Debugging Strategies
* Use logging to track the execution of your queries and identify potential issues.
* Use a database client to inspect the database schema and data.
* Use the `EXPLAIN` statement to analyze query performance.
* Use a debugger to step through your code and inspect variables.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **IDE:** Use a modern IDE such as Visual Studio Code, WebStorm, or Sublime Text.
* **TypeScript Compiler:** Use the TypeScript compiler to transpile your TypeScript code to JavaScript.
* **Drizzle Kit:** Use Drizzle Kit to manage database schema migrations.
* **Database Client:** Use a database client such as Dbeaver, TablePlus, or SQL Developer to inspect your database.
* **ESLint:** Use ESLint to lint your code and enforce coding standards.
* **Prettier:** Use Prettier to format your code and ensure consistency.
### 7.2 Build Configuration
* Use a build tool such as Webpack, Parcel, or Rollup to bundle your code.
* Configure your build tool to perform tree shaking, minification, and compression.
* Use environment variables to configure your application for different environments.
### 7.3 Linting and Formatting
* Use ESLint to lint your code and enforce coding standards.
* Use Prettier to format your code and ensure consistency.
* Configure your IDE to automatically run ESLint and Prettier on save.
### 7.4 Deployment
* Choose a deployment platform that fits your application's requirements (e.g., Vercel, Netlify, AWS, Heroku).
* Configure your deployment environment to use environment variables for database credentials and other sensitive information.
* Automate your deployment process using CI/CD.
* Ensure that your database is properly configured and secured in your deployment environment.
### 7.5 CI/CD Integration
* Use a CI/CD platform such as Jenkins, Travis CI, or GitHub Actions to automate your build, test, and deployment process.
* Configure your CI/CD pipeline to run your unit tests, integration tests, and end-to-end tests.
* Use a linting tool such as ESLint to enforce coding standards and prevent errors.
* Deploy your application automatically to your deployment environment after successful builds and tests.
By following these best practices, you can build robust, scalable, and secure applications using Drizzle ORM.
+272
View File
@@ -0,0 +1,272 @@
---
description: This rule provides comprehensive best practices for developing with Elasticsearch, covering code organization, performance, security, testing, and common pitfalls, ensuring efficient and maintainable Elasticsearch applications. These practices apply broadly across languages interacting with Elasticsearch.
globs: **/*.{py,js,java,go,ts,kt,scala,rb,php,rs,c,cpp,cs,swift,m,h}
---
- # Elasticsearch Library Best Practices
This document provides comprehensive guidelines for developing with Elasticsearch, covering code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling.
- ## 1. Code Organization and Structure
- ### Directory Structure
- **Project Root:** Contains the main application code, configuration files, and build scripts.
- **src/:** Source code for your application. This directory is further subdivided:
- **config/:** Configuration files for Elasticsearch connections and settings.
- **mappings/:** JSON files defining Elasticsearch index mappings.
- **queries/:** Stored Elasticsearch queries for reuse.
- **models/:** Data models representing Elasticsearch documents.
- **utils/:** Utility functions for interacting with Elasticsearch.
- **scripts/:** Scripts for indexing, reindexing, and data migration.
- **tests/:** Unit and integration tests.
- **docs/:** Documentation for your application and Elasticsearch integration.
- **data/:** Sample data for testing and development.
- **.cursor/:** Stores cursor rule files if using Cursor IDE.
- ### File Naming Conventions
- **Configuration Files:** `elasticsearch.config.json`, `index.mapping.json`
- **Data Models:** `user.model.js`, `product.model.py`
- **Utility Functions:** `elasticsearch.utils.go`, `query_builder.rb`
- **Test Files:** `user.model.test.js`, `elasticsearch.utils_test.py`
- ### Module Organization
- Divide your code into logical modules, such as:
- **elasticsearch_client:** Handles the Elasticsearch client initialization and connection management.
- **index_management:** Manages index creation, deletion, and mapping updates.
- **query_builder:** Provides functions for building complex Elasticsearch queries.
- **data_ingestion:** Handles data ingestion and indexing processes.
- **search_service:** Implements the search logic and result processing.
- ### Component Architecture
- Use a layered architecture to separate concerns:
- **Presentation Layer:** Handles user input and displays search results.
- **Application Layer:** Orchestrates the interaction between the presentation and domain layers.
- **Domain Layer:** Contains the core business logic and data models.
- **Infrastructure Layer:** Provides access to external services like Elasticsearch.
- ### Code Splitting
- If your application handles large datasets or complex queries, consider code splitting:
- Split large mapping files into smaller, manageable chunks. Use `@file` directives if using Cursor to include them in the primary rule file.
- Implement lazy loading for infrequently used features.
- Optimize queries to minimize the amount of data transferred.
- ## 2. Common Patterns and Anti-patterns
- ### Design Patterns
- **Repository Pattern:** Abstract data access logic behind a repository interface.
- **Factory Pattern:** Create Elasticsearch clients and query builders using factories.
- **Builder Pattern:** Construct complex Elasticsearch queries step-by-step.
- **Observer Pattern:** Notify subscribers of index updates or data changes.
- ### Recommended Approaches
- **Bulk Indexing:** Use the bulk API for efficient indexing of large datasets.
- **Scroll API:** Use the scroll API for retrieving large result sets.
- **Asynchronous Operations:** Use asynchronous operations for non-blocking Elasticsearch interactions.
- ### Anti-patterns and Code Smells
- **Over-sharding:** Avoid creating too many shards, which can lead to performance issues.
- **Ignoring Errors:** Always handle Elasticsearch errors and log them appropriately.
- **Hardcoding Queries:** Avoid hardcoding queries directly in your code. Use query builders or stored queries.
- **Excessive Data Retrieval:** Only retrieve the fields you need from Elasticsearch.
- ### State Management
- Keep track of the index state (e.g., creation date, mapping version).
- Use version control for index mappings and queries.
- Implement rollback mechanisms for data migration.
- ### Error Handling
- Use try-except blocks to catch Elasticsearch exceptions.
- Log errors with sufficient context for debugging.
- Implement retry mechanisms for transient errors.
- Implement circuit breaker pattern to prevent cascading failures.
- ## 3. Performance Considerations
- ### Optimization Techniques
- **Mapping Optimization:**
- Use the appropriate data types for your fields.
- Use `keyword` type for fields that are used for filtering or sorting.
- Use `text` type for fields that are used for full-text search.
- Disable indexing for fields that are only used for retrieval (`"index": false`).
- Consider using `multi-fields` for different types of searches (e.g., keyword and text).
- **Query Optimization:**
- Use the `filter` context for queries that do not affect scoring.
- Use the `bool` query to combine multiple conditions effectively.
- Use the `match` query for full-text searches.
- Utilize caching mechanisms for frequently executed queries.
- **Indexing Optimization:**
- Use the bulk API for indexing large amounts of data.
- Increase the refresh interval for less frequent updates.
- Optimize shard sizes based on your data volume.
- Avoid over-sharding.
- ### Memory Management
- Monitor the Elasticsearch heap usage.
- Configure the JVM heap size appropriately.
- Avoid memory leaks in your application code.
- ### Rendering Optimization (If Applicable)
- Implement pagination for large result sets.
- Use virtualization techniques for rendering large lists.
- Optimize the rendering performance of your UI components.
- ### Bundle Size Optimization
- Minimize the size of your application's bundle.
- Use code splitting to load only the necessary modules.
- Optimize your dependencies and remove unused code.
- ### Lazy Loading
- Implement lazy loading for infrequently used features.
- Load data on demand as needed.
- Use asynchronous operations for loading data.
- ## 4. Security Best Practices
- ### Common Vulnerabilities
- **Injection Attacks:** Prevent injection attacks by validating user input and sanitizing data.
- **Unauthorized Access:** Implement proper authentication and authorization mechanisms.
- **Data Breaches:** Protect sensitive data by encrypting it at rest and in transit.
- ### Input Validation
- Validate user input to prevent injection attacks and data corruption.
- Sanitize data before indexing it into Elasticsearch.
- Use regular expressions or validation libraries to enforce data constraints.
- ### Authentication and Authorization
- Use Elasticsearch's built-in security features or a third-party plugin for authentication.
- Implement role-based access control (RBAC) to restrict access to sensitive data.
- Use API keys or tokens for secure API communication.
- ### Data Protection
- Encrypt sensitive data at rest using Elasticsearch's encryption features.
- Encrypt data in transit using HTTPS.
- Mask or redact sensitive data in logs and error messages.
- ### Secure API Communication
- Use HTTPS for all API communication with Elasticsearch.
- Validate the server certificate to prevent man-in-the-middle attacks.
- Use secure protocols like TLS 1.3 or higher.
- ## 5. Testing Approaches
- ### Unit Testing
- Unit test individual components in isolation.
- Mock Elasticsearch dependencies to control test behavior.
- Use assertion libraries to verify the expected results.
- ### Integration Testing
- Integrate test different components to verify their interaction.
- Use a test Elasticsearch instance for integration tests.
- Verify that data is correctly indexed and retrieved.
- ### End-to-End Testing
- Test the entire application from end to end.
- Use automated testing frameworks like Selenium or Cypress.
- Verify that the application functions correctly in a real-world environment.
- ### Test Organization
- Organize your tests into logical categories.
- Use descriptive names for your test cases.
- Keep your tests concise and focused.
- ### Mocking and Stubbing
- Use mocking libraries to create mock Elasticsearch clients and responses.
- Use stubbing to simulate different Elasticsearch scenarios.
- Verify that your code interacts with Elasticsearch as expected.
- ## 6. Common Pitfalls and Gotchas
- ### Frequent Mistakes
- Not understanding Elasticsearch's query DSL.
- Not configuring the Elasticsearch cluster properly.
- Not monitoring Elasticsearch performance.
- ### Edge Cases
- Handling large result sets.
- Dealing with complex data types.
- Managing index mappings and updates.
- ### Version-Specific Issues
- Be aware of breaking changes between Elasticsearch versions.
- Test your application thoroughly when upgrading Elasticsearch.
- Consult the Elasticsearch documentation for version-specific information.
- ### Compatibility Concerns
- Ensure compatibility between Elasticsearch and your application's programming language.
- Use compatible versions of Elasticsearch client libraries.
- ### Debugging Strategies
- Use Elasticsearch's logging features to troubleshoot issues.
- Use the Elasticsearch API to inspect the cluster state.
- Use debugging tools to step through your code.
- ## 7. Tooling and Environment
- ### Recommended Tools
- **Elasticsearch:** The core search and analytics engine.
- **Kibana:** A visualization and exploration tool for Elasticsearch data.
- **Logstash:** A data processing pipeline for ingesting data into Elasticsearch.
- **Elasticsearch Head/Cerebro:** Cluster management and monitoring tools.
- ### Build Configuration
- Use a build tool like Maven, Gradle, or npm to manage dependencies.
- Configure your build to package your application and its dependencies.
- ### Linting and Formatting
- Use a linter like ESLint or Pylint to enforce code style guidelines.
- Use a formatter like Prettier or Black to automatically format your code.
- ### Deployment
- Deploy your Elasticsearch cluster to a cloud platform like AWS, Azure, or GCP.
- Use containerization technologies like Docker and Kubernetes.
- Automate your deployment process using tools like Ansible or Terraform.
- ### CI/CD
- Integrate your application with a CI/CD pipeline.
- Automate testing, building, and deployment processes.
- Use tools like Jenkins, GitLab CI, or CircleCI.
- ## Additional Best Practices
- **Monitoring:** Implement comprehensive monitoring of Elasticsearch cluster health, resource utilization, and query performance using tools like Prometheus, Grafana, and Elasticsearch's built-in monitoring features.
- **Logging:** Configure detailed logging to capture important events, errors, and performance metrics for troubleshooting and analysis. Use structured logging formats like JSON for easier parsing and analysis.
- **Backup and Recovery:** Implement regular backups of Elasticsearch data and configurations to prevent data loss. Test the recovery process to ensure it works as expected.
- **Capacity Planning:** Regularly assess the capacity requirements of your Elasticsearch cluster based on data growth, query load, and indexing performance. Scale your cluster accordingly to maintain optimal performance.
- **Security Auditing:** Conduct regular security audits to identify and address potential vulnerabilities. Review access controls, network configurations, and data encryption settings.
- **Stay Updated:** Keep your Elasticsearch cluster and client libraries up to date with the latest security patches and bug fixes. Follow the Elasticsearch community for updates and best practices.
By following these best practices, you can build robust, scalable, and secure applications with Elasticsearch.
+168
View File
@@ -0,0 +1,168 @@
---
description: This rule outlines best practices for developing and maintaining applications within the ELK (Elasticsearch, Logstash, Kibana) stack, including coding standards, configuration, performance, security, and testing.
globs: **/*.conf, **/*.yml, **/*.json, **/*.log
---
## ELK Stack Best Practices
This document provides comprehensive best practices for working with the ELK (Elasticsearch, Logstash, Kibana) stack, covering various aspects from code organization to security and testing.
### 1. Code Organization and Structure
- **Directory Structure Best Practices:**
- Organize configurations (Logstash pipelines, Kibana dashboards) in separate directories, such as `logstash/pipelines`, `kibana/dashboards`, and `elasticsearch/config`.
- Maintain a dedicated directory for custom scripts or plugins used within the ELK stack.
- Use a version control-friendly structure, where each configuration file is self-contained and easily traceable.
- **File Naming Conventions:**
- Use descriptive and consistent naming conventions for configuration files, such as `application-name-pipeline.conf` for Logstash pipelines or `dashboard-name.json` for Kibana dashboards.
- Employ prefixes or suffixes to denote the purpose or environment of a configuration (e.g., `dev-`, `prod-`).
- **Module Organization:**
- If using custom scripts or plugins, organize them into modules with clear interfaces and documentation.
- For Logstash pipelines, consider breaking down complex configurations into smaller, reusable modules using the `include` directive.
- **Component Architecture:**
- Design a modular architecture where each component (e.g., data ingestion, processing, visualization) is loosely coupled and can be independently scaled or updated.
- Follow a layered approach, separating concerns such as data collection, transformation, storage, and presentation.
- **Code Splitting Strategies:**
- For Logstash pipelines, split configurations into smaller files based on functionality (e.g., input, filter, output) to improve readability and maintainability.
- Use conditional logic (e.g., `if/else` statements) within Logstash pipelines to handle different data sources or processing requirements.
### 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Pipeline Pattern:** Design data ingestion pipelines using Logstash or Beats to process and transform data before indexing it in Elasticsearch.
- **Dashboard Pattern:** Create reusable Kibana dashboards and visualizations to monitor key metrics and identify trends.
- **Alerting Pattern:** Implement alerting rules in Kibana or use external tools to trigger notifications based on specific events or thresholds.
- **Recommended Approaches:**
- Use structured logging formats (e.g., JSON) to simplify data parsing and analysis.
- Implement data enrichment techniques (e.g., GeoIP lookup, user agent parsing) to add context to log data.
- Use Index Lifecycle Management (ILM) to automate index rotation, deletion, and optimization.
- **Anti-patterns:**
- Avoid using overly complex Logstash pipelines that are difficult to understand and maintain.
- Do not store sensitive data (e.g., passwords, API keys) in plain text within configuration files.
- Avoid excessive use of wildcard queries in Elasticsearch, which can negatively impact performance.
- **State Management:**
- For Logstash pipelines, use persistent queues to ensure data durability and prevent data loss during outages.
- Utilize Elasticsearch's snapshot and restore API to back up and restore data in case of disaster.
- **Error Handling:**
- Implement error handling in Logstash pipelines to gracefully handle unexpected data formats or processing errors.
- Use dead-letter queues to capture failed events and allow for later reprocessing.
- Monitor the health of ELK stack components and set up alerts for critical errors.
### 3. Performance Considerations
- **Optimization Techniques:**
- Tune Elasticsearch settings such as shard allocation, refresh interval, and bulk indexing size to optimize indexing and search performance.
- Use appropriate data types and mappings in Elasticsearch to minimize storage space and improve query performance.
- Optimize Logstash pipelines by using efficient filters, reducing the number of operations, and avoiding unnecessary data transformations.
- **Memory Management:**
- Configure JVM heap size for Elasticsearch and Logstash based on available memory and data volume.
- Monitor memory usage of ELK stack components and adjust settings as needed to prevent memory leaks or out-of-memory errors.
- **Bundle Size Optimization:**
- N/A - ELK stack does not use bundles in the traditional web development sense, but optimize configurations and data structures.
- **Lazy Loading Strategies:**
- N/A - ELK stack components load configurations on startup, but optimize data ingestion and indexing to improve overall performance.
### 4. Security Best Practices
- **Common Vulnerabilities:**
- Protect against Elasticsearch injection attacks by validating user inputs and sanitizing data before indexing it.
- Prevent unauthorized access to ELK stack components by enabling authentication and authorization.
- Secure communication between ELK stack components by enabling TLS encryption.
- **Input Validation:**
- Validate data ingested into Logstash pipelines to prevent malicious or malformed data from being indexed in Elasticsearch.
- Sanitize user inputs in Kibana dashboards to prevent cross-site scripting (XSS) attacks.
- **Authentication and Authorization:**
- Enable authentication in Elasticsearch and Kibana to restrict access to authorized users only.
- Use role-based access control (RBAC) to grant different levels of permissions to different users or groups.
- **Data Protection:**
- Encrypt sensitive data at rest in Elasticsearch using encryption at rest features or external encryption tools.
- Implement data masking or anonymization techniques to protect sensitive data in Kibana dashboards.
- **Secure API Communication:**
- Use HTTPS for all API communication with ELK stack components.
- Implement API rate limiting to prevent denial-of-service (DoS) attacks.
### 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for custom scripts or plugins used within the ELK stack.
- Mock external dependencies to isolate components during testing.
- **Integration Testing:**
- Test the integration between ELK stack components by simulating data ingestion, processing, and visualization scenarios.
- Verify that data is correctly indexed in Elasticsearch and displayed in Kibana dashboards.
- **End-to-End Testing:**
- Perform end-to-end tests to ensure that the entire ELK stack is functioning correctly and meeting performance requirements.
- Simulate real-world scenarios to validate data flow and system behavior.
- **Test Organization:**
- Organize tests into separate directories based on component or functionality.
- Use a consistent naming convention for test files and test cases.
- **Mocking and Stubbing:**
- Use mocking frameworks to create mock objects for external dependencies during unit testing.
- Stub out API calls or database queries to isolate components during integration testing.
### 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- Not configuring sufficient resources (CPU, memory, disk space) for ELK stack components.
- Over-indexing data and creating unnecessarily large indices.
- Using inefficient queries or aggregations in Elasticsearch.
- **Edge Cases:**
- Handling large volumes of data or high query loads.
- Dealing with complex data formats or unstructured log data.
- Recovering from node failures or data corruption.
- **Version-Specific Issues:**
- Incompatibilities between different versions of ELK stack components.
- Deprecated features or APIs in newer versions of Elasticsearch, Logstash, and Kibana.
- **Compatibility Concerns:**
- Ensuring compatibility between ELK stack components and other technologies in your environment.
- Addressing dependencies and conflicts between different plugins or libraries.
- **Debugging Strategies:**
- Use Elasticsearch's explain API to analyze query performance and identify bottlenecks.
- Enable debug logging in Logstash pipelines to troubleshoot data processing issues.
- Monitor system logs and metrics to identify resource constraints or errors.
### 7. Tooling and Environment
- **Recommended Development Tools:**
- IDEs with support for YAML, JSON, and Groovy.
- Command-line tools for interacting with Elasticsearch, Logstash, and Kibana.
- Monitoring tools for tracking the health and performance of ELK stack components.
- **Build Configuration:**
- Use configuration management tools (e.g., Ansible, Chef) to automate the deployment and configuration of ELK stack components.
- Store configuration files in version control to track changes and facilitate collaboration.
- **Linting and Formatting:**
- Use linters and formatters to enforce coding standards and improve code quality.
- Configure IDEs to automatically format code on save.
- **Deployment Best Practices:**
- Deploy ELK stack components on separate servers or virtual machines to isolate workloads and improve scalability.
- Use a load balancer to distribute traffic across multiple Elasticsearch nodes.
- **CI/CD Integration:**
- Integrate ELK stack deployments into your CI/CD pipeline to automate testing and deployment processes.
- Use infrastructure-as-code (IaC) tools to provision and manage ELK stack environments.
By following these best practices, you can build and maintain a robust, scalable, and secure ELK stack environment that meets your logging and analytics needs.
+220
View File
@@ -0,0 +1,220 @@
---
description: Comprehensive guide to Emacs Lisp coding standards, best practices, and common pitfalls. Focuses on maintainability, readability, and performance for building robust Emacs extensions.
globs: **/*.el
---
- ## Code Organization and Structure
- ### Directory Structure
- Organize your Emacs Lisp projects into well-defined directories to improve maintainability and discoverability.
- `/`: Project root. Contains the main `.el` file (e.g., `my-package.el`) and a README.
- `/src`: Source code. Contains the core Emacs Lisp files.
- `/lib`: Libraries. External libraries or dependencies used by your project.
- `/test`: Tests. Unit and integration tests.
- `/doc`: Documentation. User documentation and API references. Consider using `org-mode` for easy export to various formats.
- `/.cursor`: Project rules directory for Cursor AI tool.
- ### File Naming Conventions
- Use lowercase letters and hyphens for file names (e.g., `my-package.el`).
- Each file should generally correspond to a single module or component.
- Test files should be named following a consistent pattern, such as `my-module-test.el` or `my-module.test.el`.
- Always end Emacs Lisp files with the `.el` extension.
- ### Module Organization
- Encapsulate related functions and variables within modules.
- Use `provide` to declare a module and `require` to load dependencies.
- Avoid creating overly large files; break them down into smaller, more manageable modules.
- Example:
lisp
(provide 'my-module)
(require 'another-module)
(defun my-module-function (arg)
;; ...
)
- ### Component Architecture
- Design your applications using a component-based architecture to promote code reuse and modularity.
- Each component should have a well-defined interface and a clear responsibility.
- Favor composition over inheritance.
- Example: Separate UI elements from business logic.
- ### Code Splitting
- Use `autoload` to defer loading of less frequently used functions, improving startup time.
- Break up large modules into smaller files and load them on demand.
- Ensure that your package provides a mechanism for disabling or uninstalling components to avoid conflicts.
- ## Common Patterns and Anti-patterns
- ### Design Patterns
- **Command Pattern:** Encapsulate actions as objects, enabling parameterization, queuing, and logging.
- **Observer Pattern:** Define a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically (e.g., using hooks).
- **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable (e.g., customizable behavior through user options).
- ### Recommended Approaches for Common Tasks
- **Configuration Management:** Use `defcustom` for user-configurable options. Provide default values and documentation.
- **UI Creation:** Use `widget` for creating interactive UI elements.
- **Asynchronous Operations:** Leverage `timer` and `process` for non-blocking tasks.
- **Data Storage:** Consider using SQLite via `sqlite.el` for persistent data storage.
- ### Anti-patterns and Code Smells
- **Global State Mutation:** Minimize use of global variables. If necessary, use `defvar` with caution.
- **Deeply Nested Conditionals:** Refactor complex logic into smaller, more readable functions.
- **Magic Numbers/Strings:** Define constants for frequently used values.
- **Duplicated Code:** Extract common logic into reusable functions or macros.
- **Ignoring Errors:** Always handle errors and exceptions gracefully.
- ### State Management
- Prefer lexical scoping with `lexical-binding: t` to create closures and manage state within functions.
- Use `cl-letf` to temporarily redefine functions for testing or customization.
- Utilize property lists or hash tables to associate state with buffers or other objects.
- ### Error Handling
- Use `condition-case` to handle exceptions and prevent crashes.
- Provide informative error messages to users.
- Log errors to a file or the `*Messages*` buffer for debugging.
- Always clean up resources (e.g., timers, processes) in the `finally` clause of `condition-case`.
- Example:
lisp
(condition-case err
(progn
;; Code that might raise an error
(do-something))
(error
(message "An error occurred: %s" err))
(finally
;; Clean up resources
(cleanup)))
- ## Performance Considerations
- ### Optimization Techniques
- **Profiling:** Use `profiler.el` or `elp.el` to identify performance bottlenecks.
- **Byte Compilation:** Always byte-compile your Emacs Lisp code using `byte-compile-file`.
- **Caching:** Cache frequently accessed data to reduce computation time.
- **Lazy Loading:** Use `autoload` for functions that are not immediately needed.
- **Tail Recursion:** Convert recursive functions to tail-recursive form to avoid stack overflow errors.
- **StringBuilder:** Utilize `insert` for building large strings instead of repeated concatenation.
- ### Memory Management
- Minimize the creation of temporary objects.
- Reuse existing data structures when possible.
- Be mindful of garbage collection overhead; avoid creating excessive garbage.
- Use weak references where possible, with libraries such as `weak-ref` to avoid memory leaks.
- ### Rendering Optimization
- Minimize the number of buffer updates.
- Use overlays efficiently to avoid performance degradation.
- Batch updates when possible.
- ### Bundle Size Optimization
- Remove unnecessary dependencies.
- Use code minification tools to reduce the size of your Emacs Lisp files.
- Compress images and other assets.
- ### Lazy Loading
- Use `autoload` for functions and libraries that are not immediately required.
- Load dependencies on demand rather than at startup.
- Provide hooks for users to customize which features are loaded.
- ## Security Best Practices
- ### Common Vulnerabilities
- **Code Injection:** Prevent execution of untrusted code.
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent malicious scripts from being injected into UI elements.
- **Denial-of-Service (DoS):** Limit resource consumption to prevent attacks that overwhelm the system.
- **Path Traversal:** Validate file paths to prevent access to unauthorized files.
- ### Input Validation
- Sanitize all user input to prevent code injection and XSS attacks.
- Validate file paths to prevent path traversal vulnerabilities.
- Use regular expressions to enforce input formats.
- ### Authentication and Authorization
- Use secure authentication mechanisms such as OAuth or API keys.
- Implement authorization checks to ensure that users only have access to resources they are authorized to access.
- Store credentials securely using the Emacs password manager or a dedicated secrets store.
- ### Data Protection
- Encrypt sensitive data at rest and in transit.
- Use secure communication protocols such as HTTPS.
- Protect against data breaches by implementing appropriate access controls.
- ### Secure API Communication
- Use HTTPS for all API communication.
- Validate API responses to prevent data injection attacks.
- Implement rate limiting to prevent abuse.
- ## Testing Approaches
- ### Unit Testing
- Use ERT or Buttercup to write unit tests for your Emacs Lisp code.
- Test individual functions and components in isolation.
- Mock external dependencies to create a predictable testing environment.
- ### Integration Testing
- Test the interaction between different components of your Emacs Lisp application.
- Verify that data flows correctly between components.
- Ensure that your application integrates properly with Emacs itself.
- ### End-to-end Testing
- Use Director or similar tools to automate end-to-end tests.
- Simulate user interactions and verify that the application behaves as expected.
- Test the entire application from the user's perspective.
- ### Test Organization
- Organize your tests into separate files or directories.
- Use descriptive names for your test cases.
- Group related tests together.
- Provide a clear and concise test report.
- ### Mocking and Stubbing
- Use `cl-letf` or similar techniques to mock external dependencies.
- Create stubs for functions that are difficult or impossible to test directly.
- Verify that mocked functions are called with the correct arguments.
- ## Common Pitfalls and Gotchas
- ### Frequent Mistakes
- Forgetting to byte-compile Emacs Lisp code.
- Using global variables excessively.
- Ignoring error conditions.
- Writing overly complex functions.
- Failing to document code properly.
- Not using lexical binding.
- ### Edge Cases
- Handling international characters correctly.
- Dealing with different Emacs versions and platforms.
- Managing asynchronous operations and timers.
- Ensuring compatibility with other packages.
- Testing in various Emacs configurations (e.g., `-Q` for no init file).
- ### Version-Specific Issues
- Be aware of API changes between Emacs versions.
- Use conditional compilation to support multiple versions of Emacs.
- Test your code on different Emacs versions to ensure compatibility.
- ### Compatibility Concerns
- Avoid using deprecated functions and features.
- Test your code with different Emacs configurations to identify compatibility issues.
- Provide a mechanism for users to disable or uninstall your package if necessary.
- ### Debugging Strategies
- Use `edebug` to step through your code and inspect variables.
- Print debugging messages to the `*Messages*` buffer.
- Use `trace` to monitor function calls.
- Enable `debug-on-error` to catch exceptions.
- Check the Emacs error log for clues.
- ## Tooling and Environment
- ### Recommended Development Tools
- **Emacs:** The best tool for developing Emacs Lisp code.
- **ERT/Buttercup:** Testing frameworks.
- **Flycheck:** Real-time syntax checking and linting.
- **Edebug:** Interactive debugger.
- **Profiler.el/ELP:** Profiling tools.
- **Counsel/Ivy/Helm:** Completion frameworks for improved navigation.
- **Magit:** Git integration.
- ### Build Configuration
- Use a `Makefile` or similar build tool to automate common tasks such as byte-compilation, testing, and documentation generation.
- Define dependencies explicitly in your build configuration.
- Use version control to track changes to your build configuration.
- ### Linting and Formatting
- Use `flycheck` with `package-lint` and `elsa` for static code analysis.
- Enforce consistent code formatting using `aggressive-indent-mode` or similar tools.
- Configure your editor to automatically format code on save.
- ### Deployment
- Package your Emacs Lisp code into a `.el` file.
- Distribute your package via MELPA or a similar repository.
- Provide clear instructions on how to install and configure your package.
- ### CI/CD Integration
- Use GitHub Actions, Travis CI, or similar tools to automate testing and deployment.
- Run tests on every commit to ensure code quality.
- Automatically deploy your package to MELPA on release.
- ## Best Practices Summary
- Always use lexical binding: `;; -*- lexical-binding: t; -*-`.
- Prefix all global symbols with a unique project prefix to avoid namespace collisions.
- Write clear and concise documentation for all functions and variables using docstrings.
- Use `defcustom` for user-configurable options.
- Handle errors gracefully using `condition-case`.
- Byte-compile your Emacs Lisp code before deploying.
- Write unit tests for your code using ERT or Buttercup.
- Follow the Emacs Lisp Style Guide.
- Leverage the power of Emacs' interactive development environment for real-time feedback.
- @file https://raw.githubusercontent.com/bbatsov/emacs-lisp-style-guide/master/emacs-lisp-style-guide.md
- @file https://raw.githubusercontent.com/emacs-tw/awesome-elisp/master/README.md
+282
View File
@@ -0,0 +1,282 @@
---
description: This rule provides comprehensive best practices for using esbuild, focusing on performance, code organization, and security in build configurations and development workflows.
globs: **/*.{js,jsx,ts,tsx,css,json}
---
# esbuild Best Practices
This document outlines best practices for using esbuild as a JavaScript bundler. It covers various aspects, including code organization, performance optimization, security considerations, and common pitfalls to avoid.
## Library Information:
- Name: esbuild
- Tags: build-tool, javascript, bundler, performance
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
- **Source Code Directory (`src`):** House all your source code within a `src` directory. This promotes a clear separation of concerns between your source and build artifacts.
- **Configuration Files (`config` or `.config`):** Store esbuild configuration files (e.g., `esbuild.config.js`, `build.js`) in a dedicated `config` or `.config` directory. This makes it easy to identify and manage build-related settings.
- **Assets Directory (`assets`):** Place static assets like images, fonts, and other non-code files in an `assets` directory. This keeps them separate from your code and simplifies asset management.
- **Output Directory (`dist` or `build`):** esbuild commonly uses `dist` or `build` directories for storing the bundled output. Configure esbuild to output to one of these standard directories.
Example:
project-root/
├── src/
│ ├── components/
│ │ ├── MyComponent.tsx
│ │ └── ...
│ ├── utils/
│ │ ├── helpers.ts
│ │ └── ...
│ ├── index.tsx
│ └── ...
├── config/
│ ├── esbuild.config.js
│ └── ...
├── assets/
│ ├── images/
│ │ ├── logo.png
│ │ └── ...
│ ├── fonts/
│ │ ├── OpenSans.woff2
│ │ └── ...
├── dist/
│ ├── bundle.js
│ ├── styles.css
│ └── ...
├── package.json
├── tsconfig.json
└── ...
### 1.2. File Naming Conventions
- **Consistent Case:** Use either camelCase or PascalCase for JavaScript/TypeScript files, but consistently within your project. PascalCase is generally preferred for React components.
- **Descriptive Names:** Choose names that clearly reflect the file's purpose (e.g., `userProfile.tsx`, `apiClient.ts`).
- **Module-Specific Names:** If a file exports a single primary entity (e.g., a React component), use the same name for the file (e.g., `MyComponent.tsx` exports `MyComponent`).
- **CSS Modules:** Use `.module.css` or `.module.scss` for CSS Modules to scope styles locally to a component.
- **Configuration Files:** use `esbuild.config.js` or `build.js` for esbuild's configuration to make it easily identifiable.
### 1.3. Module Organization Best Practices
- **Feature-Based Modules:** Organize code by feature or functionality. Each feature should have its own directory containing all related code (components, utils, styles, etc.).
- **Reusable Modules:** Extract reusable code into separate modules (e.g., utility functions, API clients). Place these modules in a `utils` or `services` directory.
- **Avoid Circular Dependencies:** Circular dependencies can lead to unexpected behavior and bundling issues. Use tools like `madge` to detect and eliminate them.
- **Explicit Exports:** Be explicit about what you export from each module using `export` statements. This improves code clarity and tree-shaking.
### 1.4. Component Architecture Recommendations
- **Component-Based Architecture:** Adopt a component-based architecture (e.g., using React, Vue, or Svelte). This promotes code reusability, testability, and maintainability.
- **Atomic Design:** Consider using the Atomic Design methodology to structure components into atoms, molecules, organisms, templates, and pages.
- **Separation of Concerns:** Separate presentation logic (UI) from business logic (data fetching, state management). Use techniques like custom hooks to extract and reuse business logic.
### 1.5. Code Splitting Strategies
- **Dynamic Imports:** Use dynamic imports (`import()`) to load code on demand. This can significantly reduce the initial bundle size and improve page load performance. esbuild supports dynamic imports out of the box.
- **Route-Based Splitting:** Split your application into separate bundles for each route or page. This ensures that users only download the code they need for the current page.
- **Vendor Splitting:** Separate vendor libraries (e.g., React, Lodash) into a separate bundle. This allows browsers to cache vendor code separately from your application code.
- **Entry Points:** Create multiple entry points for distinct parts of your application (e.g. a landing page vs. an admin panel). esbuild will bundle these into separate output files.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Module Pattern:** Use the module pattern to encapsulate code and create private variables and functions.
- **Factory Pattern:** Use factory functions to create objects or components. This allows you to abstract the creation process and easily configure objects with different options.
- **Higher-Order Components (HOCs):** (React-specific) Use HOCs to add functionality to existing components.
- **Custom Hooks:** (React-specific) Use custom hooks to extract and reuse stateful logic.
### 2.2. Recommended Approaches for Common Tasks
- **Environment Variables:** Use environment variables to configure your application for different environments (development, staging, production). Access environment variables using `process.env`.
- **Path Aliases:** Configure path aliases to simplify imports. For example, you can alias `@components` to `src/components`. esbuild can be configured to understand these aliases.
- **CSS Preprocessing:** Integrate CSS preprocessors like Sass or Less using esbuild plugins. This allows you to use features like variables, mixins, and nesting in your CSS.
- **Minification and Tree Shaking:** Always enable minification and tree shaking for production builds to reduce bundle size. esbuild does this automatically with the `--minify` flag.
### 2.3. Anti-patterns and Code Smells
- **Global Variables:** Avoid using global variables as they can lead to naming conflicts and make it difficult to reason about your code.
- **Long Component Files:** Break down large component files into smaller, more manageable components.
- **Deeply Nested Components:** Avoid deeply nested component structures as they can make it difficult to understand the component hierarchy.
- **Over-reliance on `any`:** In TypeScript, avoid using `any` excessively as it defeats the purpose of type checking. Use more specific types whenever possible.
- **Direct DOM Manipulation (in React/Vue):** Avoid directly manipulating the DOM. Rely on the framework's virtual DOM for efficient updates.
### 2.4. State Management Best Practices
- **Component State:** Use component state (e.g., `useState` in React) for simple, localized state management.
- **Context API:** (React-specific) Use the Context API to share state between components without prop drilling.
- **Redux/Zustand/Recoil:** Use a state management library like Redux, Zustand, or Recoil for more complex application state.
- **Immutability:** Maintain immutability when updating state to avoid unexpected side effects and improve performance (especially with React).
### 2.5. Error Handling Patterns
- **Try-Catch Blocks:** Use `try-catch` blocks to handle synchronous errors.
- **Async/Await Error Handling:** Use `try-catch` blocks with `async/await` to handle asynchronous errors.
- **Error Boundaries:** (React-specific) Use error boundaries to catch errors that occur during rendering and prevent the entire application from crashing.
- **Centralized Error Logging:** Implement a centralized error logging system to track errors in your application.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Minification:** Use esbuild's built-in minification (`--minify`) to reduce the size of your JavaScript and CSS files.
- **Tree Shaking:** esbuild automatically performs tree shaking to remove unused code. Ensure that your code is written in a way that allows for efficient tree shaking (e.g., using ES modules with explicit exports).
- **Code Splitting:** Implement code splitting using dynamic imports and route-based splitting to reduce the initial bundle size.
- **Image Optimization:** Optimize images using tools like ImageOptim or TinyPNG to reduce their file size.
- **Caching:** Configure your server to cache static assets (JavaScript, CSS, images) to improve loading times for returning users.
- **Compression:** Enable gzip or Brotli compression on your server to reduce the size of files transmitted over the network.
- **Target Specific Environments:** Use the `target` option to specify the target JavaScript environment. This allows esbuild to generate code that is optimized for the specific environment.
- **Incremental Builds:** Utilize esbuild's `--watch` option and the context API for incremental builds, which significantly speeds up development by only recompiling changed files.
### 3.2. Memory Management
- **Avoid Memory Leaks:** Be mindful of memory leaks, especially in long-running applications. Remove event listeners and clear timers when they are no longer needed.
- **Use WeakRefs:** Consider using `WeakRef` in situations where you need to hold a reference to an object without preventing it from being garbage collected.
- **Profile Your Code:** Use browser developer tools to profile your code and identify memory bottlenecks.
### 3.3. Rendering Optimization (If Applicable)
- **Virtualization:** Use virtualization techniques (e.g., `react-window`, `react-virtualized`) to efficiently render large lists or tables.
- **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of expensive operations, such as event handlers or API calls.
- **Memoization:** Use memoization techniques (e.g., `React.memo`, `useMemo`) to cache the results of expensive calculations.
### 3.4. Bundle Size Optimization
- **Analyze Bundle Size:** Use tools like `esbuild-visualizer` or `webpack-bundle-analyzer` to analyze your bundle size and identify large dependencies.
- **Reduce Dependency Size:** Look for opportunities to reduce the size of your dependencies. Consider using smaller alternatives or only importing the specific parts of a library that you need.
- **Remove Dead Code:** Ensure that tree shaking is working effectively to remove unused code.
### 3.5. Lazy Loading Strategies
- **Lazy-Load Components:** Use dynamic imports to lazy-load components that are not immediately needed.
- **Lazy-Load Images:** Use lazy-loading for images that are below the fold to improve initial page load time.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by properly escaping user input and using a Content Security Policy (CSP).
- **Injection Attacks:** Prevent injection attacks (e.g., SQL injection, command injection) by validating and sanitizing user input.
- **Dependency Vulnerabilities:** Regularly audit your dependencies for known vulnerabilities using tools like `npm audit` or `yarn audit`. Update to the latest versions of your dependencies to patch vulnerabilities.
### 4.2. Input Validation
- **Validate All Input:** Validate all user input, both on the client-side and the server-side.
- **Use Strong Validation Rules:** Use strong validation rules to ensure that input is in the expected format and range.
- **Sanitize Input:** Sanitize input to remove potentially malicious characters or code.
### 4.3. Authentication and Authorization
- **Use Strong Authentication:** Use strong authentication methods, such as multi-factor authentication (MFA).
- **Implement Proper Authorization:** Implement proper authorization to ensure that users only have access to the resources they are authorized to access.
- **Securely Store Credentials:** Securely store user credentials using hashing and salting.
### 4.4. Data Protection
- **Encrypt Sensitive Data:** Encrypt sensitive data both in transit and at rest.
- **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server.
- **Protect API Keys:** Protect API keys and other sensitive configuration data by storing them in environment variables or a secure configuration store.
### 4.5. Secure API Communication
- **Use HTTPS:** Always use HTTPS for API communication.
- **Validate API Responses:** Validate API responses to ensure that they are in the expected format.
- **Implement Rate Limiting:** Implement rate limiting to prevent abuse of your API.
## 5. Testing Approaches
### 5.1. Unit Testing
- **Test Individual Components:** Unit tests should focus on testing individual components or modules in isolation.
- **Use Mocking and Stubbing:** Use mocking and stubbing to isolate the component under test from its dependencies.
- **Test Edge Cases:** Test edge cases and error conditions to ensure that the component handles them correctly.
### 5.2. Integration Testing
- **Test Interactions Between Components:** Integration tests should focus on testing the interactions between different components or modules.
- **Test API Integrations:** Test integrations with external APIs to ensure that they are working correctly.
### 5.3. End-to-End Testing
- **Test User Flows:** End-to-end tests should simulate user flows to ensure that the application is working correctly from the user's perspective.
- **Use a Testing Framework:** Use a testing framework like Cypress or Playwright to automate end-to-end tests.
### 5.4. Test Organization
- **Co-locate Tests with Code:** Store test files in the same directory as the code they are testing.
- **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what each test is verifying.
### 5.5. Mocking and Stubbing
- **Use a Mocking Library:** Use a mocking library like Jest or Sinon to create mocks and stubs.
- **Mock External Dependencies:** Mock external dependencies, such as API calls or database connections.
- **Stub Function Behavior:** Stub the behavior of functions to control their return values or side effects.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Forgetting to Bundle:** Failing to enable bundling can result in performance issues due to multiple HTTP requests.
- **Not Minifying:** Not minifying your code will result in larger file sizes and slower loading times.
- **Incorrect `tsconfig.json` Configuration:** Incorrectly configuring your `tsconfig.json` file can lead to compilation errors or unexpected behavior.
- **Not Handling Environment Variables:** Failing to properly handle environment variables can result in incorrect configuration in different environments.
- **Not Using Path Aliases:** Not using path aliases can make imports more verbose and difficult to maintain.
### 6.2. Edge Cases
- **Circular Dependencies:** Circular dependencies can lead to unexpected behavior and bundling issues.
- **Dynamic Imports with Variable Paths:** esbuild's support for dynamic imports with variable paths is limited. Be aware of the restrictions and consider alternative approaches if needed.
- **Plugin Compatibility:** Ensure that plugins are compatible with the version of esbuild you are using.
### 6.3. Version-Specific Issues
- **Breaking Changes:** Be aware of breaking changes in new versions of esbuild. Consult the release notes before upgrading.
### 6.4. Compatibility Concerns
- **Browser Compatibility:** Ensure that your code is compatible with the target browsers. Use Babel or other transpilers if necessary.
- **Node.js Compatibility:** If you are building a Node.js application, ensure that your code is compatible with the target version of Node.js.
### 6.5. Debugging Strategies
- **Source Maps:** Enable source maps to make it easier to debug your code in the browser developer tools.
- **Console Logging:** Use `console.log` statements to debug your code.
- **Debugger Statements:** Use `debugger` statements to pause execution at specific points in your code.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **VS Code:** A popular code editor with excellent support for JavaScript, TypeScript, and esbuild.
- **ESLint:** A linter for JavaScript and TypeScript that can help you identify and fix code quality issues.
- **Prettier:** A code formatter that can automatically format your code to a consistent style.
- **esbuild-visualizer:** A tool to visualize the contents of your esbuild bundle.
### 7.2. Build Configuration Best Practices
- **Use a Configuration File:** Store your esbuild configuration in a dedicated configuration file (e.g., `esbuild.config.js`).
- **Separate Configurations for Different Environments:** Create separate configurations for different environments (development, staging, production).
- **Use Environment Variables:** Use environment variables to configure your build process.
### 7.3. Linting and Formatting
- **Configure ESLint:** Configure ESLint to enforce coding style and identify potential errors.
- **Use Prettier:** Use Prettier to automatically format your code to a consistent style.
- **Integrate Linting and Formatting into Your Workflow:** Integrate linting and formatting into your development workflow using tools like Husky or lint-staged.
### 7.4. Deployment
- **Use a Build Process:** Use a build process to bundle, minify, and optimize your code before deployment.
- **Deploy to a CDN:** Deploy static assets to a content delivery network (CDN) for faster loading times.
- **Use HTTPS:** Always use HTTPS to encrypt communication between the client and the server.
### 7.5. CI/CD Integration
- **Automate Build and Testing:** Automate your build and testing process using a continuous integration and continuous delivery (CI/CD) pipeline.
- **Run Linting and Formatting Checks:** Run linting and formatting checks as part of your CI/CD pipeline.
- **Deploy Automatically:** Automate the deployment process to deploy new versions of your application automatically.
This comprehensive guide provides a solid foundation for using esbuild effectively. Remember to adapt these best practices to your specific project needs and continuously learn as the esbuild ecosystem evolves.
+5
View File
@@ -0,0 +1,5 @@
---
description: This rule provides comprehensive guidelines for ESLint, covering code organization, common patterns, performance, security, testing, and tooling, ensuring high-quality, maintainable JavaScript/TypeScript code.
globs: **/*.{js,jsx,ts,tsx,vue}
---
By following these best practices, you can ensure that your JavaScript/TypeScript code is clean, consistent, and maintainable, reducing the risk of bugs and improving overall code quality.
+299
View File
@@ -0,0 +1,299 @@
---
description: This rule provides comprehensive best practices for developing applications with Fabric.js, covering code organization, performance optimization, security considerations, and testing strategies. It aims to help developers create efficient, maintainable, and secure Fabric.js-based applications.
globs: **/*.js
---
# Fabric.js Best Practices and Coding Standards
This document outlines the best practices and coding standards for developing applications using Fabric.js. Following these guidelines will result in more maintainable, performant, and secure code.
## 1. Code Organization and Structure
### 1.1. Directory Structure
Adopt a modular directory structure to separate concerns and improve code organization. A typical Fabric.js project might have the following structure:
project-root/
├── src/
│ ├── components/
│ │ ├── CanvasComponent.js # Component for Fabric.js Canvas
│ │ ├── ObjectControls.js # Component for Object Manipulation Controls
│ │ ├── ...
│ ├── utils/
│ │ ├── canvasUtils.js # Utility functions for canvas operations
│ │ ├── imageFilters.js # Custom image filters
│ │ ├── ...
│ ├── services/
│ │ ├── canvasService.js # Service for managing canvas state
│ │ ├── ...
│ ├── models/
│ │ ├── fabricObject.js # Custom Fabric.js object definitions
│ │ ├── ...
│ ├── App.js # Main application component
│ └── index.js # Entry point
├── public/
│ ├── index.html
│ ├── ...
├── .cursor/
│ ├── rules/
│ │ └── fabricjs_best_practices.mdc
├── .gitignore
├── package.json
├── webpack.config.js # Example build configuration (if using Webpack)
└── README.md
### 1.2. File Naming Conventions
* Use descriptive file names. For example, `CanvasComponent.js` instead of `canvas.js`. Name files according to the component they contain.
* Follow a consistent naming convention (e.g., PascalCase for components, camelCase for functions and variables).
### 1.3. Module Organization
* Break down the application into smaller, reusable modules. Use ES modules (`import`/`export`) to manage dependencies.
* Each module should have a single responsibility. A single canvas utility module, a module for custom objects, etc.
* Avoid circular dependencies between modules.
### 1.4. Component Architecture
* Adopt a component-based architecture, especially when using frameworks like React, Vue, or Angular. Fabric.js can be integrated into components that manage different aspects of the canvas.
* Create reusable components for common Fabric.js elements and interactions. For example, create a component that encapsulates custom object controls.
* Separate the presentation logic from the business logic. Components should primarily focus on rendering the canvas and handling user interactions, while services or utility functions handle data manipulation and API calls.
### 1.5. Code Splitting
* If the application is large, use code splitting to reduce the initial load time. Frameworks like React and Vue provide built-in support for code splitting.
* Consider lazy-loading parts of the application that are not immediately needed, such as advanced image filters or custom object editors.
* Webpack's dynamic `import()` is a great way to implement code splitting.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Observer Pattern:** Use the Observer pattern for managing canvas events. For example, subscribe to `object:modified` to update the application state when an object is changed.
* **Factory Pattern:** Use the Factory pattern for creating Fabric.js objects. This allows you to create objects with consistent configurations and avoid code duplication. Create a `FabricObjectFactory` service.
* **Strategy Pattern:** Employ the Strategy pattern for implementing different rendering strategies or image filters. Allows for easy switching of rendering algorithms.
### 2.2. Recommended Approaches
* **Object Manipulation:** Use Fabric.js's built-in methods for manipulating objects (`set()`, `get()`, `scale()`, `rotate()`, etc.). Leverage these methods instead of directly manipulating properties to ensure proper updates and event triggering.
* **Event Handling:** Utilize Fabric.js's extensive event system for handling user interactions and object changes. Subscribe to relevant events like `mouse:down`, `object:moving`, and `selection:created` to implement custom behaviors.
* **Asynchronous Operations:** Use Promises and `async/await` for asynchronous operations, such as loading images or applying filters. This helps avoid callback hell and makes the code more readable.
### 2.3. Anti-patterns and Code Smells
* **Direct DOM Manipulation:** Avoid directly manipulating the DOM of the canvas element. Use Fabric.js's API for all canvas operations. This can lead to inconsistencies and performance issues.
* **Global State:** Avoid storing the Fabric.js canvas instance or object states in global variables. Use a state management library or component state to manage the application state.
* **Over-rendering:** Avoid unnecessary re-renders of the entire canvas. Use `canvas.renderOnAddRemove = false` and call `canvas.renderAll()` only when necessary. Also use `fabric.StaticCanvas` if interactivity isn't required.
* **Deeply Nested Callbacks:** Avoid deeply nested callbacks when working with asynchronous operations. Use Promises and `async/await` to simplify the code.
### 2.4. State Management
* Choose a state management library based on the complexity of the application. Options include:
* **React Context API:** For simple applications.
* **Redux:** For complex applications with predictable state management.
* **Vuex:** For Vue.js applications.
* **Zustand or Jotai:** Lightweight, unopinionated state management solutions.
* Store the minimal amount of state necessary. Avoid storing derived data in the state.
* Use immutable data structures to prevent accidental state mutations.
* Consider using a state management library specifically designed for canvas applications, if available.
### 2.5. Error Handling
* Use `try...catch` blocks to handle exceptions that may occur during Fabric.js operations, such as loading images or parsing JSON.
* Log errors to the console or a logging service. Provide informative error messages to help debug the application.
* Implement a global error handler to catch unhandled exceptions. Display a user-friendly error message and prevent the application from crashing.
* Consider using `canvas.discardActiveObject()` after error to prevent object interaction when error occur.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Static Canvas:** Use `fabric.StaticCanvas` when interactivity is not needed.
* **Object Selectability:** Set `object.selectable = false` when objects don't need to be selectable.
* **Control and Border Visibility:** Set `object.hasControls = false` and `object.hasBorders = false` when controls and borders are not needed.
* **Rotating Point Visibility:** Set `object.hasRotatingPoint = false` when rotation is not needed.
* **Canvas Selection:** Disable canvas selection with `canvas.selection = false` when selection is not needed.
* **Skip Target Find:** Use `canvas.skipTargetFind = true` to avoid Fabric detecting object corners on mouse movement.
* **Render on Add/Remove:** Set `canvas.renderOnAddRemove = false` when adding or removing many objects.
* **Object Visibility:** Set `object.visible = false` for objects outside the canvas drawing area.
* **Caching:** Use caching to improve rendering performance. Fabric.js automatically caches objects, but you can manually control caching with `object.cache = true` and `object.dirty = true`.
* **Offscreen Canvas:** Pre-render complex objects or repeating elements on an offscreen canvas and then draw the offscreen canvas onto the main canvas.
* **Integer Coordinates:** Avoid floating-point coordinates by rounding coordinates used in `drawImage()` using `Math.floor()`.
* **CSS Transforms:** Use CSS transforms for scaling the canvas instead of scaling the canvas context.
* **Transparency:** Set the `alpha` option to `false` when creating a drawing context with `HTMLCanvasElement.getContext()` if transparency is not needed.
* **Batch Calls:** Batch canvas calls together to reduce the number of draw operations. For example, draw a polyline instead of multiple separate lines.
* **Avoid State Changes:** Avoid unnecessary canvas state changes. Minimize changes to fill, stroke, shadow, etc.
* **Render Differences:** Render only screen differences, not the whole new state.
* **Shadow Blur:** Avoid the `shadowBlur` property whenever possible, as it is computationally expensive.
* **Text Rendering:** Minimize text rendering, as it can be slow.
* **Clear Canvas:** Experiment with different ways to clear the canvas (`clearRect()`, `fillRect()`, resizing the canvas) to find the most performant method.
* **Animations:** Use `window.requestAnimationFrame()` instead of `setInterval()` for animations.
### 3.2. Memory Management
* **Object Disposal:** When objects are no longer needed, remove them from the canvas and dispose of them using `object.dispose()` to release memory. Also consider removing event listeners manually.
* **Image Handling:** Be mindful of image sizes, and resize images before loading them into the canvas if necessary. Avoid loading very large images that can consume a lot of memory.
* **Garbage Collection:** Force garbage collection when memory usage is high (though this is generally discouraged and should be a last resort). Consider using tools to profile memory usage and identify memory leaks.
### 3.3. Rendering Optimization
* **Layered Canvases:** Use multiple layered canvases for complex scenes where some elements change frequently while others remain static.
* **Plain CSS:** Use plain CSS for large background images instead of rendering them on the canvas.
### 3.4. Bundle Size Optimization
* **Tree Shaking:** Use tree shaking to remove unused code from the Fabric.js library. Configure your build tool (e.g., Webpack, Parcel) to enable tree shaking.
* **Code Splitting:** Use code splitting to reduce the initial load time by loading only the necessary code.
* **Minification:** Minify the JavaScript code to reduce the bundle size.
* **Gzip Compression:** Use Gzip compression to reduce the size of the transferred files.
* **Use Modules Selectively:** Import only the necessary modules from Fabric.js. For example, `import { Canvas, Rect } from 'fabric'` instead of `import { fabric } from 'fabric'`.
### 3.5. Lazy Loading
* Lazy-load components or features that are not immediately needed. For example, lazy-load advanced image filters or custom object editors.
* Use dynamic imports (`import()`) to load modules on demand.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by carefully sanitizing user input before rendering it on the canvas. Be especially careful when allowing users to enter text or upload images.
* **Image Upload Vulnerabilities:** Validate image uploads to prevent malicious files from being uploaded. Check file extensions, MIME types, and image dimensions. Consider using a dedicated image processing library to sanitize images.
* **Serialization Vulnerabilities:** Be careful when serializing and deserializing Fabric.js objects. Avoid using `eval()` or other unsafe methods for deserialization.
### 4.2. Input Validation
* Validate all user input before using it to manipulate the canvas. This includes text, image URLs, and object properties.
* Use regular expressions or other validation techniques to ensure that the input matches the expected format.
* Sanitize user input to prevent XSS vulnerabilities.
### 4.3. Authentication and Authorization
* Implement authentication and authorization to restrict access to sensitive features or data. Use a secure authentication protocol, such as OAuth 2.0 or JWT.
* Store user credentials securely using hashing and salting.
* Implement role-based access control to limit access to specific features based on user roles.
### 4.4. Data Protection
* Protect sensitive data by encrypting it at rest and in transit. Use HTTPS to secure communication between the client and server.
* Store sensitive data securely using a database or other secure storage mechanism.
* Implement data loss prevention (DLP) measures to prevent sensitive data from being leaked.
### 4.5. Secure API Communication
* Use HTTPS to secure communication with APIs.
* Validate all data received from APIs.
* Implement rate limiting to prevent abuse.
* Use a secure authentication protocol, such as OAuth 2.0 or JWT.
## 5. Testing Approaches
### 5.1. Unit Testing
* Write unit tests for individual components and functions.
* Use a testing framework like Jest or Mocha.
* Mock external dependencies, such as the Fabric.js canvas instance, to isolate the unit under test.
* Test edge cases and error conditions.
### 5.2. Integration Testing
* Write integration tests to verify the interaction between different components and modules.
* Test the integration of Fabric.js with other libraries or frameworks.
* Use a testing framework like Cypress or Puppeteer to automate integration tests.
### 5.3. End-to-End Testing
* Write end-to-end tests to verify the entire application workflow.
* Simulate user interactions and verify that the application behaves as expected.
* Use a testing framework like Selenium or Playwright to automate end-to-end tests.
### 5.4. Test Organization
* Organize tests in a clear and consistent manner. Use a directory structure that mirrors the application's structure.
* Write descriptive test names that clearly indicate what is being tested.
* Use a test runner to execute the tests and generate reports.
### 5.5. Mocking and Stubbing
* Use mocking and stubbing to isolate units of code during testing.
* Mock Fabric.js objects and methods to control their behavior during tests. For example, mock the `canvas.add()` method to verify that an object is added to the canvas.
* Use a mocking library like Sinon.js or Jest's built-in mocking capabilities.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Incorrect Object Coordinates:** Misunderstanding Fabric.js's coordinate system can lead to incorrect object placement.
* **Incorrect Object Origin:** The origin of an object affects its rotation and scaling behavior. Ensure the origin is set correctly.
* **Ignoring Events:** Not using Fabric.js's event system for managing user interactions and object changes.
* **Over-reliance on `renderAll()`:** Unnecessary calls to `renderAll()` can lead to performance issues.
* **Forgetting to Dispose Objects:** Failing to dispose of objects when they are no longer needed can lead to memory leaks.
* **Conflicting Event Listeners:** Using native DOM event listeners in a way that conflicts with Fabric.js's event system.
* **Not Handling Asynchronous Operations Correctly:** Failing to use Promises and `async/await` for asynchronous operations can lead to callback hell.
### 6.2. Edge Cases
* **Text Rendering on Different Browsers:** Text rendering can vary across different browsers and operating systems. Test the application on different platforms to ensure consistent text rendering.
* **Image Loading Issues:** Images may fail to load due to network errors or CORS restrictions. Implement error handling to gracefully handle image loading failures.
* **Object Serialization with Custom Properties:** When serializing objects with custom properties, ensure that the properties are properly handled during serialization and deserialization.
* **Zoom and Pan Interactions:** Implement zoom and pan interactions carefully to avoid performance issues. Use caching and other optimization techniques to improve performance.
* **Touch Device Support:** Ensure that the application works correctly on touch devices. Handle touch events and gestures appropriately.
### 6.3. Version-Specific Issues
* **API Changes:** Be aware of API changes between different versions of Fabric.js. Consult the release notes and migration guides when upgrading Fabric.js.
* **Bug Fixes:** Check the Fabric.js issue tracker for known bugs and fixes. Consider using a specific version of Fabric.js that is known to be stable and reliable.
### 6.4. Compatibility Concerns
* **Browser Compatibility:** Ensure that the application is compatible with the target browsers. Test the application on different browsers and versions.
* **Device Compatibility:** Ensure that the application is compatible with different devices, such as desktops, laptops, tablets, and smartphones.
* **Library Conflicts:** Avoid conflicts with other JavaScript libraries or frameworks. Use a module bundler like Webpack or Parcel to manage dependencies and prevent conflicts.
### 6.5. Debugging Strategies
* **Console Logging:** Use `console.log()` to log messages and variables to the console. Use `console.error()` for error messages and `console.warn()` for warnings.
* **Debugging Tools:** Use browser developer tools to inspect the canvas, Fabric.js objects, and event listeners. Set breakpoints and step through the code to identify issues.
* **Fabric.js Debug Mode:** Enable Fabric.js debug mode to get more detailed information about canvas operations. Set `fabric.enableGLVite = true`.
* **Profiling Tools:** Use profiling tools to identify performance bottlenecks. For example, use Chrome DevTools' Performance tab to profile the application's performance.
* **Remote Debugging:** Use remote debugging to debug the application on a mobile device or other remote environment.
* **Check for Canvas Errors:** Wrap drawing operations in try/catch blocks to catch errors during rendering. Check if there are errors in the console, like WebGL context errors.
## 7. Tooling and Environment
### 7.1. Recommended Tools
* **Code Editor:** Visual Studio Code, Sublime Text, or Atom.
* **Module Bundler:** Webpack, Parcel, or Rollup.
* **Testing Framework:** Jest, Mocha, or Jasmine.
* **Linting Tool:** ESLint or JSHint.
* **Code Formatter:** Prettier.
* **Version Control System:** Git.
### 7.2. Build Configuration
* Configure the build tool to enable tree shaking and code splitting.
* Use a minifier to reduce the size of the JavaScript code.
* Configure the build tool to generate source maps for debugging.
* Use a task runner like Gulp or Grunt to automate build tasks.
### 7.3. Linting and Formatting
* Use a linter like ESLint to enforce code style and identify potential errors. Configure ESLint to use a consistent coding style guide, such as Airbnb or Google.
* Use a code formatter like Prettier to automatically format the code. Configure Prettier to work with ESLint.
* Use editor integrations to automatically lint and format the code on save.
### 7.4. Deployment
* Deploy the application to a web server, such as Apache or Nginx.
* Use a content delivery network (CDN) to serve static assets.
* Configure the web server to use Gzip compression.
* Use HTTPS to secure communication between the client and server.
* Consider using a service like Netlify or Vercel for easy deployment.
### 7.5. CI/CD Integration
* Use a continuous integration (CI) system to automate the build, test, and deployment process. Examples include Jenkins, Travis CI, CircleCI, GitHub Actions, GitLab CI.
* Configure the CI system to run the linter, code formatter, and tests on every commit.
* Configure the CI system to automatically deploy the application to the staging or production environment when the tests pass.
+331
View File
@@ -0,0 +1,331 @@
---
description: This rule outlines the best practices and coding standards for developing with FFmpeg, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.c
---
# FFmpeg Best Practices and Coding Standards
This document outlines the best practices and coding standards for developing with FFmpeg. Adhering to these guidelines will promote code quality, maintainability, performance, and security.
## 1. Code Organization and Structure
### 1.1 Directory Structure
The FFmpeg project itself has a specific, well-defined directory structure. While you don't necessarily need to replicate this exactly in your own projects, you can adapt principles from it.
* `libavcodec/`: Contains all the codecs (encoders and decoders). Organize your codec-related code in a similar manner if extending FFmpeg.
* `libavformat/`: Contains the container format handling (muxers and demuxers).
* `libavfilter/`: Contains the audio and video filters.
* `libavutil/`: Contains utility functions used throughout the project (e.g., memory management, data structures).
* `libswscale/`: Contains the video scaling and pixel format conversion functions.
* `libswresample/`: Contains the audio resampling and format conversion functions.
* `doc/`: Documentation.
* `tools/`: Tools like `ffmpeg`, `ffprobe`, and `ffplay`.
For projects *using* FFmpeg, a good directory structure is crucial:
project/
├── src/
│ ├── ffmpeg_integration/
│ │ ├── audio_processing.c
│ │ ├── video_processing.c
│ │ ├── format_handling.c
│ │ └── ...
│ ├── core/
│ │ ├── data_structures.c
│ │ ├── utils.c
│ │ └── ...
│ ├── main.c
│ └── ...
├── include/
│ ├── ffmpeg_integration/
│ │ ├── audio_processing.h
│ │ ├── video_processing.h
│ │ ├── format_handling.h
│ │ └── ...
│ ├── core/
│ │ ├── data_structures.h
│ │ ├── utils.h
│ │ └── ...
│ └── ...
├── tests/
│ ├── unit/
│ │ ├── test_audio_processing.c
│ │ ├── test_video_processing.c
│ │ └── ...
│ ├── integration/
│ │ ├── test_end_to_end.c
│ │ └── ...
│ └── ...
├── build/
├── data/
├── docs/
└── ...
### 1.2 File Naming Conventions
* Use descriptive file names. For example, `audio_encoder.c`, `video_decoder.c`, `format_muxer.c`.
* Header files should have the same base name as their corresponding source files (e.g., `audio_encoder.c` and `audio_encoder.h`).
* Test files can be prefixed with `test_` or postfixed with `_test` (e.g., `test_audio_encoder.c` or `audio_encoder_test.c`).
### 1.3 Module Organization
* Group related functionalities into modules. Each module should have a clear responsibility (e.g., audio encoding, video decoding, format handling).
* Use header files to define the public interface of each module.
* Hide implementation details within the source files.
* Minimize dependencies between modules.
### 1.4 Component Architecture
* Adopt a layered architecture. Separate concerns into different layers (e.g., presentation layer, business logic layer, data access layer).
* Use an abstraction layer to decouple your application from the FFmpeg API. This will make it easier to switch to a different multimedia library in the future.
* Consider using a plugin architecture if you need to support different codecs or formats.
### 1.5 Code Splitting Strategies
* Split large source files into smaller, more manageable files.
* Group related functions and data structures into separate source files.
* Use header files to define the interface between source files.
* Consider splitting code based on functionality or layer.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Factory Pattern:** Use a factory pattern to create instances of codecs or formats based on their names or IDs.
* **Strategy Pattern:** Use a strategy pattern to implement different encoding or decoding algorithms.
* **Observer Pattern:** Use an observer pattern for asynchronous events, like when a frame is decoded or an error occurs.
* **Resource Acquisition Is Initialization (RAII):** Use RAII to ensure that resources (e.g., memory buffers, codec contexts) are properly released when they are no longer needed. FFmpeg APIs often require explicit deallocation.
### 2.2 Recommended Approaches for Common Tasks
* **Encoding:**
* Select appropriate codecs based on the desired quality, bitrate, and compatibility.
* Configure the encoder parameters properly (e.g., bitrate, frame rate, resolution).
* Handle the encoding process asynchronously to avoid blocking the main thread.
* **Decoding:**
* Check for errors after each decoding operation.
* Allocate sufficient memory for the decoded frames.
* Convert the decoded frames to a suitable pixel format.
* **Muxing/Demuxing:**
* Choose the appropriate container format based on the desired features and compatibility.
* Set the stream parameters correctly (e.g., codec, bitrate, frame rate).
* Handle metadata properly.
* **Filtering:**
* Construct filter graphs carefully to achieve the desired effects.
* Optimize the filter graph for performance.
* Handle errors that may occur during filtering.
### 2.3 Anti-patterns and Code Smells
* **Ignoring Error Codes:** Always check the return values of FFmpeg functions and handle errors appropriately.
* **Leaking Resources:** Always free allocated memory and close opened files.
* **Global State:** Avoid using global variables as much as possible.
* **Magic Numbers:** Use named constants instead of hardcoded numerical values.
* **Long Functions:** Break down long functions into smaller, more manageable functions.
* **Unnecessary Transcoding:** Avoid transcoding between lossy formats if possible. Transcode from lossless to lossy whenever feasible, as mentioned in the provided search results.
* **Busy-waiting:** Avoid using tight loops that continuously poll for events. Use asynchronous mechanisms instead.
### 2.4 State Management
* Use structs to encapsulate the state of FFmpeg operations (e.g., encoding, decoding, filtering).
* Pass the state structs to functions that need to access the state.
* Avoid using global variables to store state information.
* Consider using a state machine to manage the different states of FFmpeg operations.
### 2.5 Error Handling
* Always check the return values of FFmpeg functions. Most functions return 0 on success and a negative value on failure.
* Use `av_strerror()` to get a human-readable error message.
* Log error messages to a file or console.
* Handle errors gracefully. Don't just crash the application.
* Use exception handling (if appropriate for the language) to catch unexpected errors.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Codec Selection:** Choose the most efficient codecs for your needs (e.g., use hardware acceleration if available).
* **Bitrate Control:** Use appropriate bitrate control methods (e.g., constant bitrate (CBR), variable bitrate (VBR)).
* **Multi-threading:** Use multi-threading to parallelize encoding, decoding, and filtering operations.
* **SIMD Instructions:** Utilize SIMD (Single Instruction, Multiple Data) instructions (e.g., SSE, AVX) to accelerate processing.
* **Caching:** Cache frequently accessed data to reduce memory access overhead.
* **Reduce Memory Copies:** Minimize unnecessary memory copies.
* **Hardware Acceleration:** Utilize hardware acceleration (e.g., VAAPI, NVENC, QSV) for encoding and decoding. As the FFmpeg documentation and release notes indicate, there is constant work on expanding HW acceleration capabilities for various codecs.
* **Filter Graph Optimization:** Optimize your filter graphs to reduce the number of operations performed.
### 3.2 Memory Management
* Use `av_malloc()` and `av_free()` to allocate and free memory.
* Always free allocated memory when it is no longer needed.
* Avoid memory leaks.
* Use memory pools to reduce memory allocation overhead.
* Be aware of potential buffer overflows.
### 3.3 Rendering Optimization (If Applicable)
* Use hardware acceleration for rendering (e.g., OpenGL, Direct3D).
* Optimize your rendering pipeline to reduce the number of draw calls.
* Use efficient data structures for storing video frames.
### 3.4 Bundle Size Optimization (If Applicable)
* Only include the codecs and formats that you need in your application.
* Use a linker to remove unused code.
* Compress your application binary.
### 3.5 Lazy Loading (If Applicable)
* Load codecs and formats on demand.
* Use asynchronous loading to avoid blocking the main thread.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
* **Buffer Overflows:** Ensure that input buffers are large enough to hold the data being read into them. Use functions like `av_strlcpy()` or `av_strlcat()` to prevent overflows.
* **Integer Overflows:** Check for potential integer overflows before performing arithmetic operations.
* **Format String Vulnerabilities:** Avoid using user-supplied input directly in format strings.
* **Denial of Service (DoS):** Limit the resources that can be consumed by FFmpeg operations (e.g., maximum bitrate, maximum frame size).
* **Arbitrary Code Execution:** Be extremely careful when using user-supplied plugins or filters. Validate the code before executing it.
* **Input Validation flaws:** As the Android Stagefright bug illustrated (mentioned in search results), carefully validate sizes and other parameters in subtitle parsing.
### 4.2 Input Validation
* Validate all input parameters before passing them to FFmpeg functions.
* Check the range of numerical values.
* Sanitize strings to prevent format string vulnerabilities.
* Use whitelists to restrict the allowed values for certain parameters.
### 4.3 Authentication and Authorization (If Applicable)
* Use strong authentication mechanisms to protect your application from unauthorized access.
* Implement proper authorization policies to restrict access to sensitive resources.
* Use secure communication protocols (e.g., HTTPS) to protect data in transit.
### 4.4 Data Protection
* Encrypt sensitive data at rest and in transit.
* Use secure storage mechanisms to protect your data from unauthorized access.
* Implement proper access control policies to restrict access to data.
* Consider watermarking video and audio content to deter piracy.
### 4.5 Secure API Communication
* Use secure protocols (e.g., HTTPS) to communicate with FFmpeg APIs.
* Validate all data received from FFmpeg APIs.
* Implement proper error handling to detect and respond to security threats.
## 5. Testing Approaches
### 5.1 Unit Testing
* Test individual components in isolation.
* Use mocking and stubbing to isolate the components being tested.
* Write unit tests for all critical functionalities.
* Use a test framework (e.g., Check, CUnit) to automate the testing process.
* Aim for high code coverage.
### 5.2 Integration Testing
* Test the interaction between different components.
* Simulate real-world scenarios.
* Use a test environment that is as close as possible to the production environment.
### 5.3 End-to-End Testing
* Test the entire application from start to finish.
* Verify that all components are working correctly together.
* Use automated testing tools to automate the testing process.
### 5.4 Test Organization
* Organize your tests into separate directories based on the component being tested.
* Use descriptive names for test files and test functions.
* Group related tests into test suites.
### 5.5 Mocking and Stubbing
* Use mocking and stubbing to isolate the components being tested.
* Create mock objects that mimic the behavior of real objects.
* Use stub functions to replace the implementation of certain functions.
* Use a mocking framework (e.g., CMock) to simplify the mocking process.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* Forgetting to initialize FFmpeg libraries (e.g., calling `avformat_network_init()` when using network protocols).
* Using deprecated APIs.
* Not handling codec context correctly.
* Misunderstanding time base conversions.
* Incorrectly setting pixel formats.
* Not properly flushing encoders at the end of encoding.
### 6.2 Edge Cases
* Handling corrupted or incomplete input files.
* Dealing with variable frame rate videos.
* Supporting different audio and video codecs.
* Handling metadata correctly.
* Properly managing threading and synchronization when using multiple threads.
### 6.3 Version-Specific Issues
* Be aware of API changes between different FFmpeg versions. Pay close attention to the `APIchanges` files released with each version (as seen in the provided search results).
* Use conditional compilation to support different versions of FFmpeg.
* Consult the FFmpeg documentation for the specific version you are using.
### 6.4 Compatibility Concerns
* Ensure that your application is compatible with different operating systems and architectures.
* Test your application on different devices.
* Use conditional compilation to support different platforms.
* Consider using a cross-platform build system (e.g., CMake).
### 6.5 Debugging
* Use a debugger (e.g., GDB) to step through the code and inspect variables.
* Use logging to track the execution of your application.
* Use a memory checker (e.g., Valgrind) to detect memory leaks and other memory errors.
* Use FFmpeg's built-in debugging tools (e.g., `-report` option).
* Check the FFmpeg mailing lists and forums for known issues and solutions.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **IDE:** Visual Studio, CLion, Eclipse.
* **Compiler:** GCC, Clang, MSVC.
* **Debugger:** GDB, LLDB.
* **Memory Checker:** Valgrind.
* **Build System:** CMake, Make.
* **Linting/Formatting:** clang-format, cppcheck.
### 7.2 Build Configuration
* Use a build system (e.g., CMake, Make) to automate the build process.
* Configure the build system to include the necessary FFmpeg libraries and header files.
* Use compiler flags to optimize the code for performance.
* Create separate build configurations for debug and release builds.
### 7.3 Linting and Formatting
* Use a linter (e.g., cppcheck) to check for coding errors and style violations.
* Use a code formatter (e.g., clang-format) to automatically format the code according to a consistent style.
* Enforce coding standards through automated checks during the build process.
* Follow the FFmpeg coding style guidelines (K&R style, 4-space indentation, as mentioned in the search results).
### 7.4 Deployment
* Package your application and its dependencies into a single distribution package.
* Use a package manager (e.g., apt, yum, Homebrew) to install your application.
* Consider using a containerization technology (e.g., Docker) to deploy your application.
### 7.5 CI/CD Integration
* Integrate your tests into a Continuous Integration/Continuous Deployment (CI/CD) pipeline.
* Run the tests automatically whenever code is committed to the repository.
* Use a CI/CD tool (e.g., Jenkins, Travis CI, GitHub Actions) to automate the CI/CD process.
* Automate the deployment process.
+303
View File
@@ -0,0 +1,303 @@
---
description: This rule provides guidelines for Firebase library usage, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure efficient, secure, and maintainable Firebase projects.
globs: **/*.{js,jsx,ts,tsx,html,css,scss,vue,swift,kt,java,py,go,rb,php,c,cpp,cs}
---
---
## Firebase Library Best Practices
This document outlines best practices for developing applications using the Firebase library. It covers various aspects, including code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling/environment setup. By following these guidelines, developers can create robust, scalable, and secure Firebase applications.
### 1. Code Organization and Structure
- **Directory Structure Best Practices:**
- Adopt a modular structure to separate concerns.
- Organize code based on features or domains (e.g., `auth`, `database`, `storage`).
- Common directory structure:
project-root/
├── src/
│ ├── components/
│ │ ├── Auth/
│ │ │ ├── Login.js
│ │ │ ├── Signup.js
│ │ ├── UI/
│ │ │ ├── Button.js
│ │ │ ├── Input.js
│ ├── services/
│ │ ├── firebase.js (Firebase initialization)
│ │ ├── authService.js (Authentication logic)
│ │ ├── databaseService.js (Database interactions)
│ ├── models/
│ │ ├── User.js (Data models)
│ ├── utils/
│ │ ├── helpers.js (Utility functions)
│ ├── App.js (Main application component)
│ └── index.js (Entry point)
├── tests/
│ ├── components/
│ ├── services/
├── .env (Environment variables)
├── firebase.json (Firebase configuration)
└── package.json
- **File Naming Conventions:**
- Use descriptive and consistent names.
- Component files: `ComponentName.js` or `ComponentName.jsx` (e.g., `Login.js`).
- Service files: `serviceNameService.js` (e.g., `authService.js`).
- Style files: `ComponentName.module.css` or `ComponentName.scss`.
- Test files: `ComponentName.test.js` or `ComponentName.spec.js`.
- **Module Organization Best Practices:**
- Encapsulate Firebase logic within dedicated modules/services.
- Create a `firebase.js` module for initializing Firebase:
javascript
// firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const storage = getStorage(app);
export { auth, db, storage };
- Use environment variables to store sensitive Firebase configuration.
- **Component Architecture Recommendations:**
- Favor functional components with hooks (React) for managing state and side effects.
- Separate UI components from Firebase data fetching logic.
- Use Higher-Order Components (HOCs) or custom hooks for reusable Firebase authentication or data access patterns.
- **Code Splitting Strategies:**
- Implement lazy loading for routes and components to reduce initial bundle size.
- Use dynamic imports for conditionally loading Firebase modules.
- Example:
javascript
// Lazy load a component
const MyComponent = React.lazy(() => import('./MyComponent'));
<React.Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</React.Suspense>
### 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Repository Pattern:** Abstract Firebase data access behind a repository interface.
- **Observer Pattern:** Utilize Firebase's real-time listeners for data synchronization.
- **Factory Pattern:** Create Firebase service instances (e.g., Firestore, Auth) using a factory function.
- **Recommended Approaches for Common Tasks:**
- **Authentication:** Use Firebase Authentication for user management. Implement multiple authentication methods (email/password, social login, etc.).
- **Data Access:** Utilize Firestore or Realtime Database for storing and retrieving data. Implement efficient querying and data modeling.
- **Storage:** Use Firebase Storage for storing files and media. Secure storage access using Firebase Storage Rules.
- **Cloud Functions:** Use Cloud Functions for backend logic and serverless tasks. Trigger functions based on Firebase events.
- **Anti-patterns and Code Smells:**
- **Directly manipulating Firebase data in UI components:** Leads to tight coupling and makes testing difficult. Use services to abstract data access.
- **Over-fetching data:** Retrieve only the necessary data to avoid performance issues. Use specific queries and projections.
- **Ignoring security rules:** Exposes your database to unauthorized access. Define and test security rules thoroughly.
- **Writing complex logic in security rules:** Can lead to performance issues and difficult maintenance. Keep security rules simple and focused on access control.
- **Hardcoding Firebase configuration:** Makes it difficult to manage multiple environments (development, staging, production).
- **State Management Best Practices:**
- **Local State:** Use React's `useState` or `useReducer` for component-specific state.
- **Context API:** Share Firebase authentication state across components.
javascript
// AuthContext.js
import React, { createContext, useState, useEffect } from 'react';
import { auth } from './firebase';
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setCurrentUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
const value = { currentUser, loading };
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
};
- **Third-Party Libraries:** Consider Redux, Zustand, or Recoil for complex state management needs.
- **Error Handling Patterns:**
- Implement try-catch blocks for Firebase operations.
- Handle Firebase-specific errors gracefully.
javascript
import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from './firebase';
const signUp = async (email, password) => {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
console.log("User created: ", user);
return user;
} catch (error) {
console.error("Error creating user: ", error.message);
// Handle specific Firebase errors (e.g., auth/email-already-in-use)
throw error;
}
};
- Provide informative error messages to the user.
- Log errors for debugging and monitoring.
### 3. Performance Considerations
- **Optimization Techniques:**
- **Index Firestore fields:** Optimize query performance by creating indexes on frequently queried fields.
- **Limit data retrieval:** Use `limit()` and `startAt()` to retrieve only the necessary data.
- **Use denormalization judiciously:** Consider denormalizing data to reduce the number of reads required for common operations, but be mindful of data consistency.
- **Batch writes:** Group multiple write operations into a single batch to reduce network overhead.
- **Optimize Cloud Functions:** Minimize function execution time by optimizing code and reducing dependencies.
- **Memory Management:**
- Properly unsubscribe from Firebase listeners to avoid memory leaks.
- Release resources when components unmount.
- Utilize garbage collection effectively.
- **Rendering Optimization:**
- Use memoization techniques (e.g., `React.memo`) to prevent unnecessary re-renders.
- Virtualize long lists to improve rendering performance.
- **Bundle Size Optimization:**
- Use tree shaking to remove unused Firebase modules.
- Minify and compress code.
- Analyze bundle size using tools like Webpack Bundle Analyzer.
- **Lazy Loading Strategies:**
- Implement lazy loading for images and other assets.
- Use code splitting to load Firebase modules only when needed.
- Example for images:
html
<img src="image.jpg" loading="lazy" alt="Image" />
### 4. Security Best Practices
- **Common Vulnerabilities and Prevention:**
- **Data breaches:** Prevent unauthorized access by enforcing strict security rules.
- **Authentication bypass:** Secure authentication flows by validating user credentials and using multi-factor authentication.
- **Denial-of-service (DoS) attacks:** Implement rate limiting and monitoring to mitigate abusive traffic.
- **Input Validation:**
- Validate all user inputs on the client-side and server-side.
- Sanitize inputs to prevent injection attacks.
- Implement data type validation and length constraints.
- **Authentication and Authorization:**
- **Use Firebase Authentication:** Leverage Firebase Authentication for user management and authentication.
- **Implement Firebase Security Rules:** Define security rules to control access to Firebase resources.
- **Use Custom Claims:** Assign custom claims to users based on their roles and permissions.
- **App Check:** Use App Check to prevent unauthorized clients from accessing your Firebase resources.
- **Data Protection:**
- **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit.
- **Regularly backup data:** Implement regular data backups to prevent data loss.
- **Comply with privacy regulations:** Adhere to privacy regulations like GDPR and CCPA.
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Implement proper authorization mechanisms to restrict access to API endpoints.
- Protect API keys and service account credentials.
### 5. Testing Approaches
- **Unit Testing:**
- **Isolate components:** Test individual components in isolation.
- **Mock Firebase dependencies:** Mock Firebase services to avoid external dependencies.
javascript
// Example using Jest
jest.mock('./firebase', () => ({
auth: {
currentUser: {},
onAuthStateChanged: jest.fn()
},
db: {
collection: jest.fn().mockReturnThis(),
doc: jest.fn().mockReturnThis(),
get: jest.fn().mockResolvedValue({})
}
}));
- **Test authentication logic:** Verify authentication flows and error handling.
- **Use Jest, Mocha, or other testing frameworks.**
- **Integration Testing:**
- **Test interactions between components:** Verify that components work together correctly.
- **Use the Firebase Emulator Suite:** Test against a local Firebase environment.
- **Test data flow:** Ensure that data is correctly stored and retrieved from Firebase.
- **End-to-End Testing:**
- **Simulate user interactions:** Test the entire application flow from the user's perspective.
- **Use Cypress, Selenium, or Puppeteer:** Automate end-to-end tests.
- **Test authentication and authorization:** Verify that users can access the correct resources.
- **Test Organization:**
- **Organize tests by component or feature:** Create separate test suites for each component or feature.
- **Use descriptive test names:** Clearly describe what each test verifies.
- **Follow a consistent testing style:** Adhere to a consistent testing style for all tests.
- **Mocking and Stubbing:**
- **Mock Firebase services:** Use mocking libraries to simulate Firebase services.
- **Stub API responses:** Stub API responses to control test data.
- **Verify function calls:** Ensure that functions are called with the correct arguments.
### 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Misconfigured security rules:** Leads to unauthorized access.
- **Inefficient queries:** Causes performance issues.
- **Ignoring error handling:** Makes it difficult to debug and maintain the application.
- **Exposing API keys:** Compromises the security of the application.
- **Edge Cases:**
- **Offline scenarios:** Handle offline scenarios gracefully.
- **Concurrent data updates:** Manage concurrent data updates to prevent data loss.
- **Large datasets:** Optimize data retrieval and rendering for large datasets.
- **Version-Specific Issues:**
- **Breaking changes:** Be aware of breaking changes in Firebase SDK updates.
- **Deprecated features:** Avoid using deprecated features.
- **Compatibility issues:** Ensure compatibility with other libraries and frameworks.
- **Compatibility Concerns:**
- **Browser compatibility:** Test the application on different browsers.
- **Device compatibility:** Test the application on different devices.
- **Framework compatibility:** Ensure compatibility with the chosen framework (e.g., React, Angular, Vue).
- **Debugging Strategies:**
- **Use Firebase console:** Monitor Firebase usage and identify issues.
- **Use browser developer tools:** Debug client-side code using browser developer tools.
- **Use logging:** Log errors and debug messages to identify and resolve issues.
### 7. Tooling and Environment
- **Recommended Development Tools:**
- **Firebase CLI:** Manage Firebase projects and deploy applications.
- **Firebase Emulator Suite:** Emulate Firebase services locally for testing.
- **IDE:** Use VS Code, WebStorm, or other IDEs with Firebase extensions.
- **Build Configuration:**
- **Use a build tool:** Use Webpack, Parcel, or Rollup to bundle and optimize code.
- **Configure environment variables:** Use `.env` files to store environment-specific configuration.
- **Set up build scripts:** Define build scripts for development, testing, and production.
- **Linting and Formatting:**
- **Use ESLint and Prettier:** Enforce consistent code style and identify potential issues.
- **Configure linting rules:** Customize linting rules to match project requirements.
- **Automate linting and formatting:** Integrate linting and formatting into the build process.
- **Deployment Best Practices:**
- **Use Firebase Hosting:** Deploy static assets and web applications to Firebase Hosting.
- **Use Cloud Functions:** Deploy backend logic to Cloud Functions.
- **Configure deployment targets:** Define deployment targets for different environments.
- **CI/CD Integration:**
- **Integrate with CI/CD pipelines:** Automate the build, test, and deployment process.
- **Use GitHub Actions, CircleCI, or other CI/CD tools:** Integrate with popular CI/CD platforms.
- **Automate testing and deployment:** Automatically run tests and deploy code on every commit or pull request.
By adhering to these best practices, developers can create efficient, secure, and maintainable Firebase applications. Remember to stay up-to-date with the latest Firebase documentation and best practices to leverage the full potential of the Firebase platform.
+276
View File
@@ -0,0 +1,276 @@
---
description: Comprehensive guide for using Flake8 effectively in Python projects, covering code style, error prevention, security, testing, and optimization. It outlines best practices, patterns, and common pitfalls to help developers maintain high code quality and adherence to standards.
globs: **/*.py
---
# Flake8 Best Practices: A Comprehensive Guide
This document provides a detailed guide on effectively using Flake8 in Python projects to maintain high code quality, enforce coding standards, and prevent common errors. It covers various aspects, including code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling.
## 1. Code Organization and Structure
### Directory Structure Best Practices
- **Flat is better than nested (but not *too* flat):** Aim for a balance. A deeply nested structure can be hard to navigate, but a completely flat structure becomes unwieldy for larger projects.
- **Package-oriented:** Organize your code into packages (directories with `__init__.py` files) representing logical components of your application.
- **Separate concerns:** Keep source code, tests, documentation, and other assets in separate top-level directories (e.g., `src`, `tests`, `docs`).
Example:
my_project/
├── src/
│ ├── my_package/
│ │ ├── __init__.py
│ │ ├── module1.py
│ │ ├── module2.py
│ ├── another_package/
│ │ ├── __init__.py
│ │ ├── ...
├── tests/
│ ├── __init__.py
│ ├── test_module1.py
│ ├── test_module2.py
├── docs/
│ ├── ...
├── .flake8
├── pyproject.toml
└── README.md
### File Naming Conventions
- **Lowercase with underscores:** Use lowercase letters and underscores for module and package names (e.g., `my_module.py`, `my_package/`).
- **Descriptive names:** Choose names that clearly indicate the purpose of the file or module.
- **Test files:** Prefix test files with `test_` (e.g., `test_my_module.py`). This is a common convention recognized by testing frameworks like `pytest`. Use underscores instead of hyphens.
### Module Organization Best Practices
- **Single responsibility principle:** Each module should have a clear, single purpose.
- **Import order:** Follow a consistent import order:
1. Standard library imports
2. Third-party imports
3. Local application/package imports
Separate each group with a blank line.
- **Avoid circular dependencies:** Design your modules to minimize or eliminate circular dependencies.
- **Explicit relative imports:** Within packages, use explicit relative imports (`from . import module`) instead of implicit relative imports (which are deprecated in Python 3). These can be enforced with plugins like `flake8-import-order`.
### Component Architecture Recommendations
- **Layered architecture:** Consider a layered architecture (e.g., presentation layer, business logic layer, data access layer) to separate concerns and improve maintainability. This can enhance testability.
- **Microservices (for larger projects):** For very large projects, explore a microservices architecture, where each service is a self-contained unit with its own codebase and deployment pipeline. This requires more overhead but offers better scalability and fault isolation.
- **Dependency Injection:** Use dependency injection to decouple components and facilitate testing.
### Code Splitting Strategies
- **Function size:** Keep functions short and focused. If a function becomes too long, consider splitting it into smaller, more manageable functions.
- **Class size:** Similarly, keep classes focused. A class should represent a single concept or responsibility.
- **Module splitting:** If a module becomes too large, consider splitting it into multiple modules based on logical groupings of functionality.
- **Package splitting:** For larger projects, split packages into subpackages to improve organization.
- **Lazy loading:** Defer the loading of modules or components until they are actually needed to improve startup time.
## 2. Common Patterns and Anti-patterns
### Design Patterns Specific to Flake8 (Indirectly)
Flake8 doesn't directly enforce design patterns, but it encourages practices that support good design:
- **Factory Pattern:** Using factories to create objects can improve code flexibility and testability. Flake8 won't directly enforce it, but a well-designed factory would adhere to Flake8's style guidelines.
- **Strategy Pattern:** Employing strategy patterns for algorithms can make code more modular and easier to maintain. Flake8’s advice on function length is key.
- **SOLID Principles:** Flake8 aids the application of SOLID principles by promoting clean, well-structured code that is easier to extend, maintain, and test. It improves readability.
### Recommended Approaches for Common Tasks
- **Configuration:** Use a `.flake8` or `setup.cfg` file to configure Flake8 settings (e.g., ignored rules, maximum line length).
- **Ignoring specific errors:** Use `# noqa` comments at the end of lines to ignore specific errors. Be specific with error codes (e.g., `# noqa: E501`) rather than using a blanket `# noqa`.
- **Integrating with pre-commit hooks:** Use pre-commit hooks to automatically run Flake8 before committing code.
- **Using plugins:** Leverage plugins to extend Flake8's capabilities (e.g., `flake8-bugbear`, `flake8-docstrings`).
### Anti-patterns and Code Smells
- **Long functions/methods:** Functions and methods that are excessively long and complex.
- **Duplicated code:** Code that is repeated in multiple places.
- **Magic numbers:** Hardcoded numerical values that lack explanation.
- **Global variables:** Excessive use of global variables can lead to unpredictable behavior.
- **Deeply nested code:** Excessive indentation can make code hard to read and understand.
- **Ignoring errors indiscriminately:** Using blanket `# noqa` comments without specifying error codes.
### State Management Best Practices
- **Minimize mutable state:** Reduce the use of mutable state to avoid unexpected side effects. Favour immutable data structures.
- **Clear ownership:** Ensure clear ownership of state. Avoid shared mutable state as much as possible.
- **State management libraries:** For complex state management, consider using libraries like Redux or MobX (if applicable in your context, e.g., for GUI applications).
### Error Handling Patterns
- **Specific exceptions:** Catch specific exceptions rather than using a broad `except Exception:`.
- **Context managers:** Use `try...finally` or `with` statements (context managers) to ensure resources are properly released, even if exceptions occur.
- **Logging:** Log exceptions and errors to help with debugging.
- **Raise exceptions appropriately:** Raise exceptions when appropriate to signal errors to calling code.
- **Avoid swallowing exceptions:** Don't catch exceptions and do nothing. At least log the error.
## 3. Performance Considerations
### Optimization Techniques Specific to Flake8 (Indirectly)
Flake8 does not directly optimize code, but it encourages practices that lead to better performance:
- **Avoid unnecessary loops:** Optimize loops to minimize the number of iterations and operations performed.
- **Use efficient data structures:** Choose the appropriate data structure for the task at hand (e.g., `set` for membership testing, `dict` for lookups).
- **Minimize object creation:** Creating objects can be expensive. Reuse objects where possible.
- **Use generators and iterators:** Use generators and iterators to process large datasets in a memory-efficient way.
- **List comprehensions & Generator expressions:** Use these to simplify code and increase its execution speed, where appropriate.
### Memory Management Considerations
- **Avoid memory leaks:** Be careful not to create memory leaks by holding onto objects longer than necessary.
- **Use weak references:** Use weak references to avoid creating circular references that prevent garbage collection.
- **Profile your code:** Use profiling tools to identify memory bottlenecks.
### Bundle Size Optimization (If Applicable - e.g., web applications)
- **Dead code elimination:** Remove unused code to reduce bundle size.
- **Code splitting:** Split your code into smaller chunks that can be loaded on demand.
- **Minification:** Minify your code to reduce file size.
- **Compression:** Use compression techniques (e.g., gzip) to reduce the size of files served to the client.
### Lazy Loading Strategies
- **Import-time optimization:** Defer the loading of modules or components until they are actually needed.
- **Route-based code splitting:** Load only the code required for the current route (if applicable in your context).
## 4. Security Best Practices
### Common Vulnerabilities and Prevention
- **SQL Injection:** Prevent SQL injection by using parameterized queries or ORMs.
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input before displaying it in HTML.
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms (e.g., CSRF tokens).
- **Authentication and Authorization:** Implement secure authentication and authorization mechanisms to protect sensitive data. Don't store passwords in plain text; use hashing algorithms like bcrypt.
- **Input Validation:** Validate all user input to prevent malicious data from entering your application.
### Input Validation Best Practices
- **Whitelist validation:** Validate input against a whitelist of allowed values.
- **Regular expressions:** Use regular expressions to validate input formats.
- **Data type validation:** Ensure that input data is of the expected type.
- **Length validation:** Limit the length of input strings to prevent buffer overflows.
### Authentication and Authorization Patterns
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
- **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.
### Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Hashing:** Use hashing to store passwords securely.
- **Data masking:** Mask sensitive data when displaying it to users.
- **Data anonymization:** Anonymize data to protect user privacy.
### Secure API Communication
- **HTTPS:** Use HTTPS for all API communication.
- **API Keys:** Securely manage API keys.
- **Rate Limiting:** Implement rate limiting to prevent abuse.
- **Input sanitization**: Sanitize data being passed to the API to prevent injection vulnerabilities.
## 5. Testing Approaches
### Unit Testing Strategies
- **Test-driven development (TDD):** Write tests before writing code.
- **Isolate units:** Isolate units of code during testing to ensure that tests are focused and reliable.
- **Use mocks and stubs:** Use mocks and stubs to replace dependencies during testing.
- **Assertion libraries:** Use assertion libraries to write clear and concise tests.
### Integration Testing Approaches
- **Test interactions between components:** Test the interactions between different components of your application.
- **Use real dependencies (when appropriate):** Use real dependencies during integration testing to ensure that components work together correctly.
- **Test data persistence:** Test data persistence to ensure that data is stored and retrieved correctly.
### End-to-End Testing Recommendations
- **Simulate user behavior:** Simulate user behavior to test the entire application flow.
- **Use automated testing tools:** Use automated testing tools (e.g., Selenium, Cypress) to automate end-to-end tests.
- **Test cross-browser compatibility:** Test your application in different browsers to ensure cross-browser compatibility.
### Test Organization Best Practices
- **Separate test code from production code:** Keep test code in a separate directory from production code.
- **Organize tests by module/component:** Organize tests into modules and components that mirror the structure of your production code.
- **Use descriptive test names:** Use descriptive test names that clearly indicate what the test is verifying.
### Mocking and Stubbing Techniques
- **Use mocking libraries:** Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to create mocks and stubs.
- **Mock external dependencies:** Mock external dependencies to isolate units of code during testing.
- **Stub return values:** Stub return values to control the behavior of mocked objects.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes
- **Ignoring Flake8 warnings:** Ignoring Flake8 warnings can lead to code quality issues and potential errors.
- **Over-reliance on `# noqa`:** Overusing `# noqa` comments can mask underlying problems in your code.
- **Inconsistent coding style:** Inconsistent coding style can make code harder to read and understand.
- **Not configuring Flake8:** Not configuring Flake8 can lead to suboptimal results.
### Edge Cases
- **Complex regular expressions:** Complex regular expressions can be difficult to understand and maintain.
- **Dynamic code generation:** Dynamic code generation can make it difficult for Flake8 to analyze code.
- **Large files:** Large files can slow down Flake8 analysis.
### Version-Specific Issues
- **Plugin compatibility:** Ensure that plugins are compatible with the version of Flake8 you are using.
- **Configuration changes:** Be aware of configuration changes between different versions of Flake8.
### Compatibility Concerns
- **Python version compatibility:** Ensure that your code is compatible with the Python versions you are targeting.
- **Dependency conflicts:** Be aware of potential dependency conflicts between Flake8 and other libraries.
### Debugging Strategies
- **Read Flake8 error messages:** Understand the meaning of Flake8 error messages to identify the root cause of problems.
- **Use a debugger:** Use a debugger to step through your code and identify errors.
- **Simplify your code:** Simplify your code to make it easier to debug.
- **Write unit tests:** Write unit tests to isolate and test individual units of code.
## 7. Tooling and Environment
### Recommended Development Tools
- **Text editors/IDEs:** VS Code, PyCharm, Sublime Text
- **Version control:** Git
- **Virtual environments:** `venv`, `virtualenv`, `conda`
- **Build tools:** `setuptools`, `poetry`, `pipenv`
### Build Configuration Best Practices
- **Use a `pyproject.toml` file:** Use a `pyproject.toml` file to specify project metadata, dependencies, and build settings.
- **Specify dependencies explicitly:** Specify dependencies explicitly to ensure that your project is reproducible.
- **Use version pinning:** Use version pinning to lock down the versions of your dependencies.
### Linting and Formatting
- **Flake8:** Use Flake8 for linting and style checking.
- **Black:** Use Black for code formatting.
- **isort:** Use isort for import sorting.
- **Pre-commit hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code.
### Deployment Best Practices
- **Containerization:** Use Docker to containerize your application.
- **Cloud platforms:** Deploy your application to a cloud platform (e.g., AWS, Azure, Google Cloud).
- **Continuous integration/continuous deployment (CI/CD):** Use CI/CD pipelines to automate the deployment process.
### CI/CD Integration Strategies
- **Integrate Flake8 into your CI/CD pipeline:** Run Flake8 as part of your CI/CD pipeline to automatically check code quality.
- **Fail the build on Flake8 errors:** Configure your CI/CD pipeline to fail the build if Flake8 detects errors.
- **Use automated testing:** Run automated tests as part of your CI/CD pipeline to ensure that your application is working correctly.
+314
View File
@@ -0,0 +1,314 @@
---
description: A comprehensive guide to best practices for developing RESTful APIs using Flask and Flask-RESTful, covering code organization, performance, security, and testing.
globs: **/*.py
---
# flask-restful Best Practices: A Comprehensive Guide
This document provides a comprehensive guide to developing RESTful APIs using Flask and Flask-RESTful, emphasizing maintainability, scalability, and performance. It covers various aspects, including code organization, common patterns, performance considerations, security, testing, and common pitfalls.
## Library Information:
- Name: flask-restful
- Tags: web, api, python, flask
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
A well-organized directory structure is crucial for maintainability. Here's a recommended structure:
project/
├── api/
│ ├── __init__.py
│ ├── resources/
│ │ ├── __init__.py
│ │ ├── user.py # User resource
│ │ ├── item.py # Item resource
│ ├── models/
│ │ ├── __init__.py
│ │ ├── user_model.py # User model
│ │ ├── item_model.py # Item model
│ ├── schemas/
│ │ ├── __init__.py
│ │ ├── user_schema.py # User schema (using Marshmallow)
│ │ ├── item_schema.py # Item schema
│ ├── utils/
│ │ ├── __init__.py
│ │ ├── auth.py # Authentication utilities
│ ├── app.py # Flask application initialization
│ ├── config.py # Configuration settings
├── tests/
│ ├── __init__.py
│ ├── test_user.py # Unit tests for user resource
│ ├── test_item.py # Unit tests for item resource
├── migrations/ # Alembic migrations (if using SQLAlchemy)
├── venv/ # Virtual environment
├── requirements.txt # Project dependencies
├── Pipfile # Pipenv file
├── Pipfile.lock # Pipenv lock file
├── README.md
* **api/**: Contains all API-related code.
* **api/resources/**: Defines the API resources (e.g., User, Item).
* **api/models/**: Defines the data models (e.g., User, Item).
* **api/schemas/**: Defines the serialization/deserialization schemas (using Marshmallow or similar).
* **api/utils/**: Utility functions (e.g., authentication, authorization).
* **api/app.py**: Initializes the Flask application.
* **api/config.py**: Stores configuration settings (e.g., database URI).
* **tests/**: Contains unit and integration tests.
* **migrations/**: Contains database migration scripts (if using SQLAlchemy).
* **venv/**: The virtual environment (should not be committed to version control).
* **requirements.txt**: Lists project dependencies. Alternatively `Pipfile` and `Pipfile.lock` for pipenv
* **README.md**: Project documentation.
### 1.2 File Naming Conventions
* Python files: Use snake_case (e.g., `user_model.py`, `item_resource.py`).
* Class names: Use PascalCase (e.g., `UserModel`, `ItemResource`).
* Variable names: Use snake_case (e.g., `user_id`, `item_name`).
* Constants: Use SCREAMING_SNAKE_CASE (e.g., `MAX_RETRIES`, `API_VERSION`).
### 1.3 Module Organization
* Group related resources into modules (e.g., a `user` module containing `user_model.py`, `user_resource.py`, `user_schema.py`).
* Use Blueprints to organize related views and other code. Blueprints can be registered with the app, tying all operations to it.
* Keep modules small and focused on a single responsibility.
* Use clear and descriptive module names.
### 1.4 Component Architecture
A common component architecture involves the following layers:
* **Resource Layer:** Exposes the API endpoints using `flask-restful`'s `Resource` class.
* **Service Layer:** Contains the business logic and interacts with the data models.
* **Model Layer:** Defines the data models and interacts with the database (if applicable).
* **Schema Layer:** Defines the serialization/deserialization logic using libraries like Marshmallow.
### 1.5 Code Splitting Strategies
* **Functional Decomposition:** Split code into functions based on their functionality.
* **Modular Decomposition:** Split code into modules based on related functionality (e.g., user management, item management).
* **Layered Architecture:** As described above, separate the resource, service, model, and schema layers.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Resource Controller:** Use `flask-restful`'s `Resource` class to define API endpoints. It provides a structured way to handle different HTTP methods for a given resource.
* **Data Access Object (DAO):** Encapsulate database access logic within DAOs to abstract the database implementation from the rest of the application.
* **Repository Pattern:** Similar to DAO, but provides a higher-level abstraction for accessing data, often used with ORMs like SQLAlchemy.
* **Serialization/Deserialization:** Use libraries like Marshmallow to handle the serialization and deserialization of data between Python objects and JSON.
* **Middleware:** Implement custom middleware to handle tasks like authentication, logging, and request validation.
* **Factory Pattern:** Used to create objects, especially resources and their dependencies, decoupling code from concrete implementations.
### 2.2 Recommended Approaches for Common Tasks
* **Input Validation:** Use Marshmallow schemas for input validation. Define the expected data types, required fields, and validation rules in the schema.
* **Authentication:** Implement authentication using JWT (JSON Web Tokens). Use libraries like `Flask-JWT-Extended` or `Authlib` to handle JWT generation, verification, and storage.
* **Authorization:** Implement authorization using roles and permissions. Use decorators to restrict access to specific endpoints based on user roles.
* **Error Handling:** Implement centralized error handling using Flask's `errorhandler` decorator. Return meaningful error messages and appropriate HTTP status codes to the client.
* **Pagination:** Implement pagination for large datasets to improve performance. Use query parameters to specify the page number and page size.
* **API Versioning:** Use URL prefixes or custom headers to version your API. This allows you to introduce breaking changes without affecting existing clients.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API. Use libraries like `Flask-Limiter` to limit the number of requests that can be made from a specific IP address within a given time period.
### 2.3 Anti-patterns and Code Smells
* **Fat Resources:** Avoid putting too much logic directly into the resource classes. Delegate business logic to service classes.
* **Tight Coupling:** Avoid tight coupling between resources and models. Use interfaces or abstract classes to decouple components.
* **Ignoring Errors:** Always handle errors gracefully and return meaningful error messages to the client.
* **Lack of Input Validation:** Failing to validate input can lead to security vulnerabilities and data corruption.
* **Hardcoding Configuration:** Avoid hardcoding configuration values in the code. Use environment variables or configuration files instead.
* **Inconsistent Naming:** Use consistent naming conventions throughout the codebase.
* **Over-engineering:** Avoid over-engineering solutions. Keep the code simple and focused on solving the specific problem.
### 2.4 State Management
Flask-RESTful is designed to be stateless. However, if you need to manage state, consider the following:
* **Session Management:** Use Flask's session management capabilities for storing user-specific data across requests.
* **Caching:** Use caching mechanisms (e.g., Redis, Memcached) for storing frequently accessed data to improve performance.
* **Database:** Store persistent state in a database.
### 2.5 Error Handling
* **Global Exception Handling:** Use `app.errorhandler` to handle exceptions globally. This provides a centralized way to catch unhandled exceptions and return appropriate error responses.
* **Custom Exceptions:** Define custom exception classes for specific error conditions. This makes it easier to handle errors in a consistent way.
* **Logging:** Log errors and exceptions to a file or a logging service. This helps with debugging and troubleshooting.
* **HTTP Status Codes:** Return appropriate HTTP status codes to indicate the success or failure of a request.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Database Optimization:** Optimize database queries, use indexes, and consider caching database results.
* **Caching:** Use caching mechanisms (e.g., Redis, Memcached) to store frequently accessed data.
* **Gunicorn with multiple workers:** Gunicorn is a WSGI server that can run multiple worker processes to handle concurrent requests. This can significantly improve performance.
* **Asynchronous Tasks:** Use Celery or other task queues for long-running tasks to avoid blocking the main thread.
* **Code Profiling:** Use profiling tools to identify performance bottlenecks in the code.
* **Connection Pooling:** Use connection pooling to reduce the overhead of establishing database connections.
* **Avoid N+1 Query Problem:** When fetching related data, use eager loading or join queries to avoid the N+1 query problem.
### 3.2 Memory Management
* **Use Generators:** Use generators for processing large datasets to avoid loading the entire dataset into memory.
* **Close Database Connections:** Always close database connections after use to release resources.
* **Limit Data Serialization:** Avoid serializing large amounts of data unnecessarily.
* **Garbage Collection:** Be aware of Python's garbage collection mechanism and avoid creating circular references.
### 3.3 Rendering Optimization
* **Use Templates:** Use Jinja2 templates for rendering HTML content. Templates can be cached to improve performance.
* **Minimize DOM Manipulation:** Minimize DOM manipulation in the client-side JavaScript code. Use techniques like virtual DOM to improve performance.
* **Compress Responses:** Use gzip compression to reduce the size of the responses.
### 3.4 Bundle Size Optimization
* **Use a CDN:** Use a Content Delivery Network (CDN) to serve static assets like CSS, JavaScript, and images.
* **Minify CSS and JavaScript:** Minify CSS and JavaScript files to reduce their size.
* **Tree Shaking:** Use tree shaking to remove unused code from the JavaScript bundles.
### 3.5 Lazy Loading
* **Lazy Load Images:** Use lazy loading for images to improve page load time.
* **Lazy Load Modules:** Use lazy loading for modules that are not immediately needed.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
* **SQL Injection:** Occurs when user input is directly inserted into SQL queries.
* **Cross-Site Scripting (XSS):** Occurs when malicious JavaScript code is injected into the website.
* **Cross-Site Request Forgery (CSRF):** Occurs when a malicious website tricks the user into performing an action on the legitimate website.
* **Authentication and Authorization Flaws:** Occurs when authentication or authorization mechanisms are not properly implemented.
* **Denial of Service (DoS):** Occurs when an attacker floods the server with requests, making it unavailable to legitimate users.
### 4.2 Input Validation
* **Validate All Input:** Validate all user input, including query parameters, request bodies, and headers.
* **Use Whitelisting:** Use whitelisting to allow only specific characters or values. Avoid blacklisting, which can be easily bypassed.
* **Escape Output:** Escape output to prevent XSS vulnerabilities.
### 4.3 Authentication and Authorization
* **Use JWT (JSON Web Tokens):** Use JWT for authentication. JWTs are a standard way to represent claims securely between two parties.
* **Implement Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
* **Use Strong Passwords:** Enforce strong password policies, such as minimum length, complexity, and expiration.
* **Implement Two-Factor Authentication (2FA):** Implement 2FA for added security.
* **Rate Limiting:** Apply rate limits to prevent brute-force attacks.
### 4.4 Data Protection
* **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server.
* **Store Passwords Securely:** Store passwords securely using a one-way hash function like bcrypt or Argon2.
* **Regularly Back Up Data:** Regularly back up data to prevent data loss.
### 4.5 Secure API Communication
* **Use HTTPS:** Always use HTTPS for API communication.
* **Validate SSL Certificates:** Validate SSL certificates to prevent man-in-the-middle attacks.
* **Use API Keys:** Use API keys to identify and authenticate clients.
* **Implement CORS:** Implement Cross-Origin Resource Sharing (CORS) to control which domains can access the API.
## 5. Testing Approaches
### 5.1 Unit Testing
* **Test Individual Components:** Unit tests should focus on testing individual components in isolation.
* **Mock Dependencies:** Use mocking to isolate the component being tested from its dependencies.
* **Test Edge Cases:** Test edge cases and boundary conditions.
* **Use Assertions:** Use assertions to verify that the code behaves as expected.
### 5.2 Integration Testing
* **Test Interactions Between Components:** Integration tests should focus on testing the interactions between components.
* **Use a Test Database:** Use a test database for integration tests.
* **Test the API Endpoints:** Test the API endpoints to ensure that they return the correct data.
### 5.3 End-to-End Testing
* **Test the Entire Application:** End-to-end tests should focus on testing the entire application, including the front-end and back-end.
* **Use a Testing Framework:** Use a testing framework like Selenium or Cypress to automate end-to-end tests.
### 5.4 Test Organization
* **Separate Test Files:** Create separate test files for each module or component.
* **Use Descriptive Test Names:** Use descriptive test names to indicate what is being tested.
* **Organize Tests by Feature:** Organize tests by feature to make it easier to find and run tests.
### 5.5 Mocking and Stubbing
* **Use Mocking Libraries:** Use mocking libraries like `unittest.mock` or `pytest-mock` to create mock objects.
* **Stub External Dependencies:** Stub external dependencies to isolate the component being tested.
* **Verify Interactions:** Verify that the component being tested interacts with its dependencies as expected.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Incorrect HTTP Method:** Using the wrong HTTP method for an operation (e.g., using GET to create a resource).
* **Missing Content-Type Header:** Failing to set the `Content-Type` header in the request.
* **Incorrect JSON Format:** Sending or receiving invalid JSON data.
* **Ignoring the `request` Object:** Not properly handling the request object.
* **Failing to Handle Errors:** Not gracefully handling exceptions and returning meaningful error messages.
* **Not Protecting Against CSRF:** Not implementing CSRF protection.
### 6.2 Edge Cases
* **Empty Data:** Handling cases where the database returns empty data.
* **Invalid Input:** Handling cases where the user provides invalid input.
* **Network Errors:** Handling network errors and timeouts.
* **Concurrent Requests:** Handling concurrent requests and race conditions.
### 6.3 Version-Specific Issues
* **Compatibility with Flask and Other Libraries:** Ensuring compatibility between flask-restful and other libraries.
* **Deprecated Features:** Being aware of deprecated features and migrating to the new ones.
### 6.4 Compatibility Concerns
* **Python Versions:** Ensuring compatibility with different Python versions.
* **Database Drivers:** Ensuring compatibility with different database drivers.
* **Operating Systems:** Ensuring compatibility with different operating systems.
### 6.5 Debugging Strategies
* **Use Logging:** Use logging to track the flow of execution and identify errors.
* **Use a Debugger:** Use a debugger to step through the code and inspect variables.
* **Read Error Messages Carefully:** Pay attention to error messages and stack traces.
* **Use Postman or curl:** Use Postman or curl to test API endpoints.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **Virtual Environment:** Use a virtual environment (e.g., `venv`, `pipenv`, `conda`) to isolate project dependencies.
* **IDE:** Use an Integrated Development Environment (IDE) like VS Code, PyCharm, or Sublime Text.
* **REST Client:** Use a REST client like Postman or Insomnia to test API endpoints.
* **Database Client:** Use a database client like DBeaver or pgAdmin to manage databases.
### 7.2 Build Configuration
* **Use a Build System:** Use a build system like Make or Fabric to automate build tasks.
* **Specify Dependencies:** Specify all project dependencies in a `requirements.txt` file or Pipfile.
* **Use a Configuration File:** Use a configuration file to store configuration values.
### 7.3 Linting and Formatting
* **Use a Linter:** Use a linter like pylint or flake8 to enforce code style guidelines.
* **Use a Formatter:** Use a formatter like black or autopep8 to automatically format the code.
### 7.4 Deployment
* **Use a WSGI Server:** Use a WSGI server like Gunicorn or uWSGI to deploy the application.
* **Use a Reverse Proxy:** Use a reverse proxy like Nginx or Apache to handle incoming requests and route them to the WSGI server.
* **Use a Load Balancer:** Use a load balancer to distribute traffic across multiple servers.
* **Use a Process Manager:** Use a process manager like Systemd or Supervisor to manage the WSGI server process.
### 7.5 CI/CD Integration
* **Use a CI/CD Tool:** Use a CI/CD tool like Jenkins, GitLab CI, or CircleCI to automate the build, test, and deployment process.
* **Run Tests Automatically:** Run unit tests and integration tests automatically on every commit.
* **Deploy Automatically:** Deploy the application automatically after the tests pass.
+163
View File
@@ -0,0 +1,163 @@
---
description: This rule file provides comprehensive guidelines for using Font Awesome effectively, covering setup, styling, accessibility, performance, and security best practices. It ensures consistent and optimized usage across projects.
globs: **/*.{html,css,js,jsx,ts,tsx}
---
# Font Awesome Best Practices
This document outlines best practices for using Font Awesome in web development projects. These guidelines cover setup, styling, accessibility, performance, security, and common pitfalls.
## 1. Setup and Usage
* **Font Awesome Kits (Recommended):**
* Use Font Awesome Kits for easy customization and automatic updates.
* Add the Kit's embed code ( `<script>` tag) to the `<head>` of your HTML document.
* Example:
html
<script src="https://kit.fontawesome.com/<your_kit_code>.js" crossorigin="anonymous"></script>
* **Package Manager (npm, yarn):**
* Install Font Awesome as a dependency:
bash
npm install @fortawesome/fontawesome-free
# or
yarn add @fortawesome/fontawesome-free
* Import the necessary CSS or JavaScript files in your application.
* **CDN (Content Delivery Network):**
* Use a CDN for quick setup, but be aware of potential performance implications and dependency on external services.
* Include the CDN link in your HTML:
html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="..." crossorigin="anonymous" />
* **Icon Usage:**
* Use CSS classes to insert icons into your project.
html
<i class="fas fa-heart"></i> <!-- Solid heart icon -->
<i class="far fa-heart"></i> <!-- Regular heart icon -->
<i class="fab fa-github"></i> <!-- GitHub icon -->
## 2. Code Organization and Structure
* **Directory Structure:**
* Place Font Awesome CSS and font files in a dedicated directory (e.g., `assets/fontawesome`). This is less relevant when using kits or CDNs.
* **File Naming Conventions:**
* Stick to the default file names provided by Font Awesome (e.g., `fontawesome.min.css`, `fontawesome.js`).
* **Module Organization:**
* When using a package manager, import Font Awesome modules in your application's entry point or relevant components.
* Example (JavaScript):
javascript
import '@fortawesome/fontawesome-free/css/all.min.css';
* **Component Architecture:**
* Create reusable icon components in your UI framework (e.g., React, Vue, Angular) to encapsulate Font Awesome usage and styling.
* Example (React):
jsx
import React from 'react';
const Icon = ({ name, style }) => (
<i className={`fa${style ? 'b' : 's'} fa-${name}`}></i>
);
export default Icon;
* **Code Splitting:**
* When using a package manager, ensure your build tool (e.g., Webpack, Parcel) correctly bundles Font Awesome files and supports code splitting if needed.
## 3. Styling and Accessibility
* **Styling:**
* Use Font Awesome's styling options to customize icon size, color, and animations.
* Use CSS classes for styling (e.g., `fa-xs`, `fa-sm`, `fa-lg`, `fa-2x`, `fa-spin`, `fa-pulse`).
* Example:
html
<i class="fas fa-heart fa-2x" style="color: red;"></i>
* **Accessibility (Crucial):**
* **Decorative Icons:** Use `aria-hidden="true"` for icons that are purely decorative.
html
<i class="fas fa-star" aria-hidden="true"></i>
* **Informative Icons:** Provide meaningful text alternatives for icons that convey information or are interactive.
* Use `aria-label` for interactive elements (e.g., buttons, links).
html
<a href="/cart" aria-label="View your shopping cart">
<i class="fas fa-shopping-cart" aria-hidden="true"></i>
</a>
* Use visually hidden text (e.g., using CSS class `sr-only`) to provide a text alternative.
html
<span class="sr-only">Search</span>
<i class="fas fa-search" aria-hidden="true"></i>
* Use the `title` attribute to provide a tooltip for sighted users (optional, but recommended).
html
<i class="fas fa-info-circle" aria-hidden="true" title="More information"></i>
## 4. Performance Considerations
* **CDN Usage:**
* Using a reputable CDN can improve performance through caching and optimized delivery. Ensure the CDN supports modern protocols like HTTP/2 or HTTP/3.
* **Self-Hosting:**
* Self-hosting gives you more control over resources but requires proper server configuration and optimization.
* Consider using a CDN in front of your origin server for better performance.
* **Web Fonts vs. SVG:**
* Font Awesome offers both web fonts and SVG versions.
* SVGs generally offer better performance and scalability but may require more setup.
* Web fonts can cause rendering issues (e.g., FOIT - Flash of Invisible Text). Consider using `font-display: swap;` in your CSS to mitigate this.
* **Subsetting (Pro Feature):**
* Use Font Awesome's Pro subsetting feature to include only the icons you need, reducing the overall file size.
* **Lazy Loading:**
* If you have a large number of icons on a page, consider lazy loading them to improve initial page load time. This can be complex and might require custom JavaScript.
## 5. Common Patterns and Anti-Patterns
* **Pattern: Icon Component:** Creating a reusable icon component is a common and effective pattern.
* **Pattern: Consistent Styling:** Define a set of CSS classes or variables for consistent icon styling across your project.
* **Anti-Pattern: Overusing Icons:** Avoid using too many icons, as it can clutter the UI and reduce readability.
* **Anti-Pattern: Inconsistent Icon Usage:** Ensure icons are used consistently throughout the application to maintain a cohesive user experience.
* **Anti-Pattern: Neglecting Accessibility:** Failing to provide proper text alternatives for icons is a major accessibility issue.
## 6. Security Best Practices
* **Vulnerability: Cross-Site Scripting (XSS):**
* Prevent XSS by sanitizing any user-provided input used in conjunction with Font Awesome icons.
* Never directly embed user input into CSS class names or HTML attributes.
* **Dependency Management:**
* Keep Font Awesome dependencies up-to-date to patch security vulnerabilities.
* Use a dependency management tool (e.g., npm, yarn) to manage and update dependencies securely.
* **Subresource Integrity (SRI):**
* When using a CDN, use SRI hashes to verify the integrity of the Font Awesome files.
html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-..." crossorigin="anonymous" />
## 7. Testing Approaches
* **Unit Testing:**
* If you create custom icon components, write unit tests to ensure they render correctly and handle different icon names and styles.
* **Integration Testing:**
* Test the integration of Font Awesome icons within your application's UI to ensure they are displayed correctly in different browsers and devices.
* **End-to-End Testing:**
* Use end-to-end tests to verify the overall user experience with Font Awesome icons, including accessibility and styling.
## 8. Common Pitfalls and Gotchas
* **Version Conflicts:** Ensure all Font Awesome files are from the same version to avoid compatibility issues.
* **CSS Specificity:** Be aware of CSS specificity when styling Font Awesome icons, as it can override your custom styles.
* **Font Loading Issues:** Address font loading issues (e.g., FOIT) by using `font-display: swap;`.
* **Incorrect Class Names:** Double-check icon class names for typos.
* **Missing Font Awesome Kit Code:** Ensure the Font Awesome Kit code is correctly added to your HTML.
## 9. Tooling and Environment
* **Development Tools:**
* Use a code editor with syntax highlighting and autocompletion for CSS and HTML.
* Use browser developer tools to inspect and debug Font Awesome styles and rendering.
* **Build Configuration:**
* Configure your build tool (e.g., Webpack, Parcel) to correctly handle Font Awesome files and optimize for production.
* **Linting and Formatting:**
* Use a linter (e.g., ESLint, Stylelint) to enforce code style and best practices for Font Awesome usage.
* **CI/CD Integration:**
* Integrate Font Awesome dependency updates and security checks into your CI/CD pipeline.
+85
View File
@@ -0,0 +1,85 @@
---
description: Provides guidelines for using gcp-cli, including best practices for scripting, configuration management, security, and performance. Focuses on automation, predictable output, and secure authentication within Google Cloud environments.
globs: **/*.{sh,yaml,tf,py}
---
- **Scripting Best Practices**:
- **Use the `--quiet` flag**: Suppress prompts for non-interactive script execution.
- **Leverage output formatting**: Employ `--format=json`, `--format=yaml`, `--format=csv`, or `--format=text` for predictable, parsable output.
- **Handle exit statuses**: Ensure scripts check exit codes for error handling. A non-zero exit status indicates an error.
- **Avoid relying on standard error messages**: These are subject to change and shouldn't be parsed for critical logic.
- **Configuration Management**:
- **Utilize named configurations**: Create multiple configurations using `gcloud config configurations create` for managing different environments (development, staging, production) or projects.
- **Set properties**: Define the active account (`gcloud config set core/account`), default project (`gcloud config set core/project`), and default region/zone (`gcloud config set compute/region` and `gcloud config set compute/zone`) either globally or per-command.
- **Authentication and Authorization**:
- **Service accounts for production**: Use service accounts with appropriate IAM roles for scripts running in production environments. Create and manage service accounts via the Google Cloud Console.
- **User accounts for interactive sessions**: Use user accounts for interactive sessions and local development.
- **Activate service accounts securely**: Use `gcloud auth activate-service-account --key-file [KEY_FILE]` to activate service accounts, ensuring the key file is securely managed.
- **Avoid storing service account keys in code**: Employ environment variables or secret management solutions to store and retrieve service account keys.
- **Impersonate Service Accounts (if applicable)**: If a user needs to act as a service account, use `gcloud config set auth/impersonate_service_account SERVICE_ACCT_EMAIL` after authenticating with `gcloud auth login`.
- **Filtering and Formatting Output**:
- **Filter output**: Use the `--filter` flag to narrow down results based on specific criteria.
- **Format output**: Use the `--format` flag to control the output format (JSON, YAML, CSV, Text, List).
- **Utilize projections**: Combine `--format` with projections to extract specific fields from the output.
- **Example: List instances in a specific zone**: `gcloud compute instances list --filter="zone:us-central1-a"`
- **Example: List projects in JSON format**: `gcloud projects list --format="json" --filter="labels.env=test AND labels.version=alpha"`
- **Code Organization and Structure (Shell Scripts)**:
- **Modularize scripts**: Break down large scripts into smaller, reusable functions.
- **Use descriptive function names**: Improve readability and maintainability.
- **Implement argument parsing**: Use `getopts` for robust argument handling.
- **Add comments**: Explain the purpose and functionality of code blocks.
- **Use consistent indentation**: Improves readability.
- **Code Organization and Structure (Terraform)**:
- **Follow the Terraform Standard Directory Structure**: Organize configurations into modules.
- **Use Modules**: Encapsulate reusable infrastructure components into modules.
- **Variables**: Use variables to parameterize your configurations.
- **Outputs**: Use outputs to expose important information about your infrastructure.
- **Remote State Management**: Store Terraform state remotely (e.g., in Google Cloud Storage) for collaboration and versioning. Secure the bucket with appropriate IAM permissions.
- **Code Organization and Structure (Python)**:
- **Package your gcp-cli interaction code into reusable modules and classes.**
- **Follow PEP 8 Style Guide for Python Code**.
- **Use Virtual Environments** for dependency management.
- **Common Patterns and Anti-patterns**:
- **Pattern**: Use `xargs` or `parallel` to execute gcloud commands in parallel for faster processing.
- **Anti-pattern**: Hardcoding credentials or sensitive information directly in scripts or configuration files. Use environment variables or secret management solutions instead.
- **Performance Considerations**:
- **Use pagination**: When retrieving large datasets, use the `--page-size` flag to limit the number of results per page and iterate through the pages.
- **Minimize API calls**: Batch operations where possible to reduce the number of API requests.
- **Caching**: Cache API responses to avoid redundant requests. Implement caching mechanisms within your scripts or applications.
- **Security Best Practices**:
- **Least Privilege**: Grant service accounts only the necessary IAM roles and permissions.
- **Regularly rotate service account keys**: Implement a key rotation policy to minimize the impact of compromised keys.
- **Use VPC Service Controls**: Restrict data exfiltration and unauthorized access to Google Cloud services.
- **Audit Logging**: Enable audit logging to track API calls and resource changes.
- **Input Validation**: Always validate user inputs and data received from external sources to prevent injection attacks.
- **Testing Approaches**:
- **Unit tests**: Mock gcloud CLI calls to isolate and test individual components.
- **Integration tests**: Verify the interaction between different Google Cloud services and your gcp-cli scripts.
- **End-to-end tests**: Simulate real-world scenarios and validate the entire workflow.
- **Use `gcloud config configurations activate` in testing** to isolate test environments.
- **Common Pitfalls and Gotchas**:
- **Default project settings**: Ensure the correct project is configured before running gcloud commands.
- **IAM propagation delays**: Be aware of potential delays when granting or revoking IAM permissions.
- **API throttling**: Handle API rate limits gracefully by implementing retry mechanisms with exponential backoff.
- **Version Compatibility**: Be aware of potential breaking changes when upgrading the gcloud CLI. Test your scripts after upgrades.
- **Tooling and Environment**:
- **Use a dedicated development environment**: Isolate your development environment from production to avoid accidental changes.
- **Use a version control system**: Track changes to your gcp-cli scripts and configuration files.
- **Set up CI/CD pipelines**: Automate testing and deployment of your gcp-cli scripts.
- **Recommended tools**: Shellcheck (for shell script linting), Terraform Validate (for Terraform configuration validation), Pylint (for python code linting).
- **Referenced Rules**:
- @file python_best_practices.mdc
- @file terraform_best_practices.mdc
- @file shell_script_best_practices.mdc
+285
View File
@@ -0,0 +1,285 @@
---
description: This rule provides coding standards and best practices for using the gensim library, focusing on NLP, topic modeling, performance, and code organization. It offers actionable guidelines for developers to create effective and maintainable gensim-based applications.
globs: **/*.py
---
# gensim Library Best Practices and Coding Standards
This document outlines the best practices for coding standards when working with the gensim library for Natural Language Processing (NLP) and topic modeling in Python. Following these guidelines will lead to more maintainable, efficient, and robust code.
## Library Information:
- Name: gensim
- Tags: python, nlp, topic-modeling
## 1. Code Organization and Structure:
### 1.1 Directory Structure Best Practices:
Adopt a clear and structured directory organization for your gensim projects. A well-defined structure enhances code readability and maintainability.
my_gensim_project/
├── data/ # Raw and processed datasets
│ ├── raw/ # Original datasets (read-only)
│ └── processed/ # Processed data (e.g., corpus, dictionary)
├── models/ # Trained gensim models
│ ├── lda/ # LDA models
│ └── lsi/ # LSI models
├── scripts/ # Scripts for data processing, model training, etc.
│ ├── preprocess.py # Data preprocessing script
│ ├── train_model.py # Model training script
│ └── evaluate.py # Model evaluation script
├── utils/ # Utility functions and modules
│ ├── helpers.py # Helper functions for common tasks
│ └── visualization.py # Visualization functions
├── notebooks/ # Jupyter notebooks for exploration and experimentation
│ ├── exploration.ipynb
│ └── analysis.ipynb
├── tests/ # Unit and integration tests
│ ├── test_preprocess.py
│ ├── test_train_model.py
│ └── conftest.py # pytest configuration file (optional)
├── README.md # Project documentation
├── requirements.txt # Project dependencies
└── .gitignore # Git ignore file
### 1.2 File Naming Conventions:
Use descriptive and consistent file names. This makes it easier to understand the purpose of each file.
- Use lowercase letters and underscores for Python files (e.g., `preprocess.py`, `train_model.py`).
- Use descriptive names that clearly indicate the file's purpose (e.g., `lda_model.pkl`, `corpus.mm`).
- For data files, include the data source or processing stage in the name (e.g., `raw_data.txt`, `processed_corpus.txt`).
- Use a consistent naming scheme for test files (e.g., `test_module.py` for testing `module.py`).
### 1.3 Module Organization:
Organize your code into logical modules. Each module should handle a specific aspect of your NLP pipeline (e.g., data loading, preprocessing, model training).
- Create separate modules for data loading, preprocessing, model training, evaluation, and visualization.
- Keep modules focused and avoid large, monolithic files.
- Use clear and descriptive names for modules and functions.
- Consider using packages to group related modules.
### 1.4 Component Architecture Recommendations:
Design your gensim applications with a component-based architecture. This promotes code reusability and maintainability.
- Break down your application into smaller, independent components, such as:
- `DataLoader`: Loads and preprocesses data.
- `CorpusBuilder`: Creates a corpus from the preprocessed data.
- `ModelTrainer`: Trains a gensim model on the corpus.
- `ModelEvaluator`: Evaluates the trained model.
- `Visualizer`: Visualizes the model results.
- Each component should have a clear interface and well-defined responsibilities.
- Use dependency injection to manage dependencies between components.
### 1.5 Code Splitting Strategies:
Split large files into smaller, manageable chunks. This improves code readability and reduces the likelihood of merge conflicts.
- Break down large functions into smaller, more focused helper functions.
- Split large modules into smaller, more focused submodules.
- Use appropriate abstraction techniques (e.g., classes, interfaces) to encapsulate related functionality.
- Consider using decorators or context managers to handle common tasks, such as logging or error handling.
## 2. Common Patterns and Anti-patterns:
### 2.1 Design Patterns:
- **Factory Pattern:** Use factory patterns to create different types of gensim models or data transformations based on configuration.
- **Strategy Pattern:** Employ strategy patterns to switch between different preprocessing techniques or similarity measures at runtime.
- **Observer Pattern:** Implement observer patterns to react to model training events, such as logging progress or saving intermediate results.
- **Pipeline Pattern:** Structure your NLP workflow as a pipeline, applying a sequence of transformations to your data.
### 2.2 Recommended Approaches for Common Tasks:
- **Text Preprocessing:** Use `gensim.utils.simple_preprocess` for basic text preprocessing, including tokenization and lowercasing. For more advanced preprocessing, integrate with NLTK or spaCy.
- **Creating a Dictionary:** Use `gensim.corpora.Dictionary` to create a dictionary from your tokenized documents. Filter out infrequent and extremely frequent words using `filter_extremes()` to improve model quality and performance.
- **Creating a Corpus:** Use `dictionary.doc2bow` to convert your documents into a bag-of-words corpus. For large corpora, use `gensim.corpora.MmCorpus` to store the corpus on disk.
- **Training a Topic Model:** Use `gensim.models.LdaModel` or `gensim.models.LsiModel` to train a topic model on your corpus. Tune the model parameters (e.g., number of topics, alpha, beta) to optimize topic coherence.
- **Evaluating a Topic Model:** Use `gensim.models.CoherenceModel` to evaluate the coherence of your topic model. Visualize the model topics using `pyLDAvis` or other visualization tools.
### 2.3 Anti-patterns and Code Smells:
- **Global Variables:** Avoid using global variables for gensim models, corpora, or dictionaries. Pass these objects as arguments to functions or classes.
- **Hardcoded Paths:** Avoid hardcoding file paths in your code. Use configuration files or environment variables to manage file paths.
- **Lack of Error Handling:** Implement proper error handling to gracefully handle unexpected exceptions. Log errors and provide informative error messages to the user.
- **Ignoring Warnings:** Pay attention to warnings generated by gensim. These warnings often indicate potential problems with your code or data.
- **Overly Complex Functions:** Avoid writing overly complex functions that perform too many tasks. Break down large functions into smaller, more focused helper functions.
### 2.4 State Management:
- Encapsulate state within classes.
- Use immutable data structures where possible.
- Avoid modifying shared state directly.
- Consider using a state management library for complex applications.
### 2.5 Error Handling:
- Use try-except blocks to catch exceptions.
- Log exceptions with traceback information.
- Provide informative error messages to the user.
- Consider using custom exception classes for gensim-specific errors.
## 3. Performance Considerations:
### 3.1 Optimization Techniques:
- **Use `MmCorpus` for large corpora:** Store your corpus on disk using `gensim.corpora.MmCorpus` to reduce memory consumption.
- **Use `LdaMulticore` for parallel training:** Train LDA models in parallel using `gensim.models.LdaMulticore` to speed up training time.
- **Optimize preprocessing:** Use efficient string processing techniques and avoid unnecessary computations during preprocessing.
- **Filter extreme values:** Use the `filter_extremes()` function to remove words that are too frequent or infrequent, which can improve the performance of the model
- **Batch Processing:** Process large datasets in batches to reduce memory consumption.
- **Vectorization:** Use NumPy's vectorized operations to speed up numerical computations.
- **Caching:** Cache intermediate results to avoid redundant computations.
### 3.2 Memory Management:
- **Use generators for large datasets:** Load and process data using generators to avoid loading the entire dataset into memory at once.
- **Delete unused objects:** Explicitly delete unused objects using `del` to release memory.
- **Use memory profiling tools:** Use memory profiling tools to identify memory leaks and optimize memory usage.
- **Limit vocabulary size:** Reduce the vocabulary size by filtering out infrequent words.
### 3.3 Rendering Optimization (If Applicable):
- N/A - gensim is primarily a backend library and does not directly involve rendering.
### 3.4 Bundle Size Optimization:
- N/A - gensim is primarily a backend library.
### 3.5 Lazy Loading:
- Load gensim models and data only when they are needed. This can reduce the initial startup time of your application.
- Use lazy initialization for expensive operations.
## 4. Security Best Practices:
### 4.1 Common Vulnerabilities:
- **Arbitrary Code Execution:** Avoid loading untrusted gensim models from external sources, as this could lead to arbitrary code execution.
- **Denial of Service:** Protect against denial-of-service attacks by limiting the size of input data and the complexity of model training.
- **Data Injection:** Sanitize input data to prevent data injection attacks, such as SQL injection or cross-site scripting (XSS).
### 4.2 Input Validation:
- Validate all input data to ensure that it conforms to the expected format and range. This can prevent errors and security vulnerabilities.
- Use regular expressions or other validation techniques to check the validity of input strings.
- Check the size of input data to prevent denial-of-service attacks.
### 4.3 Authentication and Authorization:
- N/A - gensim itself does not provide authentication or authorization mechanisms. These mechanisms should be implemented at the application level.
### 4.4 Data Protection:
- Encrypt sensitive data at rest and in transit.
- Use secure communication protocols (e.g., HTTPS) to protect data in transit.
- Implement access control policies to restrict access to sensitive data.
- Anonymize or pseudonymize data to protect user privacy.
### 4.5 Secure API Communication:
- N/A - gensim itself does not provide APIs for communication with other services. Secure API communication should be implemented at the application level.
## 5. Testing Approaches:
### 5.1 Unit Testing:
- Write unit tests for individual functions and classes. This ensures that each component of your code works as expected.
- Use a testing framework like `pytest` or `unittest` to write and run your unit tests.
- Mock external dependencies to isolate the code under test.
- Cover all branches of your code with unit tests.
### 5.2 Integration Testing:
- Write integration tests to verify that different components of your application work together correctly.
- Test the interaction between your gensim code and other libraries or services.
- Use realistic test data to simulate real-world scenarios.
### 5.3 End-to-End Testing:
- Write end-to-end tests to verify that your entire application works as expected.
- Test the application from the user's perspective.
- Automate your end-to-end tests to ensure that they are run regularly.
### 5.4 Test Organization:
- Organize your tests into a logical directory structure that mirrors your code structure.
- Use descriptive names for your test files and test functions.
- Group related tests into test classes.
### 5.5 Mocking and Stubbing:
- Use mocking and stubbing techniques to isolate the code under test.
- Mock external dependencies to avoid relying on external services or data.
- Use stubs to provide predefined responses to function calls.
## 6. Common Pitfalls and Gotchas:
### 6.1 Frequent Mistakes:
- **Incorrect Data Types:** Ensure that you are using the correct data types for gensim functions and classes. For example, gensim expects input documents to be a list of tokens, not a string.
- **Incorrect Model Parameters:** Tune the model parameters (e.g., number of topics, alpha, beta) to optimize topic coherence. Incorrect model parameters can lead to poor results.
- **Ignoring Preprocessing Steps:** Proper preprocessing is critical to the success of topic modelling. Always preprocess your data before training a gensim model.
- **Forgetting to Save/Load Models:** Trained models should be saved to disk using `model.save` and loaded using `gensim.models.LdaModel.load` or equivalent methods for other models.
### 6.2 Edge Cases:
- **Empty Documents:** Handle empty documents gracefully. Empty documents can cause errors during corpus creation or model training.
- **Documents with Only Stop Words:** Remove stop words from your documents to improve model quality. However, be aware that removing all stop words from a document can result in an empty document.
- **Very Short Documents:** Very short documents may not contain enough information to be effectively modeled.
### 6.3 Version-Specific Issues:
- Be aware of compatibility issues between different versions of gensim. Refer to the gensim documentation for information on version-specific changes.
- Use a virtual environment to manage dependencies and avoid version conflicts.
### 6.4 Compatibility Concerns:
- Ensure that your version of gensim is compatible with other libraries you are using, such as NumPy, SciPy, and scikit-learn.
- Use a virtual environment to manage dependencies and avoid version conflicts.
### 6.5 Debugging Strategies:
- Use a debugger to step through your code and inspect variables.
- Print intermediate results to verify that your code is working as expected.
- Use logging to track the execution of your code and identify potential problems.
- Read the gensim documentation and search for solutions online.
## 7. Tooling and Environment:
### 7.1 Recommended Development Tools:
- **Python:** Use Python 3.7 or later.
- **Virtual Environment:** Use a virtual environment to manage dependencies and avoid version conflicts.
- **IDE:** Use an IDE such as VS Code, PyCharm, or Jupyter Notebook.
- **Testing Framework:** Use a testing framework such as `pytest` or `unittest`.
- **Memory Profiler:** Use a memory profiler such as `memory_profiler` to identify memory leaks and optimize memory usage.
### 7.2 Build Configuration:
- Use a `requirements.txt` file to specify project dependencies.
- Use a `setup.py` file to define your project metadata and package your code for distribution.
- Use a build tool such as `Make` or `tox` to automate the build process.
### 7.3 Linting and Formatting:
- Use a linter such as `flake8` or `pylint` to enforce coding standards.
- Use a formatter such as `black` or `autopep8` to automatically format your code.
- Configure your IDE to automatically run the linter and formatter on save.
### 7.4 Deployment:
- Use a containerization tool such as Docker to package your application and its dependencies into a portable container.
- Use a deployment platform such as AWS, Google Cloud, or Azure to deploy your application to the cloud.
- Use a process manager such as `systemd` or `supervisor` to manage your application's processes.
### 7.5 CI/CD Integration:
- Use a continuous integration/continuous deployment (CI/CD) tool such as Jenkins, Travis CI, or CircleCI to automate the build, test, and deployment process.
- Configure your CI/CD pipeline to run your linters, formatters, and tests on every commit.
- Configure your CI/CD pipeline to automatically deploy your application to the cloud when tests pass.
By adhering to these best practices, you can significantly improve the quality, maintainability, and performance of your gensim projects. Always consult the official gensim documentation for the most up-to-date information and guidance.
+239
View File
@@ -0,0 +1,239 @@
---
description: Enforces best practices for GitLab CI/CD configurations, promoting efficient, maintainable, and secure pipelines. This rule covers aspects from code organization to security and testing strategies.
globs: .gitlab-ci.yml
---
# GitLab CI Best Practices
This document outlines the best practices for configuring GitLab CI/CD pipelines to ensure efficient, maintainable, and secure software development workflows.
## 1. Code Organization and Structure
A well-structured project enhances maintainability and collaboration. While GitLab CI primarily focuses on automation, the underlying code it builds significantly impacts pipeline performance and success.
### Directory Structure Best Practices
While not directly enforced by GitLab CI, consider structuring your repository to support efficient dependency management and modular builds.
* **Monorepo vs. Polyrepo:** Choose a strategy that suits your team's size and project complexity. Monorepos can simplify dependency management but may lead to larger CI execution times if not properly configured. Polyrepos offer better isolation but increase complexity.
* **Component-based structure:** Organize your code into logical components or modules. This allows for selective building and testing of individual components, reducing overall pipeline execution time.
* **`ci/` or `.gitlab/` directory:** Dedicate a directory (e.g., `ci/`, `.gitlab/`) to store CI-related scripts, templates, and configurations. This keeps the root directory clean and organized.
### File Naming Conventions
* `.gitlab-ci.yml` **(required):** The primary configuration file for GitLab CI/CD. It **must** be placed in the root directory of your project.
* `*.gitlab-ci.yml` **(optional):** Use include statements to reference additional configurations in subdirectories. Name them according to their purpose (e.g., `deploy.gitlab-ci.yml`, `test.gitlab-ci.yml`).
* `*.sh`, `*.py`, etc.: Scripts referenced by `.gitlab-ci.yml` should have descriptive names (e.g., `run_tests.sh`, `deploy_to_staging.py`).
### Module Organization
* **Define dependencies:** Explicitly declare dependencies between modules or components. This enables GitLab CI to build and test them in the correct order.
* **Separate CI configurations:** For large projects, consider creating separate `.gitlab-ci.yml` files for each module. Use `include:` to chain them into a larger workflow.
### Component Architecture Recommendations
* **Microservices:** If using a microservices architecture, each service should have its own GitLab CI configuration and pipeline.
* **Modular monolith:** For a monolithic architecture, break down the build process into stages that build and test individual components or modules.
### Code Splitting Strategies
* **Feature flags:** Use feature flags to enable or disable code sections without redeploying. GitLab offers feature flag management.
* **Dynamic imports:** (Applicable for some languages like Javascript) Dynamically load modules only when needed to decrease initial loading times and build size.
## 2. Common Patterns and Anti-patterns
Adhering to proven patterns and avoiding anti-patterns contributes to pipeline reliability and maintainability.
### Design Patterns
* **Pipeline as Code:** Treat your `.gitlab-ci.yml` as code. Version control it, review it, and test it.
* **Infrastructure as Code (IaC):** Use IaC tools (e.g., Terraform, Ansible) to manage the infrastructure used by your pipelines. This ensures consistency and reproducibility.
* **Secrets Management:** Use GitLab's built-in secrets management to store sensitive information (e.g., API keys, passwords) securely. Never hardcode secrets in your `.gitlab-ci.yml` file.
* **Idempotent Scripts:** Ensure your scripts are idempotent, meaning they can be run multiple times without causing unintended side effects.
* **Fail Fast:** Design your pipelines to fail as early as possible to avoid wasting resources on builds that are likely to fail.
* **Artifact Caching:** Cache frequently used dependencies and build artifacts to reduce build times.
### Recommended Approaches for Common Tasks
* **Dependency Management:** Use appropriate package managers (e.g., npm, pip, Maven) to manage dependencies.
* **Testing:** Implement a comprehensive testing strategy, including unit tests, integration tests, and end-to-end tests.
* **Deployment:** Use a robust deployment strategy, such as blue/green deployment or rolling deployment.
* **Notifications:** Configure notifications to alert team members of pipeline failures or successes.
### Anti-patterns and Code Smells
* **Hardcoding secrets:** Never hardcode secrets in your `.gitlab-ci.yml` file. Use GitLab's secret variables.
* **Ignoring failures:** Always address pipeline failures promptly. Ignoring failures can lead to more serious problems down the line.
* **Overly complex pipelines:** Keep your pipelines as simple as possible. Break down complex tasks into smaller, more manageable stages.
* **Lack of testing:** Insufficient testing can lead to bugs in production. Implement a comprehensive testing strategy.
* **Manual deployments:** Automate deployments as much as possible. Manual deployments are error-prone and time-consuming.
* **Long-running branches:** Avoid long-running feature branches. Merge frequently to the main branch to reduce merge conflicts.
### State Management Best Practices
* **GitLab CI Variables:** Use CI/CD variables for configurations that change between environments or pipeline runs.
* **External Databases/Key-Value Stores:** For more complex state, consider using an external database or key-value store (e.g., Redis, etcd).
### Error Handling Patterns
* **`allow_failure: true`:** Use with caution. Only use `allow_failure: true` for jobs that are not critical to the overall success of the pipeline.
* **`retry:`:** Use `retry:` to automatically retry failed jobs. This can be useful for jobs that are prone to transient errors.
* **Error Reporting:** Implement error reporting to capture and track pipeline failures. Integrate with tools like Sentry or Rollbar.
## 3. Performance Considerations
Optimizing pipeline performance reduces build times and improves developer productivity.
### Optimization Techniques
* **Parallelization:** Run jobs in parallel to reduce overall pipeline execution time. Use matrix builds for tasks that can be run independently with different configurations.
* **Caching:** Cache frequently used dependencies and build artifacts to avoid downloading them repeatedly.
* **Optimize Docker images:** Use small, optimized Docker images to reduce image pull times.
* **Efficient Scripting:** Write efficient scripts that avoid unnecessary operations.
* **Selective Builds:** Trigger builds only when necessary by using `only:` and `except:` rules. For example, trigger builds only on changes to specific files or branches.
* **Interruptible jobs:** Mark jobs as interruptible so they can be cancelled if a newer build is triggered. Avoid using this on critical steps that could leave the system in an inconsistent state.
### Memory Management
* **Resource Limits:** Set memory limits for jobs to prevent them from consuming excessive resources.
* **Garbage Collection:** Ensure your scripts properly clean up temporary files and release memory.
### Rendering Optimization (If Applicable)
* (N/A - Primarily relevant for UI-based projects, less applicable to CI configuration files).
### Bundle Size Optimization (If Applicable)
* (N/A - Primarily relevant for front-end projects, less applicable to CI configuration files themselves, but important for the code being built by the CI pipeline).
### Lazy Loading (If Applicable)
* (N/A - Primarily relevant for front-end projects, less applicable to CI configuration files themselves, but important for the code being built by the CI pipeline).
## 4. Security Best Practices
Securing your pipelines protects your code, infrastructure, and data.
### Common Vulnerabilities and Prevention
* **Secret Exposure:** Prevent secrets from being exposed in logs or environment variables. Use GitLab's secret variables and avoid printing them to the console.
* **Dependency Vulnerabilities:** Regularly scan your dependencies for vulnerabilities using tools like Snyk or GitLab's Dependency Scanning.
* **Code Injection:** Prevent code injection vulnerabilities by validating user inputs and sanitizing data.
* **Unauthorized Access:** Restrict access to your pipelines to authorized users only.
### Input Validation
* **Sanitize inputs:** Sanitize inputs from external sources (e.g., environment variables, user inputs) to prevent code injection.
### Authentication and Authorization
* **Use GitLab's authentication:** Use GitLab's built-in authentication mechanisms to protect your pipelines.
* **Limit access:** Limit access to your pipelines to authorized users only.
### Data Protection
* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit.
* **Use secure protocols:** Use secure protocols (e.g., HTTPS, SSH) to communicate with external services.
### Secure API Communication
* **Use API tokens:** Use API tokens to authenticate with external services.
* **Validate responses:** Validate responses from external services to prevent data tampering.
## 5. Testing Approaches
Thorough testing ensures the quality and reliability of your code.
### Unit Testing
* **Test individual components:** Unit tests should test individual components in isolation.
* **Use mocking and stubbing:** Use mocking and stubbing to isolate components from their dependencies.
### Integration Testing
* **Test interactions between components:** Integration tests should test the interactions between different components.
* **Use real dependencies:** Use real dependencies or mock dependencies that closely resemble the real ones.
### End-to-End Testing
* **Test the entire application:** End-to-end tests should test the entire application, from the user interface to the database.
* **Use automated testing tools:** Use automated testing tools like Selenium or Cypress.
### Test Organization
* **Organize tests by component:** Organize tests by component to make them easier to find and maintain.
* **Use a consistent naming convention:** Use a consistent naming convention for tests to make them easier to identify.
### Mocking and Stubbing
* **Use mocking libraries:** Use mocking libraries to create mock objects for testing.
* **Stub external dependencies:** Stub external dependencies to isolate components from the outside world.
## 6. Common Pitfalls and Gotchas
Understanding common pitfalls helps avoid errors and wasted time.
### Frequent Mistakes
* **Incorrect syntax:** Using incorrect YAML syntax in `.gitlab-ci.yml`.
* **Missing dependencies:** Forgetting to declare dependencies in your pipeline.
* **Overly complex pipelines:** Creating overly complex pipelines that are difficult to understand and maintain.
* **Not using caching:** Failing to cache dependencies and build artifacts.
* **Exposing secrets:** Exposing secrets in logs or environment variables.
### Edge Cases
* **Large repositories:** Large repositories can take a long time to clone and build.
* **Complex dependencies:** Complex dependencies can be difficult to manage.
* **Unstable infrastructure:** Unstable infrastructure can cause pipeline failures.
### Version-Specific Issues
* Consult the GitLab documentation for version-specific issues.
* Keep your GitLab Runner up to date.
### Compatibility Concerns
* Ensure compatibility between GitLab CI and other technologies used in your project (e.g., Docker, Kubernetes).
### Debugging Strategies
* **Review pipeline logs:** Review pipeline logs to identify errors.
* **Use debugging tools:** Use debugging tools to step through your code and identify problems.
* **Simplify the pipeline:** Simplify the pipeline to isolate the problem.
* **Reproduce the problem locally:** Try to reproduce the problem locally to make it easier to debug.
## 7. Tooling and Environment
Selecting the right tools and configuring the environment correctly is crucial for efficient CI/CD.
### Recommended Development Tools
* **Git:** A version control system.
* **Docker:** A containerization platform.
* **GitLab Runner:** A CI/CD runner.
* **IDE:** An integrated development environment (e.g., VS Code, IntelliJ).
### Build Configuration Best Practices
* **Use a Docker image:** Use a Docker image as the base for your build environment.
* **Install dependencies:** Install dependencies using a package manager (e.g., npm, pip, Maven).
* **Run tests:** Run tests to ensure the quality of your code.
* **Build artifacts:** Build artifacts that can be deployed to production.
### Linting and Formatting
* **Use linters:** Use linters to enforce code style and identify potential errors.
* **Use formatters:** Use formatters to automatically format your code.
### Deployment Best Practices
* **Use a deployment strategy:** Use a deployment strategy such as blue/green deployment or rolling deployment.
* **Automate deployments:** Automate deployments as much as possible.
* **Monitor deployments:** Monitor deployments to ensure they are successful.
### CI/CD Integration Strategies
* **Use GitLab CI/CD:** Use GitLab CI/CD to automate your build, test, and deployment processes.
* **Integrate with other tools:** Integrate GitLab CI/CD with other tools in your development workflow (e.g., Slack, Jira).
By adhering to these best practices, you can create GitLab CI/CD pipelines that are efficient, maintainable, and secure, enabling you to deliver high-quality software faster and more reliably.
+556
View File
@@ -0,0 +1,556 @@
---
description: This rule provides a comprehensive set of best practices for developing Go applications, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.go
---
- # Go Best Practices
This document outlines best practices for developing Go applications, covering various aspects of the development lifecycle.
- ## 1. Code Organization and Structure
- ### 1.1 Directory Structure
- **Recommended Structure:**
project-name/
├── cmd/
│ └── project-name/
│ └── main.go # Application entry point
├── internal/
│ ├── app/ # Application-specific business logic
│ ├── domain/ # Core domain logic and types
│ └── pkg/ # Reusable internal packages
├── pkg/ # External packages (libraries for other projects)
├── api/ # API definitions (protobuf, OpenAPI specs)
├── web/ # Web assets (HTML, CSS, JavaScript)
├── scripts/ # Build, deployment, or utility scripts
├── configs/ # Configuration files
├── .gitignore
├── go.mod
├── go.sum
└── README.md
- **Explanation:**
- `cmd`: Contains the main applications for your project. Each subdirectory should represent a separate application.
- `internal`: Holds code that's private to your application. Other projects shouldn't import these.
- `internal/app`: High-level application logic.
- `internal/domain`: Core business logic, data models, and interfaces.
- `internal/pkg`: Reusable utilities and helpers within the internal codebase.
- `pkg`: Contains reusable libraries that can be used by other projects. Use this for code you want to share.
- `api`: Defines API contracts (e.g., Protocol Buffers or OpenAPI/Swagger definitions).
- `web`: Stores static web assets like HTML, CSS, and JavaScript files.
- `scripts`: Contains scripts for building, testing, deploying, and other tasks.
- `configs`: Houses configuration files for various environments.
- ### 1.2 File Naming Conventions
- **General:** Use lowercase and snake_case for file names (e.g., `user_service.go`).
- **Test Files:** Append `_test.go` to the name of the file being tested (e.g., `user_service_test.go`).
- **Main Package:** The file containing the `main` function is typically named `main.go`.
- ### 1.3 Module Organization
- **Go Modules:** Use Go modules for dependency management. Initialize a module with `go mod init <module-name>`. The module name should reflect the repository path (e.g., `github.com/your-username/project-name`).
- **Versioning:** Follow semantic versioning (SemVer) for your modules. Use tags in your Git repository to represent releases (e.g., `v1.0.0`).
- **Vendoring:** Consider vendoring dependencies using `go mod vendor` to ensure reproducible builds, especially for critical applications. However, be mindful of vendor directory size.
- ### 1.4 Component Architecture
- **Layered Architecture:** Structure your application into layers (e.g., presentation, service, repository, data access). This promotes separation of concerns and testability.
- **Clean Architecture:** A variation of layered architecture that emphasizes dependency inversion and testability. Core business logic should not depend on implementation details.
- **Microservices:** For larger applications, consider a microservices architecture where different parts of the application are deployed as independent services.
- **Dependency Injection:** Use dependency injection to decouple components and make them easier to test. Frameworks like `google/wire` or manual dependency injection can be used.
- ### 1.5 Code Splitting
- **Package Organization:** Group related functionality into packages. Each package should have a clear responsibility. Keep packages small and focused.
- **Interface Abstraction:** Use interfaces to define contracts between components. This allows you to swap implementations without changing the code that depends on the interface.
- **Functional Options Pattern:** For functions with many optional parameters, use the functional options pattern to improve readability and maintainability.
go
type Server struct {
Addr string
Port int
Protocol string
Timeout time.Duration
}
type Option func(*Server)
func WithAddress(addr string) Option {
return func(s *Server) {
s.Addr = addr
}
}
func WithPort(port int) Option {
return func(s *Server) {
s.Port = port
}
}
func NewServer(options ...Option) *Server {
srv := &Server{
Addr: "localhost",
Port: 8080,
Protocol: "tcp",
Timeout: 30 * time.Second,
}
for _, option := range options {
option(srv)
}
return srv
}
// Usage
server := NewServer(WithAddress("127.0.0.1"), WithPort(9000))
- ## 2. Common Patterns and Anti-patterns
- ### 2.1 Design Patterns
- **Factory Pattern:** Use factory functions to create instances of complex objects.
- **Strategy Pattern:** Define a family of algorithms and encapsulate each one in a separate class, making them interchangeable.
- **Observer Pattern:** Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
- **Context Pattern:** Use the `context` package to manage request-scoped values, cancellation signals, and deadlines. Pass `context.Context` as the first argument to functions that perform I/O or long-running operations.
go
func handleRequest(ctx context.Context, req *http.Request) {
select {
case <-ctx.Done():
// Operation cancelled
return
default:
// Process the request
}
}
- **Middleware Pattern:** Chain functions to process HTTP requests. Middleware can be used for logging, authentication, authorization, and other cross-cutting concerns.
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)
})
}
- ### 2.2 Recommended Approaches for Common Tasks
- **Configuration Management:** Use a library like `spf13/viper` or `joho/godotenv` to load configuration from files, environment variables, and command-line flags.
- **Logging:** Use a structured logging library like `sirupsen/logrus` or `uber-go/zap` to log events with context and severity levels.
- **Database Access:** Use the `database/sql` package with a driver for your specific database (e.g., `github.com/lib/pq` for PostgreSQL, `github.com/go-sql-driver/mysql` for MySQL). Consider an ORM like `gorm.io/gorm` for more complex database interactions. Use prepared statements to prevent SQL injection.
- **HTTP Handling:** Use the `net/http` package for building HTTP servers and clients. Consider using a framework like `gin-gonic/gin` or `go-chi/chi` for more advanced routing and middleware features. Always set appropriate timeouts.
- **Asynchronous Tasks:** Use goroutines and channels to perform asynchronous tasks. Use wait groups to synchronize goroutines.
- **Input Validation:** Use libraries like `go-playground/validator` for validating input data. Always sanitize user input to prevent injection attacks.
- ### 2.3 Anti-patterns and Code Smells
- **Ignoring Errors:** Never ignore errors. Always handle errors explicitly, even if it's just logging them.
go
// Bad
_, _ = fmt.Println("Hello, world!")
// Good
_, err := fmt.Println("Hello, world!")
if err != nil {
log.Println("Error printing: ", err)
}
- **Panic Usage:** Avoid using `panic` for normal error handling. Use it only for truly exceptional situations where the program cannot continue.
- **Global Variables:** Minimize the use of global variables. Prefer passing state explicitly as function arguments.
- **Shadowing Variables:** Avoid shadowing variables, where a variable in an inner scope has the same name as a variable in an outer scope. This can lead to confusion and bugs.
- **Unbuffered Channels:** Be careful when using unbuffered channels. They can easily lead to deadlocks if not used correctly.
- **Overusing Goroutines:** Don't launch too many goroutines, as it can lead to excessive context switching and resource consumption. Consider using a worker pool to limit the number of concurrent goroutines.
- **Mutable Global State:** Avoid modifying global state, especially concurrently, as it can introduce race conditions.
- **Magic Numbers/Strings:** Avoid using hardcoded numbers or strings directly in your code. Define them as constants instead.
- **Long Functions:** Keep functions short and focused. If a function is too long, break it down into smaller, more manageable functions.
- **Deeply Nested Code:** Avoid deeply nested code, as it can be difficult to read and understand. Use techniques like early returns and helper functions to flatten the code structure.
- ### 2.4 State Management
- **Local State:** For simple components, manage state locally within the component using variables.
- **Shared State:** When multiple goroutines need to access and modify shared state, use synchronization primitives like mutexes, read-write mutexes, or atomic operations to prevent race conditions.
go
var mu sync.Mutex
var counter int
func incrementCounter() {
mu.Lock()
defer mu.Unlock()
counter++
}
- **Channels for State Management:** Use channels to pass state between goroutines. This can be a safer alternative to shared memory and locks.
- **Context for Request-Scoped State:** Use `context.Context` to pass request-scoped state, such as user authentication information or transaction IDs.
- **External Stores (Redis, Databases):** For persistent state or state that needs to be shared across multiple services, use an external store like Redis or a database.
- ### 2.5 Error Handling Patterns
- **Explicit Error Handling:** Go treats errors as values. Always check for errors and handle them appropriately.
- **Error Wrapping:** Wrap errors with context information to provide more details about where the error occurred. Use `fmt.Errorf` with `%w` verb to wrap errors.
go
func readFile(filename string) ([]byte, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", filename, err)
}
return data, nil
}
- **Error Types:** Define custom error types to represent specific error conditions. This allows you to handle errors more precisely.
go
type NotFoundError struct {
Resource string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s not found", e.Resource)
}
- **Sentinel Errors:** Define constant errors that can be compared directly using `==`. This is simpler than error types but less flexible.
go
var ErrNotFound = errors.New("not found")
func getUser(id int) (*User, error) {
if id == 0 {
return nil, ErrNotFound
}
// ...
}
- **Error Grouping:** Use libraries like `go.uber.org/multierr` to collect multiple errors and return them as a single error.
- **Defers for Resource Cleanup:** Use `defer` to ensure that resources are cleaned up, even if an error occurs.
go
func processFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close() // Ensure file is closed
// ...
}
- ## 3. Performance Considerations
- ### 3.1 Optimization Techniques
- **Profiling:** Use the `pprof` package to profile your application and identify performance bottlenecks. `go tool pprof` allows you to analyze CPU and memory usage.
bash
go tool pprof http://localhost:6060/debug/pprof/profile # CPU profiling
go tool pprof http://localhost:6060/debug/pprof/heap # Memory profiling
- **Benchmarking:** Use the `testing` package to benchmark critical sections of your code.
go
func BenchmarkFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
// Code to benchmark
}
}
- **Efficient Data Structures:** Choose the right data structures for your needs. For example, use `sync.Map` for concurrent access to maps.
- **String Concatenation:** Use `strings.Builder` for efficient string concatenation, especially in loops.
go
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteString("hello")
}
result := sb.String()
- **Reduce Allocations:** Minimize memory allocations, as garbage collection can be expensive. Reuse buffers and objects when possible.
- **Inline Functions:** Use the `//go:inline` directive to inline frequently called functions. However, use this sparingly, as it can increase code size.
- **Escape Analysis:** Understand how Go's escape analysis works to minimize heap allocations. Values that don't escape to the heap are allocated on the stack, which is faster.
- **Compiler Optimizations:** Experiment with compiler flags like `-gcflags=-S` to see the generated assembly code and understand how the compiler is optimizing your code.
- **Caching:** Implement caching strategies to reduce database or network calls. Use in-memory caches like `lru` or distributed caches like Redis.
- ### 3.2 Memory Management
- **Garbage Collection Awareness:** Be aware of how Go's garbage collector works. Understand the trade-offs between memory usage and CPU usage.
- **Reduce Heap Allocations:** Try to allocate memory on the stack whenever possible to avoid the overhead of garbage collection.
- **Object Pooling:** Use object pooling to reuse frequently created and destroyed objects. This can reduce the number of allocations and improve performance.
- **Slices vs. Arrays:** Understand the difference between slices and arrays. Slices are dynamically sized and backed by an array. Arrays have a fixed size. Slices are generally more flexible, but arrays can be more efficient in some cases.
- **Copying Data:** Be mindful of copying data, especially large data structures. Use pointers to avoid unnecessary copies.
- ### 3.3 Rendering Optimization (if applicable)
- This section is less relevant for back-end Go applications. If your Go application serves HTML templates:
- **Template Caching:** Cache parsed templates to avoid reparsing them on every request.
- **Efficient Template Engine:** Use an efficient template engine like `html/template` from the standard library.
- **Minimize DOM Manipulations (if using JavaScript):** Reduce the number of DOM manipulations in your JavaScript code, as they can be expensive.
- ### 3.4 Bundle Size Optimization (if applicable)
- This section is mostly irrelevant for back-end Go applications. If your Go application serves static assets:
- **Minification:** Minify your CSS and JavaScript files to reduce their size.
- **Compression:** Compress your assets using Gzip or Brotli.
- **Code Splitting (JavaScript):** Split your JavaScript code into smaller chunks that can be loaded on demand.
- ### 3.5 Lazy Loading (if applicable)
- This is mostly relevant for front-end applications, or database connections:
- **Database Connections:** Only establish database connections when they are needed.
- **Expensive Resources:** Load expensive resources (e.g., images, large data structures) only when they are actually used.
- ## 4. Security Best Practices
- ### 4.1 Common Vulnerabilities
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM that automatically escapes user input.
- **Cross-Site Scripting (XSS):** If your Go application renders HTML, prevent XSS by escaping user input before rendering it.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using CSRF tokens.
- **Command Injection:** Avoid executing external commands directly with user input. If you must, sanitize the input carefully.
- **Path Traversal:** Prevent path traversal attacks by validating and sanitizing file paths provided by users.
- **Denial of Service (DoS):** Protect against DoS attacks by setting appropriate timeouts and resource limits. Use rate limiting to prevent abuse.
- **Authentication and Authorization Issues:** Implement robust authentication and authorization mechanisms to protect sensitive data and functionality.
- **Insecure Dependencies:** Regularly audit your dependencies for known vulnerabilities. Use tools like `govulncheck` to identify vulnerabilities.
- ### 4.2 Input Validation
- **Validate All Input:** Validate all input data, including user input, API requests, and data from external sources.
- **Use Validation Libraries:** Use validation libraries like `go-playground/validator` to simplify input validation.
- **Sanitize Input:** Sanitize user input to remove potentially harmful characters or code.
- **Whitelist vs. Blacklist:** Prefer whitelisting allowed values over blacklisting disallowed values.
- **Regular Expressions:** Use regular expressions to validate complex input formats.
- ### 4.3 Authentication and Authorization
- **Use Strong Authentication:** Use strong authentication mechanisms like multi-factor authentication (MFA).
- **Password Hashing:** Hash passwords using a strong hashing algorithm like bcrypt or Argon2.
- **JWT (JSON Web Tokens):** Use JWT for stateless authentication. Verify the signature of JWTs before trusting them.
- **RBAC (Role-Based Access Control):** Implement RBAC to control access to resources based on user roles.
- **Least Privilege:** Grant users only the minimum privileges necessary to perform their tasks.
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization, allowing users to grant third-party applications access to their data without sharing their credentials.
- ### 4.4 Data Protection
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **TLS (Transport Layer Security):** Use TLS to encrypt communication between clients and servers.
- **Data Masking:** Mask sensitive data in logs and displays.
- **Regular Backups:** Regularly back up your data to prevent data loss.
- **Access Control:** Restrict access to sensitive data to authorized personnel only.
- **Data Minimization:** Collect only the data that is necessary for your application.
- ### 4.5 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.
- **Input Validation:** Validate all input data to prevent injection attacks.
- **Output Encoding:** Encode output data appropriately to prevent XSS attacks.
- **CORS (Cross-Origin Resource Sharing):** Configure CORS properly to allow requests from trusted origins only.
- ## 5. Testing Approaches
- ### 5.1 Unit Testing
- **Focus on Individual Units:** Unit tests should focus on testing individual functions, methods, or packages in isolation.
- **Table-Driven Tests:** Use table-driven tests to test multiple inputs and outputs for a single function.
go
func TestAdd(t *testing.T) {
testCases := []struct {
a, b int
expected int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tc := range testCases {
result := Add(tc.a, tc.b)
if result != tc.expected {
t.Errorf("Add(%d, %d) = %d; expected %d", tc.a, tc.b, result, tc.expected)
}
}
}
- **Test Coverage:** Aim for high test coverage. Use `go test -cover` to measure test coverage.
- **Clear Assertions:** Use clear and informative assertions. Libraries like `testify` provide helpful assertion functions.
- **Test Naming:** Use descriptive test names that clearly indicate what is being tested.
- ### 5.2 Integration Testing
- **Test Interactions Between Components:** Integration tests should test the interactions between different components of your application.
- **Use Real Dependencies (where possible):** Use real dependencies (e.g., real databases) in integration tests, where possible. This provides more realistic testing.
- **Mock External Services:** Mock external services that are not under your control.
- **Test Data Setup and Teardown:** Set up test data before each test and tear it down after each test to ensure that tests are independent.
- ### 5.3 End-to-End Testing
- **Test the Entire Application:** End-to-end tests should test the entire application, from the user interface to the backend.
- **Automated Browser Testing:** Use automated browser testing tools like Selenium or Cypress to simulate user interactions.
- **Test Real-World Scenarios:** Test real-world scenarios to ensure that the application works as expected in production.
- **Data Persistence:** Be careful of data persistence between tests. Clean up any generated data after each test run.
- ### 5.4 Test Organization
- **Test Files:** Place test files in the same directory as the code being tested. Use the `_test.go` suffix.
- **Package Tests:** Write tests for each package in your application.
- **Test Suites:** Use test suites to group related tests together.
- ### 5.5 Mocking and Stubbing
- **Interfaces for Mocking:** Use interfaces to define contracts between components, making it easier to mock dependencies.
- **Mocking Libraries:** Use mocking libraries like `gomock` or `testify/mock` to generate mocks for interfaces.
go
//go:generate mockgen -destination=mocks/mock_user_repository.go -package=mocks github.com/your-username/project-name/internal/domain UserRepository
type UserRepository interface {
GetUser(id int) (*User, error)
}
- **Stubbing:** Use stubs to replace dependencies with simple, predefined responses.
- **Avoid Over-Mocking:** Don't over-mock your code. Mock only the dependencies that are necessary to isolate the unit being tested.
- ## 6. Common Pitfalls and Gotchas
- ### 6.1 Frequent Mistakes
- **Nil Pointer Dereferences:** Be careful of nil pointer dereferences. Always check for nil before accessing a pointer.
- **Data Races:** Avoid data races by using synchronization primitives like mutexes or channels.
- **Deadlocks:** Be careful of deadlocks when using goroutines and channels. Ensure that channels are closed properly and that goroutines are not waiting on each other indefinitely.
- **For Loop Variable Capture:** Be careful when capturing loop variables in goroutines. The loop variable may change before the goroutine is executed. Copy the loop variable to a local variable before passing it to the goroutine.
go
for _, item := range items {
item := item // Copy loop variable to local variable
go func() {
// Use local variable item
}()
}
- **Incorrect Type Conversions:** Be careful when converting between types. Ensure that the conversion is valid and that you handle potential errors.
- **Incorrect Error Handling:** Ignoring or mishandling errors is a common pitfall. Always check errors and handle them appropriately.
- **Over-reliance on Global State:** Using global variables excessively leads to tight coupling and makes code difficult to test and reason about.
- ### 6.2 Edge Cases
- **Integer Overflow:** Be aware of integer overflow when performing arithmetic operations.
- **Floating-Point Precision:** Be aware of the limitations of floating-point precision.
- **Time Zones:** Be careful when working with time zones. Use the `time` package to handle time zones correctly.
- **Unicode Handling:** Be careful when handling Unicode characters. Use the `unicode/utf8` package to correctly encode and decode UTF-8 strings.
- ### 6.3 Version-Specific Issues
- **Go 1.18 Generics:** Understand how generics work in Go 1.18 and later versions. Use them judiciously to improve code reusability and type safety.
- **Module Compatibility:** Be aware of compatibility issues between different versions of Go modules. Use `go mod tidy` to update your dependencies and resolve compatibility issues.
- ### 6.4 Compatibility Concerns
- **C Interoperability:** Be aware of the complexities of C interoperability when using the `cgo` tool. Ensure that memory is managed correctly and that there are no data races.
- **Operating System Differences:** Be aware of differences between operating systems (e.g., file path separators, environment variables). Use the `os` package to handle operating system-specific behavior.
- ### 6.5 Debugging Strategies
- **Print Statements:** Use `fmt.Println` or `log.Println` to print debugging information.
- **Delve Debugger:** Use the Delve debugger (`dlv`) to step through your code and inspect variables.
bash
dlv debug ./cmd/your-application
- **pprof Profiling:** Use the `pprof` package to profile your application and identify performance bottlenecks.
- **Race Detector:** Use the race detector (`go run -race`) to identify data races in your code.
- **Logging:** Add detailed logging to your application to help diagnose issues in production.
- **Core Dumps:** Generate core dumps when your application crashes to help diagnose the cause of the crash.
- **Code Reviews:** Have your code reviewed by other developers to catch potential issues.
- ## 7. Tooling and Environment
- ### 7.1 Recommended Development Tools
- **GoLand:** A commercial IDE from JetBrains with excellent Go support.
- **Visual Studio Code:** A free and open-source editor with Go support via the Go extension.
- **Vim:** A powerful text editor with Go support via plugins.
- **gopls:** The official Go language server, providing features like code completion, linting, and formatting.
- ### 7.2 Build Configuration
- **Makefile:** Use a Makefile to automate build and deployment tasks.
makefile
build:
go build -o bin/your-application ./cmd/your-application
run:
go run ./cmd/your-application
test:
go test ./...
- **GoReleaser:** Use GoReleaser to automate the release process, including building binaries for multiple platforms, generating checksums, and creating release notes.
- **Docker:** Use Docker to containerize your application for easy deployment.
dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o /bin/your-application ./cmd/your-application
FROM alpine:latest
WORKDIR /app
COPY --from=builder /bin/your-application .
CMD ["./your-application"]
- ### 7.3 Linting and Formatting
- **gofmt:** Use `gofmt` to automatically format your Go code according to the standard style guidelines. Run it regularly to keep your code consistent.
bash
gofmt -s -w .
- **golint:** Use `golint` to check your code for style and potential issues.
- **staticcheck:** Use `staticcheck` for more comprehensive static analysis.
- **revive:** A fast, configurable, extensible, flexible, and beautiful linter for Go.
- **errcheck:** Use `errcheck` to ensure that you are handling all errors.
- **.golangci.yml:** Use a `.golangci.yml` file to configure `golangci-lint` with your preferred linting rules.
- ### 7.4 Deployment
- **Cloud Platforms:** Deploy your application to cloud platforms like AWS, Google Cloud, or Azure.
- **Kubernetes:** Deploy your application to Kubernetes for scalability and high availability.
- **Systemd:** Use systemd to manage your application as a service on Linux systems.
- **Serverless Functions:** Consider using serverless functions for small, event-driven applications.
- ### 7.5 CI/CD Integration
- **GitHub Actions:** Use GitHub Actions to automate your CI/CD pipeline.
- **GitLab CI:** Use GitLab CI to automate your CI/CD pipeline.
- **Jenkins:** Use Jenkins to automate your CI/CD pipeline.
- **CircleCI:** Use CircleCI to automate your CI/CD pipeline.
- **Automated Testing:** Run unit tests, integration tests, and end-to-end tests automatically as part of your CI/CD pipeline.
- **Automated Deployment:** Automate the deployment process to reduce the risk of human error.
- **Infrastructure as Code:** Use Infrastructure as Code (IaC) tools like Terraform or CloudFormation to automate the provisioning and management of your infrastructure.
+358
View File
@@ -0,0 +1,358 @@
---
description: Comprehensive coding standards and best practices for Godot Engine development, covering code organization, performance, testing, and security to ensure maintainable, efficient, and secure game projects. These rules are primarily for GDScript but also reference relevant C# practices where applicable.
globs: **/*.gd
---
# Godot Engine Best Practices and Coding Standards
This document outlines best practices and coding standards for Godot Engine development using GDScript and C#. Adhering to these guidelines will lead to more maintainable, efficient, and secure game projects.
## 1. Code Organization and Structure
### 1.1. Directory Structure
* **`scenes/`**: Stores all `.tscn` (scene) and `.escn` (external scene) files. Organize scenes into subdirectories based on game areas, features, or entity types (e.g., `scenes/characters/`, `scenes/levels/`, `scenes/ui/`).
* **`scripts/`**: Contains all GDScript (`.gd`) and C# (`.cs`) scripts. Mirror the scene directory structure where applicable to maintain consistency (e.g., `scripts/characters/`, `scripts/levels/`).
* **`assets/` (or `art/` / `textures/` / `audio/`):** Stores all non-code assets like textures, audio files, models, animations, and fonts. Subdivide further based on asset type (e.g., `assets/textures/`, `assets/audio/`, `assets/models/`).
* **`addons/`**: Reserved for third-party addons and plugins.
* **`data/` (or `resources/`):** Holds data files like JSON, CSV, or custom resource files used for game configuration, localization, or level data.
* **`shaders/`**: Stores custom shader files (`.shader`).
* **`autoload/`**: If using autoloaded scripts (singletons), consider a dedicated folder.
my_project/
├── scenes/
│ ├── characters/
│ │ ├── player.tscn
│ │ └── enemy.tscn
│ ├── levels/
│ │ ├── level_1.tscn
│ │ └── level_2.tscn
│ └── ui/
│ └── main_menu.tscn
├── scripts/
│ ├── characters/
│ │ ├── player.gd
│ │ └── enemy.gd
│ └── ui/
│ └── main_menu.gd
├── assets/
│ ├── textures/
│ │ ├── player.png
│ │ └── enemy.png
│ ├── audio/
│ │ ├── background.ogg
│ │ └── jump.wav
│ └── models/
│ └── character.glb
├── addons/
│ └── ...
├── data/
│ └── levels.json
└── shaders/
└── water.shader
### 1.2. File Naming Conventions
* **Scenes:** Use PascalCase (e.g., `Player.tscn`, `MainMenu.tscn`).
* **Scripts (GDScript):** Use snake_case (e.g., `player_controller.gd`, `ui_manager.gd`).
* **Scripts (C#):** Use PascalCase (e.g., `PlayerController.cs`, `UIManager.cs`).
* **Assets:** Use descriptive names with appropriate extensions (e.g., `player_idle.png`, `background_music.ogg`, `sword.glb`). Consider using snake_case for assets as well to maintain consistency.
### 1.3. Module Organization
* **Separate Concerns:** Divide your project into logical modules based on functionality (e.g., player controller, AI, UI, physics, networking). Each module should have its own directory and scripts.
* **Autoloads (Singletons):** Use autoloads sparingly. Overuse can lead to tightly coupled code. Good candidates are global managers like `GameManager`, `InputManager`, or `AudioManager`.
* **Custom Resources:** Create custom resource types for reusable data containers. This promotes data-driven design (e.g., `CharacterData`, `WeaponData`).
### 1.4. Component Architecture
* **Favor Composition over Inheritance:** Use nodes and scripts as components that can be attached to other nodes. This allows for more flexible and reusable code. Godot's scene system is built around this concept.
* **Signals:** Use signals for communication between nodes. This promotes loose coupling and allows nodes to react to events without knowing the details of other nodes.
### 1.5. Code Splitting Strategies
* **Separate Logic from Presentation:** Keep scene files focused on visual representation and node hierarchy. Move game logic, input handling, and AI to separate scripts.
* **Helper Functions:** Create utility scripts with reusable functions to avoid code duplication.
* **Script Classes (GDScript):** Define classes within scripts to encapsulate related data and functions. Use `class_name` to register the class as a global type.
* **Partial Classes (C#):** Use partial classes to split a large class into multiple files, improving organization.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Singleton (Autoload):** As mentioned before, use autoloads for global managers.
* **Observer (Signals):** Use signals for event-driven communication between nodes.
* **State Machine:** Implement state machines to manage the behavior of game entities (e.g., player states: idle, walking, jumping, attacking).
* **Object Pool:** For frequently created and destroyed objects (e.g., bullets, particles), use an object pool to reduce memory allocation overhead.
* **Factory:** Use factories to create instances of objects based on certain conditions or configurations.
### 2.2. Recommended Approaches for Common Tasks
* **Input Handling:** Use the `Input` singleton and input actions for consistent input handling. Define input maps in the project settings.
* **Scene Management:** Use `get_tree().change_scene_to_file()` or `get_tree().change_scene_to_packed()` for scene transitions.
* **Timers:** Use the `Timer` node for delayed execution or repeated events. Avoid using `yield(get_tree().create_timer(time), "timeout")` unless absolutely necessary, prefer the Timer node and signals for readability.
* **Animation:** Utilize the `AnimationPlayer` node for complex animations. For simple animations, consider tweens.
* **Networking:** Use Godot's built-in networking API for multiplayer games. Consider using a higher-level networking library like ENet or Nakama for more advanced features.
### 2.3. Anti-patterns and Code Smells
* **God Classes:** Avoid creating large classes that handle too many responsibilities. Break them down into smaller, more focused components.
* **Tight Coupling:** Minimize dependencies between nodes. Use signals and interfaces to promote loose coupling.
* **Spaghetti Code:** Avoid deeply nested conditional statements and loops. Use functions and classes to break down complex logic into smaller, more manageable pieces.
* **Magic Numbers:** Avoid using hardcoded numbers in your code. Use constants or variables instead.
* **Premature Optimization:** Don't optimize your code before you identify performance bottlenecks. Focus on writing clear and maintainable code first.
### 2.4. State Management
* **Finite State Machines (FSMs):** Use FSMs to manage the different states of game entities, such as player characters or AI agents. This helps to organize and control complex behavior.
* **State Design Pattern:** Implement the State design pattern to encapsulate the logic for each state in separate classes or scripts. This makes it easier to add, remove, or modify states without affecting other parts of the code.
* **Hierarchical State Machines (HSMs):** For more complex state management scenarios, consider using HSMs to create nested states. This allows you to define common behavior in parent states and override it in child states as needed.
### 2.5. Error Handling
* **`assert()`:** Use `assert()` for debugging to check for conditions that should always be true. These checks are disabled in release builds.
* **`try...except` (GDScript) / `try...catch` (C#):** Use try-except/try-catch blocks to handle exceptions and prevent crashes. Handle expected errors gracefully (e.g., file not found).
* **Error Signals:** Emit custom signals to notify other nodes of errors. This allows for centralized error handling and logging.
* **Return Values:** Use return values to indicate success or failure. For example, a function that loads a file could return `OK` or `ERR_FILE_NOT_FOUND`.
* **Logging:** Use `print()` (for debugging) and a dedicated logging system (for production) to track errors and warnings. Use a custom logging system that can be disabled in release builds.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Culling:** Use frustum culling and occlusion culling to reduce the number of objects that need to be rendered.
* **Level of Detail (LOD):** Use LOD to reduce the complexity of models and textures based on their distance from the camera.
* **Batching:** Batch multiple draw calls into a single draw call to reduce the overhead of rendering.
* **Object Pooling:** Reuse objects instead of creating and destroying them frequently.
* **Optimized Data Structures:** Use appropriate data structures for your data (e.g., dictionaries for fast lookups, arrays for ordered data).
* **Profiling:** Use Godot's built-in profiler to identify performance bottlenecks.
* **Multi-threading:** Utilize multi-threading for long running operations.
* **Avoid `get_node()` in Loops:** Cache node references to avoid repeated calls to `get_node()` within loops.
* **Use Typed Arrays:** In GDScript, use Typed Arrays (e.g., `PackedByteArray`, `PackedFloat32Array`) for efficient storage and manipulation of large amounts of data.
### 3.2. Memory Management
* **Resource Management:** Load resources only when needed and unload them when they are no longer used. Use `ResourceLoader.load()` and `Resource.free()`.
* **Circular References:** Avoid circular references between objects, as this can prevent them from being garbage collected.
* **Object Pooling:** As mentioned before, use object pooling to reduce memory allocation overhead.
* **Weak References:** If you need to reference an object without preventing it from being garbage collected, use a `WeakRef`.
### 3.3. Rendering Optimization
* **Reduce Draw Calls:** Minimize the number of draw calls by using techniques such as batching and instancing.
* **Optimize Shaders:** Write efficient shaders that use the minimum number of instructions.
* **Texture Compression:** Use compressed textures to reduce memory usage and improve performance.
* **Mipmaps:** Use mipmaps to improve texture filtering quality and reduce aliasing.
* **Limit Overdraw:** Reduce overdraw by avoiding overlapping transparent objects.
* **CanvasItem Z Index:** Group similar Z index values to improve rendering performance.
### 3.4. Bundle Size Optimization
* **Compress Textures:** Use compressed textures to reduce the size of your textures.
* **Optimize Audio Files:** Use compressed audio formats such as OGG Vorbis or MP3.
* **Remove Unused Assets:** Remove any unused assets from your project.
* **Use Asset Packs:** Use asset packs to share assets between multiple projects.
* **Enable Texture Compression:** In project settings, enable texture compression for release builds.
### 3.5. Lazy Loading
* **Load Scenes Asynchronously:** Load scenes in the background to prevent the game from freezing during scene transitions. Use `ResourceLoader.load_interactive()`.
* **Stream Audio:** Stream audio files instead of loading them into memory all at once.
* **Load Resources on Demand:** Load resources only when they are needed, such as when a player enters a new area.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Injection Attacks:** Prevent SQL injection, code injection, and other injection attacks by validating all user inputs.
* **Cross-Site Scripting (XSS):** Not typically a concern for standalone games, but relevant if integrating web-based content or APIs.
* **Denial of Service (DoS):** Protect your game from DoS attacks by limiting the number of requests that can be made from a single IP address.
* **Data Tampering:** Prevent players from tampering with game data by encrypting sensitive data and validating it on the server.
* **Reverse Engineering:** Obfuscate your code to make it more difficult for players to reverse engineer your game.
### 4.2. Input Validation
* **Validate All Inputs:** Validate all user inputs, including text fields, number fields, and dropdown menus.
* **Use Regular Expressions:** Use regular expressions to validate input formats.
* **Sanitize Inputs:** Sanitize inputs to remove potentially harmful characters.
* **Limit Input Length:** Limit the length of input fields to prevent buffer overflows.
* **Client-Side and Server-Side Validation:** Implement both client-side and server-side validation to prevent malicious users from bypassing client-side checks.
### 4.3. Authentication and Authorization
* **Use Secure Authentication Protocols:** Use secure authentication protocols such as OAuth 2.0 or JWT.
* **Store Passwords Securely:** Store passwords using a strong hashing algorithm such as Argon2 or bcrypt.
* **Implement Role-Based Access Control (RBAC):** Use RBAC to control access to different parts of your game based on user roles.
* **Two-Factor Authentication (2FA):** Implement 2FA to add an extra layer of security to user accounts.
### 4.4. Data Protection
* **Encrypt Sensitive Data:** Encrypt sensitive data such as passwords, API keys, and user data using a strong encryption algorithm such as AES.
* **Use HTTPS:** Use HTTPS to encrypt communication between your game and your server.
* **Protect API Keys:** Protect your API keys from being exposed by storing them securely on the server.
* **Secure Local Storage:** If storing data locally, encrypt it to prevent unauthorized access.
### 4.5. Secure API Communication
* **Use HTTPS:** Always use HTTPS for all API communication.
* **Validate API Responses:** Validate API responses to ensure that they are valid and haven't been tampered with.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
* **API Key Rotation:** Rotate your API keys regularly to prevent them from being compromised.
* **Proper Error Handling:** Implement proper error handling to prevent sensitive information from being leaked in error messages.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Individual Components:** Write unit tests to test individual components of your game, such as functions, classes, and nodes.
* **Use a Testing Framework:** Use a testing framework such as Gut (Godot Unit Testing) to write and run your unit tests.
* **Mock Dependencies:** Mock external dependencies to isolate the component being tested.
* **Test Boundary Conditions:** Test boundary conditions and edge cases to ensure that your code handles them correctly.
### 5.2. Integration Testing
* **Test Interactions Between Components:** Write integration tests to test the interactions between different components of your game.
* **Use Realistic Scenarios:** Use realistic scenarios to test how the components work together in real-world situations.
* **Verify Data Flow:** Verify that data flows correctly between the components being tested.
### 5.3. End-to-End Testing
* **Test the Entire Game:** Write end-to-end tests to test the entire game from start to finish.
* **Automate Testing:** Automate your end-to-end tests to ensure that they are run regularly.
* **Use a Testing Tool:** Use a testing tool such as Selenium or Appium to automate your end-to-end tests.
### 5.4. Test Organization
* **Create a `test/` Directory:** Create a `test/` directory in your project to store your tests.
* **Mirror the Source Code Structure:** Mirror the source code structure in your test directory to make it easier to find the tests for a given component.
* **Use Descriptive Names:** Use descriptive names for your tests to make it clear what they are testing.
* **Keep Tests Short and Focused:** Keep your tests short and focused on testing a single aspect of the code.
### 5.5. Mocking and Stubbing
* **Use Mocks to Isolate Components:** Use mocks to replace external dependencies with controlled test doubles.
* **Use Stubs to Provide Predefined Responses:** Use stubs to provide predefined responses to external dependencies.
* **Use a Mocking Framework:** Use a mocking framework such as Moq or NSubstitute to create mocks and stubs easily.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Forgetting to Connect Signals:** Ensure that you connect signals to their handlers correctly. A common mistake is to connect the signal within the editor but forget to connect dynamically created signals in code.
* **Incorrect Node Paths:** Double-check node paths when using `get_node()`. Incorrect paths will lead to `null` references and errors.
* **Not Freeing Resources:** Remember to free resources when they are no longer needed to prevent memory leaks.
* **Using Global Variables Excessively:** Avoid using global variables excessively, as this can make your code difficult to maintain and debug.
* **Ignoring the Godot Documentation:** The Godot documentation is a valuable resource. Consult it frequently to learn about new features and best practices.
### 6.2. Edge Cases
* **Floating-Point Precision:** Be aware of floating-point precision issues when comparing floating-point numbers. Use `is_equal_approx()` instead of `==`.
* **Race Conditions:** Be aware of race conditions when using threads. Use locks and other synchronization primitives to prevent data corruption.
* **Resource Loading Errors:** Handle resource loading errors gracefully. Use `is_valid()` to check if a resource loaded successfully.
* **Input Events:** Understand the difference between different input event types (e.g., `InputEventKey`, `InputEventMouseButton`) and handle them accordingly.
### 6.3. Version-Specific Issues
* **API Changes:** Be aware of API changes between Godot versions. Consult the changelog when upgrading to a new version.
* **GDScript Compatibility:** Ensure that your GDScript code is compatible with the Godot version you are using.
* **C# Version Compatibility:** Be aware of the C# version supported by your Godot version. Ensure your code is compatible. Older versions of Godot are tied to older C# versions, new versions are tied to .NET.
### 6.4. Compatibility Concerns
* **Platform-Specific Code:** Use platform-specific code sparingly. Use conditional compilation or separate scripts for platform-specific functionality.
* **Graphics Driver Compatibility:** Test your game on different graphics drivers to ensure that it works correctly.
* **Hardware Compatibility:** Test your game on different hardware configurations to ensure that it runs smoothly.
### 6.5. Debugging Strategies
* **Use the Godot Editor Debugger:** Use the Godot editor debugger to step through your code and inspect variables.
* **Use `print()` Statements:** Use `print()` statements to log information to the console.
* **Use the Remote Debugger:** Use the remote debugger to debug your game on a different device.
* **Attach a C# Debugger:** Attach a C# debugger (e.g., Visual Studio Debugger) to your project to debug C# code.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **Godot Editor:** The official Godot Engine editor.
* **Visual Studio Code:** A popular code editor with excellent support for GDScript and C#.
* **Visual Studio:** A powerful IDE for C# development, commonly used for Godot C# projects.
* **Git:** A version control system for tracking changes to your code.
* **GitHub/GitLab/Bitbucket:** Online repositories for storing and collaborating on your code.
### 7.2. Build Configuration
* **Project Settings:** Configure your project settings carefully, including input maps, rendering settings, and export settings.
* **Custom Build Steps:** Use custom build steps to automate tasks such as asset processing and code generation.
* **Export Templates:** Create export templates for different platforms to optimize your game for each platform.
### 7.3. Linting and Formatting
* **GDScript Linter:** Use a GDScript linter to check your code for style errors and potential problems. Consider creating a custom linter rule set.
* **C# Code Style:** Configure Visual Studio or VS Code to automatically format your C# code according to the C# coding conventions.
* **EditorConfig:** Use an EditorConfig file to define coding style settings for your project.
### 7.4. Deployment
* **Exporting:** Use Godot's export functionality to create builds for different platforms.
* **Distribution Platforms:** Distribute your game through platforms such as Steam, Itch.io, Google Play Store, and Apple App Store.
* **Consider platform-specific requirements:** Each platform has specific requirements for builds. For example, you will need developer accounts, store assets, and signed builds.
* **Auto-updating:** Using auto-updating on desktop builds can improve the player experience for long running projects.
### 7.5. CI/CD Integration
* **Automated Builds:** Set up a CI/CD pipeline to automatically build and test your game whenever you commit changes to your code repository.
* **Automated Testing:** Integrate your unit tests, integration tests, and end-to-end tests into your CI/CD pipeline.
* **Automated Deployment:** Automate the deployment of your game to different distribution platforms.
* **Use cloud build services:** Services such as GitHub actions, GitLab CI, and cloud build are capable of fully automating the deployment process.
## 8. GDScript Style Guide Summary
This section summarizes key GDScript style guide recommendations.
* **Formatting:**
* Use LF line endings, UTF-8 encoding, and tabs for indentation (editor default).
* Limit line length to 100 characters (preferably 80).
* Use one statement per line.
* Format multiline statements for readability using parentheses.
* Avoid unnecessary parentheses.
* Use plain English boolean operators (`and`, `or`, `not`).
* Use whitespace around operators and after commas.
* Use double quotes for strings unless single quotes avoid escapes.
* Don't omit leading or trailing zeros in floating-point numbers.
* Use lowercase for letters in hexadecimal numbers.
* Use underscores in literals for large numbers.
* **Naming Conventions:**
* Files: `snake_case.gd`
* Classes: `PascalCase`
* Nodes: `PascalCase`
* Functions: `snake_case`
* Variables: `snake_case`
* Signals: `snake_case` (past tense)
* Constants: `CONSTANT_CASE`
* Enums: `PascalCase` (names), `CONSTANT_CASE` (members)
* **Code Order (within a script):**
1. `@tool`
2. `class_name`
3. `extends`
4. Docstring (`## comment`)
5. Signals
6. Enums
7. Constants
8. `@export` variables
9. Public variables
10. Private variables
11. `@onready` variables
12. `_init()`
13. `_enter_tree()`
14. `_ready()`
15. Other virtual methods
16. Public methods
17. Private methods
18. Subclasses
* **Static Typing:**
* Use explicit type hints (`: Type`) when the type is ambiguous or for clarity.
* Use inferred types (`:=`) when the type is obvious from the assignment.
By following these best practices and coding standards, you can create more maintainable, efficient, and secure Godot Engine projects.
+262
View File
@@ -0,0 +1,262 @@
---
description: This rule provides guidelines for Google Maps JavaScript API development, covering code organization, performance, security, testing, and common pitfalls. It promotes best practices to ensure efficient, secure, and maintainable map applications.
globs: **/*.{js,jsx,ts,tsx,html,css}
---
# Google Maps JavaScript API Best Practices
This document outlines best practices for developing applications using the Google Maps JavaScript API. Following these guidelines will help you create efficient, maintainable, and secure mapping solutions.
## 1. Code Organization and Structure
### 1.1. Directory Structure
Adopt a clear and consistent directory structure to improve code maintainability and collaboration. A suggested structure is:
project-root/
src/
components/
MapComponent.js # or .jsx, .ts, .tsx
MarkerComponent.js
InfoWindowComponent.js
services/
mapService.js # Handles API calls and data processing
geolocationService.js
utils/
utils.js # Helper functions
styles/
MapComponent.css
App.js # Main application component
public/
index.html # HTML entry point
.env # API keys and environment variables
package.json # Dependencies and scripts
webpack.config.js # or equivalent
### 1.2. File Naming Conventions
* **Components:** Use PascalCase (e.g., `MapComponent.js`).
* **Services/Utilities:** Use camelCase (e.g., `mapService.js`, `geolocationService.js`).
* **Styles:** Match component names (e.g., `MapComponent.css`).
* **Images/Assets:** Use kebab-case (e.g., `custom-marker.png`).
### 1.3. Module Organization
* **ES Modules:** Use `import` and `export` for modularity.
* **Single Responsibility Principle:** Each module should have a specific purpose.
* **Avoid Circular Dependencies:** Refactor code to eliminate circular dependencies between modules.
### 1.4. Component Architecture
* **Component-Based Approach:** Break down the UI into reusable components (Map, Marker, InfoWindow, etc.).
* **Presentational and Container Components:** Separate concerns: presentational components focus on UI, while container components handle logic and data.
* **Props and State:** Use props to pass data down to components and state to manage component-specific data.
### 1.5. Code Splitting
* **Dynamic Imports:** Use dynamic imports (`import()`) to load map-related code chunks on demand.
* **Webpack/Parcel/Rollup:** Configure your bundler to create separate chunks for different parts of the application.
* **Route-Based Splitting:** If the map is only used on specific routes, load the map-related code only when the route is accessed.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Observer Pattern:** Use the Observer pattern to handle map events (e.g., marker clicks, map bounds changes). This decouples event sources from event handlers.
* **Singleton Pattern:** Use a Singleton pattern (carefully) for global map services to ensure a single instance across the application. Be mindful of testability.
* **Factory Pattern:** Employ the Factory pattern to create different types of markers or overlays based on data.
### 2.2. Recommended Approaches for Common Tasks
* **Loading the API:** Asynchronously load the Google Maps JavaScript API using a Promise. Use `async/await` syntax for cleaner code.
* **Marker Management:** Use a data-driven approach for marker creation and updates. Store marker data in an array and iterate over it to create markers.
* **InfoWindows:** Create InfoWindow instances outside of loops to avoid memory leaks. Update the content of the existing InfoWindow instead of creating new ones.
* **Event Handling:** Use event listeners provided by the API (e.g., `map.addListener('click', ...)`). Avoid inline event handlers.
### 2.3. Anti-patterns and Code Smells
* **Direct DOM Manipulation:** Avoid directly manipulating the DOM inside map components. Use the API's methods for adding and updating elements.
* **Global Variables:** Minimize the use of global variables to prevent naming conflicts and improve code encapsulation.
* **Nested Callbacks:** Avoid deeply nested callbacks (callback hell). Use Promises and `async/await` for asynchronous operations.
* **Tight Coupling:** Design components to be loosely coupled, making them easier to test and reuse.
### 2.4. State Management
* **Local Component State:** Use React's `useState` hook or similar for component-specific state.
* **Context API:** Use the Context API for sharing global map configurations or data across components.
* **Redux/Mobx:** For larger applications, consider using a state management library like Redux or Mobx to manage complex application state.
### 2.5. Error Handling
* **API Loading Errors:** Handle errors that occur during API loading (e.g., invalid API key, network issues).
* **Geolocation Errors:** Gracefully handle geolocation errors (e.g., user denied permission, browser doesn't support geolocation).
* **Try-Catch Blocks:** Use `try-catch` blocks to catch and handle exceptions during API calls and data processing.
* **User Notifications:** Display user-friendly error messages instead of crashing the application.
* **Logging:** Implement logging to track errors and debug issues.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Raster Images for Markers:** Use raster images (PNG, JPG) instead of SVG for a large number of custom markers (hundreds or more) for optimal performance.
* **Marker Clustering:** Implement marker clustering for maps with a high density of markers. Libraries like `markerclustererplus` can help.
* **Viewport Optimization:** Only render markers and overlays that are visible within the current viewport (map bounds). This reduces the number of DOM elements and improves rendering performance.
* **Debouncing/Throttling:** Use debouncing or throttling to limit the frequency of map updates in response to user interactions (e.g., panning, zooming).
* **Custom Overlays Judiciously:** Be mindful when using custom overlays. Avoid heavy computations in the `OverlayView.draw()` method, as it's called on every pan and zoom. Defer adding and removing content until the map is stationary.
### 3.2. Memory Management
* **Remove Event Listeners:** Remove event listeners when they are no longer needed to prevent memory leaks.
* **Release Resources:** Release resources (e.g., marker instances, InfoWindow instances) when they are no longer in use.
* **Avoid Unnecessary DOM Updates:** Minimize the number of DOM updates to improve rendering performance.
### 3.3. Rendering Optimization
* **Hardware Acceleration:** Ensure that hardware acceleration is enabled in the browser for smoother map rendering.
* **CSS Transitions:** Use CSS transitions for smooth animations when updating map elements.
* **WebGL:** Explore WebGL features for advanced visualizations and rendering (if applicable).
### 3.4. Bundle Size Optimization
* **Tree Shaking:** Use tree shaking to remove unused code from the bundle. Ensure your bundler is configured correctly for tree shaking.
* **Code Splitting:** Split the code into smaller chunks to reduce the initial load time.
* **Minification:** Minify the code to reduce the bundle size.
* **Compression:** Compress the bundle using Gzip or Brotli.
### 3.5. Lazy Loading
* **Lazy Loading of Map Component:** Load the map component only when it is needed (e.g., when a specific route is accessed).
* **Lazy Loading of Markers:** Load markers only when they are visible within the viewport.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **API Key Exposure:** Protect your API key and prevent it from being exposed in client-side code or version control. Restrict API key usage to specific domains or IP addresses.
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
* **Clickjacking:** Protect against clickjacking attacks by setting the `X-Frame-Options` header.
* **Data Injection:** Validate data received from the Google Maps API to prevent data injection attacks.
### 4.2. Input Validation
* **Validate User Input:** Validate user input (e.g., addresses, coordinates) before passing it to the Google Maps API.
* **Sanitize Data:** Sanitize data received from the Google Maps API before displaying it to the user.
* **Rate Limiting:** Implement rate limiting to prevent abuse of the API.
### 4.3. Authentication and Authorization
* **Secure API Key Storage:** Never store API keys directly in client-side code. Use environment variables or a backend proxy to manage API keys.
* **Restrict API Key Usage:** Restrict API key usage to specific domains or IP addresses in the Google Cloud Console.
* **Backend Authentication:** Implement backend authentication for sensitive operations (e.g., geocoding, directions). This prevents unauthorized access to the API.
### 4.4. Data Protection
* **HTTPS:** Always use HTTPS to encrypt data transmitted between the client and the server.
* **Data Encryption:** Encrypt sensitive data stored on the server.
* **Data Minimization:** Only collect and store the data that is necessary for the application.
### 4.5. Secure API Communication
* **Use HTTPS:** Always use HTTPS for API requests.
* **Validate Responses:** Validate the responses received from the API.
* **Handle Errors:** Properly handle errors returned by the API.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Individual Components:** Write unit tests for individual map components (MapComponent, MarkerComponent, etc.).
* **Mock API Calls:** Mock API calls to isolate components from external dependencies.
* **Test Event Handling:** Test event handling logic (e.g., marker click events).
### 5.2. Integration Testing
* **Test Component Interactions:** Write integration tests to verify that components work together correctly.
* **Test API Integrations:** Test the integration with the Google Maps API.
* **Use a Test Environment:** Use a test environment to avoid making changes to the production environment.
### 5.3. End-to-End Testing
* **Simulate User Interactions:** Simulate user interactions to test the entire application flow.
* **Verify Functionality:** Verify that the application functions as expected.
* **Use a Testing Framework:** Use a testing framework like Cypress or Puppeteer for end-to-end testing.
### 5.4. Test Organization
* **Directory Structure:** Maintain a clear directory structure for tests.
* **Test Naming:** Use descriptive names for tests.
* **Test Descriptions:** Provide clear descriptions of what each test does.
### 5.5. Mocking and Stubbing
* **Mock the Google Maps API:** Mock the Google Maps API to isolate components during testing.
* **Use Mocking Libraries:** Use mocking libraries like Jest or Sinon to create mocks and stubs.
* **Control Test Data:** Use stubs to control the data returned by the API during testing.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Forgetting to Enable Billing:** Ensure that billing is enabled for your Google Maps Platform project.
* **Exceeding API Usage Limits:** Monitor API usage and optimize code to avoid exceeding usage limits.
* **Using Deprecated Features:** Avoid using deprecated features of the API.
* **Ignoring Browser Compatibility:** Test the application in different browsers to ensure compatibility.
### 6.2. Edge Cases
* **Handling No Geolocation Support:** Gracefully handle the case where the browser doesn't support geolocation.
* **Handling Network Errors:** Handle network errors that occur during API calls.
* **Handling Invalid Data:** Handle invalid data returned by the API.
### 6.3. Version-Specific Issues
* **Check the API Version:** Be aware of the API version you are using and any version-specific issues.
* **Read the Release Notes:** Read the release notes for new versions of the API to be aware of any changes.
### 6.4. Compatibility Concerns
* **Library Conflicts:** Avoid using libraries that are known to conflict with the Google Maps JavaScript API (e.g., Prototype, older versions of MooTools and DateJS).
* **CSS Conflicts:** Avoid CSS conflicts by using specific CSS classes for map elements and avoiding overriding internal API styles.
### 6.5. Debugging Strategies
* **Use Browser Developer Tools:** Use browser developer tools to debug JavaScript code, inspect network requests, and analyze performance.
* **Check the Console:** Check the console for error messages and warnings.
* **Use Debugging Tools:** Use debugging tools like `console.log` or a debugger to step through the code and inspect variables.
* **Read the Documentation:** Refer to the Google Maps JavaScript API documentation for troubleshooting information.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **Code Editor:** Use a code editor like VS Code, Sublime Text, or Atom.
* **Browser Developer Tools:** Use browser developer tools for debugging and performance analysis.
* **Bundler:** Use a bundler like Webpack, Parcel, or Rollup.
* **Linting Tools:** Use linting tools like ESLint to enforce code style and identify potential errors.
### 7.2. Build Configuration
* **Configure the Bundler:** Configure the bundler to optimize code for production (e.g., minification, compression).
* **Use Environment Variables:** Use environment variables to manage API keys and other configuration settings.
* **Set Up Build Scripts:** Set up build scripts to automate the build process.
### 7.3. Linting and Formatting
* **ESLint:** Use ESLint to enforce code style and identify potential errors.
* **Prettier:** Use Prettier to automatically format code.
* **Code Style Guide:** Follow a consistent code style guide (e.g., Airbnb, Google).
### 7.4. Deployment
* **Deploy to a Web Server:** Deploy the application to a web server (e.g., Netlify, Vercel, AWS S3).
* **Use HTTPS:** Ensure that the application is served over HTTPS.
* **Configure Caching:** Configure caching to improve performance.
### 7.5. CI/CD Integration
* **Set Up a CI/CD Pipeline:** Set up a CI/CD pipeline to automate the build, test, and deployment process.
* **Use a CI/CD Tool:** Use a CI/CD tool like Jenkins, Travis CI, or CircleCI.
* **Automated Testing:** Automate testing as part of the CI/CD pipeline.
By following these best practices, you can develop robust, efficient, and maintainable Google Maps JavaScript API applications.
+141
View File
@@ -0,0 +1,141 @@
---
description: Comprehensive rules for Gradle best practices, covering code organization, performance, security, testing, and more. Provides actionable guidance to improve Gradle project maintainability and efficiency.
globs: **/*.gradle*
---
- **Use the Gradle Wrapper**: Always use the Gradle wrapper (`gradlew` and `gradlew.bat`) to ensure consistent Gradle versions across different environments. This avoids compatibility issues and simplifies collaboration.
- Command: `gradle wrapper` to generate the wrapper files.
- **Organize Build Files**: Maintain a clear structure by separating project-level (`build.gradle` in the root) and module-level (`build.gradle` in each module) build files. Use `settings.gradle` (or `settings.gradle.kts` for Kotlin DSL) to define included modules.
- Improves performance by avoiding unnecessary directory searches.
- Ensures proper project inclusion in multi-module builds.
- **Optimize Build Performance**: Employ several strategies to improve build speed:
- **Enable parallel builds**: Add `org.gradle.parallel=true` to `gradle.properties`.
- **Use build caching**: Add `org.gradle.caching=true` to `gradle.properties`.
- **Configure daemon**: Add `org.gradle.daemon=true` to `gradle.properties` (typically enabled by default).
- **Minimize dynamic dependencies**: Use fixed versions instead of ranges or `latest.release`.
- **Configure JVM Memory**: Set appropriate JVM memory in `gradle.properties` like `org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g`
- **Incremental build**: Avoid `gradle clean` unless absolutely necessary to leverage incremental build feature.
- **Configure task inputs and outputs**: Declare task inputs and outputs properly to enable up-to-date checks and caching.
- **Security Practices**: Protect sensitive information by:
- **Storing credentials in `gradle.properties`**: Exclude `gradle.properties` from version control (add it to `.gitignore`).
- **Using environment variables**: Access credentials from environment variables during the build process for CI/CD environments.
- **Avoiding hardcoding secrets**: Never hardcode API keys, passwords, or other sensitive data in build files or source code.
- **Automate Code Standards**: Implement custom Gradle tasks or plugins to enforce coding standards:
- **Use linting tools**: Integrate linters (e.g., Checkstyle, SpotBugs, PMD) into the build process.
- **Enforce code formatting**: Use code formatters (e.g., ktlint for Kotlin) and enforce formatting rules.
- **Create custom tasks**: Define custom tasks to check for specific code patterns or enforce project-specific rules.
- **Separate Source Files**: Organize source files by language (e.g., `src/main/java`, `src/main/kotlin`) and test type (e.g., `src/test/java`, `src/integrationTest/java`).
- Improves readability and maintainability.
- Enables independent execution of different test types.
- **Use Standard Conventions**: Stick to Gradle's default conventions as much as possible.
- Simplifies project structure and reduces configuration overhead.
- Makes it easier for new developers to understand the project.
- **Always Define a Settings File**: Include `settings.gradle` (or `settings.gradle.kts`) in the root directory to avoid performance impacts during project discovery.
- Explicitly defines the project name and included subprojects.
- **Use `buildSrc` to Abstract Imperative Logic**: Encapsulate complex build logic in the `buildSrc` directory.
- `buildSrc` is treated as an included build, automatically compiled and added to the build script classpath.
- Provides a clean separation of concerns and improves code reusability.
- Easier to maintain, refactor, and test the code in `buildSrc`.
- **Declare Properties in `gradle.properties` File**: Store build configuration properties in `gradle.properties` rather than in build scripts.
- Improves build script readability and maintainability.
- Allows for easy modification of build properties without changing the build script.
- **Avoid Overlapping Task Outputs**: Ensure that tasks write outputs to unique directories to prevent conflicts and ensure proper up-to-date checking.
- Prevents Gradle's build cache from being compromised.
- **Standardize Builds with a Custom Gradle Distribution**: Create a custom Gradle distribution with initialization scripts to enforce common conventions and rules across all projects in an organization.
- Ensures consistent build environments and simplifies maintenance.
- **Stop Cleaning Your Project (Unless Necessary)**: Avoid running `gradle clean` unnecessarily, as it prevents Gradle from using incremental build features and significantly slows down the build process.
- **Move Tasks to `buildSrc`**: Move custom task definitions to the `buildSrc` directory to keep build scripts clean and reusable.
- **Run Tests in Parallel**: Enable parallel test execution to reduce test execution time:
- Add `maxParallelForks = <number_of_cores>` to the `test` task configuration in `build.gradle`.
- **Version Your Project**: Use a versioning scheme (e.g., semantic versioning) to track changes and releases.
- Use plugins like `axion-release` to automate versioning based on Git tags.
- **Encapsulate Task Declarations in a Plugin**: Move task declarations into custom Gradle plugins to promote reusability and reduce duplication.
- **Use the Latest Gradle Version**: Keep Gradle updated to benefit from performance improvements, new features, and security patches.
- **Optimize Your Repositories**: Declare repositories in the correct order to avoid unnecessary network requests.
- List frequently accessed repositories first.
- **Never Commit Passwords**: Externalize credentials using `gradle.properties` or environment variables.
- **Adopt Kotlin DSL**: Favor Kotlin DSL (`build.gradle.kts`) over Groovy DSL (`build.gradle`). Kotlin DSL provides type safety, better IDE support, and improved code completion.
- **Dependency Management**:
- **Use dependency catalogs**: Define dependencies in a central `libs.versions.toml` file for consistent dependency management across modules (available with Gradle 7.4+).
- **Avoid dynamic versions**: Always use explicit dependency versions to ensure reproducible builds.
- **Check for dependency updates**: Use dependency analysis tools to identify outdated dependencies and security vulnerabilities.
- **Code Organization and Structure (Expanded)**:
- **Directory Structure**: Adhere to standard directory structures, such as `src/main/java` for Java source code, `src/main/resources` for resources, `src/test/java` for unit tests, and `src/integrationTest/java` for integration tests.
- **File Naming**: Follow consistent naming conventions for Gradle files (e.g., `build.gradle`, `settings.gradle`, `gradle.properties`).
- **Module Organization**: Organize projects into modules based on functionality or feature sets. This promotes code reuse, improves build times, and allows for more granular dependency management.
- **Component Architecture**: Consider using component-based architectures to isolate independent parts of your code. Each component has its own build file, source folder, and dependencies. This promotes modularity and reusability.
- **Code Splitting**: Decompose complex build scripts and tasks into smaller, more manageable pieces.
- **Common Patterns and Anti-patterns (Expanded)**:
- **Dependency Injection**: Leverage dependency injection frameworks (e.g., Dagger, Guice) to manage dependencies in custom tasks and plugins.
- **Declarative Configuration**: Prefer declarative configuration over imperative scripting. This promotes readability and simplifies maintenance.
- **Avoid Global State**: Minimize the use of global state in custom tasks and plugins to prevent unintended side effects.
- **Tight Coupling**: Avoid tight coupling between build logic and application code. This promotes modularity and testability.
- **Performance Considerations (Expanded)**:
- **Configuration Avoidance**: Use `afterEvaluate` sparingly, as it can delay configuration and impact build performance. Consider using configuration caching instead.
- **Task Ordering**: Ensure tasks are executed in the correct order. Inappropriate task dependencies slow down the build process.
- **Testing Approaches (Expanded)**:
- **Test Organization**: Organize tests in a clear and consistent manner. Follow a similar directory structure as source code (e.g., `src/test/java`).
- **Test Doubles**: Use mocking and stubbing techniques to isolate units of code for testing. Libraries like Mockito and PowerMock facilitate test double creation. Use carefully PowerMock, as can be problematic.
- **Tooling and Environment (Expanded)**:
- **Android Studio**: Use Android Studio as the primary IDE for Android projects. It offers excellent Gradle integration and debugging support.
- **CI/CD Integration**: Integrate Gradle builds with CI/CD systems (e.g., Jenkins, GitLab CI, GitHub Actions) to automate testing and deployment processes.
- **Code Analysis Tools**: Integrate code analysis tools (e.g., SonarQube) into the build process to identify code quality issues and security vulnerabilities.
- **IDE plugins**: Use IDE plugins, such as the Gradle build scan plugin, to analyze and optimize build performance.
- **Common Pitfalls and Gotchas (Expanded)**:
- **Dependency Conflicts**: Be aware of potential dependency conflicts and use dependency resolution strategies to manage them.
- **Cache Invalidation**: Understand how Gradle's build cache works and how to invalidate it when necessary.
- **Plugin Compatibility**: Ensure compatibility between Gradle versions and plugins. Upgrade plugins carefully.
- **Daemon issues**: The gradle daemon sometime cause unexplainable build errors. Restarting or stopping it can solve some build issues.
- **Android Specific Best Practices**:
- **Resource Management**: Optimize image resources to reduce APK size. Use vector drawables where possible.
- **Proguard/R8**: Use Proguard (or R8) to shrink and obfuscate code in release builds.
- **APK Analyzer**: Use APK Analyzer to inspect the contents of APK files and identify areas for optimization.
- **Build variants**: Use build variants to create different versions of the app for different purposes (e.g., debug, release, flavor-specific).
- **Multi-project Builds**:
- **Centralized Dependency Management:** Manage dependencies centrally within the root project or through a convention plugin, applying these dependencies to child modules. This promotes consistency and simplifies dependency updates.
- **Convention Plugins:** Create custom plugins that apply common configurations (dependencies, plugins, settings) to all subprojects. This reduces code duplication and improves maintainability.
- **Composite Builds:** Use composite builds (including local projects in your build) for collaborative development or when working on multiple projects simultaneously.
- **Kotlin DSL Specific Best Practices**:
- **Explicit Typing**: Use explicit typing to leverage Kotlin's type safety and improve code readability.
- **Extension Functions**: Define extension functions to extend the Gradle API and add custom functionality.
- **Coroutines:** Utilize Kotlin coroutines for asynchronous operations in custom tasks and plugins.
- **Monitoring and Observability**:
- **Gradle Build Scans:** Use Gradle Build Scans (using `--scan`) to capture detailed build information, analyze performance bottlenecks, and identify areas for improvement.
- **Custom Metrics:** Implement custom metrics to track key build statistics (build duration, task execution times) and monitor build health.
- **Continuous Improvement:**
- **Regular Audits:** Perform regular audits of Gradle build configurations and scripts to identify areas for optimization and improvement.
- **Stay Updated:** Keep abreast of the latest Gradle releases, best practices, and community recommendations.
- **Share Knowledge:** Document Gradle build configurations, custom tasks, and plugins. Share knowledge and best practices with other team members.
By adhering to these best practices, developers can create robust, maintainable, and efficient Android applications using Gradle as their build tool.
+5
View File
@@ -0,0 +1,5 @@
---
description: Comprehensive guide for Grafana development best practices, covering code organization, performance, security, testing, and common pitfalls to ensure robust and maintainable Grafana solutions. Includes guidance for creating efficient dashboards, data sources, and plugins.
globs: **/*.{ts,tsx,js,jsx,json,yml,yaml,md,mdc}
---
By adhering to these comprehensive best practices, you can build robust, maintainable, and secure Grafana solutions that provide valuable insights into your data and systems.
+118
View File
@@ -0,0 +1,118 @@
---
description: Comprehensive best practices and coding standards for developing, deploying, and maintaining applications on the Heroku platform. This rule emphasizes the Twelve-Factor App methodology and provides detailed guidance for optimizing application architecture, performance, security, and maintainability on Heroku.
globs: **/*
---
- Follow the Twelve-Factor App methodology for building software-as-a-service applications.
- **Codebase:** Maintain a single codebase tracked in version control (e.g., Git) for each application. Multiple deploys should be created from this single codebase.
- **Dependencies:** Explicitly declare and isolate dependencies using a dependency management tool (e.g., `requirements.txt` for Python, `package.json` for Node.js, `Gemfile` for Ruby).
- **Config:** Store configuration settings (database credentials, API keys, etc.) in environment variables. Avoid hardcoding configuration values in the application code.
- **Backing Services:** Treat backing services (databases, message queues, caches) as attached resources accessed via URLs or connection strings.
- **Build, Release, Run:** Strictly separate the build, release, and run stages. Build creates the executable, release combines the build with the config, and run executes the release in the execution environment.
- **Processes:** Execute the application as one or more stateless processes. Persist data in backing services.
- **Port Binding:** Export services via port binding. The application should be self-contained and listen for requests on a port.
- **Concurrency:** Scale out via the process model. Use multiple processes to handle concurrency.
- **Disposability:** Maximize robustness with fast startup and graceful shutdown.
- **Dev/Prod Parity:** Keep development, staging, and production environments as similar as possible.
- **Logs:** Treat logs as event streams. Write logs to standard output, and let the platform handle aggregation.
- **Admin Processes:** Run admin/management tasks as one-off processes.
- **Code Organization and Structure:**
- **Directory Structure:** Organize your project with a clear directory structure. Examples:
- `/`: Project root
- `/app`: Application source code
- `/config`: Configuration files
- `/tests`: Unit and integration tests
- `/scripts`: Deployment and maintenance scripts
- `/docs`: Documentation
- **File Naming Conventions:** Use descriptive and consistent file names (e.g., `user_model.py`, `user_controller.js`).
- **Module Organization:** Break down your application into modular components with well-defined interfaces.
- **Component Architecture:** Use a component-based architecture to promote code reuse and maintainability. Consider using frameworks like React, Angular, or Vue.js for front-end development.
- **Code Splitting:** Implement code splitting to reduce initial load times. Load modules on demand.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:** Use established design patterns (e.g., MVC, Observer, Factory) to structure your code.
- **Recommended Approaches:** Use environment variables for configuration, stateless processes, and logging to stdout.
- **Anti-patterns:** Avoid hardcoding configuration values, sticky sessions, and relying on local file storage for persistent data.
- **State Management:** Choose a state management solution appropriate for your application (e.g., Redux, Vuex, Context API) to handle global application state.
- **Error Handling:** Implement robust error handling with try-except blocks and logging of exceptions. Use a centralized error reporting system (e.g., Sentry, Rollbar) to track errors in production.
- **Performance Considerations:**
- **Optimization Techniques:** Use caching (e.g., Redis, Memcached) to reduce database load. Optimize database queries. Use asynchronous tasks for long-running operations.
- **Memory Management:** Avoid memory leaks by properly managing resources. Use garbage collection tools to identify and fix memory issues.
- **Rendering Optimization:** Optimize front-end rendering by minimizing DOM manipulations and using techniques like virtual DOM.
- **Bundle Size Optimization:** Reduce bundle size by minifying code, removing unused code, and using tree shaking.
- **Lazy Loading:** Implement lazy loading for images, modules, and other resources to improve initial load times.
- **Security Best Practices:**
- **Common Vulnerabilities:** Prevent common vulnerabilities like SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).
- **Input Validation:** Validate all user inputs to prevent malicious data from entering your application.
- **Authentication and Authorization:** Implement secure authentication and authorization mechanisms (e.g., OAuth, JWT). Use HTTPS to encrypt all communication.
- **Data Protection:** Encrypt sensitive data at rest and in transit. Use strong passwords and secure password storage.
- **Secure API Communication:** Validate API requests, use rate limiting to prevent abuse, and secure API keys.
- **Testing Approaches:**
- **Unit Testing:** Write unit tests for individual components to ensure they function correctly.
- **Integration Testing:** Write integration tests to verify the interaction between different components.
- **End-to-end Testing:** Write end-to-end tests to simulate user interactions and verify the application as a whole.
- **Test Organization:** Organize your tests in a clear and maintainable structure. Use test runners like Jest, Mocha, or pytest.
- **Mocking and Stubbing:** Use mocking and stubbing to isolate components during testing.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:** Forgetting to configure environment variables, deploying code without testing, and not handling errors properly.
- **Edge Cases:** Be aware of edge cases like slow network connections, unexpected user inputs, and resource limitations.
- **Version-Specific Issues:** Check for version-specific issues in the Heroku documentation and release notes.
- **Compatibility Concerns:** Ensure compatibility between Heroku and the technologies you are using (e.g., language versions, database drivers).
- **Debugging Strategies:** Use logging, debugging tools (e.g., Heroku logs, remote debugging), and error reporting systems to diagnose issues.
- **Tooling and Environment:**
- **Recommended Development Tools:** Use a code editor like VS Code or Sublime Text, a version control system like Git, and a dependency management tool appropriate for your language.
- **Build Configuration:** Configure your build process using buildpacks or Dockerfiles.
- **Linting and Formatting:** Use linters and formatters (e.g., ESLint, Prettier) to enforce code style and catch errors.
- **Deployment Best Practices:** Use Heroku CLI for deployment. Automate deployments using CI/CD.
- **CI/CD Integration:** Integrate your application with a CI/CD pipeline (e.g., GitHub Actions, CircleCI, Travis CI) for automated testing and deployment.
- **Specific Heroku Considerations**
- **Dynos:** Understand the different types of dynos available on Heroku and choose the appropriate dyno type for your application.
- **Buildpacks:** Use buildpacks to automatically configure your application's environment on Heroku. You can also create custom buildpacks.
- **Add-ons:** Use Heroku add-ons to easily integrate third-party services into your application (e.g., databases, caching, logging).
- **Heroku CLI:** Familiarize yourself with the Heroku CLI for managing your applications, databases and deployments.
- **Procfile:** Use a Procfile to define the processes that run in your application. This typically includes web, worker, and other processes.
- **Continuous Integration/Continuous Deployment (CI/CD)**
- Implement a robust CI/CD pipeline for automated testing and deployment.
- Use tools like GitHub Actions, CircleCI, or Jenkins to automate the build, test, and deploy processes.
- Configure automated testing to run on every code commit.
- Implement automated deployment to staging and production environments.
- Use feature flags to enable continuous deployment without breaking changes to production code.
- **Monitoring and Logging**
- Use Heroku's built-in logging capabilities to monitor application performance and identify errors.
- Integrate with third-party logging services like Sumo Logic, Datadog, or New Relic for advanced monitoring and analytics.
- Set up alerts for critical errors and performance issues.
- Use log aggregation tools to centralize and analyze logs from multiple dynos.
- **Scaling and Performance**
- Monitor application performance metrics to identify bottlenecks.
- Scale dynos horizontally to handle increased traffic.
- Use caching strategies to reduce database load and improve response times.
- Optimize database queries and indexes.
- Implement load balancing to distribute traffic across multiple dynos.
- **Security Hardening**
- Implement robust security measures to protect against common web vulnerabilities.
- Use HTTPS to encrypt all communication between clients and the server.
- Implement proper input validation and output encoding to prevent XSS and SQL injection attacks.
- Use a Content Security Policy (CSP) to restrict the sources of content that can be loaded by the browser.
- Protect against CSRF attacks by implementing CSRF tokens.
- Regularly update dependencies to patch security vulnerabilities.
- Conduct regular security audits to identify and address potential security weaknesses.
- **Database Management**
- Choose the appropriate database for your application's needs (e.g., PostgreSQL, MySQL, MongoDB).
- Use database connection pooling to improve performance.
- Optimize database queries and indexes.
- Implement database backups and recovery strategies.
- Use database migrations to manage schema changes.
- Secure database credentials and access.
By adhering to these best practices, developers can build and maintain robust, scalable, and secure applications on the Heroku platform.
+255
View File
@@ -0,0 +1,255 @@
---
description: This rule provides comprehensive best practices for using the httpx library, covering code organization, performance, security, testing, and common pitfalls. Adhering to these guidelines will improve code quality, maintainability, and security when working with httpx.
globs: **/*.py
---
# httpx Best Practices
This document outlines recommended practices for using the `httpx` library in Python. Following these guidelines will help ensure maintainable, performant, and secure code.
## Library Information:
- Name: httpx
- Tags: web, python, http-client, async
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
- **Dedicated Modules:** Organize httpx-related code into dedicated modules or packages.
- **Configuration:** Separate configuration settings (timeouts, headers, proxies) from the core logic.
- **Data Models:** Define data models (e.g., using `dataclasses` or `pydantic`) to represent request and response data.
Example:
my_project/
├── httpx_client/
│ ├── __init__.py
│ ├── client.py # httpx client setup, session management
│ ├── utils.py # Utility functions for request/response handling
│ ├── models.py # Data models for requests and responses
│ └── exceptions.py # Custom exceptions
├── ...
### 1.2 File Naming Conventions
- Use descriptive names that reflect the file's purpose (e.g., `api_client.py`, `request_utils.py`).
- Follow PEP 8 conventions (snake_case).
### 1.3 Module Organization
- **Layered Architecture:** Consider a layered architecture with modules for:
- **Client Initialization:** Handles httpx client setup (connection pooling, timeouts).
- **Request Building:** Constructs httpx Request objects.
- **Response Handling:** Parses and validates responses, handles errors.
- **Abstraction:** Abstract away direct httpx calls behind service functions or classes.
### 1.4 Component Architecture
- **Reusable Components:** Design reusable components for common tasks like:
- **Authentication:** Implementing custom authentication flows.
- **Rate Limiting:** Managing API rate limits.
- **Retry Logic:** Handling transient errors with retry mechanisms.
### 1.5 Code Splitting Strategies
- **Feature-Based Splitting:** Split code based on features or API endpoints.
- **Abstraction:** Use interfaces or abstract base classes for httpx clients to facilitate mocking and testing.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
- **Factory Pattern:** Use a factory function or class to create httpx clients with different configurations.
- **Strategy Pattern:** Implement different request strategies based on the API requirements.
### 2.2 Recommended Approaches for Common Tasks
- **Client Instance Usage:** Always use `httpx.Client()` or `httpx.AsyncClient()` for making requests. This enables connection pooling.
- **Context Managers:** Use the client as a context manager (`with httpx.Client() as client:`) or explicitly close the connection pool (`client.close()`).
- **Timeouts:** Always set timeouts to prevent hanging requests.
- **Error Handling:** Use `try-except` blocks to handle `HTTPStatusError` and `RequestError`.
- **Async Support:** Utilize `httpx.AsyncClient()` for concurrent requests.
- **Configuration Sharing:** Configure default headers, parameters, and authentication at the client level.
python
import httpx
with httpx.Client(timeout=10.0, headers={'User-Agent': 'MyApp/1.0'}) as client:
try:
response = client.get('https://example.com/api/data')
response.raise_for_status() # Raise HTTPStatusError for bad responses (4xx or 5xx)
data = response.json()
# Process data
except httpx.HTTPStatusError as e:
print(f"HTTP Error: {e}")
except httpx.RequestError as e:
print(f"Request Error: {e}")
### 2.3 Anti-patterns and Code Smells
- **Global Client Instances:** Avoid creating global httpx client instances without proper management of their lifecycle.
- **Ignoring Errors:** Never ignore exceptions raised by httpx. Always handle them appropriately.
- **Hardcoding URLs:** Avoid hardcoding URLs directly in the code. Use configuration files or environment variables.
### 2.4 State Management
- **Statelessness:** Design components to be as stateless as possible.
- **Dependency Injection:** Use dependency injection to provide httpx clients to components that need them.
### 2.5 Error Handling Patterns
- **Custom Exceptions:** Define custom exception classes to represent specific httpx-related errors.
- **Logging:** Log errors and warnings with sufficient context.
- **Retry Logic:** Implement retry logic for transient errors.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Connection Pooling:** httpx automatically uses connection pooling when using `httpx.Client()` or `httpx.AsyncClient()`. Ensure you are leveraging this by reusing client instances.
- **HTTP/2:** Enable HTTP/2 support if the server supports it.
- **Keep-Alive:** Ensure keep-alive connections are enabled.
- **Asynchronous Operations:** Use `httpx.AsyncClient()` for concurrent I/O-bound operations.
### 3.2 Memory Management
- **Streaming Responses:** Use response streaming (`response.iter_bytes()`, `response.iter_text()`) for large responses to avoid loading the entire response into memory.
- **Chunked Uploads:** Use chunked uploads for large file uploads.
### 3.3 Bundle Size Optimization
- **Tree Shaking:** Ensure your build tools perform tree shaking to remove unused httpx code.
### 3.4 Lazy Loading
- **On-Demand Initialization:** Initialize httpx clients only when they are needed.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks.
- **Man-in-the-Middle Attacks:** Always use HTTPS and verify SSL certificates.
- **Sensitive Data Exposure:** Avoid logging sensitive data (API keys, passwords).
### 4.2 Input Validation
- **Validate Request Data:** Validate all data before sending it to the API.
- **Validate Response Data:** Validate responses from the API.
### 4.3 Authentication and Authorization
- **Secure Authentication:** Use secure authentication mechanisms (OAuth 2.0, JWT).
- **Least Privilege:** Grant only the necessary permissions to users.
### 4.4 Data Protection
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and error messages.
### 4.5 Secure API Communication
- **HTTPS:** Always use HTTPS.
- **TLS 1.3:** Use TLS 1.3 or higher.
- **Certificate Pinning:** Consider certificate pinning for added security (advanced).
## 5. Testing Approaches
### 5.1 Unit Testing
- **Mocking:** Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to mock httpx calls.
- **Isolate Components:** Isolate components that use httpx for unit testing.
### 5.2 Integration Testing
- **Test Against Real APIs:** Perform integration tests against real APIs (with appropriate mocking or stubbing).
### 5.3 End-to-End Testing
- **Simulate User Flows:** Simulate end-to-end user flows that involve httpx calls.
### 5.4 Test Organization
- **Separate Test Files:** Create separate test files for each module or component.
### 5.5 Mocking and Stubbing Techniques
- **Mock Responses:** Mock httpx responses to simulate different API scenarios.
- **Patch httpx Functions:** Patch httpx functions to control their behavior during tests.
- **RESPX:** Use RESPX for advanced mocking of httpx requests and responses.
python
import httpx
import pytest
import respx
@respx.mock
async def test_get_data():
respx.get("https://example.com/api/data").mock(return_value=httpx.Response(200, json={"key": "value"}))
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com/api/data")
assert response.status_code == 200
assert response.json() == {"key": "value"}
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Forgetting to Close Clients:** Always close httpx clients to release resources.
- **Ignoring Timeouts:** Not setting timeouts can lead to hanging requests.
- **Incorrect Error Handling:** Improper error handling can mask critical errors.
- **Misunderstanding Connection Pooling:** Not reusing client instances negates connection pooling benefits.
- **Not Handling Asynchronous Context Correctly**: Using `await` improperly when using `AsyncClient()`.
### 6.2 Edge Cases
- **Character Encoding Issues:** Handle character encoding issues when processing text responses.
- **SSL Certificate Errors:** Handle SSL certificate errors gracefully.
- **Network Connectivity Issues:** Implement robust error handling for network connectivity issues.
### 6.3 Version-Specific Issues
- **Consult httpx Documentation:** Refer to the httpx documentation for version-specific issues and compatibility notes.
### 6.4 Compatibility Concerns
- **Asynchronous Libraries:** Ensure compatibility with other asynchronous libraries (e.g., asyncio).
- **Third-Party Packages:** Be aware of compatibility issues with third-party packages that use httpx.
### 6.5 Debugging Strategies
- **Logging:** Use logging to trace httpx requests and responses.
- **Debugging Tools:** Use debugging tools (e.g., pdb, ipdb) to inspect httpx code.
- **Wireshark/tcpdump:** Use network analysis tools (Wireshark, tcpdump) to capture and analyze network traffic.
## 7. Tooling and Environment
### 7.1 Recommended Tools
- **Development Environment:** Use a modern IDE (e.g., VS Code, PyCharm).
- **Dependency Management:** Use a dependency management tool (e.g., pipenv, poetry).
- **Testing Framework:** Use a testing framework (e.g., pytest, unittest).
- **Mocking Libraries:** Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`, RESPX).
### 7.2 Build Configuration
- **Reproducible Builds:** Ensure reproducible builds using dependency locking.
### 7.3 Linting and Formatting
- **PEP 8 Compliance:** Use a linter (e.g., flake8, pylint) to enforce PEP 8 compliance.
- **Code Formatting:** Use a code formatter (e.g., black, autopep8) to automatically format code.
### 7.4 Deployment
- **Containerization:** Use containerization (e.g., Docker) to ensure consistent deployments.
- **Environment Variables:** Configure httpx clients using environment variables.
### 7.5 CI/CD Integration
- **Automated Testing:** Integrate automated testing into your CI/CD pipeline.
- **Code Analysis:** Integrate code analysis tools into your CI/CD pipeline.
+164
View File
@@ -0,0 +1,164 @@
---
description: Comprehensive guide covering best practices for the Hypothesis Python library, including coding standards, testing, performance, and security. Provides actionable guidance for developers to write maintainable, robust, and efficient property-based tests.
globs: **/*.py
---
# Hypothesis Library Best Practices and Coding Standards
This document provides comprehensive guidelines for using the Hypothesis Python library effectively. Following these best practices will lead to more maintainable, robust, and efficient property-based tests.
## I. General Python Coding Standards (Applicable to Hypothesis Projects)
These are general Python coding standards that should be adhered to in any Python project, including those using Hypothesis.
* **PEP 8 Compliance:** Adhere strictly to PEP 8 style guidelines for Python code. This includes:
* Indentation: Use 4 spaces per indentation level.
* Line Length: Limit lines to a maximum of 79 characters (or 72 for comments and docstrings).
* Blank Lines: Use blank lines to separate top-level function and class definitions (two lines) and method definitions inside a class (one line).
* Imports: Group imports into standard library, third-party, and local application/library-specific imports, separated by blank lines.
* Whitespace: Avoid extraneous whitespace.
* Naming Conventions: Follow appropriate naming conventions for variables, functions, classes, and constants.
* **PEP 257 Compliance:** Follow PEP 257 for docstring conventions.
* Write docstrings for all public modules, functions, classes, and methods.
* Use triple double quotes (`"""`) for docstrings.
* Include a summary line, use case (if appropriate), arguments, return type and semantics (unless None is returned), and examples in multiline docstrings.
* **Use Python 3.12+:** Ensure that your project uses a modern version of Python (3.12 or higher) for access to the latest features and security updates.
* **Virtual Environments:** Use virtual environments (e.g., `venv` or `virtualenv`) to isolate project dependencies.
* **Dependency Management:** Use a dependency management tool like `pip` with a `requirements.txt` or `pyproject.toml` file to specify project dependencies. It's recommended to use a modern package installer such as [UV](https://astral.sh/blog/uv) for faster and more reproducible builds.
* **Code Reviews:** Conduct regular code reviews to ensure code quality and adherence to coding standards.
* **Type Hinting:** Use type hints to improve code readability and enable static analysis.
* **Linters and Formatters:** Use linters (e.g., `flake8`, `pylint`) and formatters (e.g., `black`, `autopep8`) to automatically enforce coding standards.
* **Error Handling:** Implement robust error handling using `try...except` blocks.
* **Logging:** Use the `logging` module for structured logging.
* **Clear and Concise Code:** Write code that is easy to understand and maintain.
* **Modularity:** Design your code with a modular architecture.
* **Documentation:** Write clear and comprehensive documentation.
* **Follow SOLID principles** When designing code and modules.
## II. Hypothesis-Specific Best Practices
These guidelines are specifically tailored to the Hypothesis library for property-based testing.
### A. Writing Properties
* **Focus on Properties, Not Examples:** Hypothesis excels when you define *properties* that should always hold true for a wide range of inputs, rather than just providing a fixed set of examples. A property describes a general relationship that should be invariant.
* **Define Strategies Clearly:** Strategies are the core of Hypothesis. Define strategies that generate diverse and representative data for your properties. Hypothesis provides many built-in strategies, and you can combine and customize them.
* **Shrinking is Crucial:** Hypothesis shrinks failing examples to the smallest and simplest form that still causes the failure. This simplifies debugging. Ensure your strategies are designed to allow effective shrinking.
* **Avoid Direct Assertion:** Generally, avoid directly asserting specific values within your properties. Instead, focus on asserting relationships between inputs and outputs. This strengthens the test and covers more potential cases.
* **Use Assume Sparingly:** The `assume()` function tells Hypothesis to discard certain examples. Overuse of `assume()` can make your tests less effective and potentially mask bugs. Try to refine your strategies instead of filtering excessively.
* **Make Properties Declarative:** Properties should describe *what* should happen, not *how* it should happen. This makes the tests more robust and easier to understand.
* **Test Invariants, Not Implementations:** Properties should test the high-level invariants of your code, rather than implementation details. This makes the tests more resilient to code changes.
* **Minimize Side Effects:** Properties should be as pure as possible, with minimal side effects. This makes the tests more predictable and easier to debug.
* **Consider Edge Cases:** Think about edge cases and boundary conditions that might violate your properties. Design your strategies to include these cases.
* **Use Composite Strategies:** Composite strategies allow you to combine multiple strategies to generate complex data structures. Use them to create realistic and diverse test cases.
* **Label Strategies:** Label strategies with descriptive names to improve the readability of your test output.
* **Use Dataclasses for Structured Data:** Define dataclasses to represent structured data in your properties. This improves code readability and maintainability.
### B. Strategy Design
* **Start with Built-in Strategies:** Hypothesis provides a rich set of built-in strategies for generating common data types. Start with these strategies and customize them as needed.
* **Constrain Strategies Appropriately:** Use constraints (e.g., `min_value`, `max_value`, `length`) to narrow the range of values generated by your strategies and improve test performance.
* **Use `sampled_from` for Discrete Values:** The `sampled_from` strategy is useful for generating discrete values from a list or set.
* **Combine Strategies with `one_of`:** The `one_of` strategy allows you to combine multiple strategies to generate a variety of data types.
* **Use `lists`, `sets`, and `dictionaries` to Generate Collections:** These strategies generate collections of data. Specify the element type and size constraints as needed.
* **Consider `recursive` Strategies for Nested Structures:** The `recursive` strategy allows you to generate nested data structures, such as trees or graphs.
* **Write Custom Strategies When Necessary:** If the built-in strategies are not sufficient, you can write custom strategies to generate data specific to your application.
* **Use `register_type_strategy` for Custom Types:** Register custom strategies for your custom types to make them available to other strategies.
* **Think About Shrinking When Designing Strategies:** Design your strategies with shrinking in mind. The goal is to shrink failing examples to the smallest and simplest form possible.
### C. Code Organization
* **Separate Tests from Implementation:** Keep your hypothesis tests in a separate directory from your implementation code (e.g., `tests/`).
* **Organize Tests by Module:** Mirror the structure of your implementation code in your test directory. Create a test module for each implementation module.
* **Use Descriptive Test Names:** Give your tests descriptive names that indicate the property being tested.
* **Use Fixtures for Setup and Teardown:** Use pytest fixtures to handle setup and teardown tasks for your tests.
* **Create Helper Functions for Common Tasks:** Create helper functions to encapsulate common tasks in your tests.
* **Use a `conftest.py` file:** Use a `conftest.py` file to define fixtures and other configuration options that are shared across multiple test modules.
* **Keep Test Modules Small:** Break large test modules into smaller, more manageable modules.
### D. Error Handling
* **Test for Expected Exceptions:** Use `pytest.raises` to assert that your code raises the expected exceptions under certain conditions.
* **Use Context Managers for Exception Handling:** Use context managers to handle exceptions and ensure that resources are properly released.
* **Log Errors and Warnings:** Use the `logging` module to log errors and warnings in your tests.
* **Use `report` to Add Context to Failures:** Use `hypothesis.report` to add information about the current state of the system under test to the failure report.
* **Fail Fast:** Write tests that fail quickly when a property is violated.
### E. Performance Considerations
* **Minimize Computation in Properties:** Properties should be as lightweight as possible to avoid slowing down the tests.
* **Use Caching to Avoid Redundant Computations:** Use caching to avoid redundant computations in your properties.
* **Optimize Strategies for Performance:** Optimize your strategies to generate data efficiently.
* **Use `max_examples` to Limit Test Run Time:** Use the `max_examples` setting to limit the number of examples generated by Hypothesis and prevent tests from running indefinitely.
* **Profile Slow Tests:** Use profiling tools to identify slow tests and optimize their performance.
* **Consider Data Generation Overhead:** Be aware that complex strategy definitions can have a significant performance overhead.
* **Avoid Unnecessary `assume` Calls:** Excessive use of `assume` can lead to wasted test cycles.
### F. Security Best Practices
* **Test for Input Validation:** Use Hypothesis to test the input validation logic of your code. Generate a wide range of inputs, including invalid inputs, to ensure that your code handles them correctly.
* **Test for Common Vulnerabilities:** Use Hypothesis to test for common vulnerabilities, such as SQL injection, cross-site scripting (XSS), and buffer overflows.
* **Use Strategies to Generate Malicious Inputs:** Create strategies that generate malicious inputs to test the security of your code.
* **Sanitize Inputs:** Sanitize all inputs to prevent vulnerabilities.
* **Escape Outputs:** Escape all outputs to prevent vulnerabilities.
* **Use Secure API Communication:** Use HTTPS for secure API communication.
* **Implement Authentication and Authorization:** Implement authentication and authorization to protect your data.
* **Limit User Privileges:** Limit user privileges to the minimum necessary to perform their tasks.
* **Monitor Your Application for Security Threats:** Monitor your application for security threats and respond promptly to any incidents.
### G. Common Pitfalls and Gotchas
* **Overuse of `assume()`:** As mentioned before, overuse of `assume()` can hide bugs.
* **Complex Strategy Definitions:** Complex strategy definitions can be difficult to understand and maintain.
* **Unrealistic Test Data:** Generating unrealistic test data can lead to false positives or false negatives.
* **Slow Test Execution:** Slow test execution can make it difficult to iterate quickly.
* **Lack of Understanding of Shrinking:** A lack of understanding of shrinking can make it difficult to debug failing tests.
* **Not Testing Edge Cases:** Failing to test edge cases can lead to bugs in production.
* **Ignoring Hypothesis Output:** Ignoring the Hypothesis output can cause you to miss important information about failing tests.
* **Incorrect Type Annotations:** Incorrect type annotations can cause Hypothesis to generate incorrect data.
* **Misunderstanding of Strategy Composition:** Misunderstanding how strategies are composed can lead to unexpected results.
### H. Tooling and Environment
* **pytest:** Use pytest as your test runner. It integrates seamlessly with Hypothesis and provides a rich set of features for writing and running tests.
* **hypothesis-auto:** Use the `hypothesis-auto` extension to automatically generate strategies for your dataclasses and other data types.
* **black:** Use black to automatically format your code and ensure PEP 8 compliance.
* **flake8:** Use flake8 to lint your code and identify potential problems.
* **mypy:** Use mypy to statically type check your code and identify type errors.
* **tox:** Use tox to automate testing in multiple environments.
* **CI/CD:** Integrate your tests into your CI/CD pipeline to ensure that your code is always tested before it is deployed.
* **VS Code or PyCharm:** Use a good IDE (like VS Code with the Python extension, or PyCharm) for code editing, debugging, and testing.
### I. Testing Approaches
* **Unit Testing:** Focus on testing individual units of code in isolation.
* **Integration Testing:** Test how different units of code interact with each other.
* **End-to-End Testing:** Test the entire application from end to end.
* **Property-Based Testing:** Use Hypothesis to generate a wide range of inputs and test the properties of your code.
* **Mutation Testing:** Use mutation testing to assess the quality of your tests.
### J. Recommended Workflow
1. **Start with a Property:** Define the property that you want to test.
2. **Define a Strategy:** Create a strategy to generate data for your property.
3. **Write the Test:** Write the test using Hypothesis and pytest.
4. **Run the Test:** Run the test and see if it passes.
5. **Fix Any Bugs:** If the test fails, fix the bug in your code.
6. **Repeat:** Repeat steps 1-5 until you are confident that your code is correct.
## III. Example Hypothesis Test
python
import pytest
from hypothesis import given, strategies as st
def add(x, y):
return x + y
@given(st.integers(), st.integers())
def test_addition_is_commutative(x, y):
assert add(x, y) == add(y, x)
## IV. Conclusion
By following these best practices, you can use Hypothesis to write more effective and robust property-based tests that improve the quality and reliability of your Python code.
+91
View File
@@ -0,0 +1,91 @@
---
description: This rule file provides best practices for using the Insomnia API Client, including project organization, environment management, testing, and collaboration to improve API development workflows.
globs: **/*.{json,yaml,yml,graphql,proto}
---
- **Project Organization and Structure:**
- **Workspace Structure:** Organize requests into workspaces based on projects or functional areas. Within workspaces, use folders to group related requests (e.g., authentication, user management, product catalog).
- **Environment Management:** Leverage Insomnia's environment variables for managing configurations (API keys, base URLs, authentication tokens) across different environments (development, staging, production). Use environment variables to store sensitive data and secrets instead of hardcoding them directly into requests. Create separate environments for each stage of the API lifecycle (development, testing, staging, production). This allows you to easily switch between different configurations without modifying your requests.
- **File Naming Conventions:** Use descriptive file names for Insomnia collections (e.g., `users-api.insomnia.json`, `product-management.insomnia.yaml`). Ensure that your naming convention is clear and consistent. Name files according to their function and the API they're targeting. Using date-based versioning can also be valuable.
- **Collection Splitting:** For large API definitions, consider splitting collections into smaller, more manageable files based on API modules or resources. Use Insomnia's import/export functionality to combine them when needed.
- **Git Integration:** Store your Insomnia collections and environment files in a Git repository to track changes, collaborate with team members, and implement version control. Using Git also gives you a backup of your configuration.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:**
- **Environment Overrides:** Use environment overrides to customize settings for specific requests without modifying the base environment.
- **Chained Requests:** Utilize chained requests to pass data from one request to another, enabling complex workflows (e.g., creating a user, then retrieving the user's details).
- **Dynamic Values:** Generate dynamic values (e.g., timestamps, UUIDs) using Insomnia's built-in functions to create realistic test data.
- **Recommended Approaches:**
- **API Testing:** Use Insomnia to test HTTP-based RESTful APIs as well as GraphQL APIs. Take advantage of API testing as part of your testing strategy to test your application's core business rules and help deliver better software faster.
- **GraphQL Support:** Leverage Insomnia's built-in GraphQL support for constructing and executing GraphQL queries.
- **Authentication Handling:** Configure authentication (API keys, OAuth 2.0, JWT) at the environment or request level for consistent authentication across all requests.
- **Anti-patterns:**
- **Hardcoding Sensitive Data:** Avoid storing sensitive information directly in request bodies or headers. Use environment variables instead.
- **Ignoring Response Validation:** Always validate API responses (status codes, headers, data) to ensure that the API is functioning correctly.
- **State Management:** Insomnia itself is stateless; however, you can simulate stateful interactions using chained requests and environment variables to store and reuse data across multiple requests.
- **Error Handling:** Use Insomnia's response inspection tools to analyze error responses. Define specific tests to assert that error responses are handled correctly.
- **Performance Considerations:**
- **Request Optimization:** Minimize request payload size and optimize request headers to improve API performance.
- **Connection Pooling:** Insomnia automatically manages connection pooling for efficient API communication.
- **Response Caching (Client-Side):** Consider using a proxy or interceptor to cache API responses locally for faster testing and development.
- **Security Best Practices:**
- **Vulnerability Prevention:**
- **Rate Limiting:** Simulate rate limiting scenarios to test your API's resilience to abuse.
- **Input Validation:** Thoroughly validate all inputs (headers, query parameters, request body) to prevent injection attacks.
- **Input Validation:** Utilize Insomnia's request body editor to ensure that the data being sent is correctly formatted and validated against the API's expected schema.
- **Authentication and Authorization:**
- **OAuth 2.0 Flows:** Implement OAuth 2.0 flows within Insomnia to test API authorization.
- **JWT Validation:** Validate JWT tokens returned by the API to ensure their integrity.
- **Data Protection:**
- **HTTPS:** Always use HTTPS for secure API communication. Insomnia automatically handles HTTPS requests.
- **End-to-End Encryption:** Ensure that sensitive data is encrypted both in transit and at rest. Consider using a VPN for added security.
- **Security Helpers**: Take advantage of security helpers, code creation, and environment variables.
- **Testing Approaches:**
- **Unit Testing:** While Insomnia isn't a unit testing framework, you can use it to create individual requests that target specific API endpoints and validate their responses.
- **Integration Testing:** Use Insomnia to test the interaction between different API services and components.
- **End-to-End Testing:** Create comprehensive test suites in Insomnia to simulate real-world user scenarios and validate the entire API workflow.
- **Test Organization:** Organize tests into folders based on API resources or functional areas.
- **Mocking and Stubbing:** Insomnia's mocking capabilities are essential during early stages of development or when dependent services are not available. Kong Insomnia’s mocking capabilities allow teams to simulate API responses without needing access to the actual API or back-end systems, facilitating parallel development and ensuring seamless integration testing. Kong Insomnia offers the option to mock on cloud or local for data sensitive customers.
- **Test Automation:** Integrate Insomnia with CI/CD pipelines to automate API testing as part of your development workflow. Utilize the Insomnia CLI or Newman (Postman's CLI tool) to run your Insomnia collections as part of your automated test suite.
- **Assertions:**
- Validate the structure and content of API responses using Insomnia's response inspection tools and custom JavaScript assertions.
- Verify HTTP status codes, headers, and response times to ensure that the API is performing as expected.
- **Common Pitfalls and Gotchas:**
- **Incorrect Environment Variables:** Double-check that environment variables are correctly configured and referenced in your requests.
- **Missing Authentication Headers:** Ensure that all authenticated requests include the necessary authentication headers.
- **Invalid Request Payloads:** Validate that your request payloads are correctly formatted and match the API's expected schema.
- **Rate Limit Exceeded Errors:** Be aware of API rate limits and implement appropriate retry mechanisms.
- **Data Type Mismatches:** Ensure that the data types in your request payloads match the API's expected data types.
- **Handling Large Responses:** Insomnia might struggle with extremely large API responses. Consider using a tool like `jq` to process large JSON responses.
- **Import/Export Issues:** Be aware of potential compatibility issues when importing or exporting Insomnia collections. Always test imported collections to ensure that they function correctly.
- **Version Compatibility:** Test Insomnia against the versions of APIs that you intend to target. Old API versions might have compatibility issues.
- **Debugging strategies:**
- **Response Inspection:** Use Insomnia's response inspection tools to examine the API's responses. Check the status code, headers, and body for errors or unexpected data.
- **Request Logging:** Enable request logging to capture detailed information about the API requests being sent. This can help you diagnose issues with the request payload, headers, or authentication.
- **Console Output:** Use the `console.log()` function in Insomnia's request scripts to output debug messages to the console. This can help you track the flow of data and identify potential problems.
- **Network Monitoring:** Use a network monitoring tool (e.g., Wireshark) to capture and analyze the network traffic between Insomnia and the API server. This can help you identify issues with the network connection, SSL/TLS configuration, or API server behavior.
- **Tooling and Environment:**
- **Recommended Tools:**
- Insomnia Designer: Use Insomnia Designer to visually design and document your APIs.
- Insomnia CLI: Use the Insomnia CLI to automate API testing and integrate it with your CI/CD pipelines.
- JSON Formatter: Use a JSON formatter to validate and format your JSON request payloads.
- YAML Linter: Use a YAML linter to validate your YAML API definitions.
- **Build Configuration:** Store your Insomnia collections and environment files in a Git repository to track changes, collaborate with team members, and implement version control.
- **Linting and Formatting:** Enforce consistent code style and API design by using linting and formatting tools.
- **Deployment:** Store your API keys and other sensitive information as environment variables on your deployment server. Use a secure deployment pipeline to ensure that your Insomnia collections and environment files are deployed correctly.
- **CI/CD Integration:** Use Insomnia CLI to integrate API testing into your CI/CD pipelines. Configure automated API tests to run whenever code is committed or deployed.
- **Additional Best Practices:**
- **Documentation:** Maintain clear and up-to-date documentation for your API collections and environments.
- **Collaboration:** Use Insomnia's team collaboration features to share API collections and environments with your team members.
- **Regular Updates:** Keep Insomnia up-to-date to take advantage of the latest features and security patches.
- **Modular Design:** Break down large API collections into smaller, more manageable modules to improve maintainability.
By following these best practices, you can leverage Insomnia to streamline your API development workflow, improve API quality, and ensure the security of your API services.
- **References**
- @file:./insomnia_example_rule.mdc (Example rule for chaining)
+339
View File
@@ -0,0 +1,339 @@
---
description: This rule provides comprehensive best practices for Ionic Framework development, covering code organization, performance, security, testing, and more. Following these guidelines will result in more maintainable, performant, and secure Ionic applications.
globs: **/*.{ts,html,scss}
---
---
# Ionic Framework Best Practices
This document outlines best practices for developing Ionic applications. Following these guidelines will help ensure your applications are maintainable, performant, secure, and testable.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
A well-organized directory structure is crucial for maintainability. Consider this structure as a starting point:
src/
app/
components/
my-component/
my-component.component.ts
my-component.component.html
my-component.component.scss
my-component.component.spec.ts
pages/
home/
home.page.ts
home.page.html
home.page.scss
home.page.spec.ts
services/
data.service.ts
app.component.ts
app.module.ts
app-routing.module.ts
assets/
theme/
variables.scss
environments/
environment.ts
environment.prod.ts
* **`src/app`**: Contains the core application code.
* **`src/app/components`**: Reusable UI components.
* **`src/app/pages`**: Individual application pages/views.
* **`src/app/services`**: Application services for data access, business logic, etc.
* **`src/assets`**: Static assets like images, fonts, etc.
* **`src/theme`**: Global styles and variables.
* **`src/environments`**: Environment-specific configuration.
### 1.2 File Naming Conventions
Use consistent file naming conventions:
* Components: `my-component.component.ts`, `my-component.component.html`, `my-component.component.scss`
* Pages: `home.page.ts`, `home.page.html`, `home.page.scss`
* Services: `data.service.ts`
* Modules: `app.module.ts`, `my-module.module.ts`
* Interfaces: `my-interface.ts`
* Enums: `my-enum.ts`
This consistency improves readability and maintainability.
### 1.3 Module Organization
* **Feature Modules:** Group related components, pages, and services into feature modules. This promotes modularity and lazy loading.
* **Shared Module:** Create a shared module for commonly used components, directives, and pipes.
* **Core Module:** A core module is used for application-wide services that you only need to instantiate once. Import it only into the `AppModule`.
* **Lazy Loading:** Lazy load feature modules to improve initial load time.
typescript
// Example of a Feature Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my-component/my-component.component';
import { MyPage } from './my-page/my-page.page';
import { MyService } from './my-service/my-service.service';
import { MyRoutingModule } from './my-routing.module';
@NgModule({
declarations: [MyComponent, MyPage],
imports: [CommonModule, MyRoutingModule],
providers: [MyService],
})
export class MyModule {}
### 1.4 Component Architecture
* **Smart vs. Dumb Components:**
* **Smart Components (Pages):** Handle data fetching, state management, and interactions with services.
* **Dumb Components (Components):** Receive data via inputs and emit events via outputs. Focus on presentation and UI logic.
* **Component Reusability:** Design components to be reusable across different parts of the application.
* **Avoid Direct DOM Manipulation:** Use Angular's data binding and directives instead of directly manipulating the DOM.
* **Follow the Single Responsibility Principle (SRP):** Ensure each component has a specific purpose.
### 1.5 Code Splitting
* **Lazy Loading Modules:** As mentioned, lazy load feature modules to reduce the initial bundle size.
* **Route-Based Code Splitting:** Split code based on application routes.
* **Conditional Loading:** Load components or modules only when they are needed.
## 2. Common Patterns and Anti-Patterns
### 2.1 Design Patterns
* **Model-View-Controller (MVC):** Ionic, built on Angular, largely follows the MVC pattern.
* **Singleton:** Use singletons for services that need to maintain global state (e.g., authentication service).
* **Observer:** Use RxJS Observables for asynchronous operations and data streams.
* **Facade:** Provide a simplified interface to a complex subsystem.
* **Dependency Injection:** Use Angular's dependency injection system to provide components with their dependencies.
### 2.2 Recommended Approaches for Common Tasks
* **Data Fetching:** Use Angular's `HttpClient` with RxJS Observables for making API requests.
* **Form Handling:** Use Angular's reactive forms or template-driven forms for managing form data.
* **Navigation:** Use the Ionic `NavController` for navigating between pages.
* **State Management:** Use a state management library like NgRx or Akita for complex applications.
* **UI Components:** Leverage Ionic's built-in UI components for a consistent look and feel.
### 2.3 Anti-Patterns and Code Smells
* **Massive Components:** Avoid creating components that are too large or complex. Break them down into smaller, reusable components.
* **Direct DOM Manipulation:** As mentioned, avoid directly manipulating the DOM.
* **Nested Subscriptions:** Avoid deeply nested RxJS subscriptions, which can lead to memory leaks and difficult-to-debug code. Use operators like `switchMap`, `mergeMap`, or `concatMap` to flatten subscriptions.
* **Overusing `any` Type:** Avoid using the `any` type excessively. Use specific types to improve type safety and code maintainability.
* **Ignoring Errors:** Always handle errors properly to prevent unexpected behavior.
* **Global Variables:** Avoid using global variables, which can lead to naming conflicts and unpredictable behavior.
### 2.4 State Management
* **Component State:** For simple component-specific state, use Angular's `@Input` and `@Output` decorators.
* **Service State:** For application-wide state that needs to be shared between components, use a service with RxJS `BehaviorSubject` or `ReplaySubject`.
* **NgRx/Akita:** For complex applications with significant state management needs, consider using a state management library like NgRx or Akita.
* NgRx leverages Redux principles, offering a predictable state container with actions, reducers, and effects. This is suitable for large-scale applications needing centralized state management, change tracking, and debugging tools. However, NgRx can introduce boilerplate and complexity.
* Akita, a state management pattern on top of RxJS, simplifies the process with less boilerplate and easier learning curve compared to Redux-based solutions. It’s suitable for small to medium-sized applications requiring scalable yet simple state management.
### 2.5 Error Handling
* **Centralized Error Handling:** Create a centralized error handling service to handle errors consistently across the application.
* **Error Interceptors:** Use Angular's `HttpInterceptor` to intercept HTTP requests and handle errors globally.
* **User-Friendly Error Messages:** Display user-friendly error messages to the user.
* **Logging:** Log errors to a server for debugging and monitoring purposes.
* **Retry Mechanism:** Implement a retry mechanism for transient errors.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Lazy Loading:** As previously emphasized, use lazy loading for modules and components.
* **Ahead-of-Time (AOT) Compilation:** Use AOT compilation to compile the application during the build process, which improves startup time.
* **Change Detection Optimization:**
* **`OnPush` Change Detection:** Use `OnPush` change detection strategy for components that only depend on input properties. This can significantly improve performance.
* **`trackBy` Function:** Use the `trackBy` function in `*ngFor` loops to improve rendering performance when the underlying data changes.
* **Virtual Scrolling:** Use virtual scrolling for long lists to render only the visible items.
* **Image Optimization:** Optimize images by compressing them and using appropriate formats.
* **Minify and Bundle:** Minify and bundle JavaScript and CSS files to reduce file sizes.
* **Caching:** Implement caching strategies for frequently accessed data.
* **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of event handlers.
### 3.2 Memory Management
* **Unsubscribe from Observables:** Always unsubscribe from RxJS subscriptions to prevent memory leaks. Use the `takeUntil` operator or a `Subject` to manage subscriptions.
* **Avoid Circular Dependencies:** Avoid circular dependencies between modules, which can lead to memory leaks.
* **Release Resources:** Release resources when they are no longer needed.
* **Use `async` Pipe:** Use the `async` pipe in templates to automatically unsubscribe from Observables.
### 3.3 Rendering Optimization
* **Reduce DOM Updates:** Minimize the number of DOM updates by using Angular's data binding and change detection mechanisms effectively.
* **Use CSS Transforms:** Use CSS transforms instead of directly manipulating the DOM for animations and transitions.
* **Avoid Complex Expressions in Templates:** Avoid complex expressions in templates, which can impact rendering performance. Move complex logic to component classes.
* **Virtual DOM:** Angular uses a virtual DOM, but understanding how change detection works is critical to performance.
### 3.4 Bundle Size Optimization
* **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
* **Code Splitting:** As mentioned, use code splitting to reduce the initial bundle size.
* **Remove Unused Dependencies:** Remove any unused dependencies from the `package.json` file.
* **Use Production Build:** Use the production build flag (`--prod`) when building the application for deployment.
* **Analyze Bundle Size:** Use tools like `webpack-bundle-analyzer` to analyze the bundle size and identify areas for optimization.
### 3.5 Lazy Loading
* **Lazy Load Modules:** This is a primary optimization strategy in Ionic.
* **Lazy Load Images:** Use libraries that support lazy loading of images.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and avoiding the use of `innerHTML`. Use Angular's built-in sanitization features.
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection by using tokens in HTTP requests.
* **Injection Attacks:** Prevent SQL injection and other injection attacks by using parameterized queries and input validation.
* **Insecure Data Storage:** Avoid storing sensitive data in local storage or cookies. Use secure storage mechanisms like the Ionic Native Storage plugin or a secure backend.
* **Man-in-the-Middle (MITM) Attacks:** Use HTTPS to encrypt communication between the app and the server.
* **Certificate Pinning:** Implement certificate pinning to prevent MITM attacks.
### 4.2 Input Validation
* **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user.
* **Server-Side Validation:** Always perform server-side validation to ensure data integrity.
* **Sanitize User Input:** Sanitize user input to prevent XSS attacks.
* **Use Regular Expressions:** Use regular expressions to validate input formats.
### 4.3 Authentication and Authorization
* **Use Secure Authentication:** Use a secure authentication mechanism like OAuth 2.0 or JWT (JSON Web Token).
* **Implement Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application based on user roles.
* **Store Tokens Securely:** Store authentication tokens securely using the Ionic Native Storage plugin or a secure backend.
* **Refresh Tokens:** Use refresh tokens to automatically renew authentication tokens.
* **Implement Multi-Factor Authentication (MFA):** Implement MFA for increased security.
### 4.4 Data Protection
* **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
* **Use HTTPS:** Use HTTPS for all communication between the app and the server.
* **Secure API Keys:** Protect API keys by storing them securely and using them only when necessary.
* **Data Masking:** Mask sensitive data in the UI.
* **Regular Security Audits:** Conduct regular security audits to identify and address potential vulnerabilities.
### 4.5 Secure API Communication
* **Use HTTPS:** Use HTTPS for all API communication.
* **Validate API Responses:** Validate API responses to ensure data integrity.
* **Implement Rate Limiting:** Implement rate limiting to prevent abuse of API endpoints.
* **Use API Gateways:** Use API gateways to manage and secure API traffic.
* **Secure API Keys:** Protect API keys by storing them securely and using them only when necessary.
## 5. Testing Approaches
### 5.1 Unit Testing
* **Test Components in Isolation:** Test components in isolation using mocking and stubbing techniques.
* **Test Services in Isolation:** Test services in isolation by mocking their dependencies.
* **Use Test Doubles:** Use test doubles like stubs, mocks, and spies to isolate the code under test.
* **Test Boundary Conditions:** Test boundary conditions to ensure the code handles edge cases correctly.
* **Use Code Coverage Tools:** Use code coverage tools to measure the percentage of code that is covered by tests.
### 5.2 Integration Testing
* **Test Component Interactions:** Test the interactions between components.
* **Test Service Interactions:** Test the interactions between services.
* **Test Data Flow:** Test the flow of data through the application.
* **Use Mock HTTP Backend:** Use a mock HTTP backend to simulate API responses.
### 5.3 End-to-End Testing
* **Test User Flows:** Test the complete user flows through the application.
* **Use a Testing Framework:** Use a testing framework like Cypress or Protractor for end-to-end testing.
* **Test on Real Devices:** Test the application on real devices to ensure it works correctly in different environments.
### 5.4 Test Organization
* **Locate Tests with Source Files:** Keep test files in the same directory as the source files they test (e.g., `my-component.component.spec.ts` next to `my-component.component.ts`).
* **Use Descriptive Test Names:** Use descriptive test names to clearly indicate what the test is verifying.
* **Organize Tests by Feature:** Organize tests by feature to improve test maintainability.
### 5.5 Mocking and Stubbing
* **Use Mocking Libraries:** Use mocking libraries like Jasmine or Sinon.js to create mocks and stubs.
* **Mock Dependencies:** Mock dependencies to isolate the code under test.
* **Stub API Responses:** Stub API responses to simulate different scenarios.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Not Unsubscribing from Observables:** Forgetting to unsubscribe from RxJS subscriptions.
* **Directly Manipulating the DOM:** Directly manipulating the DOM instead of using Angular's data binding.
* **Overusing `any` Type:** Overusing the `any` type.
* **Ignoring Errors:** Ignoring errors.
* **Not Validating User Input:** Not validating user input.
* **Storing Sensitive Data in Local Storage:** Storing sensitive data in local storage.
* **Not Using HTTPS:** Not using HTTPS for API communication.
### 6.2 Edge Cases
* **Handling Network Errors:** Handling network errors gracefully.
* **Handling Different Screen Sizes:** Handling different screen sizes and resolutions.
* **Handling Different Operating Systems:** Handling different operating systems (iOS and Android).
* **Handling Different Device Capabilities:** Handling different device capabilities (e.g., camera, GPS).
### 6.3 Version-Specific Issues
* **Breaking Changes:** Be aware of breaking changes in new versions of Ionic and Angular. Carefully review release notes.
* **Deprecated Features:** Avoid using deprecated features.
* **Compatibility Issues:** Test the application with different versions of Ionic and Angular to ensure compatibility.
### 6.4 Compatibility Concerns
* **Plugin Compatibility:** Ensure that plugins are compatible with the target platform and version of Ionic.
* **Browser Compatibility:** Ensure that the application works correctly in different browsers.
* **Cordova vs. Capacitor:** Understand the differences and implications of using Cordova versus Capacitor. Capacitor is generally recommended for new projects.
### 6.5 Debugging Strategies
* **Use Browser Developer Tools:** Use browser developer tools to debug JavaScript, CSS, and network requests.
* **Use Debugging Tools:** Use debugging tools like VS Code's debugger to step through code and inspect variables.
* **Use Logging:** Use logging to track the flow of execution and identify potential issues.
* **Use Remote Debugging:** Use remote debugging to debug the application on real devices.
* **Learn to read Stack Traces:** Understanding the stack trace is crucial for identifying the source of errors.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **VS Code:** VS Code is a popular IDE for Ionic development with excellent support for TypeScript, HTML, and CSS.
* **Ionic CLI:** The Ionic CLI is a command-line tool for creating, building, and deploying Ionic applications.
* **Chrome DevTools:** Chrome DevTools is a powerful tool for debugging and profiling Ionic applications.
* **Postman/Insomnia:** Use Postman or Insomnia to test API endpoints.
### 7.2 Build Configuration
* **Use Environment Variables:** Use environment variables to configure the application for different environments (e.g., development, production).
* **Configure Build Scripts:** Configure build scripts to automate build tasks.
* **Use a Build System:** Use a build system like Webpack or Parcel to manage dependencies and bundle assets.
* **Optimize Build Configuration:** Optimize the build configuration to reduce build time and bundle size.
### 7.3 Linting and Formatting
* **Use ESLint:** Use ESLint to enforce coding standards and identify potential issues.
* **Use Prettier:** Use Prettier to automatically format code.
* **Configure Editor Integration:** Configure editor integration to automatically lint and format code on save.
### 7.4 Deployment
* **Build for Production:** Build the application for production using the `--prod` flag.
* **Use a Deployment Platform:** Use a deployment platform like Firebase Hosting, Netlify, or AWS Amplify.
* **Configure HTTPS:** Configure HTTPS for the deployment environment.
* **Monitor Application Performance:** Monitor application performance after deployment.
### 7.5 CI/CD
* **Use a CI/CD Pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process.
* **Use a CI/CD Tool:** Use a CI/CD tool like Jenkins, CircleCI, or Travis CI.
* **Automate Testing:** Automate unit, integration, and end-to-end tests in the CI/CD pipeline.
* **Automate Deployment:** Automate deployment to different environments in the CI/CD pipeline.
+223
View File
@@ -0,0 +1,223 @@
---
description: This rule provides comprehensive guidelines for using isort in Python projects, covering code organization, common patterns, performance, security, testing, tooling, and common pitfalls. It aims to standardize import sorting and improve code quality.
globs: **/*.py
---
# isort Best Practices: A Comprehensive Guide
This document provides a comprehensive guide to using isort effectively in Python projects. It covers various aspects, including code organization, common patterns, performance considerations, security, testing, tooling, and common pitfalls.
## Library Information:
- Name: isort
- Tags: development, python, formatter, imports
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
While isort primarily focuses on import sorting within files, the overall directory structure impacts how imports are organized and how isort rules are applied.
- **Flat Structure (Small Projects):** For smaller projects, a flat structure might suffice, with all modules in a single directory.
- **Modular Structure (Larger Projects):** For larger projects, adopt a modular structure using packages and subpackages. This enhances maintainability and reusability.
project_name/
├── package1/
│ ├── __init__.py
│ ├── module1.py
│ └── module2.py
├── package2/
│ ├── __init__.py
│ └── module3.py
├── main.py
└── pyproject.toml (isort configuration)
### 1.2 File Naming Conventions Specific to isort
- isort doesn't enforce specific file naming conventions but follows PEP 8 recommendations.
- Use descriptive and consistent file names. For example, `utils.py`, `models.py`, `services.py`.
- Lowercase with underscores for module names: `my_module.py`
### 1.3 Module Organization Best Practices
- **Grouping Related Functionality:** Organize modules based on related functionality. For example, place database-related functions in a `db` module.
- **Avoiding Circular Imports:** Be cautious of circular import dependencies, where two or more modules import each other, leading to potential runtime errors. isort can help detect these through proper import ordering.
- **Using Relative Imports:** Utilize relative imports within packages for internal references.
python
# Within package1/module1.py
from .module2 import some_function # Relative import
# From outside the package
from package1.module1 import some_function
### 1.4 Component Architecture Recommendations
- **Layered Architecture:** Consider a layered architecture (e.g., presentation, business logic, data access) to separate concerns and facilitate modularity.
- **Microservices:** In larger applications, microservices can be used to break down the application into smaller, independent services. Each service can have its own isort configuration.
### 1.5 Code Splitting Strategies
- **Splitting Large Modules:** Decompose large modules into smaller, more manageable modules to improve readability and maintainability. Each module will have its own independent import sorting managed by isort
- **Lazy Loading:** Implement lazy loading for modules that are not immediately required to improve startup time. This may require dynamic imports, which isort can handle.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to isort
isort itself doesn't directly relate to traditional design patterns like Singleton or Factory. However, its proper usage facilitates cleaner code, which makes it easier to apply other design patterns.
- **Import Facade:** Use a module to consolidate and re-export imports from other modules to simplify external dependencies.
python
# my_package/imports.py
from .module1 import ClassA
from .module2 import function_b
__all__ = ['ClassA', 'function_b']
### 2.2 Recommended Approaches for Common Tasks
- **Sorting Imports:** Use isort to automatically sort imports alphabetically and group them by type (standard library, third-party, local).
- **Integrating with Black:** Configure isort to be compatible with Black to enforce consistent code formatting.
- **Using `pyproject.toml`:** Define isort's configuration in the `pyproject.toml` file for project-specific settings.
### 2.3 Anti-patterns and Code Smells
- **Ignoring isort:** Not using isort consistently across the project leads to inconsistent import styles and reduced readability.
- **Manual Sorting:** Manually sorting imports is error-prone and time-consuming. Use isort to automate the process.
- **Conflicting Configurations:** Having multiple, conflicting isort configurations in different parts of the project can cause inconsistencies.
- **Overly Complex Imports:** Avoid deep nesting or overly complex import statements, which reduce readability.
### 2.4 State Management
- isort is not directly involved with State Management.
### 2.5 Error Handling
- isort generally handles errors gracefully, such as when encountering syntax errors in files.
- Ensure that isort configuration is valid to avoid unexpected behavior.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Caching:** isort utilizes caching to improve performance on subsequent runs. Ensure the cache directory is properly configured.
- **Parallel Processing:** isort supports parallel processing for faster sorting of multiple files.
- **Minimizing File Size:** Sort imports to avoid any unnecessary circular dependency issues
### 3.2 Memory Management
- isort is generally memory-efficient. However, processing extremely large files may require additional memory.
### 3.3 Rendering Optimization
- isort doesn't involve rendering.
### 3.4 Bundle Size Optimization
- isort doesn't directly impact bundle size, as it's a development tool.
### 3.5 Lazy Loading
- isort works with modules using lazy loading; it sorts the import statements as they are written.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
- isort itself doesn't introduce security vulnerabilities, but improper coding practices can.
### 4.2 Input Validation
- isort doesn't handle external input; hence, input validation is not directly relevant.
### 4.3 Authentication and Authorization
- Authentication/Authorization not applicable to isort
### 4.4 Data Protection
- isort doesn't manage data.
### 4.5 Secure API Communication
- isort doesn't involve API communication.
## 5. Testing Approaches
### 5.1 Unit Testing
- Although isort is primarily a formatting tool, consider writing unit tests to ensure its configuration produces the desired output.
- Test cases can include verifying that imports are sorted correctly under various scenarios.
### 5.2 Integration Testing
- Integrate isort with other tools like Black and Flake8 in your CI/CD pipeline. Integration tests can verify that these tools work together seamlessly.
### 5.3 End-to-End Testing
- isort doesn't directly require end-to-end testing.
### 5.4 Test Organization
- Keep test files separate from source code, usually in a dedicated `tests/` directory.
### 5.5 Mocking and Stubbing
- Not applicable for isort testing.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Incorrect Configuration:** Misconfiguring the `pyproject.toml` file, leading to unexpected sorting behavior.
- **Ignoring Warnings:** Ignoring warnings from isort can result in subtle bugs and inconsistent code.
- **Not Integrating with Pre-commit:** Failing to integrate isort with pre-commit hooks allows unformatted code to be committed.
### 6.2 Edge Cases
- **Complex Import Paths:** isort might have trouble with extremely complex or dynamically generated import paths.
- **Conditional Imports:** Be careful with conditional imports (imports within `if` statements), as isort might not always handle them correctly.
### 6.3 Version-Specific Issues
- Check for compatibility issues between isort versions and other tools or libraries.
### 6.4 Compatibility Concerns
- Ensure isort is compatible with other linters (e.g., Flake8) and formatters (e.g., Black) used in the project.
### 6.5 Debugging Strategies
- **Verbose Mode:** Use isort's verbose mode to get more detailed output about its actions.
- **Configuration Testing:** Create small test files to experiment with isort configurations.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **VS Code:** Use VS Code with the Python extension for seamless integration with isort, Black, and Flake8.
- **PyCharm:** PyCharm provides excellent support for Python development, including built-in linting and formatting tools.
### 7.2 Build Configuration
- Use `pyproject.toml` to manage isort's configuration. Store configuration in version control
- Use pre-commit hooks to ensure isort is run before each commit.
### 7.3 Linting and Formatting
- Integrate isort, Black, and Flake8 for comprehensive code linting and formatting.
- Configure these tools to follow PEP 8 guidelines.
### 7.4 Deployment
- isort is not a deployment tool. Ensure that your deployment process includes running linters and formatters.
### 7.5 CI/CD Integration
- Integrate isort into your CI/CD pipeline to automatically check code quality on each commit or pull request.
- Use tools like GitHub Actions or GitLab CI to automate the process.
By following these best practices, you can effectively use isort to maintain consistent and high-quality code in your Python projects.
+296
View File
@@ -0,0 +1,296 @@
---
description: Enforces best practices for Java development, covering code style, performance, security, and testing. Provides guidelines for writing clean, maintainable, and efficient Java code.
globs: **/*.java
---
- # Java Best Practices
This document outlines comprehensive best practices for Java development, covering code organization, common patterns, performance considerations, security, testing, common pitfalls, and tooling. Adhering to these guidelines will help you write clean, maintainable, efficient, and secure Java code.
- ## 1. Code Organization and Structure
- ### 1.1 Directory Structure
- **Maven Standard Layout:** Use the standard Maven directory structure for most projects. This provides a consistent and predictable layout that's easily understood by other developers and tools.
src/
main/
java/
com/example/ <- Your package structure starts here
resources/
test/
java/
com/example/
resources/
pom.xml <- Maven project file
- **Gradle Layout:** Gradle supports the Maven layout and provides other ways to configure the source directories. Choose a layout that best fits your project's needs.
- **Package by Feature:** Organize packages by feature rather than by layer (e.g., controllers, services, repositories). This improves cohesion and reduces dependencies between features.
src/
main/
java/
com/example/
user/
UserController.java
UserService.java
UserRepository.java
product/
ProductController.java
ProductService.java
ProductRepository.java
- **Modularization:** For large projects, consider using Java modules (Jigsaw, introduced in Java 9) to improve encapsulation and reduce dependencies.
- ### 1.2 File Naming Conventions
- **Classes and Interfaces:** Use `PascalCase` (e.g., `UserController`, `UserService`).
- **Methods and Variables:** Use `camelCase` (e.g., `getUserById`, `userName`).
- **Constants:** Use `UPPER_SNAKE_CASE` (e.g., `MAX_RETRIES`, `DEFAULT_TIMEOUT`).
- **Packages:** Use all lowercase (e.g., `com.example.user`).
- **Avoid abbreviations:** Use meaningful and descriptive names.
- ### 1.3 Module Organization
- **`module-info.java`:** Use `module-info.java` to define module dependencies and exported packages. This allows for strong encapsulation and controlled access to internal APIs.
- **Explicit Dependencies:** Declare all module dependencies explicitly in `module-info.java`. Avoid relying on transitive dependencies.
- **Minimize Exports:** Only export the packages that are intended for public use. Keep internal packages hidden from other modules.
- ### 1.4 Component Architecture
- **Dependency Injection:** Use dependency injection (DI) to manage component dependencies. Frameworks like Spring and Guice simplify DI.
- **Inversion of Control (IoC):** Apply IoC to decouple components and improve testability.
- **Layered Architecture:** Structure your application into layers (e.g., presentation, business logic, data access). This promotes separation of concerns and maintainability.
- **Microservices:** For large, complex applications, consider a microservices architecture. This allows for independent development, deployment, and scaling of individual services.
- ### 1.5 Code Splitting
- **Feature Toggles:** Use feature toggles to enable or disable features at runtime. This allows for incremental deployment and testing of new features.
- **Dynamic Loading:** Use dynamic class loading to load modules or components on demand. This can reduce the initial startup time and memory footprint of your application.
- **Conditional Compilation:** Use conditional compilation (e.g., with Maven profiles) to include or exclude code based on the environment. This allows for different configurations for development, testing, and production.
- ## 2. Common Patterns and Anti-patterns
- ### 2.1 Design Patterns
- **Singleton:** Use the Singleton pattern sparingly and only when a single instance of a class is truly required. Consider dependency injection as an alternative.
- **Factory:** Use the Factory pattern to create objects without specifying their concrete classes. This promotes loose coupling and allows for easy substitution of different implementations.
- **Strategy:** Use the Strategy pattern to encapsulate different algorithms or behaviors. This allows you to switch between algorithms at runtime.
- **Observer:** Use the Observer pattern to define a one-to-many dependency between objects. This allows for loose coupling and easy addition of new observers.
- **Template Method:** Use the Template Method pattern to define the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the overall structure.
- **Builder:** Use the Builder pattern to construct complex objects with many optional parameters. This improves readability and reduces the risk of errors.
- ### 2.2 Recommended Approaches
- **Resource Management:** Always use try-with-resources to ensure proper resource management (e.g., closing streams, connections). This prevents resource leaks.
java
try (FileInputStream fis = new FileInputStream("file.txt")) {
// Use the file input stream
}
- **String Concatenation:** Use `StringBuilder` or `StringBuffer` for string concatenation, especially in loops. Avoid using the `+` operator for repeated string concatenation.
java
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
}
String result = sb.toString();
- **Collections:** Prefer Java Collections over arrays for their flexibility and utility. Use generics to ensure type safety.
- ### 2.3 Anti-patterns and Code Smells
- **God Class:** Avoid creating large classes that do too much. Break down large classes into smaller, more manageable components.
- **Long Method:** Avoid creating long methods. Break down long methods into smaller, more focused methods.
- **Shotgun Surgery:** Avoid making many small changes in multiple classes. This indicates a lack of cohesion and can make it difficult to maintain the code.
- **Data Clumps:** Avoid passing the same group of data items together in multiple methods. Create a class to encapsulate the data items.
- **Primitive Obsession:** Avoid using primitive types excessively. Create value objects to represent domain concepts.
- **Switch Statements:** Limit use of switch statements especially with larger number of cases. Consider using polymorphism with Strategy pattern.
- **Empty Catch Blocks:** Avoid empty catch blocks. Always handle exceptions appropriately, either by logging them, rethrowing them, or taking corrective action.
- ### 2.4 State Management
- **Immutability:** Prefer immutable objects whenever possible. Immutable objects are thread-safe and easier to reason about.
- **Stateless Services:** Design services to be stateless. This improves scalability and simplifies testing.
- **Session Management:** Use session management frameworks (e.g., Spring Session) to manage user sessions in web applications.
- ### 2.5 Error Handling
- **Exceptions for Exceptional Cases:** Use exceptions only for exceptional cases, not for normal control flow.
- **Specific Exception Types:** Catch specific exception types rather than generic `Exception`. This allows you to handle different types of errors differently.
- **Logging:** Log exceptions with sufficient context to aid debugging. Include the stack trace and any relevant data.
- **Custom Exceptions:** Create custom exception types to represent application-specific errors.
- **Don't Swallow Exceptions:** Never swallow exceptions without logging or handling them. It hides the exception making debugging much harder.
- ## 3. Performance Considerations
- ### 3.1 Optimization Techniques
- **Caching:** Use caching to store frequently accessed data in memory. Frameworks like Caffeine and Guava Cache provide efficient caching implementations.
- **Connection Pooling:** Use connection pooling to reuse database connections. This reduces the overhead of creating and closing connections.
- **Efficient Algorithms:** Choose appropriate algorithms for specific tasks. Consider the time and space complexity of different algorithms.
- **Lazy Initialization:** Use lazy initialization to defer the creation of objects until they are actually needed.
- **Minimize Object Creation:** Reduce unnecessary object creation. Use object pooling or reuse existing objects whenever possible.
- ### 3.2 Memory Management
- **Garbage Collection:** Understand how Java's garbage collector works. Avoid creating objects that are quickly discarded, as this puts pressure on the garbage collector.
- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage.
- **Large Objects:** Be careful when handling large objects. They can cause fragmentation and increase garbage collection times.
- ### 3.3 Rendering Optimization (If Applicable)
- **Buffering:** Use buffering to reduce the number of I/O operations when rendering large amounts of data.
- **Compression:** Use compression to reduce the size of rendered data.
- ### 3.4 Bundle Size Optimization (If Applicable)
- **Code Minification:** Use code minification to reduce the size of your codebase.
- **Dead Code Elimination:** Remove unused code to reduce the bundle size.
- ### 3.5 Lazy Loading
- **On-Demand Loading:** Load resources or components only when they are needed.
- **Virtual Proxy:** Use a virtual proxy to delay the loading of a heavy resource until it is accessed.
- ## 4. Security Best Practices
- ### 4.1 Common Vulnerabilities
- **SQL Injection:** Prevent SQL injection by using parameterized queries or prepared statements. Never concatenate user input directly into SQL queries.
- **Cross-Site Scripting (XSS):** Prevent XSS by encoding user input before displaying it in web pages.
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using anti-CSRF tokens.
- **Authentication and Authorization Issues:** Implement proper authentication and authorization mechanisms to protect sensitive resources.
- **Denial of Service (DoS):** Protect against DoS attacks by limiting request rates and implementing rate limiting.
- **Insecure Deserialization:** Prevent insecure deserialization by avoiding deserialization of untrusted data, or using secure deserialization methods.
- **Dependency Vulnerabilities:** Use tools like OWASP Dependency-Check to identify and mitigate vulnerabilities in third-party libraries.
- ### 4.2 Input Validation
- **Whitelisting:** Use whitelisting to validate input against a list of allowed values. Avoid blacklisting, as it is difficult to anticipate all possible malicious inputs.
- **Regular Expressions:** Use regular expressions to validate input patterns (e.g., email addresses, phone numbers).
- **Length Limits:** Enforce length limits on input fields to prevent buffer overflows.
- **Encoding:** Encode user input to prevent XSS attacks.
- ### 4.3 Authentication and Authorization
- **Strong Passwords:** Enforce strong password policies (e.g., minimum length, complexity).
- **Hashing:** Hash passwords using a strong hashing algorithm (e.g., bcrypt, Argon2) and a salt.
- **Two-Factor Authentication (2FA):** Implement 2FA to provide an extra layer of security.
- **Role-Based Access Control (RBAC):** Use RBAC to control access to resources based on user roles.
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
- ### 4.4 Data Protection
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and error messages.
- **Access Control:** Restrict access to sensitive data to authorized users only.
- ### 4.5 Secure API Communication
- **HTTPS:** Use HTTPS for all API communication.
- **TLS/SSL:** Configure TLS/SSL properly to ensure secure communication.
- **API Keys:** Use API keys to authenticate API clients.
- **Rate Limiting:** Implement rate limiting to prevent abuse of your APIs.
- **Input Validation:** Validate all input to your APIs to prevent injection attacks.
- ## 5. Testing Approaches
- ### 5.1 Unit Testing
- **JUnit:** Use JUnit for unit testing.
- **Mockito:** Use Mockito for mocking dependencies.
- **Arrange-Act-Assert:** Follow the Arrange-Act-Assert pattern in your unit tests.
- **Test Coverage:** Aim for high test coverage.
- **Independent Tests:** Write independent tests such that failure of one test doesn't affect another test.
- ### 5.2 Integration Testing
- **Testcontainers:** Use Testcontainers to create lightweight, disposable instances of databases and other services for integration testing.
- **Spring Boot Test:** Use Spring Boot's testing support for integration testing Spring applications.
- ### 5.3 End-to-End Testing
- **Selenium:** Use Selenium for end-to-end testing of web applications.
- **Cypress:** Consider Cypress as an alternative to Selenium for end-to-end tests.
- ### 5.4 Test Organization
- **Test Directory:** Place your tests in a separate `test` directory.
- **Naming Conventions:** Use clear naming conventions for your tests (e.g., `UserServiceTest`).
- **Test Suites:** Group related tests into test suites.
- ### 5.5 Mocking and Stubbing
- **Mockito:** Use Mockito to create mocks and stubs for your tests.
- **Verify Interactions:** Verify that your code interacts with dependencies as expected.
- **Avoid Over-Mocking:** Avoid mocking too many dependencies. Focus on mocking the dependencies that are critical to the test.
- ## 6. Common Pitfalls and Gotchas
- ### 6.1 Frequent Mistakes
- **NullPointerExceptions:** Handle null values carefully to avoid `NullPointerException`.
- **Resource Leaks:** Ensure that all resources are properly closed to avoid resource leaks.
- **Thread Safety Issues:** Be aware of thread safety issues when writing multithreaded code.
- **Ignoring Exceptions:** Never ignore exceptions without logging or handling them. It hides the exception making debugging much harder.
- ### 6.2 Edge Cases
- **Boundary Conditions:** Test boundary conditions to ensure that your code handles edge cases correctly.
- **Empty Collections:** Handle empty collections gracefully.
- **Invalid Input:** Validate input to ensure that it is within the expected range.
- ### 6.3 Version-Specific Issues
- **Deprecated APIs:** Be aware of deprecated APIs and avoid using them.
- **Compatibility Issues:** Test your code with different versions of Java to ensure compatibility.
- ### 6.4 Compatibility Concerns
- **JVM Compatibility:** Ensure that your code is compatible with different JVM implementations.
- **Library Compatibility:** Be aware of compatibility issues between different libraries.
- ### 6.5 Debugging Strategies
- **Logging:** Use logging to track the execution of your code and identify errors.
- **Debugging Tools:** Use debugging tools to step through your code and inspect variables.
- **Remote Debugging:** Use remote debugging to debug applications running on remote servers.
- **JVM Profilers:** Use profilers like JProfiler or VisualVM to identify performance bottlenecks and memory leaks.
- ## 7. Tooling and Environment
- ### 7.1 Recommended Tools
- **IntelliJ IDEA:** A powerful IDE for Java development with excellent code completion, refactoring, and debugging support.
- **Eclipse:** Another popular IDE for Java development.
- **Maven:** A build automation tool for managing dependencies, building, and deploying Java projects.
- **Gradle:** A build automation tool that provides more flexibility and control than Maven.
- ### 7.2 Build Configuration
- **Dependency Management:** Use Maven or Gradle to manage dependencies.
- **Version Control:** Use version control (e.g., Git) to track changes to your codebase.
- **Build Profiles:** Use build profiles to configure different builds for different environments.
- ### 7.3 Linting and Formatting
- **Checkstyle:** Use Checkstyle to enforce coding standards.
- **PMD:** Use PMD to find potential bugs and code smells.
- **SpotBugs:** Use SpotBugs to find potential bugs.
- **Formatter:** Use automatic code formatting tools like IntelliJ's built-in formatter or plugins like `google-java-format` for consistency.
- ### 7.4 Deployment
- **Docker:** Use Docker to containerize your applications.
- **Kubernetes:** Use Kubernetes to orchestrate your containers.
- **Cloud Platforms:** Deploy your applications to cloud platforms like AWS, Azure, or Google Cloud.
- ### 7.5 CI/CD
- **Jenkins:** Use Jenkins for continuous integration and continuous delivery.
- **GitHub Actions:** Use GitHub Actions for CI/CD.
- **GitLab CI:** Use GitLab CI for CI/CD.
- **Automated Testing:** Automate your unit, integration, and end-to-end tests in your CI/CD pipeline.
By adhering to these best practices, you can improve the quality, maintainability, and performance of your Java code. Remember to adapt these guidelines to your specific project requirements and team preferences.
+267
View File
@@ -0,0 +1,267 @@
---
description: This rule provides best practices and coding standards for the JAX library, emphasizing functional programming, JIT compilation, automatic differentiation, and immutable data structures. It also covers performance considerations, common pitfalls, and tooling recommendations.
globs: **/*.py
---
- **Functional Programming**: JAX emphasizes a functional programming style. Ensure functions are pure (no side effects, no reliance on global variables) for consistent JIT compilation and optimization.
- **JIT Compilation**: Use `@jax.jit` to decorate functions for performance optimization, especially those called multiple times with the same input shapes. Understand the implications of tracing and static arguments.
- **Automatic Differentiation**: Leverage `jax.grad()` for efficient gradient calculations and higher-order derivatives. Be mindful of how JAX handles gradients with control flow and other transformations.
- **Vectorization with `vmap`**: Utilize `jax.vmap()` for automatic vectorization instead of explicit loops. This improves performance by mapping operations across array dimensions.
- **Immutable Data Structures**: JAX arrays are immutable. Use `.at[].set()` for updates. Understand that these operations are out-of-place, returning a new array. In-place updates *may* occur under jit-compilation if the original value isn't reused, but rely on the functional style.
- **Random Number Generation**: Use `jax.random` for random number generation. Employ explicit PRNG state management. Always split the key using `jax.random.split()` before generating random numbers to avoid reusing the same state.
- **Control Flow**: Be aware of limitations when using Python control flow with `jax.jit`. Use `static_argnums` to specify arguments for tracing on concrete values if necessary. Consider structured control flow primitives like `lax.cond`, `lax.while_loop`, `lax.fori_loop`, and `lax.scan` for better traceability and avoiding large loop unrolling. Understand which control flow constructs are differentiable.
- **Dynamic Shapes**: Avoid dynamic shapes within JAX transformations like `jax.jit`, `jax.vmap`, and `jax.grad`. The shapes of output arrays must not depend on values within other arrays. Use techniques like `jnp.where` to work around the need for dynamically-sized arrays.
- **NaN Handling**: Use the NaN-checker during debugging by setting `JAX_DEBUG_NANS=True` or using `jax.config.update("jax_debug_nans", True)`. Be aware that this adds overhead and should be disabled in production.
- **Double Precision**: Enable double-precision numbers by setting the `jax_enable_x64` configuration variable at startup (`JAX_ENABLE_X64=True` environment variable, `jax.config.update("jax_enable_x64", True)`, or `jax.config.parse_flags_with_absl()`). Note that not all backends support 64-bit convolutions.
- **Non-array Inputs**: JAX generally expects NumPy arrays as inputs to its API functions. Avoid passing Python lists or tuples directly; convert them to arrays first.
- **Out-of-Bounds Indexing**: JAX handles out-of-bounds indexing by clamping the index to the bounds of the array for retrieval operations. Array update operations at out-of-bounds indices are skipped. Use the optional parameters of `ndarray.at` for finer-grained control.
- **Miscellaneous Divergences from NumPy**: Be aware of differences in type promotion rules, unsafe type casts, and other corner cases where JAX's behavior may differ from NumPy.
## Code Organization and Structure:
- **Directory Structure**: Consider a structure like this:
project_root/
├── src/
│ ├── __init__.py
│ ├── models/
│ │ ├── __init__.py
│ │ ├── model_a.py
│ │ └── model_b.py
│ ├── layers/
│ │ ├── __init__.py
│ │ ├── layer_a.py
│ │ └── layer_b.py
│ ├── utils/
│ │ ├── __init__.py
│ │ ├── data_loading.py
│ │ └── evaluation.py
│ ├── train.py
│ └── predict.py
├── tests/
│ ├── __init__.py
│ ├── models/
│ │ ├── test_model_a.py
│ │ └── test_model_b.py
│ ├── utils/
│ │ ├── test_data_loading.py
│ │ └── test_evaluation.py
│ └── test_train.py
├── notebooks/
│ ├── exploration.ipynb
│ └── analysis.ipynb
├── data/
│ ├── raw/
│ └── processed/
├── models/
│ └── saved_models/
├── .gitignore
├── README.md
├── requirements.txt
└── setup.py
- **File Naming**: Use descriptive, lowercase names with underscores (e.g., `data_loading.py`, `model_a.py`).
- **Module Organization**: Group related functionalities into modules. Use clear and concise module names.
- **Component Architecture**: Favor a modular architecture. Decouple components where possible. Use interfaces or abstract base classes when appropriate.
- **Code Splitting**: Split large files into smaller, more manageable modules. Consider splitting based on functionality or abstraction level.
## Common Patterns and Anti-patterns:
- **Design Patterns**: Consider patterns like:
- **Strategy**: For selecting different computation strategies at runtime.
- **Factory**: For creating JAX models or layers.
- **Observer**: For monitoring training progress.
- **Recommended Approaches**:
- Using `jax.tree_util` for working with nested data structures (pytrees).
- Caching intermediate results with `lru_cache` (with caution, as it introduces state).
- Using `jax.experimental.optimizers` for defining optimization schedules.
- **Anti-patterns**:
- Mutable global state within JIT-compiled functions.
- Excessive use of `static_argnums` (leads to recompilation).
- Ignoring the immutability of JAX arrays.
- Using Python loops instead of vectorized operations (`vmap`).
- Unnecessary host-device data transfers.
- Reusing PRNG keys without splitting.
- **State Management**:
- Avoid global mutable state. Pass state explicitly as function arguments.
- Consider using immutable data structures for state.
- If mutable state is absolutely necessary (e.g., in some RL settings), use JAX's stateful computation tools carefully (e.g., `jax.lax.scan` with a carry).
- **Error Handling**:
- Use `try...except` blocks for handling potential errors during data loading or preprocessing.
- Employ assertions to check for invalid input or unexpected conditions.
- Utilize logging to track errors and debug issues.
- The `JAX_DEBUG_NANS` and `JAX_DEBUG_NANS=True` flag is critical when debugging `NaN`.
## Performance Considerations:
- **Optimization Techniques**:
- JIT compilation (`jax.jit`).
- Vectorization (`jax.vmap`).
- Parallelization (`jax.pmap`).
- Fusion of operations.
- Reducing host-device data transfers.
- Choose appropriate data types (e.g., `float32` instead of `float64` if sufficient).
- Use `jax.numpy` functions instead of NumPy functions where possible.
- Avoid scalar operations inside JIT-compiled loops; use array operations.
- **Memory Management**:
- Minimize the creation of large intermediate arrays.
- Reuse arrays where possible (using `.at[].set()` for in-place updates if safe to do so).
- Be aware of memory fragmentation.
- If you are dealing with datasets larger than memory, explore data streaming/sharding approaches.
- **Rendering Optimization**: (Relevant if using JAX for visualization, e.g., with OpenGL or similar libraries)
- Batch rendering operations.
- Optimize data transfer to the rendering device (e.g., GPU).
- Consider using specialized rendering libraries that are compatible with JAX arrays.
- **Bundle Size Optimization**: (For JAX-based applications deployed in web environments)
- Tree-shake unused code.
- Minify JavaScript bundles.
- Use code splitting to load only necessary modules.
- Compress assets (e.g., images, data files).
- **Lazy Loading**:
- Load data or models only when needed.
- Use iterators or generators for large datasets.
- Implement a loading indicator to provide feedback to the user.
## Security Best Practices:
- **Common Vulnerabilities**:
- Input data poisoning.
- Model inversion attacks.
- Adversarial examples.
- Side-channel attacks (less relevant in typical JAX applications, but important in cryptographic applications).
- **Input Validation**:
- Validate input data types and ranges.
- Sanitize input data to prevent injection attacks.
- Use schema validation libraries (e.g., `cerberus`, `jsonschema`).
- **Authentication and Authorization**: (If building APIs or web services with JAX)
- Implement secure authentication mechanisms (e.g., OAuth 2.0, JWT).
- Use role-based access control (RBAC) to restrict access to sensitive resources.
- Protect API endpoints with appropriate authentication and authorization checks.
- **Data Protection**:
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms for models and data.
- Implement data masking or anonymization techniques to protect personally identifiable information (PII).
- **Secure API Communication**:
- Use HTTPS for all API communication.
- Implement proper rate limiting to prevent denial-of-service attacks.
- Use secure coding practices to prevent common web vulnerabilities (e.g., cross-site scripting, SQL injection).
## Testing Approaches:
- **Unit Testing**:
- Test individual functions or classes in isolation.
- Use `pytest` or `unittest` for writing unit tests.
- Mock external dependencies to isolate the code under test.
- Test different input scenarios and edge cases.
- Use `jax.random.PRNGKey` with a fixed seed for reproducible tests.
- **Integration Testing**:
- Test the interaction between different components or modules.
- Verify that data flows correctly between components.
- Test the integration with external services or databases.
- **End-to-End Testing**:
- Test the entire application flow from start to finish.
- Simulate real user interactions.
- Verify that the application meets the specified requirements.
- Use tools like Selenium or Cypress for end-to-end testing.
- **Test Organization**:
- Organize tests into separate directories or modules.
- Use descriptive test names.
- Follow a consistent testing style.
- **Mocking and Stubbing**:
- Use `unittest.mock` or `pytest-mock` for mocking external dependencies.
- Create stubs for complex or time-consuming operations.
- Mock JAX functions (e.g., `jax.random.normal`) to control the output of random number generators.
## Common Pitfalls and Gotchas:
- **Frequent Mistakes**:
- Mutable global state in JIT-compiled functions.
- Incorrect use of `static_argnums`.
- Ignoring JAX array immutability.
- Using Python loops instead of `vmap`.
- Reusing PRNG keys without splitting.
- **Edge Cases**:
- Handling `NaN` and `Inf` values.
- Dealing with numerical instability.
- Working with sparse data.
- Optimizing for different hardware backends (CPU, GPU, TPU).
- **Version-Specific Issues**:
- Be aware of breaking changes between JAX versions.
- Consult the JAX documentation for the latest updates and bug fixes.
- **Compatibility Concerns**:
- Ensure compatibility between JAX and other libraries (e.g., TensorFlow, PyTorch).
- Be aware of potential conflicts between JAX and NumPy versions.
- **Debugging Strategies**:
- Use the JAX debugger (`jax.debug.print`).
- Set `JAX_DEBUG_NANS=True` to detect `NaN` values.
- Use `jax.make_jaxpr` to inspect the JAX program representation.
- Use `jax.debug.visualize_jaxpr` to visualize the JAX program flow (requires graphviz).
- Profile your code to identify performance bottlenecks.
- Use a debugger (e.g., `pdb`) to step through your code and inspect variables.
## Tooling and Environment:
- **Recommended Development Tools**:
- VS Code with the Python extension.
- Jupyter Notebook or JupyterLab for interactive development.
- IPython for a powerful interactive shell.
- TensorBoard for visualizing training progress.
- **Build Configuration**:
- Use `requirements.txt` or `setup.py` to manage dependencies.
- Specify JAX version requirements.
- Use a virtual environment (e.g., `venv`, `conda`) to isolate dependencies.
- **Linting and Formatting**:
- Use `flake8` or `pylint` for linting.
- Use `black` or `autopep8` for formatting.
- Configure your editor to automatically lint and format code on save.
- **Deployment Best Practices**:
- Package your application into a Docker container.
- Use a cloud platform (e.g., AWS, Google Cloud, Azure) for deployment.
- Use a deployment framework (e.g., Flask, FastAPI) for serving APIs.
- Monitor your application for performance and errors.
- **CI/CD Integration**:
- Use a CI/CD platform (e.g., GitHub Actions, Travis CI, CircleCI).
- Automate testing, linting, and formatting.
- Automate deployment to staging and production environments.
This comprehensive guide should help developers write better JAX code, avoid common pitfalls, and build high-performance machine learning applications.
+194
View File
@@ -0,0 +1,194 @@
---
description: Comprehensive best practices for Jenkins, covering code organization, security, performance, testing, and common pitfalls. Provides guidelines for writing robust, maintainable, and secure Jenkins pipelines and configurations.
globs: **/{Jenkinsfile,*.jenkins,*.groovy}
---
# Jenkins Library Best Practices and Coding Standards
This document outlines best practices for developing and maintaining Jenkins pipelines and configurations to ensure robustness, security, and efficiency.
## 1. Code Organization and Structure
* **Directory Structure:**
* `/vars/`: Store shared pipeline libraries (Groovy files). Each file in this directory represents a callable method.
* `/resources/`: Place non-Groovy resources like configuration files or scripts used by the pipeline.
* `Jenkinsfile`: The primary pipeline definition file, typically at the root of the repository.
* `.cursor/rules`: Where .mdc rule files should be
* **File Naming Conventions:**
* Pipeline definitions: `Jenkinsfile` (recommended), or `<project-name>.jenkins`
* Shared libraries: `lowercaseCamelCase.groovy` (e.g., `buildImage.groovy`)
* Resource files: Descriptive names with appropriate extensions (e.g., `settings.xml`, `deploy.sh`)
* **Module Organization:**
* Break down complex pipelines into smaller, reusable shared libraries.
* Group related functions within shared libraries into logical modules.
* Use descriptive names for shared libraries to indicate their purpose (e.g., `awsUtils.groovy`, `dockerBuild.groovy`).
* **Component Architecture:**
* Adopt a modular design for shared libraries, separating concerns and promoting reusability.
* Create abstract functions that can be extended or customized for specific projects.
* Avoid tightly coupling shared libraries to specific projects or environments.
* **Code Splitting Strategies:**
* Split long `Jenkinsfile`s into multiple files using `load()` or shared libraries. This improves readability and maintainability.
* Delegate complex tasks to external scripts or tools invoked from the pipeline.
* Use environment variables to parameterize pipeline behavior and avoid hardcoding values.
## 2. Common Patterns and Anti-patterns
* **Design Patterns:**
* **Strategy Pattern:** Implement different build or deployment strategies based on input parameters.
* **Template Method Pattern:** Define a base pipeline structure with customizable steps for specific projects.
* **Facade Pattern:** Create a simplified interface to complex systems or tools.
* **Recommended Approaches:**
* Use declarative pipelines for improved readability and maintainability.
* Employ shared libraries to promote code reuse and consistency.
* Automate testing and security scanning within the pipeline.
* Monitor pipeline performance and optimize for speed and efficiency.
* Use a version control system (e.g., Git) to track changes to pipeline definitions and shared libraries.
* **Anti-patterns and Code Smells:**
* **Large, monolithic `Jenkinsfile`s:** Difficult to read, maintain, and debug.
* **Hardcoding sensitive information:** Compromises security and makes pipelines inflexible.
* **Lack of error handling:** Pipelines fail without clear error messages or recovery mechanisms.
* **Excessive Groovy scripting:** Can impact performance and increase complexity. Delegate tasks to external tools where possible.
* **Ignoring security vulnerabilities:** Exposes systems to potential attacks.
* **Duplicated code across pipelines:** Indicates a need for shared libraries.
* **State Management:**
* Use environment variables to store pipeline state.
* Persist state to external systems (e.g., databases, artifact repositories) for long-running pipelines.
* Avoid relying on global variables or mutable shared state.
* **Error Handling:**
* Use `try...catch` blocks to handle exceptions and prevent pipeline failures.
* Log error messages with sufficient detail to facilitate debugging.
* Implement retry mechanisms for transient errors.
* Use the `error` step to explicitly fail the pipeline with a custom message.
* Consider using `unstash` with error handling to clean up temporary files.
## 3. Performance Considerations
* **Optimization Techniques:**
* Parallelize build and test stages to reduce overall execution time.
* Use caching to avoid redundant downloads and computations.
* Optimize Groovy code for performance (e.g., avoid unnecessary iterations).
* Use lightweight agents with sufficient resources to handle the workload.
* Leverage build accelerators and distributed build systems.
* **Memory Management:**
* Avoid loading large files into memory using `JsonSlurper` or `XmlSlurper`. Use `sh` step with tools like `jq` or `xmllint` instead.
* Limit the use of global variables and shared state to reduce memory consumption.
* Monitor agent memory usage and adjust agent resources accordingly.
* **Bundle Size Optimization:** (Not directly applicable to Jenkins pipelines but relevant to applications built by Jenkins)
* Minimize dependencies and remove unused code.
* Use code splitting to load only the necessary code modules.
* Compress artifacts before archiving or deploying them.
* **Lazy Loading:** (Not directly applicable to Jenkins pipelines themselves, but is related to web applications that are built using Jenkins).
* Load resources on demand instead of upfront to reduce initial load time.
* Defer the execution of non-critical tasks until they are needed.
* Utilize asynchronous operations to avoid blocking the pipeline execution.
## 4. Security Best Practices
* **Common Vulnerabilities:**
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent malicious code injection.
* **Cross-Site Request Forgery (CSRF):** Enable CSRF protection to prevent unauthorized requests.
* **Remote Code Execution (RCE):** Avoid executing untrusted code within the pipeline.
* **Credential Theft:** Protect sensitive credentials using Jenkins' credential management system.
* **Unauthorized Access:** Implement role-based access control to restrict access to sensitive resources.
* **Input Validation:**
* Validate all user inputs to prevent malicious code injection and data corruption.
* Use parameterized builds with predefined choices to limit user input.
* Encode or escape special characters to prevent interpretation as code.
* **Authentication and Authorization:**
* Enable security and configure authentication using Jenkins' built-in user database or an external identity provider (e.g., LDAP, Active Directory).
* Implement role-based access control (RBAC) to restrict access to sensitive resources and operations.
* Use the principle of least privilege to grant only the necessary permissions to users and groups.
* Regularly audit user permissions and remove unnecessary accounts.
* **Data Protection:**
* Use Jenkins' credential management system to securely store passwords, API keys, and other sensitive information.
* Encrypt sensitive data at rest and in transit.
* Mask sensitive information in build logs to prevent exposure.
* Rotate credentials regularly to minimize the impact of potential breaches.
* **Secure API Communication:**
* Use HTTPS to encrypt communication between Jenkins and other systems.
* Authenticate all API requests using secure tokens or credentials.
* Limit API access to authorized users or systems.
* Rate-limit API requests to prevent denial-of-service attacks.
## 5. Testing Approaches
* **Unit Testing:**
* Test individual functions or modules in isolation.
* Use mocking and stubbing to isolate dependencies.
* Write unit tests for shared libraries to ensure they function correctly.
* **Integration Testing:**
* Test the interaction between different components or services.
* Verify that shared libraries integrate correctly with the pipeline.
* Use containerization to create isolated test environments.
* **End-to-End Testing:**
* Test the entire pipeline workflow from start to finish.
* Simulate real-world scenarios and user interactions.
* Use automated testing tools to execute end-to-end tests.
* **Test Organization:**
* Organize tests into logical suites based on functionality or component.
* Use descriptive names for test cases to indicate their purpose.
* Run tests automatically as part of the pipeline.
* Generate test reports and track test results over time.
* **Mocking and Stubbing:**
* Use mocking frameworks to create mock objects that simulate the behavior of dependencies.
* Stub external services or APIs to isolate the system under test.
* Use environment variables to configure mocking behavior.
## 6. Common Pitfalls and Gotchas
* **Frequent Mistakes:**
* Failing to secure Jenkins instance.
* Overusing Groovy scripting leading to performance degradation.
* Not using shared libraries for reusable code.
* Hardcoding credentials and other secrets.
* Lack of proper error handling.
* Ignoring pipeline performance monitoring.
* **Edge Cases:**
* Handling concurrent builds and resource contention.
* Dealing with flaky tests and intermittent failures.
* Managing large files and artifacts within the pipeline.
* Supporting different operating systems and environments.
* **Version-Specific Issues:**
* Compatibility issues between Jenkins versions and plugins.
* Deprecated APIs and features.
* Security vulnerabilities in older versions.
* **Compatibility Concerns:**
* Ensure compatibility between Jenkins and the tools and technologies used in the pipeline (e.g., Docker, Kubernetes, AWS).
* Test pipelines on different platforms to ensure cross-platform compatibility.
* **Debugging Strategies:**
* Use build logs and console output to diagnose pipeline failures.
* Add debug statements to Groovy code to trace execution flow.
* Use remote debugging tools to step through pipeline execution.
* Reproduce pipeline failures locally to isolate the cause.
* Utilize the `script` step with caution for complex logic, ensuring proper error handling.
* Review plugin documentation for common issues and troubleshooting tips.
## 7. Tooling and Environment
* **Recommended Development Tools:**
* IDE with Groovy support (e.g., IntelliJ IDEA, Eclipse).
* Version control system (e.g., Git).
* Build automation tools (e.g., Maven, Gradle).
* Testing frameworks (e.g., JUnit, TestNG).
* Containerization tools (e.g., Docker).
* **Build Configuration:**
* Use parameterized builds to allow users to customize build behavior.
* Define build triggers to automatically start builds on code changes or schedule.
* Configure post-build actions to archive artifacts, send notifications, or deploy the application.
* Use the `buildDiscarder` directive to clean up old builds and save disk space.
* **Linting and Formatting:**
* Use a Groovy linter to enforce coding standards and identify potential errors.
* Format Groovy code consistently to improve readability.
* Use tools like `groovy-lint` or IDE plugins for linting and formatting.
* **Deployment:**
* Use deployment plugins to automate the deployment process.
* Implement blue-green deployments or rolling deployments to minimize downtime.
* Use feature flags to decouple deployment from release.
* Use a cloud-native deployment strategy (e.g., Kubernetes) for scalable and resilient deployments.
* **CI/CD Integration:**
* Integrate Jenkins with other CI/CD tools (e.g., SonarQube, Artifactory).
* Use webhooks to trigger builds from version control systems.
* Monitor pipeline performance and identify areas for improvement.
* Implement continuous feedback loops to improve the quality of the application and the pipeline.
* Leverage Infrastructure as Code (IaC) tools such as Terraform to create ephemeral testing and build environments
By following these best practices, developers can create robust, maintainable, and secure Jenkins pipelines and configurations that streamline the software development process and improve the quality of the application.
+410
View File
@@ -0,0 +1,410 @@
---
description: This rule file provides guidelines for jQuery development, covering code organization, performance, security, and testing. It helps developers write maintainable, efficient, and secure jQuery code.
globs: **/*.js
---
# jQuery Best Practices: A Comprehensive Guide
This document outlines best practices for jQuery development to ensure code quality, performance, security, and maintainability.
## Library Information:
- Name: jQuery
- Tags: javascript, dom, library, frontend
## 1. Code Organization and Structure
A well-structured project improves maintainability, collaboration, and scalability.
### 1.1. Directory Structure Best Practices
Adopt a clear and consistent directory structure:
project-root/
├── css/
│ ├── style.css
│ └── components/
│ └── component.css
├── js/
│ ├── jquery.min.js # jQuery library (ideally from a CDN)
│ ├── app.js # Main application file
│ ├── modules/
│ │ ├── module1.js
│ │ └── module2.js
│ ├── components/
│ │ ├── component1.js
│ │ └── component2.js
│ └── utils/
│ ├── helperFunctions.js
│ └── ajaxUtils.js
├── img/
│ └── ...
├── index.html
├── .eslintrc.js # ESLint configuration (see linting section)
└── package.json # Project dependencies and scripts
**Explanation:**
- `css/`: Contains all CSS files, potentially organized into components.
- `js/`: Contains all JavaScript files, including the main application script, modules, components, and utility functions.
- `img/`: Contains images.
- `index.html`: The main HTML file.
- `.eslintrc.js`: Configuration file for ESLint (JavaScript linter).
- `package.json`: Defines project dependencies and scripts.
### 1.2. File Naming Conventions
Use descriptive and consistent file names:
- JavaScript files: `[componentName].js`, `[moduleName].js`, `[utilityName].js` (e.g., `navigation.js`, `userAuthentication.js`, `dateFormatter.js`).
- CSS files: `[componentName].css`, `style.css`.
- jQuery plugins: `jquery.[pluginName].js`.
### 1.3. Module Organization Best Practices
Organize code into logical modules:
- **Encapsulation:** Each module should encapsulate a specific functionality or feature.
- **Loose Coupling:** Modules should be loosely coupled to minimize dependencies and promote reusability.
- **Revealing Module Pattern:** Use the revealing module pattern to expose only the necessary functions and variables.
javascript
// js/modules/userAuthentication.js
const userAuthentication = (function() {
let isAuthenticated = false;
function login(username, password) {
// Authentication logic (e.g., AJAX call)
// ...
isAuthenticated = true;
}
function logout() {
// Logout logic
//...
isAuthenticated = false;
}
function isLoggedIn() {
return isAuthenticated;
}
return {
login: login,
logout: logout,
isLoggedIn: isLoggedIn
};
})();
// In app.js
$(document).ready(function() {
if (userAuthentication.isLoggedIn()) {
// Update UI for logged-in user
}
});
### 1.4. Component Architecture Recommendations
Break down the UI into reusable components:
- **Modularity:** Components should be self-contained and independent.
- **Reusability:** Components should be designed for reuse across the application.
- **Maintainability:** Component-based architecture simplifies code updates and maintenance.
javascript
// js/components/navigation.js
function Navigation(elementId, options) {
this.element = $('#' + elementId);
this.options = $.extend({}, { /* Default options */ }, options);
this.init = function() {
// Component initialization
this.element.on('click', '.nav-item', this.handleNavigation.bind(this));
};
this.handleNavigation = function(event) {
event.preventDefault();
// Navigation logic
console.log('Navigating to:', $(event.target).attr('href'));
};
this.init();
}
// In app.js
$(document).ready(function() {
const nav = new Navigation('main-nav', {
// Custom options
});
});
### 1.5. Code Splitting Strategies
Improve initial load time by splitting code into smaller chunks:
- **On-Demand Loading:** Load modules or components only when they are needed.
- **Route-Based Splitting:** Load code specific to a particular route or page.
- **Conditional Loading:** Load code based on user interactions or device capabilities.
javascript
// Example: Loading a module on button click
$('#load-module-button').on('click', function() {
$.getScript('js/modules/heavyModule.js', function() {
// Module loaded and executed
heavyModule.init();
});
});
## 2. Common Patterns and Anti-patterns
Employ established design patterns to improve code quality and avoid common mistakes.
### 2.1. Design Patterns Specific to jQuery
- **Module Pattern:** (See section 1.3). Encapsulates code and prevents global scope pollution.
- **Observer Pattern:** Facilitates communication between components without tight coupling. jQuery's event system is essentially an implementation of the observer pattern.
- **Facade Pattern:** Provides a simplified interface to a complex system (e.g., jQuery's `$`).
### 2.2. Recommended Approaches for Common Tasks
- **DOM Manipulation:** Minimize direct DOM manipulation. Use document fragments for batch updates.
- **Event Handling:** Implement event delegation for dynamically added elements.
- **AJAX:** Use `$.ajax()` for flexible AJAX requests. Use promises for asynchronous operations.
### 2.3. Anti-patterns and Code Smells
- **Global Variables:** Avoid using global variables to prevent naming conflicts and unexpected behavior.
- **Chaining Overuse:** Long chains can be difficult to read. Break them into smaller, more manageable chunks.
- **Excessive DOM Traversal:** Minimize DOM traversal by caching selectors.
- **Ignoring Performance:** Avoid complex selectors and inefficient DOM manipulation.
- **Inconsistent Coding Style:** Adhere to a consistent coding style to improve readability.
- **Mixing Concerns:** Separate HTML structure, CSS styling, and JavaScript behavior.
- **Deprecated Methods**: Avoid using deprecated methods.
### 2.4. State Management Best Practices
- **Keep it Simple:** For small applications, simple variables or data attributes may be sufficient.
- **Centralized Store:** For larger applications, consider a centralized state management solution (though jQuery is rarely used on its own for complex single page apps that require advanced state management).
- **Data Attributes:** Use data attributes (`data-*`) to store component-specific data.
### 2.5. Error Handling Patterns
- **Try-Catch Blocks:** Use `try-catch` blocks to handle exceptions gracefully.
- **AJAX Error Handling:** Implement error handling for AJAX requests using the `error` callback or `$.Deferred`'s `fail` method.
- **Global Error Handler:** Set up a global error handler to catch unhandled exceptions.
javascript
$.ajax({
url: 'api/data',
dataType: 'json',
success: function(data) {
// Process data
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX error:', textStatus, errorThrown);
// Display error message to the user
}
});
## 3. Performance Considerations
Optimize code for speed and efficiency.
### 3.1. Optimization Techniques
- **Selector Optimization:** Use ID selectors whenever possible. Be specific on the right-hand side of your selector and less specific on the left. Give your Selectors a Context.
- **Caching Selectors:** Cache jQuery selector returned objects in variables for reuse.
- **Minimize DOM Manipulations:** Batch updates, use document fragments, and detach elements before manipulation.
- **Event Delegation:** Use event delegation to reduce the number of event listeners.
- **Debouncing and Throttling:** Limit the rate at which a function is executed.
### 3.2. Memory Management Considerations
- **Avoid Memory Leaks:** Remove event listeners and data when elements are removed from the DOM.
- **Release References:** Set variables to `null` to release memory when they are no longer needed.
- **Garbage Collection:** Understand how JavaScript garbage collection works and avoid creating unnecessary objects.
### 3.3. Rendering Optimization
- **Minimize Reflows and Repaints:** Reduce the number of DOM manipulations that cause reflows and repaints.
- **Use CSS Transitions and Animations:** Use CSS transitions and animations instead of jQuery animations for better performance.
- **Hardware Acceleration:** Leverage hardware acceleration for smooth animations.
### 3.4. Bundle Size Optimization
- **Minification:** Use minification to reduce file sizes.
- **Gzip Compression:** Enable Gzip compression on the server to reduce the size of transferred files.
- **Code Splitting:** Split code into smaller chunks to improve initial load time (see section 1.5).
### 3.5. Lazy Loading Strategies
- **Lazy Load Images:** Load images only when they are visible in the viewport.
- **Lazy Load Modules:** Load modules or components only when they are needed (see section 1.5).
- **Use a Lazy Loading Library:** Consider using a library like `lozad.js` for easy lazy loading.
## 4. Security Best Practices
Protect your application against common vulnerabilities.
### 4.1. Common Vulnerabilities and Prevention
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. Use jQuery's `text()` method to set text content instead of `html()` to prevent injecting HTML code.
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection tokens.
- **SQL Injection:** Never directly use client-side data in database queries. Use parameterized queries or ORMs.
- **Open Redirects:** Validate and sanitize redirect URLs to prevent open redirects.
- **Dependency Vulnerabilities:** Keep jQuery and all dependencies up to date to patch security vulnerabilities.
### 4.2. Input Validation Best Practices
- **Client-Side Validation:** Implement client-side validation to provide immediate feedback to the user.
- **Server-Side Validation:** Always perform server-side validation to ensure data integrity.
- **Sanitize Input:** Sanitize user input to remove potentially harmful characters.
### 4.3. Authentication and Authorization Patterns
- **Use HTTPS:** Always use HTTPS to encrypt data in transit.
- **Secure Cookies:** Set the `secure` and `httpOnly` flags for cookies.
- **Authentication Tokens:** Use authentication tokens (e.g., JWT) for secure authentication.
- **Role-Based Access Control (RBAC):** Implement RBAC to restrict access to sensitive resources.
### 4.4. Data Protection Strategies
- **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in the UI to prevent unauthorized access.
- **Regular Backups:** Perform regular backups of your data.
### 4.5. Secure API Communication
- **Use HTTPS:** Always use HTTPS for API communication.
- **API Keys:** Use API keys to authenticate requests.
- **Rate Limiting:** Implement rate limiting to prevent abuse.
- **Input Validation:** Validate all input data on the server-side.
## 5. Testing Approaches
Write tests to ensure code quality and prevent regressions.
### 5.1. Unit Testing Strategies
- **Test Individual Components:** Write unit tests for individual components and modules.
- **Use a Testing Framework:** Use a JavaScript testing framework like QUnit or Jasmine.
- **Mock Dependencies:** Mock dependencies to isolate the component being tested.
### 5.2. Integration Testing Approaches
- **Test Interactions:** Write integration tests to test the interactions between components.
- **Use a Testing Framework:** Use a testing framework like Mocha or Jest.
- **Test API Integrations:** Test the integration with external APIs.
### 5.3. End-to-End Testing Recommendations
- **Simulate User Interactions:** Write end-to-end tests to simulate user interactions.
- **Use a Testing Framework:** Use a testing framework like Cypress or Puppeteer.
- **Test Critical Paths:** Test the critical paths through the application.
### 5.4. Test Organization
- **Separate Test Files:** Create separate test files for each component or module.
- **Use Descriptive Names:** Use descriptive names for test cases.
- **Organize Tests:** Organize tests into logical groups.
### 5.5. Mocking and Stubbing Techniques
- **Mock AJAX Requests:** Mock AJAX requests to isolate the component being tested.
- **Stub Functions:** Stub functions to control their behavior.
- **Use a Mocking Library:** Use a mocking library like Sinon.js.
javascript
// Example using QUnit and Sinon.js
QUnit.module('User Authentication Module', function(hooks) {
hooks.beforeEach(function() {
this.ajax = sinon.stub($, 'ajax');
});
hooks.afterEach(function() {
this.ajax.restore();
});
QUnit.test('login() should make an AJAX request', function(assert) {
this.ajax.resolves({ success: true });
userAuthentication.login('testuser', 'password');
assert.ok(this.ajax.calledOnce, 'AJAX request was made');
});
});
## 6. Common Pitfalls and Gotchas
Be aware of common mistakes and edge cases.
### 6.1. Frequent Mistakes
- **Not Caching Selectors:** Re-querying the DOM for the same element repeatedly.
- **Using Incorrect Scope (`this`):** Understanding the scope of `this` in event handlers and callbacks.
- **Ignoring Errors:** Not handling errors properly in AJAX requests and other asynchronous operations.
- **Overusing jQuery:** Using jQuery for tasks that can be done more efficiently with native JavaScript.
### 6.2. Edge Cases
- **Browser Compatibility:** Testing your code in different browsers and versions.
- **Mobile Devices:** Optimizing your code for mobile devices.
- **Accessibility:** Ensuring your code is accessible to users with disabilities.
### 6.3. Version-Specific Issues
- **Deprecated Methods:** Being aware of deprecated methods in newer versions of jQuery.
- **API Changes:** Understanding API changes between different versions of jQuery.
### 6.4. Compatibility Concerns
- **Conflicting Libraries:** Avoiding conflicts with other JavaScript libraries (e.g., Prototype, MooTools) using `$.noConflict()`.
- **Plugin Compatibility:** Ensuring that jQuery plugins are compatible with the version of jQuery being used.
### 6.5. Debugging Strategies
- **Use Browser Developer Tools:** Use browser developer tools to inspect elements, debug JavaScript code, and profile performance.
- **Console Logging:** Use `console.log()` to debug your code.
- **Breakpoints:** Set breakpoints in your code to pause execution and inspect variables.
## 7. Tooling and Environment
Use the right tools to improve productivity and code quality.
### 7.1. Recommended Development Tools
- **Text Editor/IDE:** Visual Studio Code, Sublime Text, Atom.
- **Browser:** Chrome, Firefox, Safari.
- **Debugging Tools:** Chrome DevTools, Firefox Developer Tools.
- **Build Tools:** Webpack, Parcel, Gulp.
- **Testing Frameworks:** QUnit, Jasmine, Mocha, Jest.
### 7.2. Build Configuration
- **Use a Build Tool:** Use a build tool like Webpack or Parcel to bundle and optimize your code.
- **Configure Loaders:** Configure loaders to handle different file types (e.g., JavaScript, CSS, images).
- **Optimize Output:** Optimize the output of the build process for production.
### 7.3. Linting and Formatting
- **Use a Linter:** Use a linter like ESLint to enforce coding standards and catch errors.
- **Configure Rules:** Configure linting rules to match your project's coding style.
- **Use a Formatter:** Use a code formatter like Prettier to automatically format your code.
### 7.4. Deployment
- **Minify and Gzip:** Minify and Gzip your code before deploying it.
- **Use a CDN:** Use a CDN to host static assets.
- **Cache Control Headers:** Set appropriate cache control headers.
### 7.5. CI/CD Integration
- **Automated Builds:** Automate the build process using a CI/CD tool like Jenkins, Travis CI, or GitHub Actions.
- **Automated Testing:** Automate the testing process using a CI/CD tool.
- **Automated Deployment:** Automate the deployment process using a CI/CD tool.
By following these best practices, developers can write high-quality, performant, and secure jQuery code that is easy to maintain and scale.
+256
View File
@@ -0,0 +1,256 @@
---
description: Comprehensive guidelines and best practices for writing effective, maintainable, and performant JUnit tests in Java projects. This rule file covers code organization, patterns, performance, security, testing strategies, common pitfalls, and tooling.
globs: **/*Test.java
---
# JUnit Best Practices: A Comprehensive Guide
This document provides a comprehensive guide to JUnit best practices, covering code organization, patterns, performance considerations, security, testing approaches, common pitfalls, and tooling. Following these guidelines will help you write effective, maintainable, and performant unit tests.
## 1. Code Organization and Structure
### 1.1. Directory Structure
- **Standard Maven/Gradle Project Structure:** Maintain the standard Maven/Gradle project structure to separate test code from production code.
- Production code: `src/main/java/com/example/app/...`
- Test code: `src/test/java/com/example/app/...`
- **Mirror Production Structure:** Mirror the production code structure in the test directory to improve discoverability and maintainability.
- Example:
- Production: `src/main/java/com/example/app/service/UserService.java`
- Test: `src/test/java/com/example/app/service/UserServiceTest.java`
- **Test Resources:** Place test resources (e.g., configuration files, data files, mock response files) in the `src/test/resources` directory.
### 1.2. File Naming Conventions
- **Test Class Names:** Use the `*Test.java` or `*Tests.java` suffix for test class names to clearly identify them.
- Example: `UserServiceTest.java`, `StringUtilsTests.java`
- **Test Method Names:** Use descriptive test method names that clearly indicate the scenario and expected outcome.
- Follow a naming convention like `given_condition_when_action_then_expectedResult`.
- Example: `givenValidInput_whenCalculateSum_thenReturnsCorrectSum`
### 1.3. Module Organization
- **Modular Testing:** Organize tests by module or component to improve maintainability and reduce dependencies.
- **Test Suites:** Use JUnit test suites to group related tests and run them together. This is especially useful for integration tests.
- **Separate Test Configuration:** Keep test-specific configurations separate from production configurations.
### 1.4. Component Architecture
- **Testable Components:** Design components to be easily testable by following the SOLID principles (especially Dependency Inversion).
- **Loose Coupling:** Minimize dependencies between components to facilitate isolated unit testing.
- **Dependency Injection:** Use dependency injection to provide mock implementations of dependencies during testing.
### 1.5. Code Splitting Strategies
- **Small Test Methods:** Keep test methods small and focused on testing a single behavior.
- **Helper Methods:** Use helper methods to avoid code duplication in test setup and assertions.
- **Parameterized Tests:** Utilize JUnit's parameterized tests to test the same logic with different input values.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Arrange-Act-Assert (AAA):** Structure tests using the AAA pattern to clearly separate setup (arrange), execution (act), and verification (assert) phases.
- **Test Fixture:** Use `@BeforeEach` and `@AfterEach` annotations to set up and tear down test data and resources.
- **Mock Object:** Utilize mocking frameworks (Mockito, EasyMock, PowerMock) to isolate the unit under test by simulating dependencies.
- **Page Object Model (POM):** Employ POM for UI testing to create reusable representations of web pages, making tests more readable and robust.
### 2.2. Recommended Approaches
- **Test-Driven Development (TDD):** Write tests before implementing the code to drive development and ensure testability.
- **Behavior-Driven Development (BDD):** Use BDD frameworks (e.g., Cucumber) to write tests in a natural language format, improving collaboration and understanding.
- **Code Coverage:** Aim for high code coverage (around 80%) to ensure most of the code is tested, but remember that coverage alone doesn't guarantee quality.
- **Continuous Integration:** Integrate unit tests into the CI/CD pipeline to automatically run tests on every code commit and provide immediate feedback.
### 2.3. Anti-patterns and Code Smells
- **Testing Implementation Details:** Avoid testing implementation details that might change, leading to brittle tests. Focus on testing behavior and outcomes.
- **Hard-coded Values:** Avoid hard-coding values in tests. Use constants or test data to make tests more maintainable.
- **Complex Test Logic:** Keep test logic simple and avoid complex calculations or conditional statements within tests.
- **Ignoring Edge Cases:** Don't ignore edge cases or boundary conditions. Ensure tests cover a wide range of inputs, including invalid or unexpected values.
- **Slow Tests:** Avoid slow tests that discourage developers from running them frequently.
- **Over-reliance on Mocks:** Mock judiciously; too many mocks can obscure the actual behavior and make tests less reliable.
- **Ignoring Test Failures:** Never ignore failing tests. Investigate and fix them promptly.
### 2.4. State Management
- **Isolated State:** Ensure each test has its own isolated state to avoid interference between tests. Use `@BeforeEach` to reset the state before each test.
- **Immutable Objects:** Prefer immutable objects to simplify state management and avoid unexpected side effects.
- **Stateless Components:** Design stateless components whenever possible to reduce the need for state management in tests.
### 2.5. Error Handling
- **Expected Exceptions:** Use `assertThrows` to verify that a method throws the expected exception under specific conditions.
- **Exception Messages:** Assert the exception message to ensure the correct error is being thrown with helpful context.
- **Graceful Degradation:** Test how the application handles errors and gracefully degrades when dependencies are unavailable.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Fast Execution:** Keep tests fast to encourage frequent execution. Aim for millisecond execution times.
- **Parallel Execution:** Utilize JUnit's parallel execution feature to run tests concurrently and reduce overall test execution time.
- **Data Setup Optimization:** Optimize data setup by using in-memory databases or test data builders to avoid costly database interactions.
- **Mocking Optimization:** Optimize mocking by using lightweight mocks and avoiding unnecessary stubbing.
### 3.2. Memory Management
- **Resource Management:** Ensure tests properly release resources (e.g., database connections, file streams) to avoid memory leaks.
- **Large Data Sets:** Avoid loading large data sets into memory during testing. Use smaller, representative data sets.
- **Garbage Collection:** Be mindful of garbage collection. Create and destroy objects efficiently within your tests.
### 3.3 Rendering Optimization (if applicable)
- **Headless Testing:** If UI tests are involved, consider using headless browsers to minimize resource consumption.
- **Optimized Locators:** Use efficient locators (e.g., IDs, CSS selectors) to quickly find elements during UI testing.
### 3.4 Bundle Size Optimization (if applicable)
- **Code Splitting:** Utilize code splitting techniques to minimize the bundle size of the test code. Ensure only the necessary code is included in each test bundle.
- **Tree Shaking:** Enable tree shaking to remove unused code from test dependencies.
### 3.5 Lazy Loading
- **On-Demand Initialization:** Initialize test data and mocks only when they are needed to reduce startup time and resource consumption.
- **Lazy Evaluation:** Use lazy evaluation techniques to defer the execution of expensive operations until they are actually required.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
- **Injection Attacks:** Prevent injection attacks (SQL injection, command injection) by using parameterized queries and input validation.
- **Cross-Site Scripting (XSS):** Protect against XSS attacks by encoding user inputs before rendering them in the UI.
- **Authentication and Authorization Bypass:** Ensure proper authentication and authorization mechanisms are in place to prevent unauthorized access.
- **Data Exposure:** Avoid storing sensitive data in plain text. Use encryption and secure storage mechanisms.
### 4.2. Input Validation
- **Validate All Inputs:** Validate all inputs to ensure they conform to the expected format and range. Use regular expressions, data type validation, and range checks.
- **Sanitize User Inputs:** Sanitize user inputs to remove potentially harmful characters or code. Use appropriate encoding and escaping techniques.
### 4.3. Authentication and Authorization
- **Secure Authentication:** Implement secure authentication using strong passwords, multi-factor authentication, and token-based authentication.
- **Role-Based Access Control:** Use role-based access control to restrict access to sensitive resources based on user roles.
- **Least Privilege Principle:** Grant users only the minimum privileges required to perform their tasks.
### 4.4. Data Protection
- **Encryption:** Use encryption to protect sensitive data at rest and in transit. Use strong encryption algorithms and secure key management practices.
- **Data Masking:** Mask sensitive data to prevent unauthorized access. Use appropriate masking techniques to protect personally identifiable information (PII).
- **Secure Storage:** Store sensitive data in secure storage locations with proper access controls.
### 4.5. Secure API Communication
- **HTTPS:** Use HTTPS to encrypt communication between the client and server. Obtain and install a valid SSL certificate.
- **API Authentication:** Implement API authentication using API keys, tokens, or OAuth 2.0 to verify the identity of the client.
- **Rate Limiting:** Implement rate limiting to prevent denial-of-service (DoS) attacks.
## 5. Testing Approaches
### 5.1. Unit Testing
- **Isolated Testing:** Test individual units of code in isolation from dependencies.
- **Mocking:** Use mocking frameworks (Mockito, EasyMock) to simulate dependencies.
- **Test Coverage:** Aim for high code coverage to ensure most of the code is tested.
- **Edge Cases:** Test edge cases and boundary conditions to ensure code handles unexpected inputs correctly.
- **Assertion Libraries:** Leverage assertion libraries (AssertJ, Hamcrest) for more expressive and readable assertions.
### 5.2. Integration Testing
- **Component Interactions:** Test interactions between different components or modules.
- **External Systems:** Test integration with external systems (databases, APIs) using integration tests.
- **Real Dependencies:** Use real dependencies or in-memory substitutes for integration tests.
- **Data Consistency:** Verify data consistency and integrity across different components.
### 5.3. End-to-End Testing
- **Full System Testing:** Test the entire system from end to end to ensure it functions correctly.
- **UI Testing:** Use UI testing frameworks (Selenium, Cypress) to test the user interface.
- **User Scenarios:** Simulate real user scenarios to verify the system meets user requirements.
- **Environment Parity:** Test in an environment that closely resembles the production environment.
### 5.4. Test Organization
- **Test Suites:** Organize tests into suites based on functionality or component.
- **Test Categories:** Use JUnit categories to group tests and run them selectively.
- **Test Runners:** Use test runners to execute tests and generate reports.
### 5.5. Mocking and Stubbing
- **Mocking Frameworks:** Use mocking frameworks (Mockito, EasyMock) to create mock objects that simulate dependencies.
- **Stubbing:** Stub methods to return specific values or throw exceptions during testing.
- **Verification:** Verify that methods are called with the expected arguments during testing.
- **Avoid Over-Mocking:** Mock only the necessary dependencies to avoid over-complicating tests.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Ignoring Test Failures:** Ignoring failing tests and not fixing them promptly.
- **Writing Brittle Tests:** Writing tests that are tightly coupled to implementation details.
- **Not Testing Edge Cases:** Neglecting to test edge cases and boundary conditions.
- **Writing Slow Tests:** Writing tests that take a long time to run, discouraging frequent execution.
- **Not Using Mocking Frameworks:** Failing to use mocking frameworks to isolate units under test.
### 6.2. Edge Cases
- **Null Values:** Handle null values gracefully in tests and production code.
- **Empty Collections:** Test how code handles empty collections.
- **Invalid Inputs:** Test how code handles invalid inputs (e.g., negative numbers, invalid dates).
- **Boundary Conditions:** Test boundary conditions to ensure code behaves correctly at the limits of its input range.
### 6.3. Version-Specific Issues
- **API Changes:** Be aware of API changes in different JUnit versions and update tests accordingly.
- **Dependency Conflicts:** Resolve dependency conflicts between JUnit and other libraries.
- **Compatibility Issues:** Ensure compatibility between JUnit and the Java version being used.
### 6.4. Compatibility Concerns
- **Third-Party Libraries:** Ensure compatibility between JUnit and third-party libraries being used.
- **IDE Support:** Choose an IDE that provides good support for JUnit testing.
- **Build Tools:** Integrate JUnit with build tools (Maven, Gradle) for automated testing.
### 6.5. Debugging Strategies
- **Debugging Mode:** Run tests in debugging mode to step through the code and inspect variables.
- **Logging:** Add logging statements to tests to track execution flow and identify issues.
- **Remote Debugging:** Use remote debugging to debug tests running on remote servers.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **Integrated Development Environment (IDE):** IntelliJ IDEA, Eclipse, NetBeans
- **Build Tools:** Maven, Gradle
- **Mocking Frameworks:** Mockito, EasyMock
- **Assertion Libraries:** AssertJ, Hamcrest
- **Code Coverage Tools:** JaCoCo, Cobertura
- **Static Analysis Tools:** SonarQube, FindBugs
### 7.2. Build Configuration
- **Dependency Management:** Use Maven or Gradle to manage JUnit dependencies.
- **Test Configuration:** Configure test execution options (e.g., parallel execution, code coverage) in the build file.
- **Plugin Integration:** Integrate JUnit plugins with build tools for automated testing and reporting.
### 7.3. Linting and Formatting
- **Code Style:** Follow a consistent code style (e.g., Google Java Style, Checkstyle) to improve code readability and maintainability.
- **Linting:** Use linting tools (e.g., Checkstyle, PMD) to enforce code style rules and identify potential issues.
- **Formatting:** Use code formatting tools (e.g., IntelliJ IDEA formatter, Eclipse formatter) to automatically format code according to the configured style.
### 7.4. Deployment
- **Test Environment:** Deploy applications to a test environment that closely resembles the production environment.
- **Automated Testing:** Run automated tests in the deployment pipeline to verify the application functions correctly.
- **Rollback Strategy:** Implement a rollback strategy to quickly revert to a previous version if issues are detected after deployment.
### 7.5. CI/CD Integration
- **Continuous Integration:** Integrate JUnit tests into the CI/CD pipeline to automatically run tests on every code commit.
- **Automated Testing:** Automate the execution of JUnit tests as part of the build process.
- **Reporting:** Generate test reports and publish them to the CI/CD system.
- **Failure Notifications:** Configure failure notifications to alert developers when tests fail.
By following these best practices, you can write more effective, maintainable, and performant JUnit tests, leading to higher-quality software and faster development cycles.
+323
View File
@@ -0,0 +1,323 @@
---
description: This rule enforces Keras library best practices, focusing on code clarity, modularity, performance optimization, and security considerations. It provides actionable guidance for developers to improve the quality and maintainability of Keras-based machine learning projects.
globs: **/*.py
---
# Keras Development Best Practices
This document outlines best practices for developing Keras applications. It covers various aspects of software engineering, including code organization, common patterns, performance, security, testing, and tooling.
Library Information:
- Name: keras
- Tags: ai, ml, machine-learning, python, deep-learning
## 1. Code Organization and Structure
### 1.1. Directory Structure
Adopt a well-defined directory structure to enhance maintainability and collaboration.
project_root/
├── data/ # Contains datasets (raw, processed)
├── models/ # Saved models (weights, architectures)
├── src/ # Source code
│ ├── layers/ # Custom Keras layers
│ ├── models/ # Model definitions
│ ├── utils/ # Utility functions
│ ├── callbacks/ # Custom Keras Callbacks
│ ├── preprocessing/ # Data preprocessing scripts
│ └── __init__.py # Makes 'src' a Python package
├── notebooks/ # Jupyter notebooks for experimentation
├── tests/ # Unit and integration tests
├── requirements.txt # Project dependencies
├── README.md # Project overview
└── .gitignore # Specifies intentionally untracked files that Git should ignore
### 1.2. File Naming Conventions
Use descriptive and consistent file names.
- `model_name.py`: For defining Keras models.
- `layer_name.py`: For custom Keras layers.
- `utils.py`: For utility functions.
- `data_preprocessing.py`: For data preprocessing scripts.
- `training_script.py`: Main training script.
### 1.3. Module Organization
- **Single Responsibility Principle:** Each module should have a clear and specific purpose.
- **Loose Coupling:** Minimize dependencies between modules.
- **High Cohesion:** Keep related functions and classes within the same module.
python
# src/models/my_model.py
import keras
from keras import layers
def create_model(input_shape, num_classes):
inputs = keras.Input(shape=input_shape)
x = layers.Conv2D(32, (3, 3), activation='relu')(inputs)
x = layers.MaxPooling2D((2, 2))(x)
x = layers.Flatten()(x)
outputs = layers.Dense(num_classes, activation='softmax')(x)
model = keras.Model(inputs, outputs)
return model
### 1.4. Component Architecture
- **Layers:** Encapsulate reusable blocks of computation (e.g., custom convolutional layers, attention mechanisms).
- **Models:** Define the overall architecture by combining layers.
- **Callbacks:** Implement custom training behaviors (e.g., early stopping, learning rate scheduling).
- **Preprocessing:** Separate data loading, cleaning, and transformation logic.
### 1.5. Code Splitting
- **Functions:** Break down complex logic into smaller, well-named functions.
- **Classes:** Use classes to represent stateful components (e.g., custom layers with trainable parameters).
- **Packages:** Organize modules into packages for larger projects.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Functional API:** Use the Keras Functional API for building complex, multi-input/output models.
python
input_tensor = keras.Input(shape=(784,))
hidden_layer = layers.Dense(units=64, activation='relu')(input_tensor)
output_tensor = layers.Dense(units=10, activation='softmax')(hidden_layer)
model = keras.Model(inputs=input_tensor, outputs=output_tensor)
- **Subclassing:** Subclass `keras.Model` or `keras.layers.Layer` for maximum customization.
python
class MyLayer(layers.Layer):
def __init__(self, units=32, **kwargs):
super(MyLayer, self).__init__(**kwargs)
self.units = units
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.units),
initializer='random_normal',
trainable=True)
self.b = self.add_weight(shape=(self.units,),
initializer='zeros',
trainable=True)
def call(self, inputs):
return keras.activations.relu(tf.matmul(inputs, self.w) + self.b)
- **Callbacks:** Implement custom training behaviors (e.g., custom logging, model checkpointing).
python
class CustomCallback(keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
print(f'Epoch {epoch}: Loss = {logs['loss']}')
### 2.2. Recommended Approaches
- **Data Input Pipelines:** Use `tf.data.Dataset` for efficient data loading and preprocessing.
- **Model Checkpointing:** Save model weights during training to prevent data loss and allow for resuming training.
- **Early Stopping:** Monitor validation loss and stop training when it plateaus to prevent overfitting.
- **Learning Rate Scheduling:** Adjust the learning rate during training to improve convergence.
### 2.3. Anti-Patterns
- **Hardcoding:** Avoid hardcoding values directly into your code. Use variables and configuration files instead.
- **Global Variables:** Minimize the use of global variables to prevent namespace pollution and unexpected side effects.
- **Over-Engineering:** Don't overcomplicate your code with unnecessary abstractions or complex patterns.
- **Ignoring Warnings:** Pay attention to warnings and deprecation messages, as they often indicate potential problems.
- **Training on the entire dataset without validation:** Always split your data into training, validation and testing sets to avoid overfitting.
### 2.4. State Management
- **Stateless Operations:** Prefer stateless operations whenever possible to simplify testing and debugging.
- **Model Weights:** Store model weights separately from the model architecture.
- **Configuration Files:** Use configuration files (e.g., JSON, YAML) to manage hyperparameters and other settings.
### 2.5. Error Handling
- **Exception Handling:** Use `try...except` blocks to handle potential exceptions gracefully.
- **Logging:** Log errors and warnings to help diagnose problems.
- **Validation:** Validate input data to prevent unexpected errors.
- **Assertions:** Use `assert` statements to check for conditions that should always be true.
python
try:
model = keras.models.load_model('my_model.h5')
except FileNotFoundError:
logging.error('Model file not found.')
raise
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **GPU Acceleration:** Utilize GPUs for faster training and inference.
- **Data Preprocessing:** Optimize data preprocessing pipelines to reduce overhead.
- **Batch Size:** Adjust the batch size to maximize GPU utilization.
- **Model Pruning:** Remove unnecessary weights from the model to reduce its size and improve its speed.
- **Quantization:** Reduce the precision of model weights to reduce memory consumption and improve inference speed.
- **Mixed Precision Training:** Use `tf.keras.mixed_precision.Policy` to enable mixed precision training for faster training on modern GPUs.
### 3.2. Memory Management
- **Garbage Collection:** Be mindful of memory leaks and use garbage collection to reclaim unused memory.
- **Data Types:** Use appropriate data types to minimize memory consumption (e.g., `tf.float16` instead of `tf.float32`).
- **Generators:** Use generators to load data in batches, reducing memory usage.
### 3.3. Rendering Optimization (If applicable)
Not directly applicable to Keras itself, but relevant when visualizing model outputs or training progress. Use libraries like `matplotlib` or `seaborn` efficiently and consider downsampling large datasets before plotting.
### 3.4. Bundle Size Optimization
- **Model Pruning and Quantization:** as above.
- **Selectively Import Keras Modules**: Only import the specific Keras modules needed to reduce the overall bundle size, e.g., `from keras.layers import Dense, Conv2D` instead of `import keras.layers`.
### 3.5. Lazy Loading
- **Lazy Initialization:** Defer the initialization of resources until they are actually needed.
- **Data Loading:** Load data on demand rather than loading the entire dataset into memory.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
- **Adversarial Attacks:** Protect against adversarial attacks that can fool models into making incorrect predictions.
- **Data Poisoning:** Ensure the integrity of training data to prevent data poisoning attacks.
- **Model Extraction:** Protect against model extraction attacks that can steal intellectual property.
### 4.2. Input Validation
- **Sanitize Input:** Sanitize input data to prevent injection attacks.
- **Validate Input:** Validate input data to ensure that it conforms to the expected format and range.
python
def predict(model, input_data):
if not isinstance(input_data, np.ndarray):
raise TypeError('Input data must be a NumPy array.')
if input_data.shape != (1, 784):
raise ValueError('Input data must have shape (1, 784).')
return model.predict(input_data)
### 4.3. Authentication and Authorization
- **Secure API:** Implement secure API communication using HTTPS.
- **Authentication:** Require authentication for access to sensitive data and functionality.
- **Authorization:** Enforce authorization policies to control access to resources.
### 4.4. Data Protection
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Anonymization:** Anonymize data to protect privacy.
- **Data Governance:** Implement data governance policies to ensure data quality and security.
### 4.5. Secure API Communication
- **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
- **API Keys:** Use API keys to authenticate requests.
- **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks.
## 5. Testing Approaches
### 5.1. Unit Testing
- **Test-Driven Development:** Write unit tests before writing code to ensure that the code meets the requirements.
- **Test Cases:** Create test cases for different scenarios, including edge cases and error conditions.
- **Assertions:** Use assertions to verify that the code behaves as expected.
### 5.2. Integration Testing
- **Component Interaction:** Test the interaction between different components of the application.
- **Data Flow:** Test the flow of data through the application.
- **System Integration:** Test the integration of the application with other systems.
### 5.3. End-to-End Testing
- **User Interface:** Test the user interface to ensure that it is functional and user-friendly.
- **Workflow:** Test the entire workflow from start to finish.
- **Real-World Scenarios:** Test the application in real-world scenarios to ensure that it meets the needs of the users.
### 5.4. Test Organization
- **Test Directory:** Create a dedicated `tests` directory to store test files.
- **Test Modules:** Organize tests into modules based on the components they test.
- **Test Naming Conventions:** Use clear and consistent naming conventions for test files and functions.
### 5.5. Mocking and Stubbing
- **Mock Objects:** Use mock objects to simulate the behavior of external dependencies.
- **Stub Functions:** Use stub functions to replace complex or time-consuming operations with simple, predictable results.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Incorrect Input Shapes:** Ensure that the input shapes match the expected dimensions.
- **Data Type Mismatches:** Use consistent data types throughout the application.
- **Gradient Vanishing/Exploding:** Use appropriate activation functions and weight initialization techniques to prevent gradient problems.
- **Overfitting:** Use regularization techniques (e.g., dropout, L1/L2 regularization) to prevent overfitting.
### 6.2. Edge Cases
- **Empty Datasets:** Handle empty datasets gracefully.
- **Missing Values:** Handle missing values appropriately (e.g., imputation, deletion).
- **Outliers:** Identify and handle outliers in the data.
### 6.3. Version-Specific Issues
- **API Changes:** Be aware of API changes between different versions of Keras and TensorFlow.
- **Compatibility:** Ensure that your code is compatible with the versions of Keras and TensorFlow that you are using.
### 6.4. Compatibility Concerns
- **TensorFlow Compatibility:** Verify the compatibility between Keras and TensorFlow versions. Keras 3 can run on TensorFlow 2.16 onwards but there can be backwards compatibility issues.
- **Hardware Compatibility:** Ensure compatibility with different hardware platforms (e.g., CPU, GPU, TPU).
### 6.5. Debugging Strategies
- **Logging:** Use logging to track the execution of the code and identify potential problems.
- **Debugging Tools:** Use debugging tools (e.g., `pdb`, `TensorBoard`) to inspect the state of the application.
- **Print Statements:** Use print statements to display intermediate values and debug the code.
- **TensorBoard:** Use TensorBoard to visualize the model architecture, training progress, and performance metrics.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **IDE:** Use an IDE (e.g., VS Code, PyCharm) with Keras and TensorFlow support.
- **Virtual Environment:** Use a virtual environment (e.g., `venv`, `conda`) to isolate project dependencies.
- **Jupyter Notebook:** Use Jupyter notebooks for experimentation and prototyping.
### 7.2. Build Configuration
- **Requirements File:** Use a `requirements.txt` file to specify project dependencies.
- **Setup Script:** Use a `setup.py` script to define the project metadata and installation instructions.
### 7.3. Linting and Formatting
- **PEP 8:** Adhere to PEP 8 style guidelines for Python code.
- **Linters:** Use linters (e.g., `flake8`, `pylint`) to enforce code style and identify potential problems.
- **Formatters:** Use formatters (e.g., `black`, `autopep8`) to automatically format code.
### 7.4. Deployment
- **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies.
- **Cloud Platforms:** Deploy the application to a cloud platform (e.g., AWS, Google Cloud, Azure).
- **Serving Frameworks:** Use serving frameworks (e.g., TensorFlow Serving, KServe) to deploy models for inference.
### 7.5. CI/CD Integration
- **Continuous Integration:** Automate the build, test, and integration process using CI tools (e.g., Jenkins, Travis CI, GitHub Actions).
- **Continuous Deployment:** Automate the deployment process using CD tools (e.g., AWS CodePipeline, Google Cloud Build, Azure DevOps).
This comprehensive guide provides a strong foundation for developing high-quality, maintainable, and secure Keras applications. By following these best practices, developers can improve their productivity, reduce the risk of errors, and build robust machine learning systems.
+347
View File
@@ -0,0 +1,347 @@
---
description: This rule file outlines best practices for Kivy UI development, including code organization, performance, security, and testing. Adhering to these guidelines ensures maintainable, efficient, and secure Kivy applications.
globs: **/*.{py,kv}
---
# Kivy Development Best Practices
This document provides a comprehensive guide to Kivy development best practices, covering various aspects from code organization to security and testing.
## 1. Code Organization and Structure
Proper code organization is crucial for maintainability, scalability, and collaboration in Kivy projects.
### 1.1 Directory Structure
A well-defined directory structure helps organize your Kivy project. Here's a suggested structure:
my_kivy_app/
├── app.py # Main application file
├── main.kv # Root KV file
├── screens/ # Directory for screen definitions
│ ├── __init__.py # Initialize screens package
│ ├── main_screen.py
│ ├── main_screen.kv
│ ├── settings_screen.py
│ └── settings_screen.kv
├── components/ # Directory for reusable UI components
│ ├── __init__.py # Initialize components package
│ ├── custom_button.py
│ └── custom_button.kv
├── utils/ # Utility modules
│ ├── __init__.py
│ └── helpers.py
├── data/ # Data files (JSON, images, fonts, etc.)
│ ├── images/
│ ├── fonts/
│ └── settings.json
├── tests/ # Unit and integration tests
│ ├── __init__.py
│ ├── test_main_screen.py
│ └── test_helpers.py
├── .gitignore # Git ignore file
├── README.md # Project README
└── requirements.txt # Project dependencies
* `app.py`: The main application file where you define your `App` subclass and run the application.
* `main.kv`: The root KV file that typically handles overall layout structure and screen management. It is loaded automatically if named appropriately (e.g., `myapp.kv` for a `MyApp` class).
* `screens/`: Contains individual screen definitions. Each screen can have a Python file for logic and a KV file for layout.
* `components/`: Holds reusable UI components, like custom buttons, labels, or layouts. This promotes code reuse and consistency.
* `utils/`: Includes helper functions and utility modules that provide common functionalities across the application.
* `data/`: Stores application data like images, fonts, and configuration files.
* `tests/`: Contains unit and integration tests to ensure code quality and prevent regressions.
* `.gitignore`: Specifies intentionally untracked files that Git should ignore.
* `README.md`: Provides a project overview, setup instructions, and other relevant information.
* `requirements.txt`: Lists the Python packages required to run the application. Use `pip freeze > requirements.txt` to generate this.
### 1.2 File Naming Conventions
* **Python files:** Use lowercase with underscores (snake_case), e.g., `main_screen.py`, `custom_button.py`.
* **KV files:** Use the same name as the corresponding Python file, but with the `.kv` extension, e.g., `main_screen.kv`, `custom_button.kv`.
* **Class names:** Use CamelCase, e.g., `MainScreen`, `CustomButton`.
* **Variables and functions:** Use snake_case, e.g., `screen_width`, `calculate_layout()`.
Consistent naming conventions improve code readability and maintainability.
### 1.3 Module Organization
* **Separate concerns:** Divide your application into logical modules based on functionality. For example, a module for data access, a module for UI components, and a module for business logic.
* **Use packages:** Group related modules into packages using `__init__.py` files. This helps organize your project and prevent naming conflicts.
* **Keep modules small:** Avoid creating overly large modules. Smaller modules are easier to understand, test, and reuse.
* **Use relative imports:** Within a package, use relative imports (e.g., `from . import helpers`) to refer to other modules in the same package. This makes your code more portable and less prone to errors.
### 1.4 Component Architecture
* **Create reusable components:** Design your UI with reusable components. This promotes code reuse, reduces redundancy, and makes it easier to maintain your application. Kivy's KV language and custom widget creation are ideal for this.
* **Use custom widgets:** Create custom widgets by subclassing Kivy's existing widgets or combining multiple widgets. This allows you to encapsulate complex UI elements and behavior into reusable components.
* **Follow the DRY principle (Don't Repeat Yourself):** Abstract common functionalities into reusable components or utility functions. This reduces code duplication and makes your code more maintainable.
### 1.5 Code Splitting
* **Break down large screens:** If a screen becomes too complex, break it down into smaller, manageable sub-components.
* **Lazy loading:** Load parts of the UI or data only when they are needed. This can improve startup time and reduce memory usage.
* **Dynamic loading of KV files:** Load KV files dynamically using `Builder.load_file()` when a screen or component is needed. This allows you to split your UI definition into multiple files and load them on demand.
## 2. Common Patterns and Anti-patterns
Understanding common design patterns and anti-patterns helps you write better Kivy code.
### 2.1 Design Patterns
* **Model-View-Controller (MVC) / Model-View-Presenter (MVP) / Model-View-ViewModel (MVVM):** Consider using these patterns to separate data (model), UI (view), and logic (controller/presenter/viewmodel). Kivy does not enforce a specific architecture, but these patterns can help organize your code and improve testability. MVVM is often considered more suitable due to Kivy's declarative nature.
* **Observer:** Kivy's properties and event dispatching mechanism are based on the Observer pattern. Use properties to observe changes in data and trigger UI updates accordingly.
* **Factory:** Use the Factory pattern to create different types of widgets or objects based on certain conditions or data. This can be useful for dynamically generating UI elements.
* **Singleton:** While often debated, Singletons can be useful for global configuration or access to shared resources. Use with caution and consider alternatives like dependency injection.
### 2.2 Recommended Approaches
* **Use KV language for UI definition:** Separate your UI definition from your Python code using the KV language. This improves code readability and maintainability.
* **Bind properties to UI elements:** Use Kivy's property binding mechanism to automatically update UI elements when data changes. This simplifies UI updates and reduces boilerplate code.
* **Use events for user interaction:** Use Kivy's event system to handle user interactions, such as button clicks and text input. This allows you to react to user actions and update the UI accordingly.
* **Asynchronous operations:** Use asynchronous operations (e.g., `Clock.schedule_once()`, `Clock.schedule_interval()`, or `async/await`) for long-running tasks to avoid blocking the UI thread. This ensures that your application remains responsive.
* **Data binding with properties:** Leverage Kivy properties (StringProperty, NumericProperty, ObjectProperty, etc.) for data binding between UI elements and your application's data model. This enables automatic updates of UI elements when the underlying data changes, and vice versa.
### 2.3 Anti-patterns and Code Smells
* **Tight coupling:** Avoid tight coupling between UI elements and business logic. Separate your UI definition from your logic using the KV language and appropriate design patterns.
* **God object:** Avoid creating overly large and complex classes that handle too many responsibilities. Break down large classes into smaller, more manageable classes.
* **Code duplication:** Avoid duplicating code. Abstract common functionalities into reusable components or utility functions.
* **Ignoring errors:** Don't ignore errors. Handle errors gracefully and provide meaningful feedback to the user.
* **Blocking the UI thread:** Avoid performing long-running tasks on the UI thread. Use asynchronous operations to prevent the UI from freezing.
* **Excessive use of `eval()` or `exec()`:** Avoid using `eval()` or `exec()` to execute arbitrary code, as this can introduce security vulnerabilities. Prefer safer alternatives like data binding or function calls.
* **Over-reliance on global variables:** Minimize the use of global variables, as they can make your code harder to understand and maintain. Prefer passing data explicitly between components.
### 2.4 State Management
* **Kivy Properties:** For simple state management within a widget or screen, Kivy Properties are often sufficient. They offer automatic notification when their value changes, making them easy to bind to UI elements.
* **ScreenManager:** The `ScreenManager` widget can store state associated with each screen. This is useful for managing the overall application state and passing data between screens.
* **External state management libraries:** For more complex state management requirements, consider using external libraries like: `RxPY`, `KivyMD`, or even integrating with more comprehensive frameworks like Flask for the backend.
* **Minimize mutable state:** Prefer immutable data structures to reduce the risk of unexpected side effects and improve code predictability.
* **Centralized State:** Implement a centralized state management system to ensure data consistency across different parts of the application.
### 2.5 Error Handling
* **Use `try...except` blocks:** Use `try...except` blocks to handle potential exceptions. Provide specific exception handling for different types of errors.
* **Log errors:** Log errors to a file or console for debugging purposes. Include relevant information, such as the error message, stack trace, and timestamp.
* **Provide user-friendly error messages:** Display user-friendly error messages to the user. Avoid displaying technical details that the user may not understand.
* **Handle unhandled exceptions:** Implement a global exception handler to catch unhandled exceptions and prevent the application from crashing. Log the error and display a generic error message to the user.
* **Retry mechanism:** Implement a retry mechanism for operations that may fail due to transient errors, such as network connectivity issues.
## 3. Performance Considerations
Optimizing performance is crucial for creating smooth and responsive Kivy applications.
### 3.1 Optimization Techniques
* **Use the right layout:** Choose the most efficient layout for your UI. `RelativeLayout` and `FloatLayout` can be more expensive than `BoxLayout` or `GridLayout`.
* **Minimize widget count:** Reduce the number of widgets in your UI. Consider using custom drawing or more efficient layouts to achieve the same visual effect with fewer widgets.
* **Use textures efficiently:** Load images and textures at the correct size. Avoid scaling large images down in the UI, as this can be inefficient. Use texture atlases to combine multiple small images into a single texture, reducing the number of texture swaps.
* **Use `AsyncImage` for loading images:** Load images asynchronously using `AsyncImage` to avoid blocking the UI thread.
* **Optimize drawing:** Use Kivy's drawing instructions efficiently. Batch drawing operations to reduce the number of OpenGL calls.
* **Freeze layouts:** Use `Widget.size_hint` with fixed values to help Kivy optimize layout calculations.
* **Use appropriate property types:** Use specific Kivy property types (StringProperty, NumericProperty, etc.) instead of generic ObjectProperty to improve performance.
* **Avoid complex calculations in property callbacks:** Keep property callback functions short and simple. Move complex calculations to separate functions and call them from the callbacks.
### 3.2 Memory Management
* **Release unused resources:** Release unused resources, such as images and textures, when they are no longer needed. Use `Widget.clear()` to remove all children from a widget and release their resources.
* **Use weak references:** Use weak references to avoid creating circular dependencies that can prevent objects from being garbage collected.
* **Avoid creating large lists or dictionaries:** If you need to store large amounts of data, consider using more efficient data structures, such as NumPy arrays or SQLite databases.
* **Use generators:** Use generators to process large data sets lazily, reducing memory consumption.
* **Profile your application:** Use a memory profiler to identify memory leaks and optimize memory usage.
### 3.3 Rendering Optimization
* **Use the correct OpenGL context:** Ensure that you are using the correct OpenGL context for your platform. Kivy supports both OpenGL and OpenGL ES.
* **Reduce overdraw:** Reduce overdraw by minimizing the number of overlapping UI elements.
* **Use shaders:** Use shaders to perform complex rendering effects efficiently.
* **Optimize texture loading:** Optimize texture loading by using compressed textures and mipmaps.
* **Use the `kivy.graphics` module efficiently:** Minimize the number of drawing calls and state changes. Batch drawing operations together.
### 3.4 Bundle Size Optimization
* **Remove unused code:** Remove unused code from your application to reduce the bundle size.
* **Compress images:** Compress images to reduce their file size. Use lossless compression for images that require high quality and lossy compression for images where some quality loss is acceptable.
* **Use efficient audio formats:** Use efficient audio formats, such as MP3 or Opus, to reduce the size of your audio files.
* **Obfuscate your code:** Obfuscate your code to make it harder to reverse engineer and reduce the bundle size.
* **Use code minification:** Minify your code to remove unnecessary whitespace and comments, reducing the bundle size.
* **Use code splitting:** Split your code into multiple modules and load them on demand to reduce the initial bundle size.
### 3.5 Lazy Loading
* **Load screens on demand:** Load screens only when they are needed. This can improve startup time and reduce memory usage. Use `ScreenManager.add_widget()` and `ScreenManager.remove_widget()` to manage screens dynamically.
* **Load data on demand:** Load data only when it is needed. Use asynchronous operations to load data in the background without blocking the UI thread.
* **Load images on demand:** Load images only when they are needed. Use `AsyncImage` to load images asynchronously.
* **Virtualization for lists:** When displaying long lists, use virtualization techniques to only render the visible items. This can significantly improve performance and reduce memory usage.
## 4. Security Best Practices
Security should be a primary concern when developing Kivy applications, especially those that handle sensitive data or interact with external services.
### 4.1 Common Vulnerabilities
* **Code injection:** Avoid using `eval()` or `exec()` to execute arbitrary code, as this can allow attackers to inject malicious code into your application.
* **Cross-site scripting (XSS):** Be careful when displaying user-generated content in your UI. Sanitize the content to prevent attackers from injecting malicious scripts.
* **SQL injection:** When interacting with databases, use parameterized queries or object-relational mappers (ORMs) to prevent SQL injection attacks.
* **Man-in-the-middle (MITM) attacks:** Use HTTPS to encrypt communication between your application and external services, preventing attackers from intercepting sensitive data.
* **Data leakage:** Be careful not to leak sensitive data in your application's logs or error messages. Disable debug mode in production builds.
* **Insecure storage:** Avoid storing sensitive data in plain text. Encrypt sensitive data before storing it locally or in the cloud.
### 4.2 Input Validation
* **Validate all user input:** Validate all user input to ensure that it conforms to the expected format and range. Use regular expressions or custom validation functions to validate input.
* **Sanitize user input:** Sanitize user input to remove potentially harmful characters or code. Use Kivy's built-in functions or external libraries to sanitize input.
* **Limit input length:** Limit the length of input fields to prevent buffer overflows and other security vulnerabilities.
* **Escape output:** Escape output to prevent cross-site scripting (XSS) attacks. Use Kivy's built-in functions or external libraries to escape output.
* **Use whitelisting:** Use whitelisting to allow only specific characters or patterns in input fields. This can be more secure than blacklisting, which attempts to block specific harmful characters or patterns.
### 4.3 Authentication and Authorization
* **Use secure authentication protocols:** Use secure authentication protocols, such as OAuth 2.0 or JWT, to authenticate users. Avoid storing passwords in plain text.
* **Implement multi-factor authentication (MFA):** Implement multi-factor authentication (MFA) to add an extra layer of security to user accounts.
* **Use role-based access control (RBAC):** Use role-based access control (RBAC) to restrict access to sensitive data and functionalities based on user roles.
* **Regularly audit your authentication and authorization system:** Regularly audit your authentication and authorization system to identify and fix any vulnerabilities.
* **Use password hashing:** Always hash passwords using a strong hashing algorithm (e.g., bcrypt or Argon2) before storing them. Never store passwords in plain text.
### 4.4 Data Protection
* **Encrypt sensitive data:** Encrypt sensitive data before storing it locally or in the cloud. Use strong encryption algorithms, such as AES.
* **Use secure storage:** Store sensitive data in secure storage locations, such as the Android Keystore or iOS Keychain.
* **Protect data in transit:** Use HTTPS to encrypt communication between your application and external services.
* **Comply with data privacy regulations:** Comply with data privacy regulations, such as GDPR and CCPA.
* **Implement data masking:** Mask sensitive data when displaying it in the UI or logs. This can prevent unauthorized access to sensitive information.
### 4.5 Secure API Communication
* **Use HTTPS:** Always use HTTPS to communicate with APIs. This encrypts the data transmitted between your application and the API server, preventing eavesdropping.
* **Validate API responses:** Validate API responses to ensure that they are in the expected format and do not contain any malicious data.
* **Use API keys or tokens:** Use API keys or tokens to authenticate your application with the API server. Store API keys and tokens securely.
* **Rate limiting:** Implement rate limiting to prevent denial-of-service attacks. This limits the number of requests that a client can make to the API server within a given time period.
* **Input validation on the server-side:** Validate all input data on the server-side, even if you have already validated it on the client-side. This prevents attackers from bypassing client-side validation and injecting malicious data.
## 5. Testing Approaches
Testing is essential for ensuring the quality and reliability of Kivy applications.
### 5.1 Unit Testing
* **Test individual components:** Unit tests should focus on testing individual components, such as widgets, functions, and classes, in isolation.
* **Use a testing framework:** Use a testing framework, such as `unittest` or `pytest`, to organize and run your unit tests.
* **Write clear and concise tests:** Write clear and concise tests that are easy to understand and maintain.
* **Test edge cases:** Test edge cases to ensure that your code handles unexpected input or conditions correctly.
* **Use mock objects:** Use mock objects to isolate components from external dependencies, such as databases or network services.
* **Aim for high test coverage:** Aim for high test coverage to ensure that most of your code is tested.
* **Test Kivy properties:** Ensure your tests check for proper updates to Kivy Properties, including bindings and event triggering.
### 5.2 Integration Testing
* **Test interactions between components:** Integration tests should focus on testing the interactions between different components, such as screens, widgets, and data models.
* **Test the application as a whole:** Integration tests should also test the application as a whole to ensure that all components work together correctly.
* **Use a testing framework:** Use a testing framework, such as `unittest` or `pytest`, to organize and run your integration tests.
* **Use a GUI testing framework:** If you need to test the GUI directly, consider using a GUI testing framework, such as `kivy.tests` or `pytest-kivy`.
### 5.3 End-to-End Testing
* **Simulate user interactions:** End-to-end tests should simulate user interactions to test the application from the user's perspective.
* **Test the entire application flow:** End-to-end tests should test the entire application flow to ensure that all steps work correctly.
* **Use a testing framework:** Use a testing framework, such as `Selenium` or `Appium`, to automate your end-to-end tests.
* **Run tests on different platforms:** Run your end-to-end tests on different platforms to ensure that your application works correctly on all supported platforms.
### 5.4 Test Organization
* **Create a dedicated `tests` directory:** Create a dedicated `tests` directory to store your tests.
* **Organize tests by module:** Organize your tests by module to make it easier to find and run tests.
* **Use descriptive test names:** Use descriptive test names to make it clear what each test is testing.
* **Write test documentation:** Write test documentation to explain the purpose of each test and how it works.
* **Run tests automatically:** Run your tests automatically whenever you make changes to your code. Use a continuous integration system to automate this process.
### 5.5 Mocking and Stubbing
* **Use mock objects to isolate components:** Use mock objects to isolate components from external dependencies, such as databases or network services.
* **Use stub objects to simulate external dependencies:** Use stub objects to simulate external dependencies, such as APIs or hardware devices.
* **Use a mocking framework:** Use a mocking framework, such as `unittest.mock` or `mockito`, to create mock and stub objects easily.
* **Avoid over-mocking:** Avoid over-mocking, as this can make your tests less effective. Only mock dependencies that are truly external to the component being tested.
## 6. Common Pitfalls and Gotchas
Be aware of common pitfalls and gotchas when developing Kivy applications to avoid wasting time and effort.
### 6.1 Frequent Mistakes
* **Forgetting to call `super()`:** When subclassing Kivy widgets or classes, remember to call the `super()` method to initialize the parent class properly.
* **Not understanding Kivy's property system:** Kivy's property system is powerful but can be confusing at first. Make sure you understand how properties work and how to use them effectively.
* **Blocking the UI thread:** Avoid performing long-running tasks on the UI thread, as this can cause the application to freeze.
* **Not handling events correctly:** Handle events correctly to ensure that your application responds to user interactions as expected.
* **Not using the KV language effectively:** The KV language is a powerful tool for defining UI layouts and styles. Use it effectively to separate your UI definition from your Python code.
* **Incorrect file paths in deployment:** When packaging your app, ensure that file paths to assets and other dependencies are correct relative to the packaged application.
### 6.2 Edge Cases
* **Different screen resolutions:** Test your application on different screen resolutions to ensure that the UI scales correctly.
* **Different operating systems:** Test your application on different operating systems to ensure that it works correctly on all supported platforms.
* **Different hardware devices:** Test your application on different hardware devices to ensure that it works correctly on all target devices.
* **Handling orientation changes:** Implement proper handling of orientation changes (portrait/landscape) in your layouts.
* **Input from different devices:** Be aware of differences in input from touchscreens vs. mouse/keyboard, especially when designing interactions.
### 6.3 Version-Specific Issues
* **Kivy API changes:** Be aware of API changes between different versions of Kivy. Consult the Kivy documentation for migration guides.
* **Dependency compatibility:** Ensure that your dependencies are compatible with the version of Kivy you are using.
* **Deprecated features:** Be aware of deprecated features and avoid using them in new code. Migrate existing code to use the recommended alternatives.
### 6.4 Compatibility Concerns
* **Operating system dependencies:** Be aware of operating system dependencies and ensure that your application works correctly on all supported platforms.
* **Hardware dependencies:** Be aware of hardware dependencies and ensure that your application works correctly on all target devices.
* **Python version compatibility:** Ensure your code is compatible with supported Python versions. Kivy officially supports certain Python versions, so check the Kivy documentation for details.
### 6.5 Debugging Strategies
* **Use the Kivy console:** Use the Kivy console to inspect the state of your application and execute commands dynamically.
* **Use logging:** Use logging to record information about your application's behavior. This can be helpful for debugging issues that occur in production.
* **Use a debugger:** Use a debugger, such as `pdb` or `pycharm`, to step through your code and inspect variables.
* **Use Kivy's interactive mode:** Use Kivy's interactive mode to test UI layouts and styles without running the entire application.
* **Read Kivy's error messages carefully:** Kivy's error messages often provide valuable information about the cause of the error. Read them carefully and try to understand what they mean.
* **Search the Kivy documentation and online forums:** Search the Kivy documentation and online forums for solutions to common problems. The Kivy community is very active and helpful.
## 7. Tooling and Environment
Using the right tools and environment can significantly improve your Kivy development experience.
### 7.1 Recommended Development Tools
* **Text editor/IDE:** Use a good text editor or IDE, such as VS Code, PyCharm, or Sublime Text. These tools provide features such as syntax highlighting, code completion, and debugging.
* **Kivy Designer:** Kivy Designer is a visual UI designer that allows you to create UI layouts visually. It can be helpful for prototyping and experimenting with different UI designs.
* **Buildozer:** Buildozer is a tool for packaging Kivy applications for Android, iOS, and other platforms. It simplifies the process of creating deployment packages.
* **Python virtual environment manager:** Use virtualenv, venv (Python 3.3+), or conda to create isolated Python environments for your Kivy projects. This helps manage dependencies and avoid conflicts.
### 7.2 Build Configuration
* **Use a build system:** Use a build system, such as Make or CMake, to automate the build process.
* **Create a build script:** Create a build script to automate the build process. The build script should handle tasks such as installing dependencies, compiling code, and packaging the application.
* **Use environment variables:** Use environment variables to configure the build process. This allows you to customize the build process without modifying the code.
* **Use a configuration file:** Use a configuration file to store application settings. This allows you to change application settings without modifying the code.
### 7.3 Linting and Formatting
* **Use a linter:** Use a linter, such as `flake8` or `pylint`, to check your code for style errors and potential problems.
* **Use a code formatter:** Use a code formatter, such as `black` or `autopep8`, to automatically format your code according to PEP 8 guidelines.
* **Configure your editor/IDE:** Configure your editor/IDE to run the linter and code formatter automatically whenever you save a file. This helps ensure that your code is always clean and consistent.
### 7.4 Deployment
* **Choose the right deployment method:** Choose the right deployment method for your target platform. For Android, you can use Buildozer to create an APK. For desktop platforms, you can use PyInstaller or cx_Freeze to create executable files.
* **Create a deployment script:** Create a deployment script to automate the deployment process. The deployment script should handle tasks such as building the application, packaging it, and uploading it to the target platform.
* **Test your application thoroughly:** Test your application thoroughly on the target platform before deploying it to users.
* **Follow platform-specific guidelines:** Adhere to platform-specific guidelines for packaging and distributing applications (e.g., Google Play Store guidelines, Apple App Store guidelines).
### 7.5 CI/CD Integration
* **Use a CI/CD system:** Use a continuous integration/continuous delivery (CI/CD) system, such as Jenkins, Travis CI, GitHub Actions, or GitLab CI, to automate the build, test, and deployment process.
* **Create a CI/CD pipeline:** Create a CI/CD pipeline to automate the build, test, and deployment process. The pipeline should handle tasks such as checking out the code, installing dependencies, running tests, building the application, and deploying it to the target platform.
* **Use automated testing:** Use automated testing to ensure that your code is always working correctly. The CI/CD pipeline should run your tests automatically whenever you make changes to your code.
* **Automate deployment:** Automate deployment to the target platform. The CI/CD pipeline should deploy your application automatically whenever it passes all tests.
* **Integration with code review:** Integrate your CI/CD pipeline with your code review process. The CI/CD pipeline should run tests and linters automatically whenever a new pull request is created.
By following these best practices, you can create maintainable, efficient, secure, and testable Kivy applications.
+179
View File
@@ -0,0 +1,179 @@
---
description: Comprehensive best practices and coding standards for developing applications using LangChain.js. Focuses on code organization, performance, security, testing, and common pitfalls to ensure robust and maintainable AI-driven solutions.
globs: **/*.{js,ts,jsx,tsx}
---
- **Monitor and Evaluate LLM applications**: Utilize tools like LangSmith for monitoring application performance, including logging traces, analyzing latency, and evaluating LLM outputs against predefined metrics. This helps identify bottlenecks and ensures the application meets quality standards. Enable tracing by setting environment variables:
`export LANGCHAIN_TRACING_V2="true"`
`export LANGCHAIN_API_KEY="..."`
- **Implement Stateful Agents**: Use LangGraph to build stateful agents, crucial for applications like chatbots where remembering past interactions enhances user experience. Model interactions as a graph with nodes (states) and edges (transitions).
- **Maintain High Code Quality**: Enforce strict code quality through regular testing, ESLint, and Prettier for consistent code formatting and linting.
- **Comprehensive Documentation**: Ensure all components and their interactions are well-documented for maintainability and scalability.
- **Use LangChain Expression Language (LCEL)**: Employ LCEL for composing chains in a declarative way, supporting production deployment without code changes.
- **Explore Trade-offs in Deployment**: Choose between using external LLM providers or self-hosting open-source models based on cost, latency, and privacy considerations.
- **Secure Coding Practices**: Read up on our Security best practices to make sure you're developing safely with LangChain.
## 1. Code Organization and Structure
- **Directory Structure**: Organize code into logical modules based on functionality (e.g., `chains`, `agents`, `tools`, `memory`).
src/
├── chains/
│ ├── conversationalChain.ts
│ └── summarizationChain.ts
├── agents/
│ ├── agent.ts
│ └── agentExecutor.ts
├── tools/
│ ├── searchTool.ts
│ └── calculatorTool.ts
├── memory/
│ ├── bufferMemory.ts
│ └── conversationBufferMemory.ts
├── utils/
│ ├── api.ts
│ └── helpers.ts
├── index.ts
└── types.ts
- **File Naming Conventions**: Use descriptive names, typically in `camelCase` for variables and functions, and `PascalCase` for classes and interfaces. Consider prefixes or suffixes to denote the type of module e.g., `*_chain.ts` or `*_agent.ts`
- **Module Organization**: Group related functionalities into modules with clear interfaces. Use `index.ts` files to export module members for cleaner imports.
typescript
// chains/index.ts
export * from './conversationalChain';
export * from './summarizationChain';
// Usage:
import { ConversationalChain, SummarizationChain } from '@/chains';
- **Component Architecture**: Design modular components for reusability. Implement interfaces to define contracts between components.
typescript
// Define an interface for a Tool
interface ToolInterface {
name: string;
description: string;
execute(input: string): Promise<string>;
}
// Implement the interface in a specific Tool
class SearchTool implements ToolInterface {
name = 'search';
description = 'Useful for searching the internet.';
async execute(input: string): Promise<string> {
// Implementation
}
}
- **Code Splitting**: Implement code splitting using dynamic imports to reduce initial load time, especially for large applications.
typescript
async function loadLargeModule() {
const largeModule = await import('./largeModule');
largeModule.initialize();
}
## 2. Common Patterns and Anti-patterns
- **Design Patterns**: Use the Factory pattern for creating different types of chains or agents, and the Strategy pattern for choosing different LLMs.
typescript
// Factory Pattern for creating chains
class ChainFactory {
static createChain(type: 'conversational' | 'summarization', llm: LLM) {
if (type === 'conversational') {
return new ConversationalChain(llm);
} else if (type === 'summarization') {
return new SummarizationChain(llm);
} else {
throw new Error('Invalid chain type');
}
}
}
const chain = ChainFactory.createChain('conversational', new OpenAIChat());
- **Recommended Approaches**: Leverage LangChain's built-in modules and chains when possible, and customize them as needed. Prioritize asynchronous operations to prevent blocking the main thread.
- **Anti-patterns**: Avoid deeply nested callbacks, which can lead to callback hell. Use `async/await` and promises for cleaner asynchronous code.
- **State Management**: For simple applications, manage state with React's `useState` or similar. For complex applications, consider state management libraries like Zustand or Redux.
- **Error Handling**: Implement robust error handling with `try/catch` blocks and global error handlers. Log errors with context for debugging.
typescript
async function processData() {
try {
const result = await fetchData();
// Process result
} catch (error) {
console.error('Error processing data:', error);
// Handle error (e.g., display error message to user)
}
}
## 3. Performance Considerations
- **Optimization Techniques**: Use caching to store and reuse LLM responses. Optimize prompts to reduce token usage. Debounce computationally expensive operations.
- **Memory Management**: Be mindful of memory leaks, especially when using streams or subscriptions. Properly clean up resources when components unmount.
- **Bundle Size Optimization**: Use tools like Webpack Bundle Analyzer to identify large dependencies. Use tree shaking to remove unused code.
- **Lazy Loading**: Implement lazy loading for components and modules that are not immediately needed to improve initial load time.
## 4. Security Best Practices
- **Vulnerabilities**: Prevent prompt injection attacks by carefully validating user inputs and using sandboxed execution environments.
- **Input Validation**: Sanitize user inputs to prevent malicious code execution. Limit the length of inputs to prevent denial-of-service attacks.
- **Authentication/Authorization**: Use secure authentication and authorization mechanisms to protect sensitive data and prevent unauthorized access.
- **Data Protection**: Encrypt sensitive data at rest and in transit. Comply with data privacy regulations like GDPR and CCPA.
- **Secure API Communication**: Use HTTPS for all API communication. Validate API responses to prevent data corruption.
## 5. Testing Approaches
- **Unit Testing**: Test individual components in isolation using Jest or Mocha. Mock dependencies to control test environments.
- **Integration Testing**: Test interactions between components to ensure they work together correctly. Use in-memory databases or mock APIs for integration tests.
- **End-to-end Testing**: Test the entire application flow using tools like Cypress or Puppeteer. Simulate user interactions to verify functionality.
- **Test Organization**: Organize tests into separate directories based on component or module. Use clear and descriptive test names.
- **Mocking/Stubbing**: Use mocking libraries like Jest's `jest.mock()` or Sinon.js to replace dependencies with controlled test doubles.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes**: Incorrectly configuring API keys, not handling errors properly, and overlooking prompt injection vulnerabilities.
- **Edge Cases**: Handling unexpected input formats, dealing with rate limits from LLM providers, and managing long-running operations.
- **Version-Specific Issues**: Check release notes for breaking changes when upgrading LangChain.js versions.
- **Compatibility Concerns**: Ensure compatibility between LangChain.js and other libraries, especially those related to data processing or UI frameworks.
- **Debugging Strategies**: Use console logging, debuggers, and monitoring tools like LangSmith to diagnose issues.
## 7. Tooling and Environment
- **Recommended Tools**: VS Code with TypeScript support, ESLint, Prettier, and Jest.
- **Build Configuration**: Use Webpack, Parcel, or Rollup for bundling and optimization. Configure TypeScript compiler options for strict type checking.
- **Linting/Formatting**: Enforce consistent code style with ESLint and Prettier. Use linting rules to catch potential errors and enforce best practices.
- **Deployment Best Practices**: Use serverless functions or containerization for deployment. Implement monitoring and alerting to detect issues in production.
- **CI/CD Integration**: Automate testing, linting, and deployment with CI/CD pipelines using tools like GitHub Actions or Jenkins.
+312
View File
@@ -0,0 +1,312 @@
---
description: This rule file provides comprehensive best practices for developing with LangGraph, covering code organization, performance, security, testing, and common pitfalls. It offers actionable guidance for developers to build robust and maintainable LangGraph applications.
globs: **/*.py
---
# LangGraph Best Practices and Coding Standards
This document outlines best practices and coding standards for developing with LangGraph. It aims to provide clear, actionable guidance for developers to build robust, maintainable, and scalable LangGraph applications. It covers various aspects, including code organization, common patterns, performance considerations, security, testing, and common pitfalls.
## Library Information:
- Name: langgraph
- Tags: ai, ml, llm, python, agent-framework, workflow
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
my_langgraph_project/
├── data/ # Datasets, knowledge bases, or other data files.
├── src/ # Source code.
│ ├── components/ # Reusable components (e.g., custom nodes, tools).
│ │ ├── __init__.py
│ │ ├── retrieval.py # Retrieval-related nodes
│ │ ├── tool_selector.py # Logic for selecting which tool to use
│ │ └── ...
│ ├── graphs/ # Graph definitions.
│ │ ├── __init__.py
│ │ ├── customer_support.py # Example: Customer support graph.
│ │ ├── rag_pipeline.py # Example: RAG pipeline graph.
│ │ └── ...
│ ├── utils/ # Utility functions and helpers.
│ │ ├── __init__.py
│ │ ├── config.py # Configuration loading
│ │ ├── logging.py # Logging setup
│ │ └── ...
│ ├── schemas/ # Data schemas and type definitions.
│ │ ├── __init__.py
│ │ ├── agent_state.py # Definition of agent state
│ │ └── ...
│ ├── main.py # Entry point of the application.
│ └── ...
├── tests/ # Unit and integration tests.
│ ├── __init__.py
│ ├── components/ # Tests for custom components.
│ ├── graphs/ # Tests for graph definitions.
│ ├── utils/ # Tests for utility functions.
│ └── ...
├── .env # Environment variables.
├── requirements.txt # Project dependencies.
├── pyproject.toml # Project metadata and build settings
└── README.md # Project documentation.
### 1.2. File Naming Conventions
- Python files: `snake_case.py` (e.g., `customer_support.py`, `retrieval_node.py`).
- Class names: `PascalCase` (e.g., `CustomerSupportGraph`, `RetrievalNode`).
- Variables and functions: `snake_case` (e.g., `user_query`, `process_message`).
- Configuration files: `config.yaml` or `config.json`
### 1.3. Module Organization Best Practices
- Group related functionalities into modules (e.g., `components`, `graphs`, `utils`).
- Use `__init__.py` files to make directories packages.
- Keep modules focused and avoid overly large files.
- Use relative imports within modules to avoid naming conflicts.
### 1.4. Component Architecture Recommendations
- Design reusable components for common tasks (e.g., data retrieval, text summarization, tool selection).
- Create abstract base classes or interfaces for components to promote code reuse and modularity.
- Use dependency injection to configure components and their dependencies.
- Adhere to the Single Responsibility Principle (SRP) when designing components.
### 1.5. Code Splitting Strategies
- Split large graph definitions into smaller, more manageable files.
- Use lazy loading for components that are not immediately needed.
- Consider using a module bundler (e.g., esbuild via a plugin) to optimize bundle size for deployment.
- Break the system down into microservices if warranted by scale and complexity of the overall system. Communicate between microservices using REST or message queues.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **State Management Pattern**: Encapsulate the agent state in a dedicated class or data structure to ensure consistency and maintainability. Use LangGraph's `StateGraph` to clearly define the state transitions.
- **Node Pattern**: Define reusable nodes for common tasks such as information retrieval, tool selection, and response generation.
- **Conditional Edge Pattern**: Use conditional edges to implement branching logic based on the agent state or external factors. This makes the graph more dynamic and responsive.
- **Retry Pattern:** Implement retry logic within nodes or edges to handle transient errors or API rate limits. Use exponential backoff to avoid overwhelming failing services.
- **Orchestration Pattern**: Use LangGraph as the orchestrator for complex agentic workflows, delegating specific tasks to specialized components or services.
### 2.2. Recommended Approaches for Common Tasks
- **Information Retrieval**: Use LangChain's retrieval chain or custom nodes to fetch relevant information from external sources.
- **Tool Selection**: Implement a tool selection node that dynamically chooses the appropriate tool based on the user query and agent state.
- **Response Generation**: Use LangChain's LLMChain or custom nodes to generate responses based on the retrieved information and agent state.
- **Error Handling:** Implement robust error handling within nodes and edges to gracefully handle exceptions and prevent application crashes. Log all errors and implement monitoring to quickly detect and resolve issues.
### 2.3. Anti-patterns and Code Smells
- **Monolithic Graphs**: Avoid creating overly complex graphs with too many nodes and edges. Break them down into smaller, more manageable subgraphs.
- **Hardcoded Values**: Avoid hardcoding values directly into the graph definition. Use configuration files or environment variables to manage configurable parameters.
- **Ignoring Errors**: Always handle exceptions and log errors appropriately. Ignoring errors can lead to unexpected behavior and difficult-to-debug issues.
- **Over-Reliance on Global State**: Minimize the use of global state to avoid unintended side effects and make the application more testable.
- **Lack of Testing**: Thoroughly test all components and graph definitions to ensure they function correctly and handle edge cases.
- **Infinite Loops:** Ensure the conditional edges within the graph are well-defined to avoid infinite loops.
### 2.4. State Management Best Practices
- Define a clear and concise agent state schema.
- Use immutable data structures for the agent state to avoid accidental modifications.
- Persist the agent state to a database or other storage medium to support long-running conversations or task executions. Consider using vector databases for efficient retrieval.
- Implement versioning for the agent state schema to support schema migrations.
- Use LangGraph's checkpointing feature to save and restore the agent state.
### 2.5. Error Handling Patterns
- Use try-except blocks to catch exceptions within nodes and edges.
- Log all errors and warnings with relevant context information.
- Implement retry logic for transient errors or API rate limits.
- Use fallback mechanisms to gracefully handle unrecoverable errors.
- Centralize error handling logic in a dedicated module or class.
- Implement circuit breaker pattern to prevent cascading failures.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Caching**: Implement caching for frequently accessed data or LLM responses.
- **Batching**: Batch multiple requests to external APIs to reduce latency.
- **Asynchronous Operations**: Use asynchronous operations to perform non-blocking I/O and improve responsiveness.
- **Parallel Processing**: Use multi-threading or multi-processing to parallelize computationally intensive tasks.
- **Graph Optimization**: Optimize the graph structure to minimize the number of nodes and edges.
- **Prompt Optimization**: Carefully design prompts to reduce the number of tokens and improve LLM performance.
- **Reduce LLM calls**: Cache LLM responses when possible. Fine-tune smaller models for specific tasks to reduce latency and cost.
### 3.2. Memory Management Considerations
- Monitor memory usage to detect memory leaks or excessive memory consumption.
- Use garbage collection to reclaim unused memory.
- Avoid storing large objects in the agent state.
- Use streaming or lazy loading for large data sets.
### 3.3. (Not applicable, as LangGraph doesn't directly handle rendering)
### 3.4. Bundle Size Optimization
- Use a module bundler (e.g., esbuild) to optimize bundle size.
- Remove unused code and dependencies.
- Use code splitting to load only the necessary code for each route or component.
- Compress the bundle using gzip or Brotli.
### 3.5. Lazy Loading Strategies
- Use lazy loading for components that are not immediately needed.
- Load large data sets or models on demand.
- Implement code splitting to load only the necessary code for each graph or component.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
- **Prompt Injection**: Prevent prompt injection by carefully validating user inputs and sanitizing prompts.
- **Data Leaks**: Protect sensitive data by encrypting it at rest and in transit.
- **Unauthorized Access**: Implement strong authentication and authorization mechanisms to control access to the application and its data.
- **Denial of Service (DoS)**: Implement rate limiting and request filtering to prevent DoS attacks.
- **Code Injection**: Avoid executing arbitrary code based on user inputs to prevent code injection vulnerabilities.
- **API Key Exposure**: Store API keys securely using environment variables or a secrets management system and avoid committing them to version control.
### 4.2. Input Validation
- Validate all user inputs to prevent prompt injection and other vulnerabilities.
- Use regular expressions or other validation techniques to ensure that inputs conform to the expected format.
- Sanitize inputs to remove potentially harmful characters or code.
- Enforce input length limits to prevent buffer overflows.
### 4.3. Authentication and Authorization
- Use strong authentication mechanisms (e.g., multi-factor authentication) to verify user identities.
- Implement role-based access control (RBAC) to restrict access to sensitive data and functionality.
- Use secure session management to protect user sessions from hijacking.
- Store passwords securely using hashing and salting.
### 4.4. Data Protection
- Encrypt sensitive data at rest and in transit.
- Use secure protocols (e.g., HTTPS) for all API communication.
- Implement data masking to protect sensitive data from unauthorized access.
- Regularly back up data to prevent data loss.
- Comply with relevant data privacy regulations (e.g., GDPR, CCPA).
### 4.5. Secure API Communication
- Use HTTPS for all API communication.
- Implement API authentication and authorization.
- Validate API requests and responses.
- Use rate limiting to prevent API abuse.
- Monitor API traffic for suspicious activity.
## 5. Testing Approaches
### 5.1. Unit Testing
- Write unit tests for all components and utility functions.
- Use mocking and stubbing to isolate components during testing.
- Test edge cases and error conditions.
- Aim for high test coverage.
### 5.2. Integration Testing
- Write integration tests to verify the interactions between different components.
- Test the integration with external APIs and services.
- Use a test environment that closely resembles the production environment.
### 5.3. End-to-End Testing
- Write end-to-end tests to verify the entire application flow.
- Use a testing framework such as Playwright or Selenium to automate end-to-end tests.
- Test the application from the user's perspective.
### 5.4. Test Organization
- Organize tests into separate directories for unit tests, integration tests, and end-to-end tests.
- Use descriptive names for test files and test functions.
- Follow a consistent naming convention for test files and test functions.
- Use test suites to group related tests.
### 5.5. Mocking and Stubbing
- Use mocking to replace external dependencies with mock objects.
- Use stubbing to replace complex components with simplified versions.
- Use a mocking framework such as pytest-mock to simplify mocking and stubbing.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Incorrect State Management**: Failing to properly manage the agent state can lead to inconsistent behavior and incorrect results.
- **Ignoring Edge Cases**: Neglecting to handle edge cases can cause unexpected errors and application crashes.
- **Over-Engineering**: Over-complicating the graph definition can make it difficult to understand and maintain.
- **Insufficient Testing**: Lack of thorough testing can lead to undetected bugs and application failures.
- **Not Handling Asynchronous Operations Correctly:** LangGraph, and LLMs generally, use async operations, and failing to await these operations will cause unpredictable results.
### 6.2. Edge Cases
- **Empty User Inputs**: Handle cases where the user provides empty or invalid inputs.
- **API Rate Limits**: Implement retry logic and rate limiting to handle API rate limits.
- **Unexpected API Responses**: Handle cases where external APIs return unexpected responses.
- **Large Data Sets**: Use streaming or lazy loading to handle large data sets.
### 6.3. Version-Specific Issues
- Be aware of compatibility issues between different versions of LangGraph and LangChain.
- Consult the documentation and release notes for any version-specific issues.
- Pin dependencies to specific versions to avoid unexpected behavior.
### 6.4. Compatibility Concerns
- Ensure compatibility between LangGraph and other technologies used in the application.
- Test the integration with external APIs and services.
- Use a consistent set of libraries and dependencies.
### 6.5. Debugging Strategies
- Use logging to track the execution flow and identify errors.
- Use a debugger to step through the code and inspect variables.
- Use a testing framework to write unit tests and integration tests.
- Use monitoring tools to track performance and identify bottlenecks.
- Visualize the graph structure to understand the flow of execution.
## 7. Tooling and Environment
### 7.1. Recommended Tools
- **IDE**: PyCharm, Visual Studio Code with Python extension.
- **Virtual Environment Manager**: venv, conda.
- **Testing Framework**: pytest.
- **Mocking Framework**: pytest-mock.
- **Linting and Formatting**: pylint, black.
- **Module Bundler**: esbuild via a plugin.
- **CI/CD**: GitHub Actions, GitLab CI.
- **Secrets Management**: HashiCorp Vault, AWS Secrets Manager, Azure Key Vault.
- **Monitoring**: LangSmith, Prometheus, Grafana.
### 7.2. Build Configuration
- Use a build system such as `poetry` or `pip` to manage dependencies.
- Use a configuration file such as `pyproject.toml` or `setup.py` to define project metadata and build settings.
### 7.3. Linting and Formatting
- Use a linter such as `pylint` or `flake8` to enforce code style and identify potential errors.
- Use a code formatter such as `black` or `autopep8` to automatically format the code.
- Configure the linter and formatter to use a consistent set of rules and settings.
### 7.4. Deployment
- Containerize the application using Docker.
- Deploy the application to a cloud platform such as AWS, Azure, or Google Cloud.
- Use a deployment tool such as Terraform or Ansible to automate the deployment process.
- Implement a blue-green deployment strategy to minimize downtime.
### 7.5. CI/CD
- Use a CI/CD tool such as GitHub Actions or GitLab CI to automate the testing, building, and deployment processes.
- Configure the CI/CD pipeline to run tests, linters, and formatters.
- Use a code review process to ensure code quality and security.
## Conclusion
By following these best practices and coding standards, developers can build robust, maintainable, and scalable LangGraph applications. This will also help with collaboration amongst team members working in the same codebase.
+297
View File
@@ -0,0 +1,297 @@
---
description: This rule file provides comprehensive best practices for LightGBM, covering code organization, performance, security, testing, and common pitfalls to avoid. Adhering to these guidelines will improve the efficiency, reliability, and maintainability of your LightGBM projects.
globs: **/*.{py,ipynb}
---
# LightGBM Best Practices
This document outlines best practices for developing and maintaining LightGBM-based machine learning projects. It covers various aspects, from code organization to performance optimization and security considerations.
## Library Information:
- Name: LightGBM
- Tags: ai, ml, machine-learning, python, gradient-boosting
## 1. Code Organization and Structure
### 1.1 Directory Structure
project_root/
├── data/
│ ├── raw/
│ ├── processed/
│ └── external/
├── notebooks/
│ ├── exploratory_data_analysis.ipynb
│ └── model_evaluation.ipynb
├── src/
│ ├── __init__.py
│ ├── data/
│ │ ├── __init__.py
│ │ ├── dataset.py # Data loading and preprocessing logic
│ │ └── features.py # Feature engineering functions
│ ├── models/
│ │ ├── __init__.py
│ │ ├── train.py # Model training script
│ │ ├── predict.py # Prediction script
│ │ └── model.py # Model definition (if applicable)
│ ├── utils/
│ │ ├── __init__.py
│ │ ├── logger.py # Logging utilities
│ │ └── helper.py # General helper functions
│ └── visualization/
│ ├── __init__.py
│ └── plots.py # Custom plotting functions
├── tests/
│ ├── __init__.py
│ ├── data/
│ ├── models/
│ └── utils/
├── configs/
│ └── config.yaml
├── reports/
│ └── figures/
├── .gitignore
├── README.md
├── pyproject.toml
└── requirements.txt
* **data/**: Contains raw, processed, and external data.
* **notebooks/**: Jupyter notebooks for exploration and experimentation.
* **src/**: Source code for data loading, feature engineering, model training, and prediction.
* **tests/**: Unit and integration tests.
* **configs/**: Configuration files (e.g., YAML).
* **reports/**: Generated reports and figures.
### 1.2 File Naming Conventions
* Python files: `lowercase_with_underscores.py`
* Jupyter notebooks: `descriptive_name.ipynb`
* Configuration files: `config.yaml` or `config.json`
* Data files: `data_description.csv` or `data_description.parquet`
### 1.3 Module Organization
* Group related functions and classes into modules.
* Use clear and descriptive module names.
* Minimize dependencies between modules.
### 1.4 Component Architecture
* **Data Layer:** Handles data loading, preprocessing, and feature engineering.
* **Model Layer:** Encapsulates model training, evaluation, and prediction.
* **Service Layer:** Exposes model functionality through an API or interface.
* **Configuration Layer:** Manages configuration parameters and settings.
### 1.5 Code Splitting
* Break down complex tasks into smaller, more manageable functions.
* Use classes to encapsulate related data and behavior.
* Avoid long functions and deeply nested code blocks.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Factory Pattern:** To create different LightGBM models based on configuration.
* **Strategy Pattern:** To implement different feature engineering techniques.
* **Observer Pattern:** To monitor training progress and log metrics.
### 2.2 Recommended Approaches
* **Data Preparation:** Utilize LightGBM's native support for missing values and categorical features. Convert categorical features to the `categorical` data type in pandas before splitting the data.
* **Hyperparameter Tuning:** Use techniques like grid search, random search, or Bayesian optimization (e.g., Optuna) to optimize hyperparameters. Implement early stopping to prevent overfitting.
* **Model Monitoring:** Track training and validation performance metrics to detect overfitting and adjust model complexity.
* **Feature Selection:** Use feature importance to identify and select relevant features.
* **Cross-Validation:** Use k-fold cross-validation for robust model evaluation. The `cv` function provides mean metrics and standard deviations across folds.
### 2.3 Anti-patterns and Code Smells
* **Hardcoding hyperparameters:** Avoid hardcoding; use configuration files.
* **Ignoring missing values:** LightGBM handles missing values, so explicitly using them is fine, but ensure you understand their impact.
* **Overfitting:** Monitor training vs. validation performance and use regularization.
* **Large, monolithic functions:** Break down into smaller, testable units.
* **Ignoring feature importances:** Use feature importance to help drive feature selection and understand your model.
### 2.4 State Management
* Use configuration files to manage model parameters and training settings.
* Store model artifacts (e.g., trained models, scalers) in a designated directory.
* Use version control to track changes to code and data.
### 2.5 Error Handling
* Use `try-except` blocks to handle potential exceptions.
* Log errors and warnings using a logging library (e.g., `logging`).
* Provide informative error messages to the user.
* Implement retry mechanisms for transient errors.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Hyperparameter Tuning:** Optimize hyperparameters such as learning rate, number of leaves, and tree depth.
* **Early Stopping:** Implement early stopping to prevent overfitting and reduce training time.
* **Parallel Training:** Enable parallel training for faster computations (data/feature/voting parallel).
* **GPU Acceleration:** Enable GPU usage for accelerated training when possible.
* **Feature Selection:** Remove irrelevant or redundant features to improve performance.
* **Reduce data size:** Consider downcasting numerical types (e.g., float64 to float32) if precision loss is acceptable.
* **Histogram-based algorithms:** LightGBM uses histogram-based algorithms for faster training on large datasets.
### 3.2 Memory Management
* **`max_bin` Parameter:** Reduce `max_bin` to decrease memory usage (may impact accuracy).
* **`save_binary` Parameter:** Use `save_binary` to save data in a binary format for faster loading and reduced memory usage.
* **Data Types:** Use appropriate data types to minimize memory footprint (e.g., `int32` instead of `int64`).
* **Garbage Collection:** Explicitly call `gc.collect()` to free up unused memory.
### 3.3 Bundle Size Optimization (If applicable for deployment)
* Remove unnecessary dependencies.
* Use code minification and compression techniques.
* Optimize image assets.
### 3.4 Lazy Loading
* Load data and models only when needed.
* Use generators to process large datasets in chunks.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
* **Untrusted Input:** Vulnerable to injection attacks if model is used directly on user-provided data without sanitization.
* **Model Poisoning:** If training data is sourced from untrusted sources, the model can be poisoned.
* **Denial of Service (DoS):** Malicious input crafted to consume excessive resources.
### 4.2 Input Validation
* Validate input data to ensure it conforms to expected types and ranges.
* Sanitize input data to prevent injection attacks.
* Use a schema validation library (e.g., `cerberus`, `jsonschema`).
### 4.3 Authentication and Authorization
* Implement authentication to verify the identity of users.
* Use authorization to control access to resources and functionality.
* Use secure protocols (e.g., HTTPS) for API communication.
### 4.4 Data Protection
* Encrypt sensitive data at rest and in transit.
* Use data masking to protect sensitive information.
* Implement access controls to restrict access to data.
### 4.5 Secure API Communication
* Use HTTPS for all API communication.
* Implement input validation and sanitization.
* Use rate limiting to prevent abuse.
* Monitor API traffic for suspicious activity.
## 5. Testing Approaches
### 5.1 Unit Testing
* Test individual functions and classes in isolation.
* Use mocking and stubbing to isolate dependencies.
* Write tests for different input scenarios and edge cases.
* Verify expected outputs and side effects.
### 5.2 Integration Testing
* Test interactions between different components.
* Verify data flow and consistency.
* Test API endpoints and data pipelines.
### 5.3 End-to-End Testing
* Test the entire application flow from start to finish.
* Simulate real-world user scenarios.
* Verify that the application meets all requirements.
### 5.4 Test Organization
* Organize tests into separate directories based on component.
* Use clear and descriptive test names.
* Follow a consistent testing style.
### 5.5 Mocking and Stubbing
* Use mocking to replace external dependencies with controlled substitutes.
* Use stubbing to provide predefined responses for function calls.
* Use a mocking library (e.g., `unittest.mock`, `pytest-mock`).
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Data Leakage:** Accidentally using future information during training.
* **Incorrect Feature Scaling:** Using inappropriate scaling methods.
* **Ignoring Categorical Features:** Not treating categorical features correctly.
* **Not tuning for imbalanced classes:** Ignoring the need to adjust for imbalanced datasets.
* **Improper Cross-Validation:** Setting up cross-validation incorrectly.
### 6.2 Edge Cases
* **Rare Categories:** Handling infrequent categorical values.
* **Missing Data Patterns:** Understanding the nature and impact of missing data.
* **Outliers:** Detecting and handling extreme values in your dataset.
### 6.3 Version-Specific Issues
* Refer to the LightGBM release notes for known issues and bug fixes.
* Stay up-to-date with the latest version of LightGBM.
### 6.4 Compatibility Concerns
* Ensure compatibility between LightGBM and other libraries (e.g., scikit-learn, pandas).
* Address potential conflicts between different versions of dependencies.
### 6.5 Debugging Strategies
* Use a debugger (e.g., `pdb`) to step through code and inspect variables.
* Log intermediate values and execution paths.
* Use assertions to verify expected behavior.
* Simplify the problem by isolating components.
* Consult the LightGBM documentation and community forums.
## 7. Tooling and Environment
### 7.1 Recommended Tools
* **Python:** The primary language for LightGBM development.
* **pandas:** For data manipulation and analysis.
* **NumPy:** For numerical computations.
* **scikit-learn:** For machine learning algorithms and tools.
* **Jupyter Notebook:** For interactive development and experimentation.
* **IDE:** VSCode, PyCharm, or similar.
* **Optuna/Hyperopt:** For hyperparameter optimization.
### 7.2 Build Configuration
* Use a build system (e.g., `setuptools`, `poetry`) to manage dependencies and build packages.
* Create a `requirements.txt` file to list project dependencies.
* Use a virtual environment to isolate project dependencies.
### 7.3 Linting and Formatting
* Use a linter (e.g., `flake8`, `pylint`) to enforce code style and identify potential errors.
* Use a formatter (e.g., `black`, `autopep8`) to automatically format code.
* Configure the IDE to automatically run linters and formatters.
### 7.4 Deployment Best Practices
* Containerize the application using Docker.
* Deploy the application to a cloud platform (e.g., AWS, Azure, GCP).
* Use a deployment tool (e.g., Kubernetes, Docker Compose).
* Monitor the application for performance and errors.
### 7.5 CI/CD Integration
* Use a CI/CD pipeline (e.g., Jenkins, GitLab CI, GitHub Actions) to automate testing and deployment.
* Run unit and integration tests in the CI/CD pipeline.
* Deploy code to staging and production environments.
By adhering to these best practices, you can develop robust, efficient, and maintainable LightGBM-based machine learning projects.
+158
View File
@@ -0,0 +1,158 @@
---
description: This rule outlines best practices and coding standards for developing with LlamaIndex, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure maintainable, efficient, and secure LlamaIndex applications.
globs: **/*.py
---
# LlamaIndex Best Practices and Coding Standards
This document provides comprehensive guidance on developing high-quality applications using LlamaIndex. It covers various aspects of development, including code organization, performance optimization, security considerations, and testing strategies.
## 1. Code Organization and Structure
* **Directory Structure Best Practices:**
* `data/`: Store data sources (e.g., documents, PDFs) used by LlamaIndex.
* `indices/`: Contains index definitions and configurations.
* `queries/`: Defines query engines and query logic.
* `models/`: Place custom LLM or embedding model configurations.
* `utils/`: Utility functions and helper classes.
* `tests/`: Unit, integration, and end-to-end tests.
* `scripts/`: Scripts for data ingestion, index building, or other automation tasks.
* **File Naming Conventions:**
* Data loaders: `*_loader.py` (e.g., `pdf_loader.py`)
* Index definitions: `*_index.py` (e.g., `vector_index.py`)
* Query engines: `*_query_engine.py` (e.g., `knowledge_graph_query_engine.py`)
* Models: `*_model.py` (e.g., `custom_llm_model.py`)
* Utilities: `*_utils.py` (e.g., `text_processing_utils.py`)
* Tests: `test_*.py` (e.g., `test_vector_index.py`)
* **Module Organization:**
* Group related functionalities into modules (e.g., `data_ingestion`, `indexing`, `querying`).
* Use clear and descriptive module names.
* Minimize dependencies between modules to improve maintainability.
* **Component Architecture:**
* **Data Connectors:** Abstract data loading logic into reusable connectors.
* **Index Structures:** Use appropriate index structures (e.g., `VectorStoreIndex`, `KnowledgeGraphIndex`) based on data characteristics and query requirements.
* **Query Engines:** Decouple query logic from index structures.
* **LLM Abstraction:** Abstract LLM calls using interfaces for flexibility and testability.
* **Code Splitting:**
* Break down large functions into smaller, well-defined functions.
* Use classes to encapsulate related data and behavior.
* Extract reusable code into separate modules or packages.
## 2. Common Patterns and Anti-patterns
* **Design Patterns:**
* **Factory Pattern:** For creating different types of indexes or query engines.
* **Strategy Pattern:** For choosing different retrieval or ranking algorithms.
* **Decorator Pattern:** For adding pre-processing or post-processing steps to queries.
* **Recommended Approaches:**
* **Data Ingestion:** Use `SimpleDirectoryReader` or custom data connectors to load data.
* **Indexing:** Choose the appropriate index type based on your data and query needs. Consider `VectorStoreIndex` for semantic search, `KnowledgeGraphIndex` for knowledge graph-based queries, and `ComposableGraph` for combining multiple indexes.
* **Querying:** Use `as_query_engine()` to create a query engine from an index. Customize the query engine with different retrieval and response synthesis modules.
* **Evaluation:** Use LlamaIndex's evaluation modules to measure the performance of your LLM application (e.g., retrieval and LLM response quality).
* **Anti-patterns and Code Smells:**
* **Tight Coupling:** Avoid tight coupling between components. Use interfaces and dependency injection to promote loose coupling.
* **God Classes:** Avoid creating large classes that do too much. Break them down into smaller, more focused classes.
* **Code Duplication:** Avoid duplicating code. Extract common code into reusable functions or classes.
* **Ignoring Errors:** Don't ignore errors. Handle them gracefully or raise exceptions.
* **State Management:**
* Use LlamaIndex's `StorageContext` to persist indexes to disk.
* Consider using a database to store application state.
* **Error Handling:**
* Use `try-except` blocks to handle exceptions.
* Log errors for debugging purposes.
* Provide informative error messages to the user.
## 3. Performance Considerations
* **Optimization Techniques:**
* **Indexing:** Optimize index construction by using appropriate chunk sizes and overlap.
* **Querying:** Optimize query performance by using appropriate retrieval and ranking algorithms.
* **Caching:** Cache query results to improve performance.
* **Parallelization:** Parallelize data loading and indexing tasks.
* **Memory Management:**
* Use generators to process large datasets in chunks.
* Release memory when it is no longer needed.
* **Bundle Size Optimization:** (Not directly applicable to LlamaIndex as it is a backend library, but relevant if building a web UI on top)
* Remove unused code.
* Use code splitting to load only the code that is needed.
* **Lazy Loading:**
* Load data and models only when they are needed.
* Use lazy initialization to defer the creation of objects until they are first used.
## 4. Security Best Practices
* **Common Vulnerabilities:**
* **Prompt Injection:** Prevent prompt injection attacks by carefully sanitizing user input and using appropriate prompt engineering techniques.
* **Data Leaks:** Protect sensitive data by using appropriate access control and encryption.
* **API Key Exposure:** Avoid exposing API keys in your code. Use environment variables or a secure configuration management system to store API keys.
* **Input Validation:**
* Validate all user input to prevent injection attacks.
* Sanitize input to remove potentially harmful characters.
* **Authentication and Authorization:**
* Implement authentication and authorization to control access to your application.
* Use strong passwords and multi-factor authentication.
* **Data Protection:**
* Encrypt sensitive data at rest and in transit.
* Use appropriate access control to protect data.
* **Secure API Communication:**
* Use HTTPS to encrypt communication between your application and the LlamaIndex API.
* Validate the server certificate to prevent man-in-the-middle attacks.
## 5. Testing Approaches
* **Unit Testing:**
* Write unit tests for all core components, including data connectors, index structures, and query engines.
* Use mocking and stubbing to isolate components during testing.
* **Integration Testing:**
* Write integration tests to verify that different components work together correctly.
* Test the integration between LlamaIndex and other libraries or frameworks.
* **End-to-end Testing:**
* Write end-to-end tests to verify that the entire application works as expected.
* Test the application with real data and user scenarios.
* **Test Organization:**
* Organize tests into separate directories for unit, integration, and end-to-end tests.
* Use clear and descriptive test names.
* **Mocking and Stubbing:**
* Use mocking and stubbing to isolate components during testing.
* Use a mocking framework such as `unittest.mock` or `pytest-mock`.
## 6. Common Pitfalls and Gotchas
* **Frequent Mistakes:**
* Using the wrong index type for the data.
* Not optimizing query performance.
* Not handling errors gracefully.
* Exposing API keys.
* Not validating user input.
* **Edge Cases:**
* Handling large documents.
* Handling noisy or incomplete data.
* Handling complex queries.
* **Version-Specific Issues:**
* Be aware of breaking changes in LlamaIndex releases.
* Refer to the LlamaIndex documentation for version-specific information.
* **Compatibility Concerns:**
* Ensure that LlamaIndex is compatible with the other libraries and frameworks that you are using.
* Test your application thoroughly to identify any compatibility issues.
* **Debugging Strategies:**
* Use logging to track the execution of your application.
* Use a debugger to step through your code and inspect variables.
* Use LlamaIndex's debugging tools to diagnose issues.
## 7. Tooling and Environment
* **Recommended Development Tools:**
* **IDE:** VS Code, PyCharm
* **Package Manager:** Poetry, pip
* **Testing Framework:** pytest
* **Linting and Formatting:** flake8, black
* **Build Configuration:**
* Use a build system such as `poetry` to manage dependencies.
* Create a `requirements.txt` file to list dependencies.
* **Linting and Formatting:**
* Use a linter such as `flake8` to enforce code style.
* Use a formatter such as `black` to automatically format code.
* **Deployment Best Practices:**
* Use a containerization technology such as Docker to package your application.
* Use a cloud platform such as AWS, Azure, or GCP to deploy your application.
* **CI/CD Integration:**
* Use a CI/CD system such as GitHub Actions or Jenkins to automate the build, test, and deployment process.
+294
View File
@@ -0,0 +1,294 @@
---
description: This rule provides comprehensive guidelines for developing AI applications with LlamaIndex-JS, covering code organization, performance, security, and testing best practices. It aims to ensure robust, efficient, and secure LLM-powered applications.
globs: **/*.{js,ts,jsx,tsx}
---
# LlamaIndex-JS Best Practices and Coding Standards
This document outlines the best practices and coding standards for developing AI and ML applications using the LlamaIndex-JS library. Following these guidelines will help you build robust, efficient, secure, and maintainable applications.
## 1. Code Organization and Structure
### 1.1. Directory Structure
Adopt a modular directory structure to organize your LlamaIndex-JS project. Here’s a recommended structure:
my-llamaindex-app/
├── src/
│ ├── components/ # Reusable UI components (if applicable)
│ │ ├── MyComponent.tsx
│ │ └── ...
│ ├── services/ # API services and data fetching logic
│ │ ├── llamaIndexService.ts # LlamaIndex specific functionalities
│ │ └── ...
│ ├── utils/ # Utility functions and helpers
│ │ ├── dataProcessing.ts
│ │ └── ...
│ ├── index/ # Index management
│ │ ├── documentLoaders.ts # Custom document loaders
│ │ ├── indexBuilders.ts # Logic for building indices
│ │ └── ...
│ ├── prompts/ # Custom prompt templates
│ │ ├── summarizationPrompt.ts
│ │ └── ...
│ ├── models/ # Data models and interfaces
│ │ ├── document.ts
│ │ └── ...
│ ├── app.ts # Main application entry point
│ └── ...
├── tests/
│ ├── unit/
│ │ └── ...
│ ├── integration/
│ │ └── ...
│ └── ...
├── .env # Environment variables
├── package.json
├── tsconfig.json # TypeScript configuration
├── README.md
└── ...
### 1.2. File Naming Conventions
* Use descriptive and consistent file names.
* For components, use PascalCase (e.g., `MyComponent.tsx`).
* For utility functions and services, use camelCase (e.g., `llamaIndexService.ts`, `dataProcessing.ts`).
* For configuration files, use kebab-case (e.g., `tsconfig.json`).
### 1.3. Module Organization
* **Encapsulation:** Group related functions, classes, and interfaces into modules.
* **Single Responsibility Principle:** Each module should have a clear and specific purpose.
* **Explicit Exports:** Use explicit `export` statements to define the public API of each module.
* **Avoid Circular Dependencies:** Be mindful of circular dependencies between modules, as they can lead to runtime errors and make code harder to understand.
### 1.4. Component Architecture (If Applicable)
* If your LlamaIndex-JS application includes a user interface (e.g., using React), follow a component-based architecture.
* **Presentational Components:** Focus on rendering UI elements and receiving data as props.
* **Container Components:** Handle data fetching, state management, and logic.
* **Component Composition:** Build complex UIs by composing smaller, reusable components.
### 1.5. Code Splitting
* Use dynamic imports (`import()`) to split your code into smaller chunks.
* Lazy-load components or modules that are not immediately needed.
* This can significantly improve initial load time and reduce the overall bundle size.
typescript
// Example of lazy loading a module
async function loadMyModule() {
const myModule = await import('./myModule');
myModule.doSomething();
}
## 2. Common Patterns and Anti-Patterns
### 2.1. Design Patterns
* **Retrieval-Augmented Generation (RAG):** Implement RAG to enhance LLM responses by retrieving relevant data from external sources.
* **Factory Pattern:** Use factory functions to create instances of LlamaIndex objects, abstracting the creation logic.
* **Strategy Pattern:** Employ different indexing or query strategies based on the specific use case.
* **Observer Pattern:** Use this to react to changes in the underlying data or model.
### 2.2. Recommended Approaches for Common Tasks
* **Data Loading:** Use `Document` objects and `BaseReader` classes for loading data from various sources.
* **Indexing:** Choose appropriate index types (e.g., `VectorStoreIndex`, `SummaryIndex`) based on your data and query requirements.
* **Querying:** Use `QueryEngine` to orchestrate complex queries and retrieve relevant information.
* **Evaluation:** Implement evaluation metrics to measure the performance of your RAG pipeline.
### 2.3. Anti-Patterns and Code Smells
* **Tight Coupling:** Avoid tight coupling between LlamaIndex-JS components and other parts of your application.
* **Global State:** Minimize the use of global state, as it can make your application harder to reason about.
* **Ignoring Errors:** Always handle errors gracefully and provide informative error messages.
* **Over-Complicating Queries:** Keep queries simple and focused on retrieving the most relevant information.
* **Not using `async/await`:** Use `async/await` when dealing with asynchronous operations to avoid callback hell.
### 2.4. State Management
* Choose a state management library or pattern that fits your application's needs (e.g., React Context, Redux, Zustand).
* Keep state minimal and derive values as needed.
* Use immutable data structures to simplify state updates.
### 2.5. Error Handling
* Use `try...catch` blocks to handle exceptions.
* Provide informative error messages to the user.
* Log errors for debugging purposes.
* Consider using a centralized error handling mechanism.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Efficient Indexing:** Optimize indexing by selecting appropriate chunk sizes and embedding models. Experiment to find optimal values.
* **Caching:** Cache frequently accessed data to reduce latency.
* **Asynchronous Operations:** Use asynchronous operations to avoid blocking the main thread.
* **Vector Store Selection:** Choose vector stores that support efficient similarity search (e.g., FAISS, Annoy, Qdrant).
### 3.2. Memory Management
* Be mindful of memory usage, especially when dealing with large datasets.
* Use garbage collection effectively.
* Avoid creating unnecessary objects.
* Use streams for processing large files.
### 3.3. Rendering Optimization (If Applicable)
* Use virtualization techniques to render large lists efficiently.
* Memoize components to prevent unnecessary re-renders.
* Optimize images and other assets.
### 3.4. Bundle Size Optimization
* Use tree shaking to remove unused code.
* Minify and compress your code.
* Use code splitting to load only the code that is needed for each page.
* Analyze bundle size using tools like Webpack Bundle Analyzer.
### 3.5. Lazy Loading
* Implement lazy loading for non-critical components or modules.
* This can improve initial load time and reduce the overall bundle size.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Prompt Injection:** Protect against prompt injection attacks by sanitizing user input and validating LLM responses. Consider using libraries such as LLM Guard by Protect AI.
* **Data Leakage:** Prevent data leakage by carefully controlling access to sensitive information.
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks (if applicable, in UI components).
* **API Key Exposure:** Protect API keys and other sensitive credentials by storing them securely and avoiding hardcoding them in your code.
### 4.2. Input Validation
* Validate all user input to prevent malicious data from entering your application.
* Use appropriate validation techniques for each type of input.
* Sanitize input to remove potentially harmful characters.
### 4.3. Authentication and Authorization
* Implement authentication to verify the identity of users.
* Implement authorization to control access to resources.
* Use strong passwords and encryption.
* Follow the principle of least privilege.
### 4.4. Data Protection
* Encrypt sensitive data at rest and in transit.
* Use secure storage mechanisms.
* Implement data loss prevention (DLP) measures.
* Regularly back up your data.
### 4.5. Secure API Communication
* Use HTTPS for all API communication.
* Validate API responses to ensure data integrity.
* Implement rate limiting to prevent abuse.
* Use API keys or other authentication mechanisms.
## 5. Testing Approaches
### 5.1. Unit Testing
* Write unit tests to verify the functionality of individual components and functions.
* 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 components and modules.
* Test the integration with external services and APIs.
### 5.3. End-to-End Testing
* Write end-to-end tests to verify the overall functionality of the application.
* Simulate user interactions and verify the expected behavior.
### 5.4. Test Organization
* Organize your tests into separate directories for unit, integration, and end-to-end tests.
* Use descriptive test names.
* Keep tests concise and focused.
### 5.5. Mocking and Stubbing
* Use mocking and stubbing to isolate units of code during testing.
* Use a mocking library such as Jest or Sinon.
* Avoid over-mocking, as it can make your tests less effective.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* Incorrectly configuring the LlamaIndex-JS client.
* Using the wrong index type for your data.
* Not handling errors properly.
* Ignoring performance considerations.
* Not securing your application against vulnerabilities.
### 6.2. Edge Cases
* Handling large documents or datasets.
* Dealing with complex queries.
* Handling different data formats.
* Dealing with rate limits from external APIs.
### 6.3. Version-Specific Issues
* Be aware of breaking changes between LlamaIndex-JS versions.
* Consult the release notes and migration guides when upgrading.
* Test your application thoroughly after upgrading.
### 6.4. Compatibility Concerns
* Ensure compatibility between LlamaIndex-JS and other libraries or frameworks that you are using.
* Test your application in different environments.
### 6.5. Debugging Strategies
* Use a debugger to step through your code and inspect variables.
* Log messages to the console to track the execution flow.
* Use error monitoring tools to track errors in production.
* Use the LlamaIndex-JS documentation and community forums to find solutions to common problems.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* Node.js
* npm or yarn
* TypeScript (recommended)
* VS Code or other IDE
* LlamaIndex Studio for visualization
* Postman or Insomnia for testing APIs
### 7.2. Build Configuration
* Use a build tool such as Webpack or Parcel to bundle your code.
* Configure your build tool to optimize your code for production.
* Use environment variables to configure your application.
### 7.3. Linting and Formatting
* Use a linter such as ESLint to enforce coding standards.
* Use a formatter such as Prettier to format your code consistently.
* Configure your IDE to automatically lint and format your code.
### 7.4. Deployment
* Choose a deployment platform that meets your needs (e.g., Vercel, Netlify, AWS).
* Configure your deployment environment to use environment variables.
* Set up monitoring and logging to track the performance of your application.
### 7.5. CI/CD Integration
* Use a CI/CD platform such as GitHub Actions or Jenkins to automate your build, test, and deployment processes.
* Configure your CI/CD pipeline to run your tests automatically.
* Use automated deployment to deploy your application to production.
By following these best practices, you can build robust, efficient, secure, and maintainable AI applications using LlamaIndex-JS.
+131
View File
@@ -0,0 +1,131 @@
---
description: This rule enforces LLVM's coding standards and promotes best practices for writing efficient, maintainable, and robust code within the LLVM ecosystem. It covers style, language usage, optimization strategies, and more.
globs: **/*.{h,hpp,c,cc,cpp,ll,mlir}
---
- Adhere to LLVM's coding standards to ensure code consistency, readability, and maintainability.
- Always follow the [LLVM Coding Standards](https://llvm.org/docs/CodingStandards.html) and [LLVM Developer Policy](https://llvm.org/docs/DeveloperPolicy.html).
## Languages, Libraries, and Standards
- Use modern, standard-conforming, and portable C++ code (C++17 or later, as supported by major toolchains).
- Prefer LLVM's own libraries (e.g., `llvm::DenseMap`, `llvm::SmallVector`) over the C++ standard library when appropriate for performance or integration benefits. Consult the LLVM Programmer's Manual for details.
- Use Python (with the minimum version specified in the Getting Started documentation) for automation, build systems, and utility scripts.
- Format Python code with `black` and `darker` to adhere to PEP 8 standards.
## Mechanical Source Issues
- Write clear diagnostic messages using succinct and correct English.
- Follow the recommended `#include` style: Main module header first, followed by LLVM project headers (most specific to least specific), then system headers.
- Limit source code width to 80 columns.
- Prefer spaces to tabs in source files.
- Avoid trailing whitespace.
- Format multi-line lambdas like blocks of code.
- Use braced initializer lists as if the braces were parentheses in a function call.
## Language and Compiler Issues
- Treat compiler warnings as errors.
- Write portable code, encapsulating non-portable code behind well-defined interfaces.
- Do not use RTTI or exceptions.
- Prefer C++-style casts (`static_cast`, `reinterpret_cast`, `const_cast`) over C-style casts, except when casting to `void` to suppress unused variable warnings or between integral types.
- Do not use static constructors (global variables with constructors or destructors).
- Use `struct` when all members are public, and `class` otherwise.
- Avoid using braced initializer lists to call constructors with non-trivial logic.
- Use `auto` type deduction to make code more readable, but be mindful of unnecessary copies.
- Beware of non-determinism due to the ordering of pointers in unordered containers.
- Beware of non-deterministic sorting order of equal elements; use `llvm::sort` instead of `std::sort`.
## Style Issues
- Layer libraries correctly to avoid circular dependencies. Use Unix linker principles to enforce this.
- `#include` as little as possible, especially in header files. Use forward declarations when possible.
- Use namespace qualifiers to implement previously declared functions in source files; avoid opening namespace blocks.
- Use early exits and `continue` statements to simplify code and reduce indentation.
- Don't use `else` or `else if` after control flow interrupting statements like `return`, `break`, `continue`, or `goto`.
- Turn predicate loops into predicate functions.
## The Low-Level Issues
- Name types, functions, variables, and enumerators properly, using descriptive and consistent names.
- Assert liberally to check preconditions and assumptions. Include informative error messages in assertions. Use `llvm_unreachable` to mark code that should never be reached. Avoid `assert(false)`. When assertions produce “unused value” warnings, move the call into the assert or cast the value to void.
- Do not use `using namespace std`. Explicitly qualify identifiers from the standard namespace.
- Don't use default labels in fully covered switches over enumerations to catch new enumeration values. Use `llvm_unreachable` after the switch to suppress GCC warnings about reaching the end of a non-void function.
- Use range-based for loops wherever possible.
- Don’t evaluate `end()` every time through a loop; evaluate it once before the loop starts.
- `#include <iostream>` is forbidden. Use `raw_ostream` instead.
- Avoid `std::endl`; use `\n` instead.
- Don’t use `inline` when defining a function in a class definition; it's implicit.
## Microscopic Details
- Put a space before an open parenthesis only in control flow statements, but not in normal function call expressions and function-like macros.
- Prefer preincrement (`++X`) over postincrement (`X++`).
- Don't indent namespaces; add comments indicating which namespace is being closed when helpful.
## Code Organization and Structure
- **Directory Structure:** Follow the existing LLVM directory structure conventions. New components should typically reside in a subdirectory within an existing high-level category (e.g., `lib/Transforms`, `include/llvm/Analysis`). Consider the intended audience (end-user tool vs. internal library) when choosing a location.
- **File Naming:** Use descriptive names for files, matching the class or functionality they contain. Header files should have a `.h` or `.hpp` extension, and implementation files should have a `.cpp`, `.cc`, or `.c` extension (depending on whether they are C or C++). MLIR files should have `.mlir` extension.
- **Module Organization:** Break down large components into smaller, more manageable modules. Each module should have a well-defined purpose and interface. Minimize dependencies between modules.
- **Component Architecture:** Design components with clear separation of concerns. Use interfaces and abstract classes to promote loose coupling and enable polymorphism. Follow the principle of least privilege.
- **Code Splitting:** Decompose large functions into smaller, well-named helper functions. Use namespaces to group related functions and classes.
## Common Patterns and Anti-patterns
- **Visitor Pattern:** LLVM frequently uses the Visitor pattern for traversing and manipulating data structures (e.g., the LLVM IR). Implement visitor classes for custom analysis or transformations.
- **Pass Infrastructure:** Leverage LLVM's pass infrastructure for implementing optimization and analysis passes. Create new pass types (e.g., analysis pass, transformation pass) as needed.
- **Factory Pattern:** Use the Factory pattern to create instances of classes based on runtime parameters or configuration settings.
- **Singleton Pattern (Avoid):** Minimize the use of the Singleton pattern, as it can lead to tight coupling and make testing difficult. Consider dependency injection instead.
- **Global Variables (Avoid):** Avoid global variables whenever possible, as they can introduce unexpected side effects and make code harder to reason about. Use configuration objects or dependency injection instead.
## Performance Considerations
- **Inline Hints:** Use `inline` judiciously to guide the compiler to inline frequently called functions. Avoid inlining large or complex functions.
- **Profile-Guided Optimization (PGO):** Use PGO to optimize code based on runtime profiles. This can significantly improve performance for frequently executed code paths.
- **LTO (Link-Time Optimization):** Enable LTO to allow the compiler to optimize code across module boundaries.
- **Memory Management:** Use LLVM's memory management facilities (e.g., `BumpPtrAllocator`, `ScopedHashTable`) for efficient memory allocation. Avoid excessive memory allocation and deallocation.
- **Avoid Unnecessary Copies:** Pass objects by reference or pointer to avoid unnecessary copying.
- **Use `SmallVector`:** Use `llvm::SmallVector` for small, fixed-size vectors to avoid dynamic memory allocation.
- **Cache Locality:** Consider cache locality when designing data structures and algorithms.
## Security Best Practices
- **Input Validation:** Validate all external inputs to prevent vulnerabilities such as buffer overflows and code injection. Use LLVM's API for parsing various file formats.
- **Sanitizers:** Use AddressSanitizer (ASan), MemorySanitizer (MSan), and UndefinedBehaviorSanitizer (UBSan) during development and testing to detect memory errors and undefined behavior.
- **Avoid Code Injection:** Do not construct code by concatenating strings or using other techniques that could lead to code injection vulnerabilities.
- **Data Validation:** Make sure to validate any data being retrieved from memory or other storage locations. Use `llvm::isSafeToLoadUnconditionally` to check if data is safe to load.
## Testing Approaches
- **Unit Tests:** Write unit tests for individual components and functions. Use the LLVM testing framework (e.g., `lit`) to automate test execution.
- **Integration Tests:** Write integration tests to verify the interaction between different components. Create realistic test cases that exercise common use scenarios.
- **Regression Tests:** Add regression tests for any bug fixes to prevent regressions in future versions.
- **Fuzzing:** Use fuzzing techniques to identify corner cases and potential vulnerabilities. Integrate fuzzing into the CI/CD pipeline.
- **Code Coverage:** Measure code coverage to ensure that tests exercise all important code paths. Use `llvm-cov` to generate code coverage reports.
## Common Pitfalls and Gotchas
- **Incorrect Use of APIs:** Carefully read the documentation for LLVM APIs and ensure they are used correctly. Pay attention to preconditions and postconditions.
- **Memory Leaks:** Ensure that all allocated memory is properly deallocated. Use memory leak detection tools to identify memory leaks.
- **Dangling Pointers:** Avoid dangling pointers by ensuring that objects are not deleted while they are still being referenced.
- **Undefined Behavior:** Avoid undefined behavior, as it can lead to unpredictable results. Use sanitizers to detect undefined behavior.
- **Version Compatibility:** Be aware of version compatibility issues when using LLVM with other libraries or tools. Test your code with different versions of LLVM.
## Tooling and Environment
- **Clang:** Use Clang as the primary compiler for LLVM projects. Clang provides excellent support for C++ standards and LLVM extensions.
- **CMake:** Use CMake to manage the build process for LLVM projects. CMake is a cross-platform build system generator that is well-supported by LLVM.
- **LLVM Tools:** Utilize the LLVM tools (e.g., `llvm-as`, `llvm-dis`, `opt`, `lli`) for various tasks such as assembling and disassembling LLVM IR, optimizing code, and executing LLVM bitcode.
- **Git:** Use Git for version control. Follow the LLVM Git commit message conventions.
- **CI/CD:** Integrate CI/CD pipelines into LLVM development. Use test suites as part of your development cycle.
## Additional Notes
- When extending or modifying existing code, adhere to the style already in use.
- Document your code clearly and concisely. Provide comments explaining the purpose of functions, classes, and variables.
- Keep pull requests small and focused. This makes it easier for reviewers to understand and approve your changes.
- Be responsive to feedback from reviewers and address any issues promptly.
- Engage with the LLVM community to ask questions, share knowledge, and contribute to the project.
- Refer to existing documentation and examples in the LLVM codebase for guidance on how to implement new features and functionality.
By following these guidelines, you can write high-quality LLVM code that is efficient, maintainable, and robust. This ensures consistent code quality and facilitates collaboration within the LLVM community.
+306
View File
@@ -0,0 +1,306 @@
---
description: This rule provides guidelines and best practices for developing robust, maintainable, and performant data visualizations using Matplotlib in Python. It covers aspects from code organization to testing and security considerations.
globs: **/*.py
---
# Matplotlib Best Practices
This document outlines best practices for using Matplotlib, a powerful Python library for creating static, interactive, and animated visualizations. Adhering to these guidelines will help you write cleaner, more maintainable, and performant code for your data visualization projects.
Library Information:
- Name: matplotlib
- Tags: ai, ml, data-science, python, data-visualization
## 1. Code Organization and Structure
Proper code organization is essential for maintainability and collaboration. For visualization projects using Matplotlib, the organization becomes crucial due to the complexity that can arise from numerous plotting options and data manipulation.
### 1.1 Directory Structure
Adopt a structured directory layout to separate source code, data, and output. A typical project structure might look like this:
project_name/
├── src/
│ ├── __init__.py
│ ├── data_processing.py # Data loading, cleaning, and transformation functions
│ ├── plotting_functions.py # Reusable plotting functions using Matplotlib
│ ├── main.py # Main script to orchestrate the visualization
├── data/
│ ├── raw/ # Original, unmodified data
│ ├── processed/ # Data that has been cleaned and transformed
├── output/
│ ├── images/ # Saved plot images
│ ├── reports/ # Generated reports or summaries
├── notebooks/ # Jupyter notebooks for exploration
├── tests/ # Testing directory
│ ├── __init__.py
│ ├── test_data_processing.py
│ ├── test_plotting_functions.py
├── README.md
├── requirements.txt
├── .gitignore
### 1.2 File Naming Conventions
* Use descriptive and consistent file names.
* Python files: `snake_case.py` (e.g., `data_processing.py`, `plotting_functions.py`).
* Image files: `descriptive_name.png`, `descriptive_name.jpg`, or `descriptive_name.svg`.
* Data files: `descriptive_name.csv`, `descriptive_name.json`.
### 1.3 Module Organization
* Group related functions and classes into modules.
* Use meaningful module names that reflect their purpose (e.g., `data_processing`, `plotting_utils`).
* Import modules using explicit relative imports when working within the same package (e.g., `from . import data_processing`).
* Avoid circular dependencies between modules.
### 1.4 Component Architecture
* **Data Abstraction Layer:** Create modules dedicated to data loading, cleaning, and transformation. This isolates the visualization logic from the data source.
* **Plotting Abstraction Layer:** Develop reusable plotting functions that encapsulate common Matplotlib configurations. This promotes code reuse and consistency.
* **Configuration Management:** Store plot configurations (colors, styles, labels) in a separate configuration file (e.g., a JSON or YAML file). This allows for easy modification of plot aesthetics without changing the code.
* **Orchestration Layer:** A main script responsible for calling the data loading, processing and plotting functions and assembling the final visualization, like `main.py` in the example structure above.
### 1.5 Code Splitting Strategies
* **Functional Decomposition:** Break down complex plotting tasks into smaller, manageable functions.
* **Class-Based Organization:** Use classes to represent complex plot structures (e.g., a custom chart type) or to manage plot state (see section on State Management below).
* **Separate Data Handling:** Ensure functions which load and clean data are distinct from plotting functionalities.
* **Configuration Driven:** Define plot styles and settings in external configuration files (JSON, YAML) which are then read by plotting functions, allowing easy style modifications.
## 2. Common Patterns and Anti-patterns
Recognizing and applying appropriate design patterns can significantly improve the quality of your Matplotlib code. Similarly, awareness of anti-patterns can help you avoid common pitfalls.
### 2.1 Design Patterns
* **Object-Oriented API:** Prioritize using Matplotlib's object-oriented API (`fig, ax = plt.subplots()`) over the stateful `pyplot` interface. The object-oriented API provides greater flexibility and control, especially for complex plots.
* **Template Method:** Create a base class for common plot types with abstract methods for data loading and customization. Subclasses can then implement these methods to create specific plots.
* **Strategy Pattern:** Define different plotting strategies as separate classes. The main plotting function can then dynamically choose the appropriate strategy based on the data or user input.
* **Observer Pattern:** Useful in interactive plots where changes in one element (e.g., a slider) trigger updates in other elements of the plot. Matplotlib's event handling system can be leveraged for this pattern.
### 2.2 Recommended Approaches for Common Tasks
* **Creating Subplots:** Use `plt.subplots()` to create figures with multiple subplots. Specify the number of rows and columns, and unpack the returned figure and axes objects for individual manipulation.
* **Customizing Plots:** Use the `ax.set()` method to set plot titles, axis labels, legends, and other properties. For more fine-grained control, use methods like `ax.set_xlabel()`, `ax.set_ylabel()`, `ax.set_title()`, etc.
* **Adding Legends:** Use `ax.legend()` to add a legend to the plot. Customize the legend appearance and location as needed.
* **Saving Plots:** Use `fig.savefig()` to save plots to files. Specify the desired file format, resolution (dpi), and other options.
* **Working with Color Maps:** Use `cmap` argument in plotting functions to apply color maps to your data. Consider using perceptually uniform color maps to avoid visual distortions.
* **Handling Date Data:** Matplotlib provides excellent support for date data. Use `matplotlib.dates` module to format and manipulate dates on the axes. Use `dateutil.parser` for flexible date parsing.
* **Interactive plots:** Utilize Matplotlib's interactive capabilities with `plt.ion()` and `plt.ioff()` to update plots dynamically in a loop. Use widgets such as sliders and buttons for user interaction.
### 2.3 Anti-patterns and Code Smells
* **Excessive Use of `pyplot` Interface:** Relying heavily on the `pyplot` interface can lead to tightly coupled and less maintainable code. Embrace the object-oriented API for better structure and flexibility.
* **Hardcoding Plot Configurations:** Avoid hardcoding plot configurations (colors, styles, labels) directly in the code. Use configuration files or dictionaries to manage these settings.
* **Copy-Pasting Plotting Code:** Duplicating plotting code across multiple scripts leads to redundancy and makes it difficult to maintain consistency. Create reusable plotting functions instead.
* **Ignoring Performance Considerations:** Creating very complex plots with huge amount of data without considering optimization can result in slow rendering and high memory usage.
* **Not Handling Exceptions:** Failure to handle potential exceptions (e.g., file not found, invalid data) can lead to unexpected program termination.
* **Overplotting:** In scatter plots, overlapping data points can obscure the underlying distribution. Use techniques like transparency (`alpha`) or jitter to mitigate overplotting.
### 2.4 State Management
* **Encapsulate Plot State:** Use classes or functions to encapsulate the state of a plot. This makes it easier to manage complex plot configurations and ensures that plots are rendered consistently.
* **Avoid Global State:** Minimize the use of global variables to store plot state. This can lead to unexpected side effects and make it difficult to reason about the code.
* **Use Configuration Objects:** Create configuration objects to store plot settings. This allows you to easily modify the appearance of your plots without changing the code.
### 2.5 Error Handling
* **Use `try...except` Blocks:** Wrap potentially problematic code (e.g., file I/O, data processing) in `try...except` blocks to handle exceptions gracefully.
* **Log Errors:** Use the `logging` module to log errors and warnings. This helps you identify and diagnose problems in your code.
* **Provide Informative Error Messages:** When raising exceptions, provide informative error messages that help the user understand the cause of the problem.
* **Validate Inputs:** Before using data in your plots, validate the data to ensure it is in the expected format and range. Handle invalid data appropriately.
* **Custom Exceptions:** Create custom exception classes for specific error conditions in your plotting code. This improves code readability and makes it easier to handle errors.
## 3. Performance Considerations
Performance is a crucial aspect when dealing with large datasets or complex visualizations. Optimizing your code can significantly improve rendering speed and reduce memory consumption.
### 3.1 Optimization Techniques
* **Vectorization:** Use NumPy's vectorized operations to perform calculations on entire arrays instead of looping through individual elements. This can significantly improve performance.
* **Data Aggregation:** Aggregate data before plotting it to reduce the number of data points. This can be especially helpful for large datasets.
* **Use Efficient Plot Types:** Choose plot types that are appropriate for the data and the visualization goal. For example, use histograms to visualize distributions instead of scatter plots.
* **Limit Data Points:** Plot only the necessary data points. Avoid plotting unnecessary details that do not contribute to the visualization.
* **Caching:** Cache intermediate results to avoid redundant calculations. This can be helpful for computationally intensive tasks.
* **Simplify Complex Geometries:** Reduce the complexity of plot elements by simplifying geometries or using approximations.
### 3.2 Memory Management
* **Release Unused Memory:** Explicitly release memory occupied by large data structures when they are no longer needed. Use `del` statement to remove references to objects.
* **Use Generators:** Use generators to process large datasets in chunks instead of loading the entire dataset into memory. This can significantly reduce memory consumption.
* **Avoid Creating Copies:** Avoid creating unnecessary copies of data. Use in-place operations whenever possible.
* **Sparse Data Structures:** For sparse datasets, consider using sparse data structures to reduce memory consumption.
### 3.3 Rendering Optimization
* **Use Blitting:** Use blitting to redraw only the parts of the plot that have changed. This can significantly improve rendering speed for interactive plots.
* **Reduce Figure Size:** Reduce the size of the figure to improve rendering speed. Smaller figures require less memory and processing power.
* **Rasterize Vector Graphics:** For very complex plots, consider rasterizing vector graphics to reduce rendering time. Use the `rasterized=True` option in plotting functions.
* **Use Hardware Acceleration:** Ensure that Matplotlib is using hardware acceleration if available. This can significantly improve rendering speed.
### 3.4 Bundle Size Optimization
* This is generally less relevant for Matplotlib as it's a backend library, not typically bundled for frontend use.
* However, if integrating Matplotlib plots into web applications, pre-render the images on the server-side and serve static images to the client.
### 3.5 Lazy Loading
* Delay loading large datasets until they are needed. This can improve the startup time of your application.
* Load only the data that is visible in the plot. As the user zooms or pans, load additional data as needed.
* Use lazy loading techniques to create thumbnails or previews of plots without rendering the full plot.
## 4. Security Best Practices
While Matplotlib is primarily a visualization library, security considerations are important when dealing with untrusted data or integrating Matplotlib into web applications.
### 4.1 Common Vulnerabilities
* **Code Injection:** If user-provided data is used to construct plot commands, it could lead to code injection vulnerabilities. Always sanitize user input before using it in plot commands.
* **Denial of Service (DoS):** Creating extremely complex plots with large datasets can consume excessive resources and lead to DoS attacks. Implement resource limits and input validation to prevent this.
* **Cross-Site Scripting (XSS):** If integrating Matplotlib plots into web applications, be careful about how the plots are displayed. Sanitize any user-provided data that is displayed in the plot to prevent XSS attacks.
* **Data Leakage:** Be cautious about displaying sensitive data in plots. Ensure that the data is properly anonymized or obfuscated before plotting it.
### 4.2 Input Validation
* **Validate Data Types:** Ensure that the data used for plotting is of the expected type (e.g., numeric, date).
* **Validate Data Ranges:** Ensure that the data falls within the expected range. This can prevent unexpected behavior and potential errors.
* **Sanitize User Input:** If user input is used to generate plot commands, sanitize the input to prevent code injection vulnerabilities.
* **Limit Input Size:** Limit the size of the input data to prevent DoS attacks.
### 4.3 Authentication and Authorization
* This section is generally less relevant for Matplotlib, as it doesn't typically handle user authentication directly.
* If the visualizations are part of a larger application that has authentication, ensure that the correct users are authenticated before showing the plots.
* Implement authorization to control which users have access to specific plots or data.
### 4.4 Data Protection
* **Anonymize Sensitive Data:** Before plotting sensitive data, anonymize or obfuscate it to protect user privacy.
* **Use Secure Storage:** Store sensitive data securely, using encryption and access controls.
* **Comply with Regulations:** Ensure that your data handling practices comply with relevant regulations (e.g., GDPR, HIPAA).
### 4.5 Secure API Communication
* If integrating Matplotlib plots into web applications, use secure API communication protocols (e.g., HTTPS).
* Validate and sanitize data received from APIs before using it in plots.
* Implement rate limiting to prevent API abuse.
## 5. Testing Approaches
Thorough testing is essential to ensure the quality and reliability of your Matplotlib code. Unit tests, integration tests, and end-to-end tests all play a role in validating different aspects of your code.
### 5.1 Unit Testing
* **Test Individual Functions and Classes:** Write unit tests to verify the behavior of individual functions and classes in your plotting code.
* **Use Assertions:** Use assertions to check that the output of your functions is as expected.
* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that your code handles unexpected input gracefully.
* **Test Error Handling:** Test that your code handles exceptions correctly.
* **Use Mocking:** Use mocking to isolate units of code from their dependencies. This makes it easier to test units of code in isolation.
* **Parameterize Tests:** Write parameterized tests to test the same function with different inputs and expected outputs. This reduces code duplication and improves test coverage.
### 5.2 Integration Testing
* **Test Interactions Between Modules:** Write integration tests to verify that different modules in your plotting code work together correctly.
* **Test Data Flow:** Test the flow of data through your plotting pipeline to ensure that data is processed correctly.
* **Test Plot Rendering:** Test that plots are rendered correctly and that they contain the expected elements.
* **Test Data Integration:** Test the integration with data sources, ensuring that the data is loaded correctly.
### 5.3 End-to-End Testing
* **Test the Entire Plotting Workflow:** Write end-to-end tests to verify that the entire plotting workflow works correctly, from data loading to plot rendering.
* **Simulate User Interactions:** Simulate user interactions (e.g., zooming, panning, clicking) to test the behavior of interactive plots.
* **Verify Visual Output:** Use visual testing tools to compare the rendered plots against baseline images. This can help you detect visual regressions.
### 5.4 Test Organization
* **Create a Separate Test Directory:** Create a separate directory for your tests.
* **Use Descriptive Test Names:** Use descriptive test names that indicate what the test is verifying.
* **Organize Tests by Module:** Organize your tests by module to make it easier to find and run tests.
* **Use Test Runners:** Use test runners (e.g., `pytest`, `unittest`) to run your tests and generate reports.
### 5.5 Mocking and Stubbing
* **Mock External Dependencies:** Mock external dependencies (e.g., data sources, APIs) to isolate units of code from their dependencies.
* **Stub Function Calls:** Stub function calls to control the behavior of functions that are called by the code under test.
* **Use Mocking Libraries:** Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to simplify the process of creating mocks and stubs.
## 6. Common Pitfalls and Gotchas
Knowing common pitfalls and gotchas can save you a lot of time and frustration when working with Matplotlib.
### 6.1 Frequent Mistakes
* **Incorrect Axis Limits:** Forgetting to set the correct axis limits can result in plots that are difficult to interpret.
* **Missing Labels and Titles:** Forgetting to add labels and titles to plots makes them less informative and harder to understand.
* **Overlapping Labels:** Overlapping labels can make plots difficult to read. Use techniques like rotation or alignment to avoid overlapping labels.
* **Incorrect Color Maps:** Using inappropriate color maps can distort the data and make it difficult to interpret the plots.
* **Not Handling Missing Data:** Not handling missing data can result in unexpected errors or incorrect plots. Use appropriate techniques to handle missing data (e.g., imputation, filtering).
* **Ignoring Aspect Ratio:** Ignoring the aspect ratio of the plot can result in distorted visualizations. Use `ax.set_aspect('equal')` to ensure that the aspect ratio is correct.
### 6.2 Edge Cases
* **Empty Datasets:** Handle the case where the dataset is empty gracefully.
* **Non-Numeric Data:** Handle the case where the data contains non-numeric values.
* **Infinite Values:** Handle the case where the data contains infinite values.
* **NaN Values:** Handle the case where the data contains NaN (Not a Number) values.
* **Large Datasets:** Handle the case where the dataset is very large. Use techniques like data aggregation and lazy loading to improve performance.
### 6.3 Version-Specific Issues
* **API Changes:** Be aware of API changes between different versions of Matplotlib. Consult the documentation for the specific version you are using.
* **Compatibility Issues:** Be aware of compatibility issues between Matplotlib and other libraries (e.g., NumPy, Pandas).
* **Bug Fixes:** Be aware of bug fixes in newer versions of Matplotlib. Upgrading to the latest version may resolve known issues.
### 6.4 Compatibility Concerns
* **NumPy Version:** Ensure that your NumPy version is compatible with your Matplotlib version.
* **Pandas Version:** Ensure that your Pandas version is compatible with your Matplotlib version.
* **Operating System:** Be aware of potential compatibility issues between Matplotlib and different operating systems (e.g., Windows, macOS, Linux).
* **Backend Rendering Engine:** Be aware of potential compatibility issues between Matplotlib and different backend rendering engines (e.g., Agg, TkAgg, WebAgg).
### 6.5 Debugging Strategies
* **Use Print Statements:** Use print statements to inspect the values of variables and data structures.
* **Use Debuggers:** Use debuggers (e.g., `pdb`, `ipdb`) to step through your code and examine the state of the program.
* **Use Logging:** Use logging to record events and errors in your code. This can help you identify and diagnose problems.
* **Simplify the Plot:** Simplify the plot to isolate the source of the problem. Remove unnecessary elements or reduce the amount of data being plotted.
* **Check the Documentation:** Consult the Matplotlib documentation for information about specific functions and methods.
* **Search Online:** Search online for solutions to common problems. Stack Overflow and other online forums can be valuable resources.
* **Isolate the issue**: Comment out portions of the plotting routine to isolate which sections are causing unexpected behavior.
## 7. Tooling and Environment
Using the right tools and environment can significantly improve your productivity and the quality of your Matplotlib code.
### 7.1 Recommended Development Tools
* **IDE:** Use an Integrated Development Environment (IDE) such as VS Code, PyCharm, or Spyder. These tools provide features such as code completion, debugging, and testing.
* **Jupyter Notebooks:** Use Jupyter Notebooks for interactive exploration and development.
* **Virtual Environments:** Use virtual environments to isolate project dependencies.
* **Version Control:** Use version control systems (e.g., Git) to track changes to your code.
### 7.2 Build Configuration
* **Use `requirements.txt`:** Create a `requirements.txt` file to specify project dependencies. Use `pip freeze > requirements.txt` to generate the file.
* **Use `setup.py`:** Create a `setup.py` file to package your plotting code into a reusable library. This file defines the metadata about the library (name, version, author, etc.) and the dependencies required to install it.
* **Use `pyproject.toml`:** For modern projects, consider using `pyproject.toml` to manage build dependencies and configurations. It offers a more standardized and flexible approach compared to `setup.py`.
### 7.3 Linting and Formatting
* **Use Linters:** Use linters (e.g., `flake8`, `pylint`) to identify potential errors and style violations in your code.
* **Use Formatters:** Use formatters (e.g., `black`, `autopep8`) to automatically format your code according to PEP 8 style guidelines.
* **Configure IDE:** Configure your IDE to automatically run linters and formatters when you save your code.
### 7.4 Deployment Best Practices
* **Containerization:** Use containerization technologies (e.g., Docker) to create portable and reproducible deployment environments. This ensures that your plotting code runs consistently across different platforms.
* **Cloud Platforms:** Deploy your plotting code to cloud platforms (e.g., AWS, Azure, Google Cloud) for scalability and reliability.
* **Serverless Functions:** Consider using serverless functions to deploy individual plotting tasks as independent units. This can be a cost-effective way to run plotting code on demand.
### 7.5 CI/CD Integration
* **Use CI/CD Pipelines:** Set up Continuous Integration/Continuous Deployment (CI/CD) pipelines to automate the build, test, and deployment process. This helps ensure that your code is always in a releasable state.
* **Run Tests Automatically:** Configure your CI/CD pipeline to automatically run tests whenever you commit code. This helps you catch errors early.
* **Deploy Automatically:** Configure your CI/CD pipeline to automatically deploy your code to production environments after it has passed all tests.
+177
View File
@@ -0,0 +1,177 @@
---
description: Comprehensive guidelines for effective Maven project management, covering code organization, dependency management, performance optimization, and security best practices. This rule provides actionable advice to avoid common pitfalls and promote maintainable, scalable Maven projects.
globs: **/pom.xml
---
---
- **Introduction**
This guide provides comprehensive best practices for effectively using Maven in Java development, focusing on code organization, dependency management, performance, security, testing, and tooling. Adhering to these guidelines will result in more maintainable, scalable, and robust Maven projects.
- **Code Organization and Structure**
- **Standard Directory Structure:**
- Follow the standard Maven directory structure for consistency and ease of understanding:
project-root/
├── src/
│ ├── main/
│ │ ├── java/ # Source code
│ │ ├── resources/ # Resources (e.g., properties files)
│ ├── test/
│ │ ├── java/ # Test code
│ │ ├── resources/ # Test resources
├── pom.xml # Maven project definition
- **File Naming Conventions:**
- Java source files: `YourClass.java`
- Resource files: `application.properties`, `log4j2.xml`
- POM files: `pom.xml`
- **Module Organization (Multi-Module Projects):**
- For larger projects, consider using a multi-module structure:
parent-project/
├── pom.xml # Parent POM (defines dependencies, plugins, versions)
├── module1/
│ └── pom.xml # Module-specific POM
├── module2/
│ └── pom.xml
└── ...
- Parent POM handles shared configurations.
- Each module has its specific functionality and dependencies.
- **Component Architecture:**
- Organize code into logical components (e.g., data access, business logic, UI).
- Use interfaces to define contracts between components.
- Employ dependency injection to manage component dependencies.
- **Code Splitting Strategies:**
- Split large classes into smaller, more manageable units based on functionality.
- Create utility classes for reusable code.
- Break down complex processes into separate methods.
- **Common Patterns and Anti-patterns**
- **Design Patterns:**
- **Factory Pattern:** Use factories to create instances of objects, especially when the exact type of object needed is not known at compile time.
- **Singleton Pattern:** Ensure only one instance of a class exists (use with caution).
- **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable.
- **Recommended Approaches:**
- **Dependency Injection:** Use frameworks like Spring to manage dependencies and improve testability.
- **Configuration Management:** Externalize configuration using properties files or environment variables.
- **Logging:** Use a logging framework like Log4j 2 or SLF4J for consistent logging practices.
- **Anti-Patterns:**
- **God Classes:** Avoid large, monolithic classes that handle too many responsibilities.
- **Copy-Paste Programming:** Extract common code into reusable methods or classes.
- **Ignoring Exceptions:** Always handle exceptions properly; don't just catch and ignore them.
- **Hardcoding Values:** Externalize configuration values to avoid hardcoding.
- **State Management:**
- For web applications, use session management carefully.
- Avoid storing sensitive data in sessions.
- Use appropriate scoping for managed beans (e.g., request, session, application).
- **Error Handling:**
- Use try-catch blocks to handle exceptions gracefully.
- Log exceptions with sufficient context.
- Provide user-friendly error messages.
- Use custom exception classes to represent specific error conditions.
- **Performance Considerations**
- **Optimization Techniques:**
- **Profiling:** Use profiling tools (e.g., VisualVM, YourKit) to identify performance bottlenecks.
- **Caching:** Implement caching (e.g., using Ehcache or Redis) to reduce database load and improve response times.
- **Connection Pooling:** Use connection pooling to manage database connections efficiently.
- **Efficient Data Structures:** Choose appropriate data structures for your specific needs (e.g., HashMap, ArrayList).
- **Optimize Database Queries:** Use indexes, avoid full table scans, and optimize SQL queries.
- **Memory Management:**
- **Garbage Collection:** Understand how garbage collection works and tune JVM settings if necessary.
- **Object Pooling:** Use object pooling for frequently created and destroyed objects.
- **Avoid Memory Leaks:** Ensure resources are properly released to prevent memory leaks.
- **Bundle Size Optimization:**
- Use ProGuard or other code shrinking tools to reduce the size of JAR files.
- Remove unused dependencies.
- Optimize resource files (e.g., compress images).
- **Lazy Loading:**
- Use lazy loading for resources or data that are not immediately needed.
- Implement pagination for large datasets.
- **Security Best Practices**
- **Common Vulnerabilities:**
- **Dependency Vulnerabilities:** Regularly scan dependencies for known vulnerabilities (using Snyk, OWASP Dependency-Check).
- **SQL Injection:** Use parameterized queries or ORM frameworks to prevent SQL injection.
- **Cross-Site Scripting (XSS):** Encode user input properly to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms.
- **Authentication and Authorization Flaws:** Use strong authentication and authorization mechanisms.
- **Input Validation:**
- Validate all user input to prevent malicious data from entering the system.
- Use whitelisting to define allowed values.
- Sanitize input to remove potentially harmful characters.
- **Authentication and Authorization:**
- Use a secure authentication mechanism (e.g., OAuth 2.0, OpenID Connect).
- Implement role-based access control (RBAC) to restrict access to resources.
- Use strong password policies.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to secure communication.
- Store passwords securely using hashing algorithms (e.g., bcrypt).
- **Secure API Communication:**
- Use API keys or OAuth 2.0 to authenticate API requests.
- Validate API requests to prevent malicious input.
- Limit the rate of API requests to prevent abuse.
- **Testing Approaches**
- **Unit Testing:**
- Use JUnit or TestNG for unit testing.
- Write tests for all critical components and methods.
- Use mocking frameworks (e.g., Mockito, EasyMock) to isolate units under test.
- Aim for high code coverage.
- **Integration Testing:**
- Test the interaction between different components or services.
- Use embedded databases or mock services for testing.
- Test data access layers, API endpoints, and message queues.
- **End-to-End Testing:**
- Simulate real user scenarios to test the entire application flow.
- Use testing frameworks like Selenium or Cypress.
- Test the user interface, business logic, and data access layers.
- **Test Organization:**
- Place test code in the `src/test/java` directory.
- Organize tests into packages that mirror the source code structure.
- Use descriptive test names.
- **Mocking and Stubbing:**
- Use mocking frameworks to create mock objects for dependencies.
- Use stubs to provide predefined responses for method calls.
- Avoid over-mocking; test the actual behavior when possible.
- **Common Pitfalls and Gotchas**
- **Dependency Conflicts:** Use `mvn dependency:tree` to identify and resolve dependency conflicts. Use `<dependencyManagement>` to control versions.
- **Version Mismatches:** Ensure all modules in a multi-module project use compatible versions of dependencies.
- **Transitive Dependencies:** Be aware of transitive dependencies and their potential impact on your project.
- **Incorrect Scopes:** Use the correct dependency scopes (e.g., compile, runtime, test, provided) to avoid including unnecessary dependencies in the final artifact.
- **Snapshot Dependencies:** Avoid using snapshot dependencies in production environments.
- **Tooling and Environment**
- **Recommended Development Tools:**
- **IDE:** IntelliJ IDEA, Eclipse, NetBeans
- **Build Tool:** Apache Maven
- **Version Control:** Git
- **Dependency Scanning:** Snyk, OWASP Dependency-Check
- **Static Analysis:** SonarQube, FindBugs
- **Build Configuration:**
- Use properties to define reusable values (e.g., versions, file paths).
- Configure plugins properly and use appropriate versions.
- Use profiles to manage different build configurations (e.g., development, production).
- **Linting and Formatting:**
- Use code formatters (e.g., IntelliJ IDEA code style, Eclipse code formatter) to ensure consistent code formatting.
- Use static analysis tools to identify potential issues.
- **Deployment:**
- Use Maven plugins (e.g., `maven-deploy-plugin`) to deploy artifacts to a repository.
- Use configuration management tools (e.g., Ansible, Chef, Puppet) to automate deployment.
- Follow best practices for deploying Java applications (e.g., using application servers, containers).
- **CI/CD Integration:**
- Integrate Maven builds with CI/CD pipelines (e.g., Jenkins, GitLab CI, GitHub Actions).
- Automate testing, code analysis, and deployment.
- Use build automation tools to manage the build process.
- **Conclusion**
By adhering to these best practices, you can build robust, maintainable, and secure Maven projects. Regular code reviews, continuous integration, and proactive dependency management will further enhance the quality and reliability of your software.
+241
View File
@@ -0,0 +1,241 @@
---
description: This rule provides best practices for developing with Microsoft Teams, covering code organization, performance, security, testing, and common pitfalls. Adhering to these guidelines will ensure robust, maintainable, and secure Teams applications.
globs: **/*.{js,jsx,ts,tsx}
---
- # Code Organization and Structure
- Effective code organization is critical for maintainability and scalability in Microsoft Teams application development.
- ## Directory Structure Best Practices
- **src/**: Contains all source code.
- **components/**: Reusable UI components.
- **modules/**: Independent, reusable modules with specific functionalities (e.g., authentication, data fetching).
- **pages/** or **views/**: Top-level components representing different application views/pages.
- **services/**: Code interacting with Microsoft Teams APIs or other external services.
- **utils/** or **helpers/**: Utility functions, constants, and helper classes.
- **styles/**: CSS, SCSS, or other styling-related files.
- **types/**: TypeScript type definitions (if using TypeScript).
- **public/**: Static assets (images, fonts, etc.).
- **tests/**: Unit, integration, and end-to-end tests.
- **.cursor/**: Stores Cursor-specific project rules.
- ## File Naming Conventions
- **Components:** PascalCase (e.g., `MyTeamsComponent.tsx`).
- **Modules:** camelCase (e.g., `teamsAuthentication.ts`).
- **Styles:** kebab-case (e.g., `my-teams-component.scss`).
- **Tests:** `<filename>.test.ts` or `<filename>.spec.ts` (e.g., `MyTeamsComponent.test.tsx`).
- **Interfaces/Types:** Capitalized with a leading `I` if an interface (e.g., `IUser.ts`).
- ## Module Organization
- Favor small, focused modules with clear responsibilities.
- Use dependency injection to manage dependencies between modules.
- Consider using an inversion of control (IoC) container for more complex applications.
- ## Component Architecture
- **Presentational Components:** Responsible for rendering UI; receive data and callbacks as props.
- **Container Components:** Fetch data, manage state, and pass data to presentational components.
- Consider using a state management library like Redux, Zustand, or Jotai for complex applications.
- ## Code Splitting
- Use dynamic imports to lazy-load modules and components.
- Implement route-based code splitting to reduce the initial bundle size.
- Analyze bundle size using tools like Webpack Bundle Analyzer to identify large dependencies.
- # Common Patterns and Anti-patterns
- Employing established design patterns and avoiding anti-patterns are crucial for writing clean, maintainable code in Microsoft Teams development.
- ## Design Patterns
- **Observer Pattern:** Useful for subscribing components to changes in Teams state (e.g., user presence, channel messages).
- **Factory Pattern:** Abstract component creation to simplify management of different Teams context variables or user settings.
- **Strategy Pattern:** To handle different API authentication approaches and use appropriate logic depending on where code is run (webpage or Teams client)
- **Facade Pattern:** Simplify complex Teams API interactions by providing a higher-level interface.
- ## Recommended Approaches
- Use the Microsoft Teams Client SDK for interacting with the Teams client.
- Prefer asynchronous operations to avoid blocking the UI thread.
- Implement proper error handling for API calls and user input.
- Adopt responsive design principles to ensure your application works well on different screen sizes.
- ## Anti-patterns and Code Smells
- **Deeply Nested Components:** Leads to performance issues and difficulty in understanding the component hierarchy.
- **God Objects:** Modules or components with too many responsibilities.
- **Copy-Pasted Code:** Indicates a lack of proper abstraction and code reuse.
- **Ignoring Errors:** Can lead to unexpected behavior and difficult-to-debug issues.
- **Over-reliance on `any` Type (TypeScript):** Reduces the benefits of TypeScript's type safety.
- ## State Management
- For simple components, use React's built-in `useState` hook.
- For complex applications, consider using a state management library:
- **Redux:** Predictable state container with a centralized store and unidirectional data flow.
- **Zustand:** Small, fast, and scalable bearbones state-management solution.
- **Jotai:** Primitive and flexible state management with an atomic model.
- Avoid mutating state directly; use immutability techniques.
- ## Error Handling
- Use `try...catch` blocks to handle exceptions gracefully.
- Implement global error handling to catch unhandled exceptions.
- Log errors to a central location for monitoring and debugging.
- Provide informative error messages to the user.
- # Performance Considerations
- Optimizing performance is crucial for providing a smooth user experience in Microsoft Teams applications.
- ## Optimization Techniques
- **Memoization:** Cache the results of expensive function calls to avoid redundant computations.
- **Debouncing and Throttling:** Limit the rate at which functions are executed in response to user input.
- **Virtualization:** Render only the visible portion of large lists or tables.
- **Code Splitting:** As mentioned earlier, divide code into smaller chunks to reduce initial load time.
- **Efficient Data Structures:** Use appropriate data structures for optimal performance (e.g., Maps instead of Objects for frequent lookups).
- ## Memory Management
- Avoid memory leaks by properly cleaning up resources (e.g., event listeners, timers).
- Use weak references when necessary to avoid preventing garbage collection.
- Monitor memory usage using browser developer tools to identify potential issues.
- ## Rendering Optimization
- Use React.memo or similar techniques to prevent unnecessary re-renders.
- Optimize images and other assets to reduce file size.
- Minimize DOM manipulations.
- ## Bundle Size Optimization
- Use tree shaking to remove unused code from dependencies.
- Minify and compress code using tools like Terser and Gzip.
- Analyze bundle size to identify large dependencies and consider alternatives.
- ## Lazy Loading
- Lazy-load images and other assets that are not immediately visible.
- Use Intersection Observer API to detect when elements are visible.
- Lazy load modules by incorporating `React.lazy` and `Suspense`.
- # Security Best Practices
- Security is paramount when developing Microsoft Teams applications to protect user data and prevent vulnerabilities.
- ## Common Vulnerabilities
- **Cross-Site Scripting (XSS):** Injecting malicious scripts into the application.
- **Cross-Site Request Forgery (CSRF):** Attacking users into performing actions without their consent.
- **Authentication and Authorization Flaws:** Improperly securing user authentication and authorization mechanisms.
- **Data Injection:** SQL injection, LDAP injection, etc.
- ## Prevention Strategies
- **Input Validation:** Sanitize and validate all user input to prevent injection attacks.
- **Output Encoding:** Escape output to prevent XSS attacks.
- **Content Security Policy (CSP):** Configure CSP to restrict the sources of content that the browser is allowed to load.
- **Regular Security Audits:** Conduct regular security audits to identify and address vulnerabilities.
- ## Authentication and Authorization
- Use OAuth 2.0 for secure authentication and authorization.
- Implement proper role-based access control (RBAC) to restrict access to sensitive data and functionality.
- Store credentials securely using appropriate encryption and hashing techniques.
- ## Data Protection
- Encrypt sensitive data at rest and in transit.
- Implement data loss prevention (DLP) policies to prevent sensitive information from being shared inappropriately.
- Follow privacy best practices to protect user data.
- ## Secure API Communication
- Use HTTPS for all API communication.
- Validate server-side certificate.
- Implement proper authentication and authorization for API endpoints.
- Use rate limiting to prevent denial-of-service attacks.
- # Testing Approaches
- Comprehensive testing is essential for ensuring the quality and reliability of Microsoft Teams applications.
- ## Unit Testing
- Test individual components and modules in isolation.
- Use mocking and stubbing to isolate dependencies.
- Aim for high code coverage to ensure that all parts of the code are tested.
- ## Integration Testing
- Test the interaction between different components and modules.
- Verify that data flows correctly between different parts of the application.
- Test integrations with Microsoft Teams APIs and other external services.
- ## End-to-End Testing
- Test the entire application flow from the user's perspective.
- Simulate real-world user scenarios.
- Use tools like Cypress or Playwright to automate end-to-end tests.
- ## Test Organization
- Organize tests into logical groups based on functionality or component.
- Use clear and descriptive test names.
- Keep tests small and focused.
- ## Mocking and Stubbing
- Use mocking libraries like Jest or Sinon.js to create mocks and stubs.
- Mock external dependencies to isolate the code under test.
- Use stubs to provide controlled responses from dependencies.
- # Common Pitfalls and Gotchas
- Being aware of common pitfalls and gotchas can save developers time and effort when developing Microsoft Teams applications.
- ## Frequent Mistakes
- Improperly handling asynchronous operations.
- Not validating user input.
- Exposing sensitive data in the client-side code.
- Failing to handle errors gracefully.
- Neglecting performance optimization.
- Not localizing application for different locales
- ## Edge Cases
- Handling different Teams client versions and platforms.
- Dealing with network connectivity issues.
- Handling unexpected API responses.
- Managing different user roles and permissions.
- Handling large data sets.
- ## Version-Specific Issues
- Be aware of breaking changes in Microsoft Teams API updates.
- Test your application with different Teams client versions.
- Use feature detection to adapt to different API capabilities.
- ## Compatibility Concerns
- Ensure that your application is compatible with different browsers and devices.
- Test your application with different operating systems.
- Use polyfills to support older browsers.
- ## Debugging Strategies
- Use browser developer tools to debug client-side code.
- Use logging to track application flow and identify errors.
- Use remote debugging to debug server-side code.
- Use a debugger to step through code and inspect variables.
- # Tooling and Environment
- Choosing the right tools and environment can significantly improve the development experience for Microsoft Teams applications.
- ## Recommended Development Tools
- **Visual Studio Code:** Code editor with excellent TypeScript support and debugging capabilities.
- **Microsoft Teams Toolkit:** Provides templates and tools for creating and deploying Teams applications.
- **Node.js:** JavaScript runtime environment for server-side development.
- **NPM or Yarn:** Package managers for managing dependencies.
- **Webpack or Parcel:** Module bundlers for bundling code and assets.
- **React Developer Tools:** Browser extension for debugging React components.
- ## Build Configuration
- Use a build system like Webpack or Parcel to automate the build process.
- Configure the build system to optimize code for production (e.g., minification, compression).
- Use environment variables to manage different configuration settings for different environments.
- ## Linting and Formatting
- Use ESLint or TSLint to enforce coding style and prevent errors.
- Use Prettier to automatically format code.
- Configure the code editor to automatically format code on save.
- ## Deployment
- Deploy your application to Azure or another cloud provider.
- Use Microsoft Teams App Studio to create and manage your Teams app package.
- Submit your app to the Microsoft Teams app store for wider distribution.
- ## CI/CD Integration
- Use a CI/CD system like Azure DevOps, GitHub Actions, or Jenkins to automate the build, test, and deployment process.
- Configure the CI/CD system to run tests and linters automatically.
- Use automated deployments to deploy changes to production quickly and reliably.
- # Additional Best Practices
- **Accessibility:** Ensure your application is accessible to users with disabilities.
- **Localization:** Localize your application for different languages and regions.
- **Documentation:** Write clear and concise documentation for your code.
- **Collaboration:** Use a version control system like Git to collaborate with other developers.
- **Stay Up-to-Date:** Keep up with the latest Microsoft Teams API updates and best practices.
By adhering to these best practices, developers can create robust, maintainable, secure, and high-performing Microsoft Teams applications that provide a great user experience.
+282
View File
@@ -0,0 +1,282 @@
---
description: This rule provides comprehensive best practices for the MLX library, covering code organization, performance, security, testing, and common pitfalls. It aims to promote consistent, efficient, and maintainable code when working with MLX on Apple platforms.
globs: **/*.swift
---
# MLX Library Best Practices
This document outlines the recommended best practices and coding standards for developing applications using the MLX library on Apple platforms, primarily using Swift. Following these guidelines will help ensure code quality, maintainability, performance, and security.
## 1. Code Organization and Structure
A well-structured project is crucial for scalability and maintainability. Here's how to organize your MLX projects effectively:
### 1.1. Directory Structure
Adopt a modular directory structure that separates concerns and promotes reusability. A typical project structure might look like this:
MyMLXProject/
├── Data/
│ ├── Datasets.swift # Classes/structs for handling datasets
│ ├── Preprocessing.swift # Data preprocessing utilities
├── Models/
│ ├── ModelDefinitions.swift # MLX Model Definitions (structs/classes)
│ ├── Layers.swift # Custom layers for your models
│ ├── LossFunctions.swift # Loss functions for training
├── Training/
│ ├── Trainer.swift # Training loop and optimization logic
│ ├── Metrics.swift # Evaluation metrics
├── Inference/
│ ├── InferenceEngine.swift # Model inference and prediction code
├── Utilities/
│ ├── Helpers.swift # Helper functions and extensions
│ ├── Configuration.swift # Project configuration settings
├── UI/
│ ├── ViewControllers.swift # UI-related code (if applicable)
│ ├── Views.swift # Custom UI views
├── Tests/
│ ├── UnitTests.swift # Unit tests for individual components
│ ├── IntegrationTests.swift # Integration tests for the application
├── MyMLXProject.xcodeproj # Xcode project file
├── Podfile # CocoaPods dependencies (if using)
├── Package.swift # Swift Package Manager manifest (if using)
### 1.2. File Naming Conventions
- Use descriptive and consistent names for your files.
- Follow the `PascalCase` convention for Swift files (e.g., `ModelDefinitions.swift`).
- Name files according to the primary type or functionality they contain.
- Use suffixes like `View`, `Controller`, `Model`, `Helper`, `Manager` to clearly indicate the role of the file.
### 1.3. Module Organization
- Organize your code into logical modules or Swift packages using Swift Package Manager (SPM).
- Each module should encapsulate a specific set of functionalities, such as data processing, model definitions, or training logic.
- Modules should have well-defined interfaces and minimize dependencies between them to promote reusability and testability.
### 1.4. Component Architecture
Consider using established architectural patterns like MVVM (Model-View-ViewModel) or VIPER (View-Interactor-Presenter-Entity-Router), especially for applications with a UI. However, even in non-UI projects:
- **Data Layer**: Responsible for data loading, preprocessing, and storage. This could interface with Core Data, files, or network resources.
- **Model Layer**: Holds the MLX model definitions, custom layers, and any associated logic. Focus on making these types lightweight and easily serializable (if needed).
- **Service Layer**: Manages model training, inference, and evaluation. This layer orchestrates the interaction between the data and model layers.
- **Utility Layer**: Contains helper functions, extensions, and common utilities used throughout the project.
### 1.5. Code Splitting Strategies
- Break down large files into smaller, more manageable units based on functionality or responsibility.
- Use extensions to logically group related methods within a class or struct (e.g., `// MARK: - Data Loading`).
- Employ protocols to define clear interfaces between components and enable loose coupling.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Factory Pattern**: Use factory methods or classes to create instances of MLX models, layers, or optimizers, especially when dealing with complex configurations or dependencies.
- **Strategy Pattern**: Implement different optimization algorithms or loss functions as strategies that can be swapped in and out during training.
- **Observer Pattern**: Employ the observer pattern to notify components about training progress or model updates.
### 2.2. Recommended Approaches for Common Tasks
- **Data Loading**: Use `MLXData` or custom data loaders to efficiently load and preprocess your training data. Consider using memory mapping for large datasets.
- **Model Definition**: Define your models using `MLX` layers and sequential models. Leverage functional programming techniques for building complex model architectures.
- **Training Loop**: Implement a well-structured training loop that iterates over the data, performs forward and backward passes, updates model parameters, and evaluates performance.
- **Inference**: Use `MLXModel.predict` or custom inference engines to make predictions on new data.
- **Evaluation**: Implement robust evaluation metrics and visualizations to monitor model performance and identify potential issues.
### 2.3. Anti-Patterns and Code Smells
- **Massive View Controllers**: Avoid placing all MLX-related logic directly within view controllers. Delegate tasks to service layers or dedicated MLX components.
- **Global State**: Minimize the use of global variables or singletons to manage MLX model instances or training data. Instead, pass these objects as dependencies.
- **Hardcoded Values**: Avoid hardcoding model hyperparameters or data paths. Use configuration files or dependency injection to manage these values.
- **Ignoring Errors**: Handle potential errors during data loading, model training, or inference gracefully, rather than ignoring or suppressing them.
- **Synchronous Operations on the Main Thread**: Offload time-consuming operations like model training or inference to background threads to prevent blocking the main thread and freezing the UI.
### 2.4. State Management
- For simple applications, pass state directly between components or use a simple state container object.
- For more complex applications, consider using state management frameworks like Combine or SwiftUI's `@StateObject` and `@EnvironmentObject`. Or a dedicated state management framework for ML models.
- Store model parameters and training progress in a dedicated state object and update it during the training loop.
- Make sure MLX-related state is properly handled and persisted across application lifecycle events (e.g., app termination, backgrounding).
### 2.5. Error Handling
- Use Swift's `Error` protocol and `do-catch` blocks to handle potential errors during data loading, model training, or inference.
- Create custom error types to represent specific MLX-related errors.
- Log error messages with sufficient context to aid debugging.
- Provide user-friendly error messages or feedback to the user when appropriate.
## 3. Performance Considerations
ML workloads are inherently performance-sensitive. Optimize your MLX code for speed and efficiency:
### 3.1. Optimization Techniques
- **Vectorization**: Leverage `MLX`'s vectorized operations to perform computations on entire arrays or matrices rather than iterating over individual elements.
- **Data Type Optimization**: Use the appropriate data types for your model parameters and training data (e.g., `Float16` or `Float32` instead of `Float64`).
- **Memory Optimization**: Minimize memory allocations and deallocations during the training loop. Re-use buffers and avoid unnecessary data copies.
- **Graph Compilation**: If MLX supports it, compile your model graph to optimize its execution. This can significantly improve inference speed.
- **GPU Acceleration**: Ensure your MLX code is running on the GPU for faster computations (if available). Verify GPU usage using system monitoring tools.
### 3.2. Memory Management
- Be mindful of memory usage, especially when dealing with large datasets or complex models.
- Use memory profiling tools to identify memory leaks or excessive memory allocations.
- Release unused memory explicitly when possible.
- Consider using techniques like data streaming or batch processing to reduce memory footprint.
### 3.3. Rendering Optimization (If Applicable)
- MLX is focused on numerical computation, but if you are visualizing outputs, use techniques like Metal shaders to optimize rendering if you are drawing visualizations of ML data.
### 3.4. Bundle Size Optimization
- If using dependencies, consider the impact of external dependencies on the application bundle size.
- Use code stripping and dead code elimination to remove unused code and resources.
- Compress images, models, and other assets to reduce their size.
### 3.5. Lazy Loading
- Lazy load large models or datasets only when they are needed to reduce startup time and memory footprint.
- Use placeholder data or loading indicators while lazy-loading data in the background.
## 4. Security Best Practices
Even though MLX focuses on numerical computation, security is still important:
### 4.1. Common Vulnerabilities and Prevention
- **Model Poisoning**: Prevent malicious actors from injecting adversarial data into your training set to degrade model performance or inject biases.
- **Mitigation**: Implement data validation and sanitization techniques. Monitor data sources and investigate anomalies.
- **Model Extraction**: Protect your trained models from being stolen or reverse-engineered by unauthorized parties.
- **Mitigation**: Use model encryption or obfuscation techniques. Implement access controls and authentication mechanisms.
- **Adversarial Attacks**: Defend against adversarial attacks that can trick your models into making incorrect predictions.
- **Mitigation**: Implement adversarial training techniques or input validation mechanisms.
### 4.2. Input Validation
- Validate all external inputs, including user data, API responses, and configuration files, to prevent malicious data from compromising your application or models.
- Sanitize input data to remove or escape potentially harmful characters or code.
- Use type checking and data validation libraries to ensure data conforms to expected formats and ranges.
### 4.3. Authentication and Authorization
- Implement robust authentication and authorization mechanisms to protect access to your models, training data, and API endpoints.
- Use secure password storage techniques like hashing and salting.
- Implement role-based access control (RBAC) to restrict access to sensitive resources based on user roles.
### 4.4. Data Protection
- Encrypt sensitive data at rest and in transit to prevent unauthorized access.
- Use secure storage options like the iOS Keychain to store sensitive information like API keys or passwords.
- Implement data masking or anonymization techniques to protect user privacy.
### 4.5. Secure API Communication
- Use HTTPS to encrypt communication between your application and external APIs or services.
- Implement certificate pinning to prevent man-in-the-middle attacks.
- Validate API responses to ensure data integrity and prevent data injection attacks.
## 5. Testing Approaches
Thorough testing is essential for ensuring the reliability and correctness of your MLX code:
### 5.1. Unit Testing
- Write unit tests to verify the functionality of individual components, such as model layers, loss functions, or data preprocessing utilities.
- Use mocking and stubbing techniques to isolate components and simulate dependencies.
- Test edge cases and boundary conditions to ensure robust behavior.
### 5.2. Integration Testing
- Write integration tests to verify the interaction between different components or modules.
- Test the data flow through the application pipeline, from data loading to model inference.
- Verify that the application integrates correctly with external APIs or services.
### 5.3. End-to-End Testing
- Write end-to-end tests to simulate user interactions and verify the overall application functionality.
- Test the user interface (if applicable) to ensure it behaves as expected.
- Verify that the application meets the specified performance and security requirements.
### 5.4. Test Organization
- Organize your tests into separate test suites or folders based on the component or functionality being tested.
- Use descriptive names for your test methods to clearly indicate their purpose.
- Follow a consistent naming convention for your test files (e.g., `MyComponentTests.swift`).
### 5.5. Mocking and Stubbing
- Use mocking frameworks to create mock objects that simulate the behavior of dependencies during unit testing.
- Use stubbing techniques to provide pre-defined responses or values for dependencies during testing.
- Avoid over-mocking or stubbing, as it can make tests brittle and less reliable.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Incorrect Data Shapes**: Ensure that your input data and model parameters have the correct shapes and dimensions. Incorrect shapes can lead to errors or unexpected behavior.
- **Gradient Vanishing/Exploding**: Be aware of gradient vanishing or exploding problems during training. Use techniques like gradient clipping or batch normalization to mitigate these issues.
- **Overfitting**: Monitor your model's performance on a validation set to prevent overfitting. Use regularization techniques or dropout to reduce overfitting.
- **Not Freezing the graph before production**: After training and validation, ensure that MLX is not attempting to recalculate the graph each time inference is called. Freeze the graph before deploying to production.
### 6.2. Edge Cases
- **Handling Missing Data**: Implement strategies for handling missing data in your datasets. Consider using imputation techniques or creating custom data loaders.
- **Dealing with Imbalanced Datasets**: Address imbalanced datasets by using techniques like oversampling, undersampling, or weighted loss functions.
- **Handling Out-of-Memory Errors**: Be prepared to handle out-of-memory errors when dealing with large models or datasets. Reduce batch sizes, use memory mapping, or distribute training across multiple GPUs.
### 6.3. Version-Specific Issues
- Be aware of potential compatibility issues between different versions of MLX and other dependencies.
- Consult the MLX documentation and release notes for information on known issues or breaking changes.
- Use dependency management tools like CocoaPods or SPM to manage dependencies and ensure compatibility.
### 6.4. Compatibility Concerns
- Consider compatibility between MLX and other technologies used in your project, such as Core ML or Metal.
- Use feature detection or conditional compilation to handle different platform versions or hardware capabilities.
### 6.5. Debugging Strategies
- Use Xcode's debugger to step through your code and inspect variables.
- Use logging statements to track the execution flow and data values.
- Use visualization tools to inspect model architectures, data distributions, and training progress.
- Leverage MLX's error messages and stack traces to identify and resolve issues.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **Xcode**: Use Xcode as your primary IDE for developing MLX applications on Apple platforms.
- **Metal Performance Shaders**: Use Metal Performance Shaders (MPS) to optimize performance on Apple GPUs.
- **Instruments**: Use Instruments to profile your application's performance and identify bottlenecks.
- **TensorBoard**: Use TensorBoard to visualize model architectures, training progress, and evaluation metrics.
### 7.2. Build Configuration
- Configure your Xcode project to optimize build settings for performance (e.g., enable optimization levels, disable debugging symbols).
- Use build configurations (e.g., Debug, Release) to manage different build settings for development and production environments.
- Use environment variables to configure application behavior based on the environment.
### 7.3. Linting and Formatting
- Use SwiftLint to enforce coding style guidelines and identify potential code quality issues.
- Use SwiftFormat to automatically format your code according to a consistent style.
- Configure Xcode to automatically run SwiftLint and SwiftFormat during the build process.
### 7.4. Deployment
- Prepare your MLX models and data for deployment. Convert models to efficient formats (e.g., Core ML) if necessary.
- Use code signing and provisioning profiles to ensure secure application distribution.
- Deploy your application to the App Store or distribute it using enterprise deployment mechanisms.
### 7.5. CI/CD Integration
- Integrate your MLX project with a continuous integration and continuous delivery (CI/CD) system like Jenkins, Travis CI, or GitHub Actions.
- Configure CI/CD pipelines to automatically build, test, and deploy your application on every code change.
- Use automated testing frameworks to verify the correctness of your MLX code and models.
By following these best practices, you can develop robust, efficient, and secure MLX applications that leverage the power of machine learning on Apple platforms.
+249
View File
@@ -0,0 +1,249 @@
---
description: This rule provides comprehensive best practices and coding standards for using the Mockito library in Java projects. It covers code organization, patterns, performance, security, testing, and common pitfalls to enhance test reliability and maintainability.
globs: **/*.java
---
# Mockito Best Practices and Coding Standards
This document provides comprehensive guidelines for using the Mockito library effectively in Java projects. It covers various aspects, including code organization, common patterns, performance considerations, security, testing, and common pitfalls.
## Library Information:
- Name: Mockito
- Tags: testing, java, mocking, unit-testing
## 1. Code Organization and Structure
### 1.1 Directory Structure
- **Standard Maven/Gradle Structure:** Follow the standard Maven or Gradle project structure.
- `src/main/java`: Production code.
- `src/test/java`: Test code.
- `src/test/resources`: Test resources (e.g., data files).
- **Package Structure:** Mirror the package structure of your production code in your test code.
- Example: If your production code is in `com.example.service`, your test code should be in `com.example.service` (or a subpackage like `com.example.service.tests`).
### 1.2 File Naming Conventions
- **Test Class Naming:**
- Use the same name as the class being tested, followed by `Test` or `IT` (for integration tests).
- Examples: `UserServiceTest`, `ProductRepositoryIT`.
- **Test Method Naming:**
- Use descriptive names that clearly indicate what is being tested.
- Consider using the pattern `should_[expectedBehavior]_when_[condition]`.
- Example: `should_returnUser_when_userExists()`.
### 1.3 Module Organization
- **Single Module:** For small projects, a single module is usually sufficient.
- **Multi-Module Projects:** For larger projects, consider breaking down the project into modules based on functionality.
- Example: `core`, `service`, `repository`, `api`.
- Ensure that test code for each module resides within that module.
### 1.4 Component Architecture
- **Layered Architecture:** A common and effective architecture is layered architecture (e.g., presentation, service, data access).
- **Test Each Layer:** Write unit tests for each layer in isolation using Mockito to mock dependencies.
- **Integration Tests:** Write integration tests to verify the interactions between layers.
### 1.5 Code Splitting Strategies
- **Test-Driven Development (TDD):** Write tests before writing production code. This naturally leads to smaller, testable units of code.
- **Refactoring:** Regularly refactor your code to improve its structure and testability.
- **Extract Methods:** If a method is too complex to test easily, extract smaller, more focused methods.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to Mockito
- **Mock Object:** The core pattern in Mockito is the Mock Object pattern, where dependencies are replaced with controlled test doubles.
- **Dependency Injection:** Use dependency injection to make your code testable. Mockito is most effective when dependencies are easily replaceable with mocks.
### 2.2 Recommended Approaches for Common Tasks with Mockito
- **Mocking Dependencies:** Use `@Mock` annotation for cleaner mock creation.
- **Injecting Mocks:** Use `@InjectMocks` to automatically inject mocks into the class under test.
- **Verifying Interactions:** Use `verify()` to ensure that expected method calls occurred.
- **Stubbing Method Calls:** Use `when(...).thenReturn(...)` to define the return values of mocked method calls.
- **Capturing Arguments:** Use `ArgumentCaptor` to capture and assert arguments passed to mocked methods.
### 2.3 Anti-patterns and Code Smells to Avoid
- **Over-mocking:** Avoid mocking classes that are easy to instantiate and use directly (e.g., value objects, simple data structures).
- **Testing Implementation Details:** Focus on testing behavior rather than implementation details. Tests should not break when you refactor code internally.
- **Ignoring Test Failures:** Investigate and fix test failures promptly. Don't ignore failing tests.
- **Writing Untestable Code:** Design code with testability in mind. Avoid tightly coupled code and dependencies.
- **Misusing Spies:** Use spies sparingly. If you need to spy on a class, it might be a sign that the class has too many responsibilities.
- **Chaining `when()` calls excessively:** If you have long chains of `when()` calls, it might indicate that your class under test is doing too much.
- **Using `reset()` frequently:** Frequent use of `reset()` might suggest that your tests are not properly isolated or that your mocks are holding too much state.
### 2.4 State Management Best Practices
- **Isolated Tests:** Each test should be independent of other tests. Avoid sharing state between tests.
- **Fresh Mocks:** Create fresh mock objects for each test using `@BeforeEach` or `@Before` (JUnit 4).
- **Avoid Static State:** Minimize the use of static variables or shared mutable state that could affect test results.
### 2.5 Error Handling Patterns
- **Expected Exceptions:** Use `@Test(expected = Exception.class)` (JUnit 4) or `assertThrows()` (JUnit 5) to verify that expected exceptions are thrown.
- **Exception Handling in Mocks:** Use `when(...).thenThrow(...)` to simulate exceptions thrown by mocked dependencies.
- **Verification of Exception Handling:** If the code under test catches exceptions, verify that appropriate error handling logic is executed (e.g., logging, retries).
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Lazy Initialization:** Initialize mocks only when they are needed to reduce startup time.
- **Efficient Stubbing:** Stub only the methods that are actually used in the test case.
- **Avoid Excessive Verification:** Verify only the interactions that are relevant to the test case.
### 3.2 Memory Management
- **Limited Mock Scope:** Keep the scope of mock objects as narrow as possible (e.g., within a method). This allows them to be garbage collected sooner.
- **Avoid Large Mocks:** Avoid creating mocks that consume large amounts of memory (e.g., mocks with many fields or methods).
### 3.3 Rendering Optimization (N/A)
- Mockito is primarily a testing framework and does not directly involve rendering.
### 3.4 Bundle Size Optimization (N/A)
- Mockito is a testing dependency and is not included in the production bundle.
### 3.5 Lazy Loading Strategies (Not Directly Applicable)
- Lazy loading is typically used for loading data or resources. Mockito doesn't directly use lazy loading patterns, although you can lazily initialize mocks if necessary.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **Unintended Side Effects:** Ensure that mocked methods do not introduce unintended side effects that could compromise security.
- **Sensitive Data Exposure:** Avoid logging or storing sensitive data in mock objects.
### 4.2 Input Validation Best Practices
- **Validate Inputs in Production Code:** Mockito tests should verify that input validation is performed correctly in the production code.
- **Simulate Invalid Inputs:** Use Mockito to simulate invalid inputs and verify that the code handles them appropriately.
### 4.3 Authentication and Authorization Patterns
- **Mock Authentication/Authorization Services:** Mock authentication and authorization services to test different security scenarios (e.g., authorized vs. unauthorized users).
- **Verify Access Control:** Use Mockito to verify that access control checks are performed correctly in the production code.
### 4.4 Data Protection Strategies
- **Encryption:** If sensitive data is used in mock objects, ensure that it is encrypted.
- **Data Masking:** Use data masking techniques to protect sensitive data in mock objects.
### 4.5 Secure API Communication
- **Mock API Clients:** Mock API clients to simulate different API responses, including error conditions.
- **Verify Secure Communication:** Use Mockito to verify that secure communication protocols (e.g., HTTPS) are used when interacting with APIs.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test Individual Units:** Unit tests should focus on testing individual units of code (e.g., classes, methods) in isolation.
- **Mock Dependencies:** Use Mockito to mock dependencies and control their behavior.
- **Test All Scenarios:** Write tests for all possible scenarios, including normal cases, edge cases, and error conditions.
### 5.2 Integration Testing Approaches
- **Test Interactions Between Units:** Integration tests should focus on testing the interactions between different units of code.
- **Use Real Dependencies (If Possible):** Use real dependencies whenever possible to ensure that the integration works correctly.
- **Mock External Systems:** Mock external systems (e.g., databases, APIs) to control their behavior and simulate different scenarios.
### 5.3 End-to-End Testing Recommendations (Beyond Mockito)
- **Use UI Testing Frameworks:** Use UI testing frameworks (e.g., Selenium, Cypress) to test the entire application flow.
- **Test User Interactions:** End-to-end tests should simulate real user interactions to ensure that the application works as expected.
### 5.4 Test Organization Best Practices
- **Separate Test Classes:** Create separate test classes for each class being tested.
- **Descriptive Test Names:** Use descriptive test names that clearly indicate what is being tested.
- **Arrange, Act, Assert:** Follow the Arrange, Act, Assert (AAA) pattern in your tests.
- **Keep Tests Short and Focused:** Keep tests short and focused on testing a single aspect of the code.
### 5.5 Mocking and Stubbing Techniques
- **`@Mock` Annotation:** Use `@Mock` to create mock objects.
- **`@InjectMocks` Annotation:** Use `@InjectMocks` to automatically inject mock objects into the class under test.
- **`when(...).thenReturn(...)`:** Use `when(...).thenReturn(...)` to stub method calls.
- **`verify(...)`:** Use `verify(...)` to verify that method calls occurred.
- **`ArgumentCaptor`:** Use `ArgumentCaptor` to capture and assert arguments passed to mocked methods.
- **`doReturn(...).when(...)`:** Use `doReturn(...).when(...)` when stubbing void methods or methods that are called multiple times.
- **`thenAnswer(...)`:** Use `thenAnswer(...)` to provide custom logic for stubbing method calls.
- **`thenThrow(...)`:** Use `thenThrow(...)` to simulate exceptions thrown by mocked methods.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Mocking Everything:** Mocking simple classes can lead to brittle tests. Use real objects when possible.
- **Testing Implementation Details:** Focus on testing behavior, not implementation.
- **Ignoring Test Failures:** Always investigate and fix test failures promptly.
- **Not Using Argument Matchers Properly:** When using argument matchers, ensure that all arguments are either exact values or matchers.
- **Forgetting to Initialize Mocks:** Ensure that mocks are initialized using `MockitoAnnotations.initMocks(this)` or `@ExtendWith(MockitoExtension.class)` (JUnit 5).
### 6.2 Edge Cases to Be Aware Of
- **Final Classes and Methods:** Mockito cannot mock final classes or methods by default. Consider using the Mockito inline mock maker or PowerMock (though PowerMock should be used as a last resort due to complexity).
- **Static Methods:** Mockito cannot mock static methods by default. Consider using the Mockito inline mock maker or PowerMock.
- **Equals and HashCode:** Mockito can have issues with `equals()` and `hashCode()` methods, especially when using argument matchers. Be careful when mocking classes that rely heavily on these methods.
- **Order of Interactions:** Mockito verifies interactions in the order they occur. Be mindful of the order of method calls when writing tests.
### 6.3 Version-Specific Issues
- **Mockito 2 vs. Mockito 3 vs. Mockito 4/5:** Be aware of the differences between Mockito versions. Some features may be deprecated or added in newer versions.
- **Java Version Compatibility:** Ensure that your Mockito version is compatible with your Java version.
### 6.4 Compatibility Concerns
- **JUnit Version:** Ensure that your Mockito version is compatible with your JUnit version.
- **Other Testing Frameworks:** Mockito can be used with other testing frameworks, but ensure that there are no compatibility issues.
- **IDE Integration:** Ensure that your IDE has proper support for Mockito and JUnit.
### 6.5 Debugging Strategies
- **Print Statements:** Use print statements to debug the code and verify that the mock objects are behaving as expected.
- **IDE Debugger:** Use the IDE debugger to step through the code and inspect the mock objects.
- **Mockito Spy:** Use a Mockito spy to partially mock a class and observe its behavior.
- **Verbose Logging:** Use verbose logging to see all method calls and their return values.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE:** IntelliJ IDEA, Eclipse, or Visual Studio Code.
- **Build Tool:** Maven or Gradle.
- **Testing Framework:** JUnit 4 or JUnit 5.
- **Code Coverage Tool:** JaCoCo or SonarQube.
### 7.2 Build Configuration Best Practices
- **Dependency Management:** Use Maven or Gradle to manage Mockito dependencies.
- **Test Dependencies:** Declare Mockito as a test dependency to ensure that it is not included in the production code.
- **Plugin Configuration:** Configure Maven or Gradle plugins to run tests and generate code coverage reports.
### 7.3 Linting and Formatting
- **Code Style:** Follow a consistent code style (e.g., Google Java Style, Checkstyle).
- **Linting Rules:** Use linting tools (e.g., PMD, SpotBugs) to enforce coding standards and identify potential issues.
- **Formatting:** Use code formatters (e.g., IntelliJ IDEA formatter, Eclipse formatter) to automatically format your code.
### 7.4 Deployment Best Practices (N/A)
- Mockito is a testing dependency and is not deployed with the production code.
### 7.5 CI/CD Integration
- **Automated Builds:** Configure your CI/CD system (e.g., Jenkins, CircleCI, GitHub Actions) to automatically build and test your code.
- **Test Execution:** Run unit tests and integration tests as part of the CI/CD pipeline.
- **Code Coverage:** Generate code coverage reports as part of the CI/CD pipeline and set thresholds for code coverage.
- **Static Analysis:** Perform static analysis as part of the CI/CD pipeline to identify potential issues.
## Conclusion
By following these best practices, you can write more effective and maintainable tests using Mockito. Remember to focus on testing behavior, avoid over-mocking, and keep your tests short and focused.
+101
View File
@@ -0,0 +1,101 @@
---
description: This rule file outlines best practices for using mypy in Python projects, emphasizing gradual adoption, consistent configuration, and leveraging advanced features for improved code quality and maintainability. It covers code organization, performance, security, testing, common pitfalls, and tooling.
globs: **/*.py
---
# Mypy Best Practices and Coding Standards
This document outlines the recommended best practices for using Mypy in Python projects. Following these guidelines can lead to more maintainable, robust, and understandable code.
## 1. Gradual Typing and Adoption
- **Start Small:** When introducing Mypy to an existing codebase, focus on a manageable subset of the code first. Choose modules or files that are relatively isolated or self-contained.
- **Iterative Annotation:** Gradually increase the coverage by adding type hints as you modify or add new code. Avoid large-scale refactoring solely for the purpose of adding type hints.
- **`# type: ignore` Strategically:** Use `# type: ignore` comments sparingly to temporarily suppress errors in code that is not yet fully typed. Always include a specific error code when using `# type: ignore` to avoid unintentionally ignoring other errors. Review these regularly.
- **Prioritize Widely Imported Modules:** Focus on annotating modules that are imported by many other modules. This will provide the greatest benefit in terms of type checking and error detection.
## 2. Consistent Configuration and Integration
- **Standardized Configuration:** Ensure that all developers use the same Mypy configuration and version. Use a `mypy.ini` file or a `pyproject.toml` file to define the project's Mypy settings. This file should be version-controlled.
- **CI Integration:** Integrate Mypy checks into your Continuous Integration (CI) pipeline to catch type errors early in the development process. Use a pre-commit hook to run Mypy before committing code.
- **Editor Integration:** Encourage developers to use Mypy integration in their code editors to get real-time feedback on type errors. Most popular Python editors, such as VS Code, PyCharm, and Sublime Text, have Mypy plugins or extensions.
- **Version Pinning:** Pin the version of mypy in your project's dependencies to ensure consistent behavior across different environments.
## 3. Leveraging Advanced Features
- **Strict Mode:** Utilize Mypy's strict mode (enabled with the `--strict` flag) to catch more potential errors. Strict mode enables a collection of stricter type checking options.
- **`--warn-unused-ignores`:** Use this flag to identify `# type: ignore` comments that are no longer necessary because the corresponding errors have been fixed.
- **`--disallow-untyped-defs`:** Use this flag to require type annotations for all function definitions.
- **`--disallow-incomplete-defs`:** Use this flag to disallow function definitions with incomplete type annotations.
- **`--check-untyped-defs`:** Use this flag to type check function bodies even if the signature lacks type annotations.
- **Protocols and Structural Subtyping:** Take advantage of Mypy's support for protocols and structural subtyping to define flexible interfaces and improve code reusability.
- **Generics:** Use generics to write type-safe code that can work with different types of data.
- **TypedDict:** Use `TypedDict` to define the types of dictionaries with known keys and values. This can help to prevent errors when working with data structures.
## 4. Code Organization and Structure
- **Directory Structure:** Use a well-defined directory structure to organize your code. A common pattern is the `src` layout, where the project's source code is located in a `src` directory.
- **File Naming Conventions:** Follow consistent file naming conventions. Use lowercase letters and underscores for module names (e.g., `my_module.py`).
- **Module Organization:** Organize your code into logical modules. Each module should have a clear purpose and a well-defined interface.
- **Component Architecture:** Design your application using a component-based architecture. Each component should be responsible for a specific task and should have well-defined inputs and outputs.
- **Code Splitting:** Split large modules into smaller, more manageable files. This can improve code readability and maintainability.
## 5. Common Patterns and Anti-patterns
- **Dependency Injection:** Use dependency injection to decouple components and improve testability.
- **Abstract Factories:** Use abstract factories to create families of related objects without specifying their concrete classes.
- **Singletons:** Avoid using singletons excessively. They can make code harder to test and reason about.
- **Global State:** Minimize the use of global state. It can make code harder to understand and debug.
- **Exception Handling:** Use exception handling to gracefully handle errors and prevent the application from crashing. Avoid catching generic exceptions (e.g., `except Exception:`). Catch specific exceptions and handle them appropriately.
## 6. Performance Considerations
- **Profiling:** Use profiling tools to identify performance bottlenecks in your code.
- **Caching:** Use caching to store frequently accessed data and reduce the number of expensive operations.
- **Lazy Loading:** Use lazy loading to defer the loading of resources until they are actually needed.
- **Efficient Data Structures:** Choose appropriate data structures for your data. For example, use sets for membership testing and dictionaries for key-value lookups.
- **Avoid Unnecessary Copying:** Avoid making unnecessary copies of data. This can consume memory and slow down your code.
## 7. Security Best Practices
- **Input Validation:** Validate all user inputs to prevent injection attacks and other security vulnerabilities. Use type annotations to enforce type constraints on function arguments.
- **Authentication and Authorization:** Implement robust authentication and authorization mechanisms to protect your application from unauthorized access.
- **Data Protection:** Protect sensitive data by encrypting it and storing it securely.
- **Secure API Communication:** Use HTTPS to encrypt communication between your application and external APIs.
- **Dependency Management:** Regularly audit your project's dependencies for security vulnerabilities and update them to the latest versions.
## 8. Testing Approaches
- **Unit Testing:** Write unit tests for all components in your application. Unit tests should verify that each component behaves as expected in isolation.
- **Integration Testing:** Write integration tests to verify that different components in your application work together correctly.
- **End-to-End Testing:** Write end-to-end tests to verify that the entire application works as expected from the user's perspective.
- **Test Organization:** Organize your tests into a clear and logical structure. Use separate directories for unit tests, integration tests, and end-to-end tests.
- **Mocking and Stubbing:** Use mocking and stubbing to isolate components during testing and to simulate external dependencies.
## 9. Common Pitfalls and Gotchas
- **`Any` Type:** Avoid using the `Any` type excessively. It effectively disables type checking for the corresponding code.
- **Inconsistent Type Annotations:** Ensure that type annotations are consistent throughout your codebase. Inconsistent type annotations can lead to unexpected errors.
- **Ignoring Errors:** Avoid ignoring Mypy errors without a good reason. Mypy errors usually indicate a real problem in your code.
- **Version Compatibility:** Be aware of compatibility issues between different versions of Mypy and other libraries.
- **Circular Dependencies:** Avoid circular dependencies between modules. They can make code harder to understand and test.
## 10. Tooling and Environment
- **Development Tools:** Use a good code editor with Mypy integration, such as VS Code, PyCharm, or Sublime Text.
- **Build Configuration:** Use a build system, such as `setuptools` or `poetry`, to manage your project's dependencies and build process.
- **Linting and Formatting:** Use a linter, such as `flake8` or `ruff`, to enforce code style and detect potential errors. Use a code formatter, such as `black` or `ruff`, to automatically format your code.
- **Deployment:** Deploy your application to a production environment using a container system, such as Docker, or a cloud platform, such as AWS or Google Cloud.
- **CI/CD:** Integrate Mypy into your CI/CD pipeline to automatically check your code for type errors before deploying it to production.
## 11. Additional Best Practices
- **Use type hints for all function arguments and return values.** This makes it easier to understand what types of data the function expects and returns.
- **Use type aliases to simplify complex type annotations.** This can make your code more readable and maintainable.
- **Use the `typing` module to access advanced type features.** The `typing` module provides a number of useful type-related classes and functions, such as `List`, `Dict`, `Union`, and `Optional`.
- **Use the `reveal_type()` function to inspect the type of an expression.** This can be helpful for debugging type-related issues.
- **Keep your code clean and well-organized.** This makes it easier to understand and maintain.
- **Write clear and concise comments.** This helps others understand your code and how it works.
- **Follow the PEP 8 style guide.** This ensures that your code is consistent and readable.
- **Use a version control system.** This allows you to track changes to your code and collaborate with others.
By following these best practices, you can improve the quality, maintainability, and robustness of your Python code that uses mypy and other Python tools.
+278
View File
@@ -0,0 +1,278 @@
---
description: This rule provides guidelines for best practices and coding standards when developing applications with Neo4j. It covers aspects from code organization and performance to security and testing.
globs: **/*.cypher
---
# Neo4j Development Best Practices
This document outlines best practices and coding standards for developing applications using Neo4j. These guidelines are designed to promote maintainability, performance, and security.
Library Information:
- Name: neo4j
- Tags: database, graph, nosql, relationships
## 1. Code Organization and Structure
### 1.1 Directory Structure
Organize your project with a clear directory structure that separates concerns. A recommended structure is as follows:
project_root/
├── data/ # Contains data files for import/export
├── queries/ # Stores Cypher queries
├── src/ # Source code for the application
│ ├── models/ # Defines data models and graph schemas
│ ├── services/ # Contains business logic and Neo4j interactions
│ ├── utils/ # Utility functions and helper classes
│ ├── config/ # Configuration files
│ └── app.js # Main application file
├── tests/ # Unit, integration, and end-to-end tests
├── .env # Environment variables
├── package.json # Node.js project configuration
├── requirements.txt # Python project dependencies
└── README.md
### 1.2 File Naming Conventions
* **Cypher Queries:** Use descriptive names (e.g., `get_user_friends.cypher`).
* **Models:** Name files according to the entity they represent (e.g., `user.js`, `movie.py`).
* **Services:** Use a service-based naming convention (e.g., `user_service.js`, `movie_service.py`).
* **Tests:** Match test file names to the source file names (e.g., `user_service.test.js`).
### 1.3 Module Organization
Break down your application into modules based on functionality. Use well-defined interfaces and avoid circular dependencies.
* **Node.js:** Use ES modules (`import`, `export`) or CommonJS (`require`, `module.exports`).
* **Python:** Utilize packages and modules for organizing code.
### 1.4 Component Architecture
Design a component architecture that promotes reusability and maintainability. Consider using patterns like Model-View-Controller (MVC) or a layered architecture.
* **Models:** Define data structures and interact with the Neo4j database.
* **Services:** Implement business logic and handle data manipulation.
* **Controllers (or equivalent):** Handle user requests and orchestrate interactions between models and services.
### 1.5 Code Splitting
For large applications, use code splitting to improve initial load times. Load modules and components on demand when they are needed.
* **Node.js:** Use dynamic imports (`import()`) for on-demand loading.
* **Frontend Frameworks (if applicable):** Use framework-specific code-splitting techniques (e.g., React.lazy, Vue.js's async components).
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Repository Pattern:** Abstract data access logic behind a repository interface. This makes it easier to switch database implementations or mock data access for testing.
* **Unit of Work:** Group multiple database operations into a single transaction to ensure atomicity.
* **Data Mapper:** Transfer data between domain objects and the database.
* **Graph Traversal Pattern:** Encapsulate common graph traversal logic into reusable functions or classes.
### 2.2 Recommended Approaches for Common Tasks
* **Creating Nodes and Relationships:** Use Cypher queries with parameters to avoid SQL injection and improve performance.
* **Querying Data:** Use Cypher's `MATCH` clause for efficient graph traversal. Leverage indexes and constraints for optimal query performance.
* **Data Validation:** Validate data before inserting it into the database. Use constraints to enforce data integrity at the database level.
* **Error Handling:** Implement robust error handling to gracefully handle database errors and prevent application crashes.
### 2.3 Anti-patterns and Code Smells
* **Over-fetching Data:** Avoid retrieving unnecessary data from the database. Use projections in Cypher queries to select only the required properties.
* **Long Cypher Queries:** Break down complex Cypher queries into smaller, more manageable queries.
* **Lack of Indexing:** Ensure that frequently queried properties are indexed to improve query performance.
* **Ignoring Constraints:** Define and enforce constraints to maintain data integrity and consistency.
* **Hardcoding Values:** Avoid hardcoding values in Cypher queries. Use parameters instead.
* **Excessive Relationship Traversal in Application Code:** Prefer to execute complex relationship traversals within Cypher rather than in application code which reduces the amount of data transported and is significantly faster.
### 2.4 State Management
* **Stateless Services:** Design services to be stateless to improve scalability and testability.
* **Session Management:** Use appropriate session management techniques for web applications.
* **Caching:** Implement caching to reduce database load and improve response times.
### 2.5 Error Handling
* **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions consistently.
* **Logging:** Log errors and warnings to help with debugging and monitoring.
* **Retry Logic:** Implement retry logic for transient database errors.
* **Custom Exceptions:** Define custom exceptions for specific error conditions.
* **Graceful Degradation:** Design the application to degrade gracefully in case of database failures.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Indexing:** Create indexes on frequently queried properties.
* **Constraints:** Use constraints to enforce data integrity and improve query performance.
* **Query Optimization:** Analyze Cypher query execution plans and optimize queries for performance.
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead.
* **Batch Operations:** Use batch operations to insert or update multiple nodes and relationships in a single transaction.
* **Profile Queries:** Use `PROFILE` or `EXPLAIN` to understand query performance.
* **Use `apoc.periodic.iterate` for batch processing** When dealing with large datasets, `apoc.periodic.iterate` allows for batch processing and avoids exceeding memory limits.
### 3.2 Memory Management
* **Limit Result Set Size:** Use `LIMIT` in Cypher queries to restrict the number of returned results.
* **Stream Data:** Stream data from the database to avoid loading large amounts of data into memory.
* **Garbage Collection:** Monitor garbage collection and tune JVM settings for optimal performance (Java-based implementations).
### 3.3 Bundle Size Optimization
* **Tree shaking** remove unused code
* **Minification:** Minify code to reduce bundle size.
* **Compression:** Compress bundles to reduce transfer size.
### 3.4 Lazy Loading
* **On-Demand Loading:** Load data and components on demand when they are needed.
* **Pagination:** Use pagination to load data in smaller chunks.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
* **Cypher Injection:** Prevent Cypher injection by using parameterized queries.
* **Authentication Bypass:** Secure authentication mechanisms and avoid relying on client-side authentication.
* **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit.
* **Authorization Flaws:** Implement robust authorization mechanisms to control access to resources.
### 4.2 Input Validation
* **Sanitize Inputs:** Sanitize user inputs to prevent Cross-Site Scripting (XSS) attacks.
* **Validate Inputs:** Validate user inputs to ensure they conform to expected formats and values.
* **Parameterize Queries:** Always use parameterized queries to prevent Cypher injection.
### 4.3 Authentication and Authorization
* **Secure Authentication:** Use strong authentication mechanisms such as OAuth 2.0 or JWT.
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
* **Least Privilege Principle:** Grant users only the minimum necessary permissions.
* **Neo4j's built-in security:** Utilize Neo4j's built-in authentication and authorization mechanisms for database access.
### 4.4 Data Protection
* **Encryption at Rest:** Encrypt sensitive data at rest using Neo4j's encryption features or third-party encryption solutions.
* **Encryption in Transit:** Use HTTPS to encrypt data in transit.
* **Data Masking:** Mask sensitive data in logs and reports.
* **Regular Backups:** Perform regular backups to protect against data loss.
* **Database Auditing:** Enable database auditing to track access and modifications to data.
* **Avoid Storing Sensitive Data:** Only store necessary sensitive data. Consider tokenization or anonymization where applicable.
### 4.5 Secure API Communication
* **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 API requests to prevent malicious input.
## 5. Testing Approaches
### 5.1 Unit Testing
* **Test Individual Components:** Unit test individual components in isolation.
* **Mock Dependencies:** Use mocking to isolate components from external dependencies.
* **Test Edge Cases:** Test edge cases and boundary conditions.
* **Test Data Validation** Unit tests should cover data validation logic.
### 5.2 Integration Testing
* **Test Interactions:** Test the interactions between different components.
* **Test Database Interactions:** Test the interactions between the application and the Neo4j database.
* **Use Test Databases:** Use separate test databases for integration tests.
### 5.3 End-to-End Testing
* **Test Full Workflows:** Test the complete end-to-end workflows of the application.
* **Automate Tests:** Automate end-to-end tests to ensure consistent results.
### 5.4 Test Organization
* **Organize Tests:** Organize tests in a clear and logical manner.
* **Use Test Suites:** Use test suites to group related tests together.
* **Naming Convention:** Follow a clear naming convention for test files and test methods.
### 5.5 Mocking and Stubbing
* **Mock Neo4j Driver:** Mock the Neo4j driver to isolate components from the database.
* **Stub Responses:** Stub database responses to control the data returned by the database.
* **Verify Interactions:** Verify that components interact with the database as expected.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Lack of Planning:** Failing to properly plan the graph schema and data model.
* **Ignoring Performance:** Neglecting to optimize Cypher queries and database configuration.
* **Poor Security:** Failing to implement proper security measures.
* **Insufficient Testing:** Insufficient testing leading to bugs and regressions.
* **Not Utilizing Indexes:** Neglecting to create indexes on frequently queried properties.
### 6.2 Edge Cases
* **Large Graphs:** Handling very large graphs with millions or billions of nodes and relationships.
* **Concurrent Access:** Managing concurrent access to the database.
* **Transaction Management:** Properly managing transactions to ensure data consistency.
* **Handling Null Values:** Understanding how Neo4j handles null values and handling them appropriately.
### 6.3 Version-Specific Issues
* **API Changes:** Be aware of API changes between different versions of the Neo4j driver and database.
* **Cypher Syntax:** Be aware of changes to the Cypher syntax in different versions of Neo4j.
* **Deprecated Features:** Avoid using deprecated features.
### 6.4 Compatibility Concerns
* **Driver Compatibility:** Ensure that the Neo4j driver is compatible with the version of the Neo4j database.
* **Operating System Compatibility:** Ensure that the application is compatible with the target operating system.
* **Java Version Compatibility:** Ensure the Java version is compatible (if using Java-based drivers).
### 6.5 Debugging Strategies
* **Logging:** Use logging to track the execution of the application and identify errors.
* **Debuggers:** Use debuggers to step through the code and inspect variables.
* **Neo4j Browser:** Use the Neo4j Browser to visualize the graph and execute Cypher queries.
* **Cypher Profiler:** Use the Cypher profiler to analyze the performance of Cypher queries.
* **APOC Procedures:** Use APOC Procedures to aid with debugging and monitoring.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **Neo4j Browser:** A web-based interface for interacting with the Neo4j database.
* **Neo4j Desktop:** A desktop application for managing Neo4j databases.
* **IntelliJ IDEA/PyCharm:** IDEs with excellent support for Neo4j development.
* **VS Code:** Popular code editor with Neo4j extensions.
* **APOC Library:** Provides many helpful stored procedures.
### 7.2 Build Configuration
* **Dependency Management:** Use a dependency management tool (e.g., npm, pip) to manage project dependencies.
* **Environment Variables:** Use environment variables to configure the application for different environments.
* **Build Scripts:** Use build scripts to automate the build process.
### 7.3 Linting and Formatting
* **ESLint/Pylint:** Use linters to enforce coding standards and identify potential errors.
* **Prettier/Black:** Use formatters to automatically format code.
* **Consistent Style:** Maintain a consistent coding style throughout the project.
### 7.4 Deployment Best Practices
* **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies.
* **Cloud Deployment:** Deploy the application to a cloud platform (e.g., AWS, Azure, GCP).
* **Load Balancing:** Use load balancing to distribute traffic across multiple instances of the application.
* **Monitoring:** Monitor the application to detect and respond to issues.
* **Immutable Infrastructure:** Treat servers as immutable; rebuild instead of modifying.
### 7.5 CI/CD Integration
* **Automated Builds:** Automate the build process using a CI/CD pipeline.
* **Automated Tests:** Run automated tests as part of the CI/CD pipeline.
* **Automated Deployments:** Automate the deployment process using a CI/CD pipeline.
* **Version Control:** Use version control (e.g., Git) to manage the codebase.
* **Trunk-Based Development:** Consider trunk-based development for faster feedback cycles.
By following these best practices, developers can build robust, scalable, and secure Neo4j applications.
+293
View File
@@ -0,0 +1,293 @@
---
description: This rule file outlines best practices for Netlify development, covering code structure, performance, security, testing, and deployment. It aims to provide a comprehensive guide for building robust and scalable applications on Netlify.
globs: **/*.{js,jsx,ts,tsx,html,css,scss,md}
---
# Netlify Library Best Practices and Coding Standards
This document outlines best practices for developing applications using Netlify, encompassing code organization, performance considerations, security measures, testing strategies, and deployment procedures. Adhering to these guidelines will ensure the creation of robust, scalable, and maintainable applications on the Netlify platform.
## 1. Code Organization and Structure
### 1.1 Directory Structure
A well-defined directory structure is crucial for maintainability and collaboration. Here's a recommended structure:
project-root/
├── .netlify/ # Netlify-specific configuration (auto-generated)
├── functions/ # Serverless functions
│ └── api/ # API endpoint functions
│ └── hello.js
├── src/ # Source code
│ ├── components/ # Reusable UI components
│ │ ├── Button.jsx
│ │ └── Header.jsx
│ ├── pages/ # Pages for different routes
│ │ ├── index.jsx
│ │ └── about.jsx
│ ├── styles/ # CSS, SCSS, or other styling
│ │ ├── global.css
│ │ └── components/
│ ├── utils/ # Utility functions
│ │ └── api.js
│ ├── App.jsx # Main application component
│ ├── index.jsx # Entry point for React
│ └── routes.js # Routing configuration
├── static/ # Static assets (images, fonts, etc.)
│ ├── img/
│ └── fonts/
├── public/ # Public files to be deployed
│ └── index.html
├── tests/ # Tests
│ ├── unit/
│ └── integration/
├── netlify.toml # Netlify configuration file
├── package.json # Node.js dependencies
└── README.md
### 1.2 File Naming Conventions
* **Components:** Use PascalCase for component file names (e.g., `MyComponent.jsx`).
* **Styles:** Use kebab-case for style file names (e.g., `my-component.css`).
* **Functions:** Use camelCase or kebab-case for function file names (e.g., `helloWorld.js` or `hello-world.js`).
* **Images:** Use descriptive names (e.g., `product-image.jpg`).
### 1.3 Module Organization
* **Group Related Code:** Place related functions, components, and styles into separate modules/directories.
* **Single Responsibility Principle:** Each module should have a clear and single purpose.
* **Avoid Circular Dependencies:** Carefully manage dependencies between modules to prevent circular dependencies.
* **Use ES Modules:** Utilize ES modules (`import/export`) for better code organization and tree shaking.
### 1.4 Component Architecture
* **Component-Based Approach:** Build your UI using reusable components.
* **Presentational and Container Components:** Separate concerns by using presentational components (UI only) and container components (data fetching and logic).
* **Atomic Design:** Consider using atomic design principles (atoms, molecules, organisms, templates, pages) for a scalable component architecture.
### 1.5 Code Splitting
* **Dynamic Imports:** Use dynamic imports (`import()`) to load modules on demand.
* **Route-Based Splitting:** Split your application based on routes so that only the necessary code is loaded for a given route. This will improve the initial loading time for the end user.
* **Component-Based Splitting:** Use React.lazy or similar mechanisms to load components only when they are needed.
* **Webpack or Parcel Bundler Configuration:** Configure your bundler (Webpack, Parcel, etc.) for optimal code splitting.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **JAMstack Architecture:** Embrace the JAMstack architecture (JavaScript, APIs, Markup) for faster and more secure websites.
* **Serverless Functions:** Utilize Netlify Functions for backend logic (API endpoints, background tasks). Follow the function handler structure and consider using middleware for common tasks like authentication.
* **Git-Based Workflow:** Use Git for version control and continuous deployment with Netlify.
* **Environment Variables:** Store sensitive information (API keys, database credentials) in environment variables, and access them from your serverless functions. Ensure you configure these in Netlify's UI and use `process.env.VARIABLE_NAME`.
### 2.2 Recommended Approaches
* **Form Handling:** Use libraries like Formik or React Hook Form for form handling.
* **State Management:** Choose a state management solution appropriate for the complexity of your application (e.g., Context API, Redux, Zustand).
* **API Calls:** Use `fetch` or libraries like Axios for making API calls. Implement error handling and loading states.
* **Image Optimization:** Optimize images before deployment to improve performance. Consider using Netlify Large Media for automatic image optimization.
### 2.3 Anti-patterns
* **Committing Secrets:** Avoid committing API keys or other secrets to your Git repository.
* **Over-reliance on Client-Side Rendering:** Minimize client-side rendering for better SEO and initial load time. Use static site generation (SSG) or server-side rendering (SSR) where appropriate.
* **Ignoring Performance Budgets:** Establish performance budgets and monitor your application's performance regularly. Use tools such as Lighthouse, WebPageTest, and Chrome DevTools.
* **Unnecessary Dependencies:** Avoid including unnecessary dependencies in your project.
* **Direct DOM Manipulation:** Avoid direct DOM manipulation in React components; let React handle the updates.
### 2.4 State Management
* **Context API:** Use React's Context API for simple state management.
* **Redux:** Use Redux for more complex state management requirements.
* **Zustand:** Consider Zustand for a simple and unopinionated state management solution.
* **Avoid Global State:** Minimize the use of global state to avoid performance issues and make code easier to reason about.
* **Immutable Updates:** Use immutable updates when updating state to improve performance and prevent unexpected side effects.
### 2.5 Error Handling
* **Try-Catch Blocks:** Use try-catch blocks in your serverless functions to handle errors gracefully.
* **Centralized Error Handling:** Implement a centralized error handling mechanism to log errors and display user-friendly messages.
* **ErrorBoundary:** Use React's `ErrorBoundary` component to catch errors in your UI.
* **Logging:** Log errors to a service like Sentry, Rollbar, or Netlify's built-in logging for monitoring and debugging.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Code Splitting:** Implement code splitting to reduce initial load time.
* **Lazy Loading:** Lazy load images and other assets to improve performance.
* **Image Optimization:** Optimize images using tools like ImageOptim, TinyPNG, or Netlify Large Media.
* **Caching:** Utilize browser caching and CDN caching to reduce server load and improve response times. Netlify automatically handles CDN caching.
* **Minification:** Minify your CSS and JavaScript files to reduce their size.
* **Compression:** Use Gzip or Brotli compression to reduce the size of your files.
### 3.2 Memory Management
* **Avoid Memory Leaks:** Be careful to avoid memory leaks in your JavaScript code. Properly clean up event listeners and timers.
* **Use Efficient Data Structures:** Use appropriate data structures for your data to optimize memory usage.
* **Limit Large Data Sets:** Avoid loading large datasets into memory if possible.
### 3.3 Rendering Optimization (if applicable)
* **Virtual DOM:** React's Virtual DOM provides significant rendering optimization. Ensure you are using React efficiently, minimizing unnecessary re-renders.
* **Memoization:** Use `React.memo` to prevent re-rendering components unless their props change.
* **Pure Components:** Use `PureComponent` or implement `shouldComponentUpdate` for class components to prevent unnecessary re-renders.
### 3.4 Bundle Size Optimization
* **Analyze Bundle Size:** Use tools like Webpack Bundle Analyzer or Parcel Size Analyzer to identify large dependencies.
* **Tree Shaking:** Enable tree shaking in your bundler to remove unused code.
* **Code Minimization:** Utilize code minification in your build process.
* **Remove Unused Dependencies:** Review your dependencies and remove any unused ones.
### 3.5 Lazy Loading
* **Intersection Observer:** Use the Intersection Observer API to lazy load images and other assets when they come into view.
* **React Lazy:** Use React.lazy for component-level lazy loading.
* **Dynamic Imports:** Use dynamic imports for modules that are not needed immediately.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and escaping output.
* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using CSRF tokens.
* **Injection Attacks:** Prevent SQL injection and other injection attacks by using parameterized queries and validating user inputs.
* **Authentication and Authorization:** Implement secure authentication and authorization mechanisms to protect sensitive data.
* **Exposed API Keys:** Avoid exposing API keys in client-side code. Store them in environment variables and access them from your serverless functions.
### 4.2 Input Validation
* **Client-Side Validation:** Use client-side validation to provide immediate feedback to users.
* **Server-Side Validation:** Always perform server-side validation to ensure data integrity and prevent malicious inputs.
* **Sanitization:** Sanitize user inputs to remove potentially harmful characters.
* **Escaping:** Escape output to prevent XSS attacks.
### 4.3 Authentication and Authorization
* **Netlify Identity:** Use Netlify Identity for simple authentication and authorization.
* **Third-Party Authentication:** Use third-party authentication providers like Auth0, Firebase Authentication, or AWS Cognito.
* **JSON Web Tokens (JWT):** Use JWTs to securely transmit user information between the client and server.
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
### 4.4 Data Protection
* **Encryption:** Encrypt sensitive data at rest and in transit.
* **Secure Storage:** Store sensitive data in secure storage locations.
* **Regular Backups:** Perform regular backups of your data.
* **Data Minimization:** Only collect and store the data that is necessary.
* **Compliance:** Ensure your application complies with relevant data protection regulations (e.g., GDPR, CCPA).
### 4.5 Secure API Communication
* **HTTPS:** Use HTTPS for all API communication.
* **API Keys:** Use API keys to authenticate requests to your API.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
* **CORS:** Configure CORS (Cross-Origin Resource Sharing) to allow only authorized domains to access your API.
## 5. Testing Approaches
### 5.1 Unit Testing
* **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 Code Paths:** Test all code paths, including error handling.
* **Use a Testing Framework:** Use a testing framework like Jest, Mocha, or Jasmine.
### 5.2 Integration Testing
* **Test Interactions:** Integration tests should focus on testing the interactions between different components and modules.
* **Test API Calls:** Test the integration with your API endpoints.
* **Use a Testing Framework:** Use a testing framework like Cypress, Puppeteer, or Selenium.
### 5.3 End-to-End Testing
* **Test User Flows:** End-to-end tests should focus on testing complete user flows.
* **Simulate User Interactions:** Simulate user interactions, such as clicking buttons and filling out forms.
* **Use a Testing Framework:** Use a testing framework like Cypress, Puppeteer, or Selenium.
### 5.4 Test Organization
* **Separate Test Files:** Create separate test files for each component or module.
* **Organize Tests by Type:** Organize tests by type (unit, integration, end-to-end).
* **Use Descriptive Test Names:** Use descriptive test names to make it easier to understand what each test is testing.
### 5.5 Mocking and Stubbing
* **Mock API Calls:** Mock API calls to avoid making real API calls during testing.
* **Stub Dependencies:** Stub dependencies to isolate the component being tested.
* **Use a Mocking Library:** Use a mocking library like Jest's `jest.mock` or Sinon.js.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Not Using Environment Variables:** Failing to use environment variables for sensitive information.
* **Over-complicating Serverless Functions:** Creating serverless functions that are too large and complex.
* **Not Handling Errors:** Failing to handle errors gracefully in serverless functions.
* **Ignoring Performance:** Ignoring performance considerations and creating slow-loading applications.
* **Not Testing:** Failing to test your application thoroughly.
### 6.2 Edge Cases
* **Long Build Times:** Long build times can be a problem for large applications. Optimize your build process to reduce build times.
* **Function Cold Starts:** Serverless functions can experience cold starts, which can increase response times. Use techniques like keep-alive to reduce cold start times.
* **CDN Invalidation:** Ensure your CDN invalidates cache correctly when you deploy new versions of your application.
### 6.3 Version-Specific Issues
* **Netlify CLI Updates:** Stay up-to-date with the latest Netlify CLI to avoid compatibility issues.
* **Node.js Versions:** Ensure your Node.js version is compatible with Netlify Functions.
* **Dependency Updates:** Regularly update your dependencies to address security vulnerabilities and bug fixes.
### 6.4 Compatibility Concerns
* **Browser Compatibility:** Test your application in different browsers to ensure compatibility.
* **Device Compatibility:** Test your application on different devices (desktop, mobile, tablet) to ensure compatibility.
* **Accessibility:** Ensure your application is accessible to users with disabilities by following accessibility guidelines (WCAG).
### 6.5 Debugging Strategies
* **Netlify Logs:** Use Netlify's built-in logging to debug issues.
* **Console Logging:** Use `console.log` statements to debug your code.
* **Debugging Tools:** Use browser debugging tools like Chrome DevTools or Firefox Developer Tools.
* **Remote Debugging:** Use remote debugging tools to debug serverless functions.
## 7. Tooling and Environment
### 7.1 Recommended Tools
* **VS Code:** VS Code with extensions like ESLint, Prettier, and Netlify.
* **Netlify CLI:** Netlify Command Line Interface for local development and deployment.
* **Git:** Git for version control.
* **npm or Yarn:** npm or Yarn for package management.
* **Webpack, Parcel, or Rollup:** Webpack, Parcel, or Rollup for bundling your code.
### 7.2 Build Configuration
* **Netlify TOML:** Use the `netlify.toml` file to configure your build process. Set environment variables, build commands, and deploy contexts.
* **Build Commands:** Define build commands to transpile your code, optimize assets, and generate static files.
* **Deploy Contexts:** Use deploy contexts to create different environments (e.g., production, staging, development).
### 7.3 Linting and Formatting
* **ESLint:** Use ESLint to enforce code style and prevent errors.
* **Prettier:** Use Prettier to automatically format your code.
* **Husky and lint-staged:** Use Husky and lint-staged to run linters and formatters before committing code.
### 7.4 Deployment
* **Git-Based Deployment:** Deploy your application by pushing your code to a Git repository connected to Netlify.
* **Netlify CLI Deployment:** Deploy your application using the Netlify CLI.
* **Atomic Deploys:** Netlify provides atomic deploys, ensuring that your site is always in a consistent state during updates.
* **Rollbacks:** Easily roll back to previous deployments if necessary.
### 7.5 CI/CD Integration
* **GitHub Actions:** Integrate with GitHub Actions for automated testing and deployment.
* **CircleCI:** Integrate with CircleCI for continuous integration and continuous deployment.
* **Travis CI:** Integrate with Travis CI for continuous integration and continuous deployment.
By following these best practices, you can create robust, scalable, secure, and maintainable applications using Netlify.
+278 -159
View File
@@ -1,169 +1,288 @@
---
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.
description: This rule provides comprehensive guidance for Next.js development, covering code organization, performance, security, testing, and common pitfalls. It helps developers build robust, scalable, and maintainable Next.js applications by adhering to community-accepted best practices and coding standards.
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.
# Next.js Best Practices
- **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.
This document outlines best practices for developing Next.js applications, focusing on code organization, performance optimization, security, testing strategies, and common pitfalls to avoid. Adhering to these guidelines will help you build robust, scalable, and maintainable applications.
- **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.
## 1. Code Organization and Structure
- **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.
### Directory Structure
- **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.
* **`app/`**: (Recommended - Next.js 13+) Contains route handlers, server components, and client components.
* `page.tsx`: Represents the UI for a route.
* `layout.tsx`: Defines the layout for a route and its children.
* `loading.tsx`: Displays a loading UI while a route segment is loading.
* `error.tsx`: Handles errors within a route segment.
* `head.tsx`: Manages the `<head>` metadata for a route.
* `route.ts`: Defines server-side route handlers (API routes).
* `[dynamic-segment]`: Dynamic route segments, using brackets.
* `@folder-name`: Route Groups to organize routes without affecting URL structure.
* **`pages/`**: (Legacy - Before Next.js 13) Contains page components.
* `api/`: Serverless functions (API routes).
* `_app.js/tsx`: Custom App component (wraps all pages).
* `_document.js/tsx`: Custom Document component (control the entire HTML document).
* **`components/`**: Reusable UI components.
* **`lib/`**: Utility functions, helper functions, and third-party integrations.
* **`hooks/`**: Custom React hooks.
* **`styles/`**: Global styles and CSS modules.
* **`public/`**: Static assets (images, fonts, etc.).
* **`types/`**: TypeScript type definitions and interfaces.
* **`utils/`**: Contains utilities and helper functions, along with any API-related logic.
- **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.**
**Recommendation:** Prefer the `app/` directory structure for new projects as it aligns with the latest Next.js features and best practices. When using `pages/`, keep it simple and migrate to `app/` when feasible.
- **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.**
### File Naming Conventions
- **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.**
* **Components:** `ComponentName.jsx` or `ComponentName.tsx`
* **Pages:** `page.js`, `page.jsx`, `page.ts`, `page.tsx` (within the `app` or `pages` directory)
* **Layouts:** `layout.js`, `layout.jsx`, `layout.ts`, `layout.tsx` (within the `app` directory)
* **API Routes:** `route.js`, `route.ts` (within the `app/api` directory or `pages/api` directory)
* **Hooks:** `useHookName.js` or `useHookName.ts`
* **Styles:** `ComponentName.module.css` or `ComponentName.module.scss`
* **Types:** `types.ts` or `interfaces.ts`
### Module Organization
* **Co-location:** Keep related components, styles, and tests in the same directory.
* **Feature-based modules:** Group files by feature rather than type (e.g., `components/user-profile/`, not `components/button`, `components/form`).
* **Avoid deeply nested directories:** Keep the directory structure relatively flat to improve navigation.
### Component Architecture
* **Presentational vs. Container Components:** Separate components that handle data fetching and state management (container components) from those that only render UI (presentational components).
* **Atomic Design:** Organize components into atoms, molecules, organisms, templates, and pages for better reusability and maintainability.
* **Composition over inheritance:** Favor composition to create flexible and reusable components.
* **Server Components (app directory):** Use server components by default for improved performance. Only use client components when interactivity (event handlers, useState, useEffect) is required.
### Code Splitting
* **Dynamic imports:** Use `next/dynamic` to load components only when they are needed, improving initial load time. Example: `dynamic(() => import('../components/MyComponent'))`.
* **Route-level code splitting:** Next.js automatically splits code based on routes, so each page only loads the necessary JavaScript.
* **Granular code splitting:** Break down large components into smaller chunks that can be loaded independently.
## 2. Common Patterns and Anti-patterns
### Design Patterns
* **Higher-Order Components (HOCs):** Reusable component logic.
* **Render Props:** Sharing code between React components using a prop whose value is a function.
* **Hooks:** Extracting stateful logic into reusable functions.
* **Context API:** Managing global state.
* **Compound Components:** Combining multiple components that work together implicitly.
### Recommended Approaches
* **Data fetching:** Use `getServerSideProps` or `getStaticProps` or server components for fetching data on the server-side. Use `SWR` or `React Query` for client-side data fetching and caching.
* **Styling:** Use CSS Modules, Styled Components, or Tailwind CSS for component-level styling. Prefer Tailwind CSS for rapid development.
* **State Management:** Use React Context, Zustand, Jotai, or Recoil for managing global state. Redux is an option, but often overkill for smaller Next.js projects.
* **Form Handling:** Use `react-hook-form` for managing forms and validation.
* **API Routes:** Use Next.js API routes for serverless functions.
### Anti-patterns and Code Smells
* **Over-fetching data:** Only fetch the data that is needed by the component.
* **Blocking the main thread:** Avoid long-running synchronous operations in the main thread.
* **Mutating state directly:** Always use `setState` or hooks to update state.
* **Not memoizing components:** Use `React.memo` to prevent unnecessary re-renders.
* **Using `useEffect` without a dependency array:** Ensure the dependency array is complete to prevent unexpected behavior.
* **Writing server side code in client components:** Can expose secrets or cause unexpected behavior.
### State Management
* **Local State:** Use `useState` for component-specific state.
* **Context API:** Use `useContext` for application-wide state that doesn't change often.
* **Third-party libraries:** Use `Zustand`, `Jotai`, or `Recoil` for more complex state management needs. These are simpler and more performant alternatives to Redux for many Next.js use cases.
### Error Handling
* **`try...catch`:** Use `try...catch` blocks for handling errors in asynchronous operations.
* **Error Boundary Components:** Create reusable error boundary components to catch errors in child components. Implement `getDerivedStateFromError` or `componentDidCatch` lifecycle methods.
* **Centralized error logging:** Log errors to a central service like Sentry or Bugsnag.
* **Custom Error Pages:** Use `_error.js` or `_error.tsx` to create custom error pages.
* **Route-level error handling (app directory):** Use `error.tsx` within route segments to handle errors specific to that route.
## 3. Performance Considerations
### Optimization Techniques
* **Image optimization:** Use `next/image` component for automatic image optimization, including lazy loading and responsive images.
* **Font optimization:** Use `next/font` to optimize font loading and prevent layout shift.
* **Code splitting:** Use dynamic imports and route-level code splitting to reduce initial load time.
* **Caching:** Use caching strategies (e.g., `Cache-Control` headers, `SWR`, `React Query`) to reduce data fetching overhead.
* **Memoization:** Use `React.memo` to prevent unnecessary re-renders of components.
* **Prefetching:** Use the `<Link prefetch>` tag to prefetch pages that are likely to be visited.
* **SSR/SSG:** Use Static Site Generation (SSG) for content that doesn't change often and Server-Side Rendering (SSR) for dynamic content.
* **Incremental Static Regeneration (ISR):** Use ISR to update statically generated pages on a regular interval.
### Memory Management
* **Avoid memory leaks:** Clean up event listeners and timers in `useEffect` hooks.
* **Minimize re-renders:** Only update state when necessary to reduce the number of re-renders.
* **Use immutable data structures:** Avoid mutating data directly to prevent unexpected side effects.
### Rendering Optimization
* **Server Components (app directory):** Render as much as possible on the server to reduce client-side JavaScript.
* **Client Components (app directory):** Only use client components when interactivity is required. Defer rendering of non-critical client components using `React.lazy`.
### Bundle Size Optimization
* **Analyze bundle size:** Use tools like `webpack-bundle-analyzer` to identify large dependencies.
* **Remove unused code:** Use tree shaking to remove unused code from your bundles.
* **Use smaller dependencies:** Replace large dependencies with smaller, more lightweight alternatives.
* **Compression:** Enable Gzip or Brotli compression on your server to reduce the size of the transferred files.
### Lazy Loading
* **Images:** Use `next/image` for automatic lazy loading of images.
* **Components:** Use `next/dynamic` for lazy loading of components.
* **Intersection Observer:** Use the Intersection Observer API for manual lazy loading of content.
## 4. Security Best Practices
### Common Vulnerabilities
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. Be especially careful when rendering HTML directly from user input.
* **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. Avoid storing secrets in client-side code.
* **Exposing sensitive data:** Protect API keys and other sensitive data by storing them in environment variables and accessing them on the server-side.
### Input Validation
* **Server-side validation:** Always validate user input on the server-side.
* **Client-side validation:** Use client-side validation for immediate feedback, but don't rely on it for security.
* **Sanitize input:** Sanitize user input to remove potentially malicious code.
* **Use a validation library:** Use a library like `zod` or `yup` for validating user input.
### Authentication and Authorization
* **Use a secure authentication provider:** Use a service like Auth0, NextAuth.js, or Firebase Authentication for secure authentication.
* **Store tokens securely:** Store tokens in HTTP-only cookies or local storage.
* **Implement role-based access control:** Use role-based access control to restrict access to sensitive resources.
* **Protect API endpoints:** Use authentication middleware to protect API endpoints.
### Data Protection
* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit.
* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server.
* **Regularly update dependencies:** Keep your dependencies up to date to patch security vulnerabilities.
* **Secure environment variables:** Never commit environment variables to your repository. Use a secrets management tool if necessary.
### Secure API Communication
* **Use HTTPS:** Use HTTPS for all API communication.
* **Authenticate API requests:** Use API keys or tokens to authenticate API requests.
* **Rate limiting:** Implement rate limiting to prevent abuse of your API.
* **Input validation:** Validate all API request parameters.
* **Output encoding:** Properly encode API responses to prevent injection attacks.
## 5. Testing Approaches
### Unit Testing
* **Test individual components:** Write unit tests for individual components to ensure they are working correctly.
* **Use a testing framework:** Use a testing framework like Jest or Mocha.
* **Mock dependencies:** Mock external dependencies to isolate components during testing.
* **Test edge cases:** Test edge cases and error conditions to ensure the component is robust.
* **Use React Testing Library:** Prefer React Testing Library for component testing as it encourages testing from a user perspective, promoting better accessibility and more robust tests.
### Integration Testing
* **Test interactions between components:** Write integration tests to ensure that components are working together correctly.
* **Test API calls:** Test API calls to ensure that data is being fetched and saved correctly.
* **Use a testing framework:** Use a testing framework like Jest or Mocha with libraries like `msw` (Mock Service Worker) to intercept and mock API calls.
### End-to-End Testing
* **Test the entire application:** Write end-to-end tests to ensure that the entire application is working correctly.
* **Use a testing framework:** Use a testing framework like Cypress or Playwright.
* **Test user flows:** Test common user flows to ensure that the application is providing a good user experience.
* **Focus on critical paths:** Prioritize end-to-end tests for critical user flows to ensure application stability.
### Test Organization
* **Co-locate tests with components:** Keep tests in the same directory as the components they are testing.
* **Use a consistent naming convention:** Use a consistent naming convention for test files (e.g., `ComponentName.test.js`).
* **Organize tests by feature:** Organize tests by feature to improve maintainability.
### Mocking and Stubbing
* **Mock external dependencies:** Mock external dependencies to isolate components during testing.
* **Stub API calls:** Stub API calls to prevent network requests during testing.
* **Use a mocking library:** Use a mocking library like Jest's built-in mocking capabilities or `msw`.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes
* **Not understanding server-side rendering:** Failing to utilize SSR effectively can impact SEO and initial load performance.
* **Over-complicating state management:** Using Redux for simple state management needs can add unnecessary complexity.
* **Not optimizing images:** Not using `next/image` can result in large image sizes and slow loading times.
* **Ignoring security best practices:** Neglecting security can lead to vulnerabilities.
* **Not testing the application thoroughly:** Insufficient testing can result in bugs and regressions.
* **Accidentally exposing API keys or secrets in client-side code.**
### Edge Cases
* **Handling errors gracefully:** Implement proper error handling to prevent the application from crashing.
* **Dealing with different screen sizes:** Ensure the application is responsive and works well on different screen sizes.
* **Supporting different browsers:** Test the application in different browsers to ensure compatibility.
* **Managing complex data structures:** Use appropriate data structures and algorithms to efficiently manage complex data.
### Version-Specific Issues
* **Breaking changes:** Be aware of breaking changes when upgrading Next.js versions.
* **Deprecated features:** Avoid using deprecated features.
* **Compatibility with third-party libraries:** Ensure that third-party libraries are compatible with the Next.js version being used.
### Compatibility Concerns
* **Browser compatibility:** Ensure that the application is compatible with the target browsers.
* **Third-party library compatibility:** Ensure that third-party libraries are compatible with Next.js.
### Debugging Strategies
* **Use the browser developer tools:** Use the browser developer tools to inspect the DOM, debug JavaScript, and analyze network requests.
* **Use console.log statements:** Use `console.log` statements to debug code.
* **Use a debugger:** Use a debugger to step through code and inspect variables.
* **Use error logging:** Log errors to a central service to track and analyze issues.
## 7. Tooling and Environment
### Recommended Development Tools
* **VS Code:** Code editor with excellent support for JavaScript, TypeScript, and React.
* **ESLint:** Linter for identifying and fixing code style issues.
* **Prettier:** Code formatter for automatically formatting code.
* **Chrome Developer Tools:** Browser developer tools for debugging and profiling.
* **React Developer Tools:** Browser extension for inspecting React components.
* **Webpack Bundle Analyzer:** Tool for analyzing the size of the Webpack bundle.
### Build Configuration
* **Use environment variables:** Store configuration values in environment variables.
* **Use a build script:** Use a build script to automate the build process.
* **Optimize build settings:** Optimize build settings for production (e.g., enable minification, tree shaking).
### Linting and Formatting
* **Use ESLint with recommended rules:** Configure ESLint with a set of recommended rules for JavaScript and React.
* **Use Prettier for automatic formatting:** Configure Prettier to automatically format code on save.
* **Integrate linting and formatting into the build process:** Integrate linting and formatting into the build process to ensure that code is always consistent.
* **Use a shared configuration:** Ensure that all developers are using the same linting and formatting configuration.
### Deployment
* **Use Vercel for easy deployment:** Vercel is the recommended platform for deploying Next.js applications.
* **Use a CDN for static assets:** Use a CDN to serve static assets from a location that is geographically close to the user.
* **Configure caching:** Configure caching to improve performance and reduce server load.
* **Monitor application health:** Monitor application health to detect and resolve issues quickly.
### CI/CD Integration
* **Use a CI/CD pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process.
* **Run tests in the CI/CD pipeline:** Run tests in the CI/CD pipeline to ensure that code is working correctly before it is deployed.
* **Automate deployments:** Automate deployments to reduce the risk of human error.
+406
View File
@@ -0,0 +1,406 @@
---
description: This rule provides a comprehensive guide to nginx configuration best practices, covering code organization, common patterns, performance, security, testing, pitfalls, and tooling.
globs: **/nginx.conf
---
# nginx Configuration Best Practices
This document outlines best practices for configuring nginx as a web server, reverse proxy, and load balancer. Adhering to these guidelines promotes maintainability, security, and performance.
## 1. Code Organization and Structure
### 1.1 Directory Structure
Maintain a well-organized directory structure to manage configuration files efficiently.
/etc/nginx/
├── nginx.conf # Main nginx configuration file
├── conf.d/ # Site-specific configurations (symlinks preferred)
│ ├── default.conf # Default configuration
│ ├── example.com.conf# Site-specific configuration
│ └── ...
├── snippets/ # Reusable configuration snippets
│ ├── ssl-params.conf # SSL parameters
│ ├── proxy-params.conf # Reverse proxy parameters
│ └── ...
└── modules-enabled/ # Enabled modules (usually managed by package manager)
**Explanation:**
* `/etc/nginx/nginx.conf`: The main configuration file that includes other configurations.
* `/etc/nginx/conf.d/`: Contains site-specific configurations. Symlinking from `/etc/nginx/sites-available/` to `/etc/nginx/sites-enabled/` is a common, more manageable pattern.
* `/etc/nginx/snippets/`: Stores reusable configuration snippets, promoting modularity and reducing duplication.
### 1.2 File Naming Conventions
Adopt consistent file naming conventions for clarity.
* Site-specific configurations: `domain.com.conf` or `application-name.conf`.
* Snippets: `description.conf` (e.g., `ssl-params.conf`, `proxy-params.conf`).
### 1.3 Modular Configuration
Break down complex configurations into smaller, reusable modules (snippets).
**Example: `snippets/ssl-params.conf`**
nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_ecdh_curve prime256v1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
**Usage in site configuration:**
nginx
server {
listen 443 ssl;
server_name example.com;
include snippets/ssl-params.conf;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
location / {
# ...
}
}
### 1.4 Component Architecture
Design your nginx configurations with a clear separation of concerns:
* **Global Settings**: Core directives in `nginx.conf` affecting all virtual hosts.
* **Virtual Host Configuration**: Separate files for each site/application in `conf.d/`.
* **Reusable Blocks**: Snippets for common settings like SSL, reverse proxy configurations, or access control.
### 1.5 Code Splitting
For large and complex configurations, split files by functionality (e.g., routing rules, security policies, caching configurations). Use `include` directives to assemble the complete configuration.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Reverse Proxy**: Forward requests to backend servers. Useful for load balancing, caching, and security.
* **Load Balancer**: Distribute traffic across multiple backend servers for high availability and scalability. Use `upstream` blocks.
* **Static Content Server**: Efficiently serve static files like images, CSS, and JavaScript.
* **Cache**: Reduce latency and server load by caching frequently accessed content.
### 2.2 Recommended Approaches for Common Tasks
* **Serving Static Content:**
nginx
location /static/ {
alias /var/www/example.com/static/;
expires 30d;
access_log off;
}
* **Reverse Proxy to a Backend Server:**
nginx
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
upstream backend_server {
server backend1.example.com;
server backend2.example.com;
}
* **Implementing Basic Authentication:**
nginx
location /protected/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
### 2.3 Anti-patterns and Code Smells
* **Large, Monolithic Configuration Files**: Difficult to manage and debug. Break them into smaller, modular files using `include`.
* **Duplicated Configuration Blocks**: Create snippets to reuse common configurations.
* **Using `if` Statements Excessively**: `if` statements can have performance implications. Prefer using `try_files` or other more efficient directives.
* **Insecure Configuration**: Exposing sensitive information, using weak ciphers, or not implementing proper access controls.
* **Ignoring Error Logs**: Neglecting to monitor and analyze error logs can lead to undetected issues.
### 2.4 State Management
Nginx itself is generally stateless. State management is typically handled by backend applications. However, Nginx Plus offers features like session persistence (sticky sessions) for load balancing.
* **Session Persistence (Nginx Plus):**
nginx
upstream backend {
server backend1.example.com;
server backend2.example.com;
sticky cookie srv_id expires=1h;
}
### 2.5 Error Handling
* **Custom Error Pages**: Configure custom error pages for a better user experience.
nginx
error_page 404 /404.html;
location = /404.html {
root /var/www/example.com/html;
internal;
}
* **Logging**: Use comprehensive logging to capture errors and warnings for troubleshooting.
* **Retry Logic**: Implement retry logic in your application or use Nginx's `proxy_next_upstream` directive to retry failed requests on different backend servers.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Enable Gzip Compression**: Compress text-based responses to reduce bandwidth usage.
nginx
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
* **Enable Caching**: Cache static content and dynamic responses to reduce server load and improve response times. Use `proxy_cache_path` and `proxy_cache` directives.
nginx
proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
location / {
proxy_pass http://backend_server;
proxy_cache my_cache;
proxy_cache_valid 200 302 1h;
proxy_cache_valid 404 10m;
proxy_cache_use_stale error timeout updating invalid_header http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
}
}
* **Tune Worker Processes and Connections**: Adjust `worker_processes` and `worker_connections` based on your server's resources.
nginx
worker_processes auto;
events {
worker_connections 1024;
}
* **HTTP/2 or HTTP/3**: Enable HTTP/2 or HTTP/3 for improved performance.
* **Keep-Alive Connections**: Enable keep-alive connections to reduce latency by reusing existing connections.
nginx
keepalive_timeout 65;
### 3.2 Memory Management
* **Optimize Buffer Sizes**: Tune buffer sizes (e.g., `proxy_buffer_size`, `proxy_buffers`) to match your application's needs and avoid memory fragmentation.
* **Monitor Memory Usage**: Use tools like `top` or `htop` to monitor nginx's memory usage and identify potential memory leaks.
### 3.3 Rendering Optimization (If applicable)
Nginx primarily serves content; rendering optimization is typically handled by the backend application.
* **Content Delivery Network (CDN)**: Offload static content delivery to a CDN.
### 3.4 Bundle Size Optimization (If applicable)
This primarily applies to serving static assets.
* **Minify and Compress**: Minify and compress CSS and JavaScript files before serving them.
* **Use Brotli**: Consider using Brotli compression, which offers better compression ratios than Gzip.
### 3.5 Lazy Loading (If applicable)
This is typically implemented at the application level.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
* **SQL Injection**: Prevent SQL injection by validating and sanitizing user inputs at the application level.
* **Cross-Site Scripting (XSS)**: Implement proper output encoding and use HTTP headers like `X-XSS-Protection` and `Content-Security-Policy`.
nginx
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
* **Clickjacking**: Prevent clickjacking by setting the `X-Frame-Options` header.
nginx
add_header X-Frame-Options "SAMEORIGIN";
* **Buffer Overflow**: Keep Nginx up to date to patch vulnerabilities related to buffer overflows.
* **Denial of Service (DoS)**: Implement rate limiting to prevent DoS attacks.
nginx
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
location / {
limit_req zone=mylimit burst=5 nodelay;
# ...
}
### 4.2 Input Validation
* **Validate User Inputs**: Validate all user inputs at the application level to prevent malicious data from reaching backend servers.
* **Limit Request Size**: Limit the size of incoming requests to prevent buffer overflows and DoS attacks.
nginx
client_max_body_size 2m;
### 4.3 Authentication and Authorization
* **Basic Authentication**: Use basic authentication for simple access control. However, it's not secure over HTTP; always use HTTPS.
* **JWT (JSON Web Tokens)**: Implement JWT-based authentication for APIs.
* **OAuth 2.0**: Use OAuth 2.0 for delegated authorization.
* **Access Control Lists (ACLs)**: Use ACLs to control access to specific resources based on IP addresses or other criteria.
nginx
allow 192.168.1.0/24;
deny all;
### 4.4 Data Protection
* **HTTPS**: Use HTTPS to encrypt all traffic between clients and the server. Obtain and configure SSL/TLS certificates.
* **Secure Storage**: Store sensitive data (e.g., passwords, API keys) securely using encryption and access controls.
### 4.5 Secure API Communication
* **API Keys**: Require API keys for all API requests.
* **Rate Limiting**: Implement rate limiting to prevent abuse and DoS attacks.
* **Input Validation**: Validate all API request parameters.
* **Output Encoding**: Encode API responses to prevent XSS attacks.
## 5. Testing Approaches
### 5.1 Unit Testing
Nginx configuration files are difficult to unit test directly. Unit testing is more relevant for custom Nginx modules written in C.
### 5.2 Integration Testing
* **Test Configuration Syntax**: Use `nginx -t` to test the syntax of your configuration files.
* **Test with Docker**: Use Docker containers to create isolated test environments.
* **Test with Real Traffic**: Use tools like `ab` (Apache Bench) or `wrk` to simulate real traffic and measure performance.
### 5.3 End-to-End Testing
Use tools like Selenium or Cypress to automate end-to-end tests of your application.
### 5.4 Test Organization
* **Separate Test Environment**: Create a separate test environment that mirrors your production environment.
* **Automated Testing**: Automate your testing process using CI/CD pipelines.
### 5.5 Mocking and Stubbing
* **Mock Backend Services**: Mock backend services to isolate your Nginx configuration and test different scenarios.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Incorrect Syntax**: Nginx configuration syntax can be tricky. Always test your configuration files using `nginx -t`.
* **Missing Semicolons**: Forgetting semicolons at the end of directives.
* **Incorrect File Permissions**: Ensure that Nginx has the necessary permissions to read configuration files and access static content.
* **Not Reloading Configuration**: Forgetting to reload Nginx after making changes to the configuration files (e.g., `nginx -s reload`).
* **Using `if` Statements Inappropriately**: Overusing `if` can lead to unexpected behavior and performance issues. Prefer `try_files` or other alternatives.
### 6.2 Edge Cases
* **Handling Large Files**: Tune buffer sizes and timeouts when handling large file uploads or downloads.
* **WebSockets**: Configure Nginx to properly proxy WebSocket connections.
* **Long URIs**: Configure `client_header_buffer_size` and `large_client_header_buffers` to handle long URIs.
### 6.3 Version-Specific Issues
* **Check Release Notes**: Review the release notes for each Nginx version to identify any breaking changes or known issues.
* **Test Upgrades**: Test Nginx upgrades in a staging environment before deploying to production.
### 6.4 Compatibility Concerns
* **Backend Application Compatibility**: Ensure that your Nginx configuration is compatible with the backend applications you are using.
* **TLS Versions and Ciphers**: Choose TLS versions and ciphers that are compatible with your clients and backend servers.
### 6.5 Debugging Strategies
* **Error Logs**: Check Nginx error logs (`/var/log/nginx/error.log`) for errors and warnings.
* **Access Logs**: Analyze Nginx access logs (`/var/log/nginx/access.log`) to understand traffic patterns and identify potential issues.
* **`nginx -t`**: Use `nginx -t` to test the syntax of your configuration files.
* **Verbose Logging**: Enable verbose logging to capture more detailed information about requests and responses.
* **tcpdump/Wireshark**: Use `tcpdump` or Wireshark to capture and analyze network traffic.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **Text Editor**: Use a text editor with syntax highlighting and autocompletion for Nginx configuration files (e.g., VS Code with Nginx configuration extension).
* **Command-Line Tools**: Use command-line tools like `nginx`, `curl`, `ab`, and `tcpdump` for testing and debugging.
* **Docker**: Use Docker for creating isolated test environments.
### 7.2 Build Configuration
* **Version Control**: Store your Nginx configuration files in a version control system (e.g., Git).
* **Configuration Management**: Use configuration management tools like Ansible or Chef to automate the deployment and management of your Nginx configuration.
### 7.3 Linting and Formatting
* **Nginx Linter**: Use an Nginx linter to check your configuration files for syntax errors and best practices violations (e.g., `nginx -t`).
* **Code Formatting**: Use a code formatter to ensure consistent formatting of your configuration files.
### 7.4 Deployment Best Practices
* **Blue-Green Deployment**: Use blue-green deployment to minimize downtime during deployments.
* **Canary Deployment**: Use canary deployment to test new Nginx configurations with a small subset of users before rolling them out to the entire user base.
* **Rollback Strategy**: Have a rollback strategy in place in case of deployment failures.
### 7.5 CI/CD Integration
* **Automated Testing**: Integrate automated testing into your CI/CD pipeline.
* **Configuration Validation**: Validate Nginx configuration files as part of your CI/CD pipeline.
* **Automated Deployment**: Automate the deployment of Nginx configuration files using CI/CD tools like Jenkins, GitLab CI, or CircleCI.
By following these best practices, you can create a robust, secure, and performant Nginx configuration that meets the needs of your web applications.
+304
View File
@@ -0,0 +1,304 @@
---
description: Provides comprehensive guidance on best practices for coding standards, performance, security, and testing in NLTK projects. This rule helps developers write clean, maintainable, and efficient NLP code using NLTK.
globs: **/*.py
---
- Follow these guidelines for consistency and maintainability of your code.
# NLTK Coding Standards and Best Practices
This document outlines coding standards and best practices for developing applications using the Natural Language Toolkit (NLTK) in Python.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
Adopt a clear and logical directory structure to organize your NLTK project. A typical structure might look like this:
my_nltk_project/
├── data/ # Raw data files
├── processed_data/ # Processed data files (e.g., tokenized, stemmed)
├── models/ # Trained models (e.g., sentiment analysis models)
├── scripts/ # Python scripts for data processing, training, etc.
│ ├── __init__.py # Make the scripts directory a Python package
│ ├── data_processing.py
│ ├── model_training.py
│ └── utils.py
├── tests/ # Unit and integration tests
│ ├── __init__.py
│ ├── test_data_processing.py
│ └── test_model_training.py
├── notebooks/ # Jupyter notebooks for experimentation
├── requirements.txt # Project dependencies
├── README.md
└── .gitignore
* `data/`: Stores raw data used for training and analysis. Keep this separate and under version control if the dataset is small. For larger datasets, use DVC (Data Version Control) or similar.
* `processed_data/`: Save intermediate and final processed data here. This avoids recomputing the same steps repeatedly. Consider using Parquet or Feather format for efficient storage and retrieval of processed dataframes.
* `models/`: Stores trained NLTK models. Use a consistent naming convention (e.g., `sentiment_model_v1.pkl`) and consider using a model registry (e.g., MLflow, Weights & Biases) for managing model versions and metadata.
* `scripts/`: Contains reusable Python modules for data processing, model training, and utility functions. Structure this directory into submodules if the project becomes complex.
* `tests/`: Holds unit tests and integration tests to ensure code correctness. Aim for high test coverage.
* `notebooks/`: Jupyter notebooks are useful for exploring data and prototyping code. Keep notebooks clean and well-documented, and consider refactoring useful code into the `scripts/` directory.
* `requirements.txt`: Lists all project dependencies, allowing for easy installation via `pip install -r requirements.txt`. Use `pip freeze > requirements.txt` to generate this file.
### 1.2 File Naming Conventions
Follow consistent file naming conventions to improve readability and maintainability:
* Python scripts: Use snake_case (e.g., `data_processing.py`).
* Data files: Use descriptive names that indicate the contents (e.g., `raw_text_data.csv`, `processed_data.parquet`).
* Model files: Include versioning and relevant information in the name (e.g., `sentiment_model_v1.pkl`).
* Test files: Prefix with `test_` and mirror the naming of the modules they test (e.g., `test_data_processing.py`).
### 1.3 Module Organization Best Practices
Organize your code into logical modules within the `scripts/` directory. Each module should focus on a specific task or set of related functionalities. Here's an example:
python
# scripts/data_processing.py
import nltk
def tokenize_text(text):
# Tokenize text using NLTK
tokens = nltk.word_tokenize(text)
return tokens
def remove_stopwords(tokens):
# Remove stopwords using NLTK
stopwords = nltk.corpus.stopwords.words('english')
filtered_tokens = [token for token in tokens if token.lower() not in stopwords]
return filtered_tokens
# scripts/model_training.py
import nltk
import pickle
def train_sentiment_model(data):
# Train a sentiment analysis model using NLTK
# ...
model = ...
return model
def save_model(model, filepath):
# Save the trained model to a file
with open(filepath, 'wb') as f:
pickle.dump(model, f)
### 1.4 Component Architecture Recommendations
Design your application with a clear component architecture. Consider using a layered architecture:
* **Data Layer:** Handles data loading, cleaning, and preprocessing. Responsible for interacting with data sources (e.g., files, databases, APIs).
* **Processing Layer:** Implements NLP tasks such as tokenization, stemming, lemmatization, POS tagging, and parsing. This layer relies heavily on NLTK functionalities.
* **Model Layer:** Trains and evaluates NLP models. Includes code for feature extraction, model selection, and hyperparameter tuning.
* **Application Layer:** Provides the user interface or API for interacting with the NLP application. Handles user input and presents results.
### 1.5 Code Splitting Strategies
Break down large code files into smaller, more manageable chunks. Use functions, classes, and modules to improve code organization and reusability.
* **Functions:** Encapsulate specific tasks into well-defined functions with clear inputs and outputs. Use docstrings to document function purpose, arguments, and return values.
* **Classes:** Group related data and functions into classes. Use inheritance and polymorphism to create reusable and extensible code. For example, you could create a base `TextProcessor` class and subclasses for different text processing tasks (e.g., `SentimentAnalyzer`, `TopicModeler`).
* **Modules:** Organize code into modules based on functionality. Use relative imports to access modules within the same package.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Strategy Pattern:** Use this pattern to implement different text processing algorithms (e.g., stemming algorithms). Define a common interface for all algorithms and allow the client to choose the desired algorithm at runtime.
* **Factory Pattern:** Use this pattern to create different types of NLTK objects (e.g., different types of tokenizers or stemmers). This promotes loose coupling and makes it easier to switch between different implementations.
* **Observer Pattern:** Use this pattern to notify interested components when data changes (e.g., when a new document is added to a corpus). This can be useful for real-time NLP applications.
### 2.2 Recommended Approaches for Common Tasks
* **Text Preprocessing:** Create a reusable pipeline for text preprocessing. This pipeline should include tokenization, lowercasing, punctuation removal, stopword removal, stemming/lemmatization, and any other necessary steps.
* **Feature Extraction:** Use NLTK's feature extraction capabilities (e.g., bag-of-words, TF-IDF) to convert text data into numerical features suitable for machine learning models.
* **Model Training:** Use scikit-learn or other machine learning libraries in conjunction with NLTK to train and evaluate NLP models. Use cross-validation to estimate model performance and hyperparameter tuning to optimize model parameters.
* **Sentiment Analysis:** Use pre-trained sentiment analysis models (e.g., VADER) or train your own model using NLTK and scikit-learn.
* **Topic Modeling:** Use NLTK and Gensim to perform topic modeling on text data.
### 2.3 Anti-patterns and Code Smells
* **Global Variables:** Avoid using global variables, as they can lead to unexpected side effects and make code difficult to debug. Use dependency injection or other techniques to pass data between components.
* **Hardcoded Values:** Avoid hardcoding values in your code. Use configuration files or environment variables to store configurable parameters.
* **Long Functions:** Avoid writing long, complex functions. Break down large functions into smaller, more manageable chunks.
* **Code Duplication:** Avoid duplicating code. Create reusable functions or classes to encapsulate common functionality.
* **Ignoring Errors:** Don't ignore errors. Implement proper error handling to prevent unexpected crashes and provide informative error messages.
* **Over-commenting/Under-commenting:** Strike a balance. Comments should explain *why* you're doing something, not *what* the code is already clearly showing. Conversely, don't under-comment complex logic.
### 2.4 State Management Best Practices
* **Stateless Functions:** Prefer stateless functions whenever possible. Stateless functions are easier to test and reason about.
* **Immutable Data Structures:** Use immutable data structures whenever possible. Immutable data structures prevent accidental modification of data and make code more robust.
* **Configuration Management:** Use a configuration management library (e.g., `configparser`) to store application settings and parameters. This makes it easier to change settings without modifying code.
### 2.5 Error Handling Patterns
* **Try-Except Blocks:** Use `try-except` blocks to handle potential exceptions. Catch specific exceptions rather than using a generic `except` block. Log exceptions for debugging purposes.
* **Logging:** Use the `logging` module to log events, errors, and warnings. Configure logging levels to control the amount of information that is logged. Use a consistent logging format.
* **Custom Exceptions:** Define custom exceptions for specific error conditions in your application. This makes it easier to handle errors in a consistent and informative way.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Profiling:** Use profiling tools (e.g., `cProfile`) to identify performance bottlenecks in your code.
* **Vectorization:** Use NumPy's vectorized operations to perform calculations on arrays of data. Vectorization is significantly faster than looping over individual elements.
* **Caching:** Use caching to store frequently accessed data and avoid redundant calculations. Use the `functools.lru_cache` decorator for simple caching.
* **Parallelization:** Use multiprocessing or threading to parallelize computationally intensive tasks.
* **Efficient Data Structures:** Choose appropriate data structures for your needs. Use sets for fast membership testing and dictionaries for fast key-value lookups.
* **Lazy Loading:** Defer the loading of large datasets or models until they are actually needed. This can significantly reduce startup time.
### 3.2 Memory Management
* **Generators:** Use generators to process large datasets in chunks. Generators produce data on demand, which reduces memory consumption.
* **Data Type Optimization:** Use the most appropriate data types for your data. For example, use `int8` instead of `int64` if your integers are within the range of `int8`.
* **Garbage Collection:** Be aware of Python's garbage collection mechanism. Avoid creating circular references that can prevent objects from being garbage collected.
* **Del Statements:** Use `del` statements to explicitly release memory when objects are no longer needed.
### 3.3 Rendering Optimization (If Applicable)
NLTK itself doesn't typically involve direct rendering like a UI framework, but visualization of NLTK outputs (e.g., parse trees) might. In such cases, libraries like Matplotlib or Graphviz might be used. Follow their respective optimization guides.
### 3.4 Bundle Size Optimization
This is more relevant for web applications using NLTK in the backend. For such cases:
* **Dependency Management:** Only include the NLTK modules that are actually needed by your application. Avoid importing entire modules if you only need a few functions.
* **Code Minification:** Minify your Python code to reduce its size. This can be done using tools like `pyminify`.
### 3.5 Lazy Loading Strategies
* **Delayed Imports:** Import NLTK modules only when they are needed. This can reduce startup time if your application doesn't use all of NLTK's functionalities.
* **Conditional Loading:** Load different NLTK modules based on the application's configuration. This allows you to only load the modules that are relevant to the current task.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
* **Arbitrary Code Execution:** Be careful when loading data from untrusted sources. Avoid using `eval()` or `pickle.load()` on untrusted data, as these can be exploited to execute arbitrary code. Use safer alternatives such as JSON or CSV.
* **Denial of Service (DoS):** Protect your application from DoS attacks by limiting the size of input data and using appropriate timeouts. Avoid unbounded loops or recursive functions that can consume excessive resources.
* **Regular Expression Denial of Service (ReDoS):** Be careful when using regular expressions, as complex regular expressions can be exploited to cause ReDoS attacks. Use simple and efficient regular expressions, and limit the backtracking depth.
### 4.2 Input Validation
* **Data Type Validation:** Validate the data type of input values to prevent type errors and unexpected behavior.
* **Range Validation:** Validate that input values are within acceptable ranges.
* **Format Validation:** Validate that input data is in the expected format (e.g., using regular expressions).
* **Sanitization:** Sanitize input data to remove potentially harmful characters or code. Use appropriate escaping techniques to prevent injection attacks.
### 4.3 Authentication and Authorization
* **Authentication:** Implement authentication to verify the identity of users. Use strong passwords and multi-factor authentication.
* **Authorization:** Implement authorization to control access to resources. Use role-based access control (RBAC) to assign permissions to users based on their roles.
### 4.4 Data Protection
* **Encryption:** Encrypt sensitive data at rest and in transit. Use strong encryption algorithms and manage keys securely.
* **Data Masking:** Mask sensitive data when displaying it to users. This can prevent unauthorized access to sensitive information.
* **Access Control:** Implement strict access control policies to limit access to sensitive data. Only grant access to users who need it.
### 4.5 Secure API Communication
* **HTTPS:** Use HTTPS to encrypt communication between your application and the API. This prevents eavesdropping and man-in-the-middle attacks.
* **API Keys:** Use API keys to authenticate your application with the API. Protect your API keys and do not embed them in your code.
* **Rate Limiting:** Implement rate limiting to prevent abuse of your API. This can protect your API from DoS attacks.
## 5. Testing Approaches
### 5.1 Unit Testing
* **Test-Driven Development (TDD):** Write unit tests before writing code. This helps you to design your code in a testable way and ensures that your code meets the requirements.
* **Test Coverage:** Aim for high test coverage. Use a test coverage tool to measure the percentage of code that is covered by tests.
* **Assertions:** Use assertions to verify that your code is behaving as expected. Use informative error messages to help you debug your code.
### 5.2 Integration Testing
* **Test Dependencies:** Test the integration of your code with external dependencies (e.g., databases, APIs). Use mock objects or test doubles to isolate your code from external dependencies during unit testing.
* **Test Scenarios:** Test different scenarios to ensure that your code handles different inputs and edge cases correctly.
### 5.3 End-to-End Testing
* **User Interface Testing:** Test the user interface of your application to ensure that it is working as expected. Use automated testing tools to automate UI testing.
* **System Testing:** Test the entire system to ensure that all components are working together correctly.
### 5.4 Test Organization
* **Test Directory:** Create a separate `tests/` directory to store your tests.
* **Test Modules:** Create separate test modules for each module in your application. Use the same naming conventions as your application modules.
* **Test Classes:** Group related tests into test classes. Use descriptive names for your test classes.
* **Test Functions:** Create separate test functions for each test case. Use descriptive names for your test functions.
### 5.5 Mocking and Stubbing
* **Mock Objects:** Use mock objects to replace external dependencies during unit testing. This allows you to isolate your code from external dependencies and test it in a controlled environment.
* **Stubbing:** Use stubbing to replace complex or time-consuming operations with simple or fast operations during testing. This can improve the speed and reliability of your tests.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Incorrect Data Preparation:** Failing to properly clean and prepare data can lead to inaccurate results.
* **Overfitting:** Training a model that is too complex for the data can lead to overfitting. Use regularization techniques and cross-validation to prevent overfitting.
* **Ignoring Rare Words:** Ignoring rare words can lead to a loss of information. Use techniques such as stemming or lemmatization to group related words together.
* **Using Default Parameters:** Relying on default parameters without understanding their implications can lead to unexpected behavior.
* **Not Documenting Code:** Failing to document code makes it difficult to understand and maintain.
### 6.2 Edge Cases
* **Empty Strings:** Handle empty strings gracefully.
* **Special Characters:** Handle special characters correctly.
* **Unicode:** Handle Unicode characters correctly. Use UTF-8 encoding for all text files.
* **Missing Data:** Handle missing data appropriately.
### 6.3 Version-Specific Issues
* **API Changes:** Be aware of API changes between different versions of NLTK. Check the NLTK documentation for migration guides.
* **Dependency Conflicts:** Be aware of potential dependency conflicts between NLTK and other libraries. Use a virtual environment to isolate your project's dependencies.
### 6.4 Compatibility Concerns
* **Python Version:** Ensure that your code is compatible with the desired version of Python.
* **Operating System:** Be aware of potential compatibility issues between different operating systems.
### 6.5 Debugging Strategies
* **Print Statements:** Use `print` statements to debug your code. Print the values of variables and the results of calculations.
* **Debuggers:** Use a debugger to step through your code and inspect the values of variables.
* **Logging:** Use the `logging` module to log events, errors, and warnings. Review the logs to identify the cause of problems.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **IDE:** Use an IDE such as Visual Studio Code, PyCharm, or Spyder. These IDEs provide features such as code completion, debugging, and refactoring.
* **Virtual Environment Manager:** Use a virtual environment manager such as `venv` or `conda` to isolate your project's dependencies.
* **Package Manager:** Use a package manager such as `pip` or `conda` to install and manage your project's dependencies.
* **Version Control System:** Use a version control system such as Git to track changes to your code.
* **Data Version Control (DVC):** For larger datasets that are under version control use DVC.
### 7.2 Build Configuration
* **Makefile:** Use a `Makefile` to automate common tasks such as building, testing, and deploying your application.
* **Setup Script:** Use a `setup.py` script to package your application for distribution.
### 7.3 Linting and Formatting
* **Linting:** Use a linter such as `pylint` or `flake8` to check your code for style errors and potential problems.
* **Formatting:** Use a code formatter such as `black` or `autopep8` to automatically format your code according to a consistent style guide.
### 7.4 Deployment
* **Containerization:** Use containerization technologies such as Docker to package your application and its dependencies into a self-contained unit. This makes it easier to deploy your application to different environments.
* **Cloud Platform:** Deploy your application to a cloud platform such as AWS, Google Cloud, or Azure.
### 7.5 CI/CD Integration
* **Continuous Integration:** Use a continuous integration (CI) system such as Jenkins, Travis CI, or CircleCI to automatically build and test your code whenever changes are pushed to your version control system.
* **Continuous Deployment:** Use a continuous deployment (CD) system to automatically deploy your application to production after it has passed all tests.
By adhering to these coding standards and best practices, you can develop NLTK applications that are clean, maintainable, efficient, and secure.
+316
View File
@@ -0,0 +1,316 @@
---
description: Comprehensive best practices and coding standards for Python projects using the nose2 testing framework. Covers code organization, common patterns, performance, security, testing, and tooling.
globs: **/*test*.py
---
# nose2 Best Practices and Coding Standards
This document provides a comprehensive guide to best practices and coding standards for Python projects using the nose2 testing framework. Following these guidelines will help you write clean, maintainable, and efficient testing code.
## 1. Code Organization and Structure
### 1.1. Directory Structure
- **Dedicated Test Directory:** Maintain a dedicated directory (e.g., `tests/`) at the project root to house all test files. This keeps test code separate from the application code.
- **Mirror Application Structure:** Mirror the structure of your application code within the test directory. For example, if your application has modules in `myapp/module1/` and `myapp/module2/`, create corresponding directories `tests/module1/` and `tests/module2/`.
- **Test Modules:** Each application module should have a corresponding test module. For `myapp/module.py`, the test module should be named `tests/test_module.py` or `tests/module_test.py`
Example:
myproject/
├── myapp/
│ ├── __init__.py
│ ├── module1.py
│ ├── module2.py
│ └── ...
├── tests/
│ ├── __init__.py
│ ├── test_module1.py
│ ├── test_module2.py
│ └── ...
├── ...
### 1.2. File Naming Conventions
- **Test File Prefix:** Name test files with a prefix like `test_` or a suffix `_test` (e.g., `test_module.py` or `module_test.py`). nose2 automatically discovers files that follow this convention.
- **Descriptive Names:** Use descriptive file names that clearly indicate the module or component being tested. For example, `test_user_authentication.py` for tests related to user authentication.
### 1.3. Module Organization
- **Single Responsibility:** Each test module should focus on testing a single application module or a closely related set of functionalities.
- **Test Classes:** Organize tests within a module into test classes. Each class should test a specific aspect or component of the module. Inherit from `unittest.TestCase`.
- **Test Functions/Methods:** Each test case should be a separate function (starting with `test_`) within a test class. These methods should be small, focused, and test a single condition or scenario.
Example:
python
# tests/test_user.py
import unittest
from myapp import user
class TestUser(unittest.TestCase):
def setUp(self):
# Setup code to run before each test
self.user = user.User("testuser", "password")
def tearDown(self):
# Teardown code to run after each test
pass
def test_user_creation(self):
self.assertEqual(self.user.username, "testuser")
self.assertTrue(self.user.check_password("password"))
def test_invalid_password(self):
self.assertFalse(self.user.check_password("wrong_password"))
### 1.4. Component Architecture
- **Isolate Components:** Design your application to isolate components, making them easier to test independently. Use dependency injection or other techniques to decouple modules.
- **Testable Interfaces:** Define clear and testable interfaces between components. This allows you to mock or stub dependencies during testing.
### 1.5. Code Splitting Strategies
- **Functional Decomposition:** Split large test functions into smaller, more manageable functions that focus on specific aspects of the test.
- **Parameterization:** Use parameterized tests (e.g., with `nose2.tools.params`) to test the same code with different inputs and expected outputs. This avoids code duplication and improves test coverage.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Arrange-Act-Assert (AAA):** Follow the AAA pattern in each test: _Arrange_ the test environment (set up data, mock dependencies), _Act_ (execute the code under test), and _Assert_ (verify the expected outcome).
- **Test Fixtures:** Use `setUp` and `tearDown` methods in `unittest.TestCase` to create and clean up test fixtures (e.g., database connections, temporary files) before and after each test.
- **Mocking:** Use mocking libraries like `unittest.mock` or `mock` to replace real dependencies with controlled substitutes during testing. This allows you to isolate the code under test and simulate various scenarios.
### 2.2. Recommended Approaches
- **Test-Driven Development (TDD):** Write tests before writing the application code. This helps you define clear requirements and ensure that the code is testable.
- **Behavior-Driven Development (BDD):** Use BDD frameworks like `behave` to write tests in a human-readable format that describes the expected behavior of the system.
- **Focus on Edge Cases:** Don't only test the happy path. Dedicate tests to verify edge cases, boundary conditions, and error handling.
### 2.3. Anti-patterns and Code Smells
- **Over-testing:** Avoid testing implementation details that are likely to change. Focus on testing the behavior and expected outputs of the code.
- **Fragile Tests:** Tests that break frequently due to minor code changes are fragile. Strive for tests that are resilient to refactoring and implementation changes.
- **Slow Tests:** Slow tests can significantly slow down the development process. Optimize your tests to run quickly. Use techniques like mocking and in-memory databases to speed up testing.
- **Ignoring Test Failures:** Always investigate and fix failing tests. Don't ignore them or disable them without a proper reason.
- **Redundant Assertions:** Avoid having more than one assertion per test case unless absolutely necessary. Multiple assertions make it hard to pinpoint what failed.
### 2.4. State Management
- **Isolate Test State:** Each test should be independent and not rely on the state left by previous tests. Use `setUp` and `tearDown` to ensure a clean state for each test.
- **Avoid Global State:** Minimize the use of global variables or shared state in your application, as they can make tests harder to write and maintain.
### 2.5. Error Handling
- **Test Exception Handling:** Write tests to verify that your code raises the correct exceptions in error scenarios.
- **Use `assertRaises`:** Use `self.assertRaises(ExceptionType, callable, *args, **kwargs)` to assert that a specific exception is raised when calling a function or method.
- **Context Managers for Asserting Exceptions:** Use context managers when checking for exceptions in more complex scenarios.
Example:
python
import unittest
class MyClass:
def divide(self, a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
class TestMyClass(unittest.TestCase):
def setUp(self):
self.my_class = MyClass()
def test_divide_valid(self):
self.assertEqual(self.my_class.divide(10, 2), 5)
def test_divide_by_zero(self):
with self.assertRaises(ValueError) as context:
self.my_class.divide(10, 0)
self.assertEqual(str(context.exception), "Cannot divide by zero")
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Profiling:** Use profiling tools to identify performance bottlenecks in your tests. Optimize the slowest tests first.
- **Mocking Expensive Operations:** Mock out slow operations (e.g., database queries, network requests) during testing to reduce test execution time.
- **Caching Test Data:** Cache frequently used test data to avoid redundant calculations or data retrieval.
### 3.2. Memory Management
- **Clean Up Resources:** Ensure that tests properly clean up any resources they allocate (e.g., files, database connections) to avoid memory leaks.
- **Limit Test Data Size:** Use realistic but minimal test data to reduce memory consumption during testing.
### 3.3. Rendering Optimization (If Applicable)
- This is generally not applicable to `nose2` testing itself, but if testing code involves UI rendering, strategies like reducing render frequency and complexity should be considered.
### 3.4. Bundle Size Optimization (If Applicable)
- This is generally not applicable to `nose2` testing itself.
### 3.5. Lazy Loading
- **Lazy Initialization of Test Data:** Defer the initialization of test data until it is actually needed by a test case. This can reduce test setup time and memory consumption.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
- **Insecure Dependencies:** Use dependency scanning tools to identify and address vulnerabilities in third-party libraries used by your application or tests.
- **Hardcoded Secrets:** Avoid hardcoding secrets (e.g., passwords, API keys) in your tests. Use environment variables or configuration files to store sensitive information.
- **Insufficient Input Validation:** Test that your application properly validates user inputs to prevent injection attacks and other security vulnerabilities.
### 4.2. Input Validation
- **Test Boundary Conditions:** Test that your application handles invalid or unexpected inputs gracefully, including boundary conditions, edge cases, and malicious inputs.
### 4.3. Authentication and Authorization
- **Test Authentication Flows:** Write tests to verify that your application correctly authenticates users and grants access to authorized resources.
- **Role-Based Access Control (RBAC):** If your application uses RBAC, test that users with different roles have the appropriate permissions.
### 4.4. Data Protection
- **Test Data Encryption:** If your application encrypts sensitive data, test that the encryption and decryption processes are working correctly.
- **Secure Storage:** Test that sensitive data is stored securely (e.g., using hashed passwords, encrypted databases).
### 4.5. Secure API Communication
- **Test HTTPS:** If your application communicates with external APIs, test that it uses HTTPS to encrypt the communication.
- **API Key Security:** Protect API keys and other credentials used for API communication. Don't store them directly in the code, and use appropriate access controls.
## 5. Testing Approaches
### 5.1. Unit Testing
- **Focus on Individual Units:** Unit tests should focus on testing individual functions, methods, or classes in isolation.
- **Mock Dependencies:** Use mocking to isolate the unit under test from its dependencies.
- **Test All Code Paths:** Aim for high code coverage by testing all possible code paths and branches.
### 5.2. Integration Testing
- **Test Interactions Between Components:** Integration tests verify that different components of the application work together correctly.
- **Use Real Dependencies (Where Possible):** Unlike unit tests, integration tests should use real dependencies (e.g., databases, external APIs) where feasible, or integration-specific lightweight replacements.
### 5.3. End-to-End (E2E) Testing
- **Test the Entire System:** E2E tests simulate real user scenarios and test the entire application from end to end.
- **Use Automated Testing Tools:** Use automated testing tools like Selenium or Cypress to automate E2E tests.
### 5.4. Test Organization
- **Test Suites:** Use test suites to group related tests together. This makes it easier to run specific sets of tests.
- **Test Runners:** Use test runners (e.g., `nose2`, `pytest`) to discover and execute tests automatically.
### 5.5. Mocking and Stubbing
- **`unittest.mock`:** Use the `unittest.mock` library (or the older `mock` library for Python 2) to create mock objects and stub out dependencies.
- **`patch` Decorator:** Use the `patch` decorator to replace objects or attributes with mock objects during testing.
- **`side_effect`:** Use the `side_effect` attribute of mock objects to simulate different behaviors or raise exceptions when the mock object is called.
Example:
python
import unittest
from unittest.mock import patch
class MyClass:
def get_data(self):
# This method might make an external API call
return "Real data"
def process_data(self):
data = self.get_data()
return data.upper()
class TestMyClass(unittest.TestCase):
@patch('__main__.MyClass.get_data') # Patch the get_data method
def test_process_data(self, mock_get_data):
# Configure the mock to return a specific value
mock_get_data.return_value = "Mock data"
my_class = MyClass()
result = my_class.process_data()
self.assertEqual(result, "MOCK DATA")
mock_get_data.assert_called_once() # Verify that the mock was called
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Not Using `setUp` and `tearDown` Correctly:** Failing to properly set up test conditions or clean up resources after each test can lead to inconsistent test results.
- **Ignoring Dependencies:** Forgetting to mock out dependencies can make tests slow, unreliable, and prone to external factors.
- **Asserting Too Much in One Test:** Trying to test too many things in a single test case makes it difficult to identify the source of failures and maintain the tests.
- **Writing Tests That Are Too Specific:** Writing tests that are tightly coupled to the implementation details can make them brittle and difficult to maintain.
### 6.2. Edge Cases
- **Null Values:** Test how your application handles null or missing values.
- **Empty Collections:** Test how your application handles empty lists, dictionaries, or sets.
- **Large Data Sets:** Test how your application performs with large amounts of data.
- **Special Characters:** Test how your application handles special characters in user inputs.
- **Date and Time Zones:** Test how your application handles different date and time zones.
### 6.3. Version-Specific Issues
- **Python Version Compatibility:** nose2 requires Python 3. Ensure compatibility across different minor versions of Python 3.
- **Dependency Versions:** Be aware of compatibility issues between nose2 and its dependencies. Specify version constraints in your project's requirements file.
### 6.4. Compatibility Concerns
- **`unittest` Compatibility:** nose2 extends `unittest`, so understanding `unittest` is fundamental. Be aware of any differences in behavior between standard `unittest` and nose2.
### 6.5. Debugging Strategies
- **Use a Debugger:** Use a debugger (e.g., `pdb`, `ipdb`) to step through your tests and examine the state of the application.
- **Print Statements:** Use `print` statements to output debugging information to the console.
- **Logging:** Use the `logging` module to record debugging information to a file. This is useful for debugging tests that run in a CI/CD environment.
- **Isolate the Problem:** When a test fails, try to isolate the problem by running the test in isolation or by commenting out parts of the test.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **IDE:** PyCharm, VS Code with Python extension, or other Python-friendly IDE.
- **Text Editor:** Sublime Text, Atom, or other text editor.
- **Debugger:** `pdb` (Python Debugger) or `ipdb` (IPython Debugger).
- **Mocking Library:** `unittest.mock` (built-in) or `mock` (for older Python versions).
### 7.2. Build Configuration
- **`setup.py` or `pyproject.toml`:** Use `setup.py` or `pyproject.toml` to define your project's dependencies and build configuration.
- **`requirements.txt`:** Use `requirements.txt` to list the project's dependencies. Generate this file using `pip freeze > requirements.txt`.
- **Virtual Environments:** Use virtual environments (e.g., `venv`, `virtualenv`) to isolate the project's dependencies from the system's Python environment.
### 7.3. Linting and Formatting
- **Pylint:** Use Pylint to enforce coding standards and detect potential errors in your code. Configure Pylint with a `.pylintrc` file.
- **pycodestyle (formerly pep8):** Use pycodestyle to check your code for compliance with PEP 8.
- **Flake8:** Use Flake8 as a wrapper around pycodestyle, pyflakes, and McCabe complexity checker.
- **Black:** Use Black to automatically format your code according to a consistent style.
- **isort:** Use isort to automatically sort your imports.
### 7.4. Deployment Best Practices
- This is generally out of scope of `nose2` itself, but automated testing as part of the deployment pipeline ensures high quality code.
### 7.5. CI/CD Integration
- **GitHub Actions, GitLab CI, Jenkins:** Integrate nose2 into your CI/CD pipeline to automatically run tests whenever code is pushed or merged.
- **Test Reporting:** Configure your CI/CD system to generate test reports and display test results.
- **Code Coverage Reporting:** Integrate code coverage tools (e.g., `coverage.py`) into your CI/CD pipeline to track code coverage and identify areas that need more testing.
- **Fail Fast:** Configure your CI/CD pipeline to fail immediately if any tests fail. This prevents broken code from being deployed to production.
By following these best practices and coding standards, you can create robust and reliable Python testing code using nose2.
+263
View File
@@ -0,0 +1,263 @@
---
description: This rule provides comprehensive best practices for developing applications using the notion-api library, covering code organization, performance, security, testing, and common pitfalls.
globs: **/*.{js,ts,jsx,tsx}
---
# Notion API Library Best Practices
This document outlines the recommended best practices for developing applications using the `notion-api` library. Following these guidelines will help you create maintainable, performant, secure, and testable Notion integrations.
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
Adopt a clear and consistent directory structure to improve code maintainability and collaboration. Here's a suggested structure for projects using `notion-api`:
project-root/
├── src/
│ ├── components/ # Reusable UI components (if applicable)
│ ├── pages/ # Page-specific components/logic (if applicable)
│ ├── services/ # Notion API interaction logic
│ │ ├── notion-client.js # or notion-client.ts: Initializes the Notion client
│ │ ├── database-service.js # or database-service.ts: Handles database interactions
│ │ ├── page-service.js # or page-service.ts: Handles page interactions
│ │ └── utils.js # or utils.ts: Utility functions for API calls, data formatting
│ ├── models/ # Data models for Notion objects
│ ├── utils/ # General utility functions
│ ├── config/ # Configuration files
│ └── app.js # or app.ts: Main application entry point
├── tests/ # Unit and integration tests
├── .env # Environment variables
├── package.json # Project dependencies
└── README.md # Project documentation
### 1.2. File Naming Conventions
Use descriptive and consistent file names:
* **Components:** `ComponentName.jsx` or `ComponentName.tsx`
* **Services:** `service-name.js` or `service-name.ts`
* **Models:** `model-name.js` or `model-name.ts`
* **Utility functions:** `utility-name.js` or `utility-name.ts`
* **Configuration files:** `config-name.js` or `config-name.ts`
### 1.3. Module Organization
Organize your code into logical modules based on functionality. For `notion-api`, this commonly involves separating:
* **Notion Client Initialization:** A module responsible for initializing the Notion client with your API key. This should handle authentication.
* **Data Access Layer (Services):** Modules that encapsulate all interactions with the Notion API. These modules should provide functions for common operations like creating pages, querying databases, and updating content. Use separate modules for database and page-related operations.
* **Data Models:** Define TypeScript interfaces or JavaScript classes to represent Notion objects (e.g., Page, Database, Block). This improves type safety and code readability.
* **Utility Functions:** Create utility functions for tasks such as formatting data for the Notion API, handling pagination, and error handling.
### 1.4. Component Architecture (If Applicable)
If you're building a UI that interacts with the Notion API, consider using a component-based architecture (e.g., React, Vue, Angular). Separate concerns by creating reusable components for displaying and interacting with Notion data.
### 1.5. Code Splitting
For larger applications, use code splitting to improve initial load times. Lazy-load components and modules that are not immediately needed. This is particularly useful for components that display large amounts of Notion data or perform complex API operations.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Repository Pattern:** Use the repository pattern to abstract data access logic. This makes it easier to switch data sources in the future (e.g., using a mock API for testing).
* **Adapter Pattern:** Adapt the data returned by the Notion API to your application's specific needs. This helps decouple your application from the API's data structure.
* **Singleton Pattern (for Notion Client):** Use the singleton pattern to ensure only one instance of the Notion client is created. This can improve performance and avoid rate limiting issues.
### 2.2. Recommended Approaches for Common Tasks
* **Fetching Data:** Use asynchronous functions (`async/await`) to fetch data from the Notion API. Implement proper error handling (see below).
* **Creating Pages:** Use the `pages.create` method to create new pages. Ensure you provide the required properties for the parent (database or page).
* **Querying Databases:** Use the `databases.query` method to query databases. Learn how to use filters, sorts, and pagination to retrieve the data you need efficiently.
* **Updating Content:** Use the `blocks.update` and `pages.update` method to update content. Understand how to update different types of blocks and page properties.
* **Handling Pagination:** Implement proper pagination to handle large datasets. Use the `has_more` and `next_cursor` properties returned by the API to iterate through all pages of data.
### 2.3. Anti-patterns and Code Smells
* **Directly calling the Notion API in UI components:** This violates separation of concerns and makes testing difficult. Use a service layer to handle API interactions.
* **Hardcoding API keys:** Store API keys in environment variables and never commit them to your repository.
* **Ignoring errors:** Always handle errors and log them appropriately. Do not swallow exceptions.
* **Over-fetching data:** Only request the data you need. Use filters and projections to reduce the amount of data transferred.
* **Creating too many Notion client instances:** Re-use existing client instances to optimize performance and avoid rate limiting.
* **Lack of Pagination:** Neglecting to handle pagination when fetching large datasets from Notion databases.
### 2.4. State Management (If Applicable)
If you're building a UI, choose a state management solution that fits your application's complexity (e.g., React Context, Redux, Zustand). Store Notion data in a normalized format to improve performance and avoid unnecessary re-renders. Use selectors to efficiently retrieve data from the state.
### 2.5. Error Handling Patterns
Implement robust error handling to gracefully handle API errors and unexpected situations.
* **Try-Catch Blocks:** Use `try-catch` blocks to wrap API calls and handle potential errors.
* **Error Logging:** Log errors with sufficient detail to facilitate debugging.
* **User Feedback:** Provide informative error messages to the user.
* **Retry Mechanism:** Implement a retry mechanism for transient errors (e.g., network errors, rate limiting).
* **Centralized Error Handling:** Create a centralized error handling function or middleware to handle errors consistently across your application.
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Caching:** Implement caching to reduce the number of API calls. Cache frequently accessed data in memory or in a persistent store.
* **Batching:** Batch multiple API requests into a single request to reduce network overhead (where supported by the API. Currently, Notion's API offers limited batching capabilities.
* **Minimize Data Transfer:** Only request the data you need. Use filters and projections to reduce the amount of data transferred.
* **Compression:** Enable compression (e.g., gzip) to reduce the size of API responses.
* **Optimize Database Queries:** Carefully design your database queries to retrieve data efficiently. Use indexes to improve query performance.
### 3.2. Memory Management
* **Avoid Memory Leaks:** Be mindful of memory leaks, especially in long-running applications. Release resources when they are no longer needed.
* **Use Efficient Data Structures:** Use efficient data structures to store Notion data. Avoid creating unnecessary copies of data.
### 3.3. Rendering Optimization (If Applicable)
* **Virtualization:** Use virtualization to efficiently render large lists of Notion blocks.
* **Memoization:** Use memoization to avoid re-rendering components that haven't changed.
* **Code Splitting:** As described above.
### 3.4. Bundle Size Optimization
* **Tree Shaking:** Use tree shaking to remove unused code from your bundles.
* **Minification:** Minify your code to reduce bundle size.
* **Code Splitting:** As described above.
* **Use a CDN:** Serve static assets from a CDN to improve loading times.
### 3.5. Lazy Loading
* **Lazy Load Images:** Lazy load images to improve initial load times.
* **Lazy Load Components:** As described above.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and Prevention
* **API Key Exposure:** Never commit API keys to your repository. Store them in environment variables and access them securely.
* **Injection Attacks:** Sanitize user input to prevent injection attacks (e.g., SQL injection, XSS).
* **Cross-Site Scripting (XSS):** If your application renders user-generated content from Notion, sanitize it to prevent XSS attacks.
* **Cross-Site Request Forgery (CSRF):** Implement CSRF protection to prevent malicious websites from making requests on behalf of authenticated users.
* **Man-in-the-Middle Attacks:** Ensure that all communication with the Notion API is encrypted using HTTPS.
### 4.2. Input Validation
* **Validate All User Input:** Validate all user input before sending it to the Notion API. This includes checking data types, formats, and ranges.
* **Sanitize User Input:** Sanitize user input to remove potentially harmful characters.
### 4.3. Authentication and Authorization
* **Use OAuth 2.0:** Use OAuth 2.0 for authentication and authorization. This allows users to grant your application access to their Notion data without sharing their passwords.
* **Store Tokens Securely:** Store access tokens securely. Use encryption or a secure storage mechanism (e.g., Keychain).
* **Follow the Principle of Least Privilege:** Only request the permissions you need.
### 4.4. Data Protection
* **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
* **Follow Data Privacy Regulations:** Comply with all applicable data privacy regulations (e.g., GDPR, CCPA).
* **Regularly Audit Security Practices:** Regularly audit your security practices to identify and address potential vulnerabilities.
### 4.5. Secure API Communication
* **Use HTTPS:** Ensure that all communication with the Notion API is encrypted using HTTPS.
* **Validate SSL Certificates:** Validate SSL certificates to prevent man-in-the-middle attacks.
* **Use a Secure API Client:** Use a secure API client that supports encryption and certificate validation.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Individual Components:** Unit test individual components and modules to ensure they function correctly in isolation.
* **Mock External Dependencies:** Mock external dependencies (e.g., the Notion API) to isolate your code and make tests more predictable.
* **Use a Testing Framework:** Use a testing framework like Jest or Mocha to write and run your unit tests.
### 5.2. Integration Testing
* **Test Interactions Between Components:** Integration test the interactions between different components and modules to ensure they work together correctly.
* **Use a Test Database:** Use a test database to avoid affecting your production data.
* **Seed the Test Database:** Seed the test database with sample data to make tests more realistic.
### 5.3. End-to-End Testing
* **Test the Entire Application Flow:** End-to-end test the entire application flow to ensure that everything works correctly from start to finish.
* **Use a Testing Framework:** Use a testing framework like Cypress or Puppeteer to write and run your end-to-end tests.
* **Run Tests in a CI/CD Pipeline:** Run your tests in a CI/CD pipeline to ensure that changes don't break existing functionality.
### 5.4. Test Organization
* **Create a Dedicated Test Directory:** Create a dedicated test directory to store your tests.
* **Follow a Consistent Naming Convention:** Follow a consistent naming convention for your test files.
* **Organize Tests by Feature:** Organize tests by feature to make them easier to find and maintain.
### 5.5. Mocking and Stubbing
* **Use Mocking Libraries:** Use mocking libraries like Jest or Sinon to create mocks and stubs.
* **Mock the Notion API:** Mock the Notion API to isolate your code and make tests more predictable.
* **Stub API Responses:** Stub API responses to control the data returned by the API.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Not Understanding the Notion API Data Model:** Failing to understand the Notion API data model can lead to incorrect API calls and unexpected results. Study the documentation thoroughly.
* **Misunderstanding Rate Limits:** Exceeding rate limits can lead to temporary blocking. Implement proper rate limiting handling and retry mechanisms.
* **Improperly Handling Errors:** Ignoring errors can lead to silent failures and difficult debugging. Always handle errors and log them appropriately.
* **Not Using Pagination:** Failing to use pagination can lead to incomplete data retrieval. Implement proper pagination to handle large datasets.
### 6.2. Edge Cases
* **Empty Databases:** Handle the case where a database is empty or doesn't contain the expected properties.
* **Deleted Pages:** Handle the case where a page has been deleted or moved.
* **Permission Errors:** Handle the case where the application doesn't have the required permissions to access a page or database.
* **API Downtime:** Handle the case where the Notion API is temporarily unavailable.
### 6.3. Version-Specific Issues
* **Breaking Changes:** Be aware of breaking changes in new versions of the Notion API. Test your application thoroughly after upgrading.
* **Deprecated Features:** Avoid using deprecated features, as they may be removed in future versions.
### 6.4. Compatibility Concerns
* **Library Conflicts:** Be aware of potential library conflicts between `notion-api` and other libraries in your project.
* **Browser Compatibility:** Ensure that your application is compatible with the target browsers.
### 6.5. Debugging Strategies
* **Use Debugging Tools:** Use debugging tools to inspect your code and identify errors.
* **Log API Requests and Responses:** Log API requests and responses to help diagnose issues.
* **Use a Network Monitor:** Use a network monitor to inspect network traffic and identify performance bottlenecks.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **IDE:** Visual Studio Code, IntelliJ IDEA, or WebStorm
* **Node.js:** A JavaScript runtime environment
* **npm or Yarn:** Package managers
* **Git:** Version control system
* **Postman or Insomnia:** API testing tools
### 7.2. Build Configuration
* **Use a Build Tool:** Use a build tool like Webpack or Parcel to bundle your code.
* **Configure Environment Variables:** Configure environment variables to store API keys and other sensitive information.
* **Use a .gitignore File:** Use a `.gitignore` file to exclude sensitive files from your repository.
### 7.3. Linting and Formatting
* **Use a Linter:** Use a linter like ESLint or JSHint to enforce coding standards.
* **Use a Formatter:** Use a formatter like Prettier to automatically format your code.
* **Configure CI/CD:** Configure CI/CD to automatically lint and format your code.
### 7.4. Deployment
* **Choose a Deployment Platform:** Choose a deployment platform that fits your application's needs (e.g., Vercel, Netlify, AWS).
* **Configure Environment Variables:** Configure environment variables on your deployment platform to store API keys and other sensitive information.
* **Monitor Your Application:** Monitor your application to identify and address performance issues and errors.
### 7.5. CI/CD Integration
* **Use a CI/CD Platform:** Use a CI/CD platform like GitHub Actions or GitLab CI/CD to automate your build, test, and deployment processes.
* **Run Tests in CI/CD:** Run your tests in your CI/CD pipeline to ensure that changes don't break existing functionality.
* **Automate Deployment:** Automate deployment to reduce the risk of human error.
+299
View File
@@ -0,0 +1,299 @@
---
description: This rule provides comprehensive best practices and coding standards for the Numba library, covering code organization, performance optimization, security, testing, and common pitfalls. It aims to help developers write efficient, maintainable, and secure Numba code.
globs: **/*.py
---
# Numba Best Practices and Coding Standards
This document outlines best practices and coding standards for the Numba library to help developers write efficient, maintainable, and secure code.
## Library Information:
- Name: numba
- Tags: ai, ml, gpu-computing, python, jit-compiler
## 1. Code Organization and Structure
### 1.1. Directory Structure
- **`src/`:** Contains the main source code. Subdivide into modules or packages based on functionality (e.g., `src/core`, `src/cuda`, `src/npyimpl`).
- **`tests/`:** Contains unit, integration, and end-to-end tests. Mirror the `src/` structure to easily locate corresponding tests.
- **`examples/`:** Provides example scripts and notebooks demonstrating how to use numba features.
- **`docs/`:** Stores documentation in reStructuredText or Markdown format.
- **`benchmarks/`:** Contains benchmark scripts for performance evaluation.
- **`scripts/`:** Utilities and helper scripts for development, testing, or deployment.
- **`.cursor/rules/`:** Store custom rules for AI-assisted code generation (e.g., this file).
Example:
my_project/
├── src/
│ ├── __init__.py
│ ├── core/
│ │ ├── __init__.py
│ │ ├── functions.py
│ │ ├── types.py
│ ├── cuda/
│ │ ├── __init__.py
│ │ ├── kernels.py
│ │ ├── device.py
│ ├── npyimpl/
│ │ ├── __init__.py
│ │ ├── array_methods.py
│ │ ├── reductions.py
├── tests/
│ ├── __init__.py
│ ├── core/
│ │ ├── test_functions.py
│ │ ├── test_types.py
│ ├── cuda/
│ │ ├── test_kernels.py
│ │ ├── test_device.py
│ ├── npyimpl/
│ │ ├── test_array_methods.py
│ │ ├── test_reductions.py
├── examples/
│ ├── mandelbrot.py
│ ├── gaussian_blur.ipynb
├── docs/
│ ├── source/
│ │ ├── conf.py
│ │ ├── index.rst
│ ├── Makefile
├── benchmarks/
│ ├── bench_matmul.py
├── scripts/
│ ├── build_extensions.py
├── .cursor/
│ ├── rules/
│ │ ├── numba_rules.mdc
├── setup.py
├── README.md
├── LICENSE
### 1.2. File Naming Conventions
- Python files: Use descriptive lowercase names with underscores (e.g., `array_methods.py`, `type_inference.py`).
- Test files: Prefix with `test_` and mirror the module/file being tested (e.g., `test_array_methods.py`).
- Class names: Use PascalCase (e.g., `NumbaTypeManager`, `CUDADeviceContext`).
- Function and variable names: Use lowercase with underscores (e.g., `jit_compile`, `input_array`).
- Constants: Use uppercase with underscores (e.g., `DEFAULT_NUM_THREADS`, `MAX_ARRAY_SIZE`).
### 1.3. Module Organization
- Group related functionality into modules. For example, put all type-related code in a `types` module.
- Use `__init__.py` files to define packages and control namespace imports.
- Keep modules focused and avoid large, monolithic modules.
- Use relative imports within packages (e.g., `from . import functions`).
### 1.4. Component Architecture
- Design with clear separation of concerns (e.g., type inference, code generation, runtime execution).
- Employ interfaces or abstract base classes for loose coupling between components.
- Use dependency injection to manage component dependencies.
- Favor composition over inheritance to promote code reuse and flexibility.
### 1.5. Code Splitting
- Break down large functions into smaller, more manageable functions.
- Group related functions into classes or modules.
- Use decorators to add functionality without modifying the original code (e.g., `@jit`, `@vectorize`).
- Extract common code into reusable utility functions.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
- **Decorator Pattern:** Used extensively in Numba via the `@jit`, `@njit`, `@vectorize`, and `@cuda.jit` decorators for applying transformations and optimizations to functions.
- **Factory Pattern:** Can be used to create different types of compiled functions based on runtime conditions or configurations.
- **Strategy Pattern:** Employ different compilation strategies based on target architecture or optimization level.
### 2.2. Recommended Approaches
- **Use `@njit` whenever possible:** This enforces no-python mode, maximizing performance. Only fall back to `@jit` if no-python mode is not feasible.
- **Explicitly specify types:** When possible, define input and output types using Numba's type system for increased performance and type safety.
- **Utilize `prange` for parallel loops:** When using `parallel=True`, use `numba.prange` instead of `range` for loops that can be executed in parallel.
- **Minimize data transfer between CPU and GPU:** When using CUDA, keep data on the GPU as much as possible and pre-allocate output arrays.
- **Use structured array when possible:** When working with complex data, leverage the power of structured arrays to improve data access times and readability.
### 2.3. Anti-patterns
- **Relying on object mode:** Object mode is significantly slower than no-python mode. Avoid it by ensuring your code is compatible with no-python mode.
- **Excessive use of global variables:** Global variables can hinder type inference and optimization. Pass data as function arguments instead.
- **Unnecessary data copying:** Avoid copying data between CPU and GPU or within memory unless absolutely necessary.
- **Ignoring profiling results:** Don't guess where performance bottlenecks are. Use profiling tools to identify and address them.
- **Using Python data structures like dictionaries and lists directly inside `@njit` decorated code:** These data structures usually trigger object mode and hinder performance. Opt for `typed-list` and `typed-dict` when possible.
### 2.4. State Management
- Avoid mutable global state within Numba-compiled functions. Mutating global state can lead to unpredictable behavior and make debugging difficult.
- If state needs to be maintained, consider using a class with methods decorated with `@njit` to encapsulate the state and operations.
- When working with CUDA, manage device memory explicitly to avoid memory leaks and ensure efficient resource utilization.
### 2.5. Error Handling
- Use `try...except` blocks to handle potential exceptions within Numba-compiled functions.
- Propagate errors gracefully and provide informative error messages.
- Consider using Numba's error reporting mechanisms for custom error handling.
- Handle CUDA errors properly when working with GPU code.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Just-In-Time (JIT) Compilation:** Leverage `@jit` and `@njit` decorators for automatic code optimization.
- **Vectorization:** Utilize `@vectorize` decorator for element-wise operations on arrays.
- **Parallelization:** Employ `parallel=True` and `prange` for parallel loop execution on multi-core CPUs.
- **CUDA Acceleration:** Use `@cuda.jit` decorator to compile and execute code on NVIDIA GPUs.
- **`fastmath`:** Use `fastmath=True` when strict IEEE 754 compliance is not required to enable aggressive optimizations.
- **Loop Unrolling:** Manually unroll loops to reduce loop overhead when appropriate.
- **Memory Alignment:** Ensure data is properly aligned in memory for efficient access.
- **Kernel Fusion:** Combine multiple operations into a single kernel to reduce memory access and improve performance.
- **Use Intel SVML:** If possible, install and use the Intel Short Vector Math Library (SVML) for optimized transcendental functions.
### 3.2. Memory Management
- **Minimize data transfer between CPU and GPU:** Keep data on the GPU as much as possible.
- **Pre-allocate output arrays:** Use `cuda.device_array` or `np.empty` to pre-allocate memory.
- **Use CUDA Device Arrays:** Operate directly on device arrays to avoid implicit data transfers.
- **Use `del` keyword to free unused arrays:** Use the `del` keyword to release large arrays or variables and free up memory after they're no longer needed.
### 3.3. Bundle Size Optimization
- Numba itself doesn't directly impact front-end bundle sizes (as it operates on the backend Python code). However, minimizing dependencies and using efficient numerical algorithms can indirectly reduce the overall application size.
### 3.4. Lazy Loading
- Numba JIT compilation performs lazy loading by default. Functions are compiled only when they are first called.
- This can be beneficial for large applications where not all functions need to be compiled immediately.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
- **Code Injection:** Avoid using `eval()` or `exec()` with user-supplied input, as this can lead to arbitrary code execution.
- **Integer Overflow:** Be mindful of potential integer overflows when performing arithmetic operations.
- **Buffer Overflow:** Prevent buffer overflows by validating array dimensions and sizes before performing operations.
- **Denial of Service (DoS):** Limit resource usage (e.g., memory, CPU time) to prevent DoS attacks.
### 4.2. Input Validation
- Validate all user-supplied input before passing it to Numba-compiled functions.
- Check data types, ranges, and sizes to prevent unexpected behavior or errors.
- Sanitize input to remove potentially malicious characters or code.
### 4.3. Data Protection
- Avoid storing sensitive data in plain text. Encrypt sensitive data at rest and in transit.
- Implement access controls to restrict access to sensitive data to authorized users only.
### 4.4. Secure API Communication
- Use HTTPS for all API communication to encrypt data in transit.
- Implement authentication and authorization mechanisms to verify the identity of clients and restrict access to resources.
- Protect against Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) attacks.
## 5. Testing Approaches
### 5.1. Unit Testing
- Write unit tests for individual functions and classes to verify their correctness.
- Use the `unittest` or `pytest` frameworks for writing and running tests.
- Mock external dependencies to isolate the code being tested.
- Test different input values and edge cases to ensure robustness.
### 5.2. Integration Testing
- Write integration tests to verify the interaction between different components or modules.
- Test the integration between Numba-compiled functions and other parts of the application.
- Use realistic test data to simulate real-world scenarios.
### 5.3. End-to-End Testing
- Write end-to-end tests to verify the overall functionality of the application.
- Test the entire workflow from user input to output to ensure that all components are working correctly.
- Use automated testing tools to run tests regularly.
### 5.4. Test Organization
- Organize tests in a directory structure that mirrors the source code.
- Use descriptive test names to indicate the functionality being tested.
- Write clear and concise test cases that are easy to understand and maintain.
### 5.5. Mocking and Stubbing
- Use mocking and stubbing to replace external dependencies with controlled substitutes during testing.
- This allows you to isolate the code being tested and simulate different scenarios.
- Use libraries like `unittest.mock` or `pytest-mock` for mocking and stubbing.
- Make sure mocks respect type constraints used within the tested code.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
- **Incorrect data types:** Numba relies on type inference, so providing incorrect data types can lead to unexpected results or errors. Explicitly specify types when possible.
- **Unsupported Python features:** Numba does not support all Python features. Be aware of the limitations and use supported alternatives.
- **Not using no-python mode:** Forgetting to use `@njit` or `nopython=True` can result in significantly slower performance due to object mode compilation.
- **Ignoring performance profiling:** Failing to profile your code can lead to inefficient optimizations or missed opportunities for performance improvements.
- **Over-optimizing too early:** Focus on writing correct and readable code first, then optimize only when necessary.
- **Incompatible NumPy versions:** Make sure you are using a compatible NumPy version that Numba supports.
### 6.2. Edge Cases
- **Division by zero:** Handle potential division by zero errors gracefully.
- **NaN and Inf values:** Be aware of how NaN and Inf values can propagate through calculations.
- **Large arrays:** Be mindful of memory usage when working with large arrays, especially on GPUs.
- **Multithreading issues:** When using `parallel=True`, be aware of potential race conditions and data synchronization issues.
### 6.3. Version-Specific Issues
- Consult the Numba documentation and release notes for any version-specific issues or compatibility concerns.
- Pay attention to deprecation warnings and update your code accordingly.
### 6.4. Compatibility Concerns
- Ensure compatibility between Numba and other libraries you are using, such as NumPy, SciPy, and CUDA.
- Be aware of potential conflicts between different versions of these libraries.
### 6.5. Debugging Strategies
- Use the `print()` function or a debugger to inspect variables and execution flow.
- Check the Numba documentation and community forums for troubleshooting tips.
- Use the `numba.errors.DEBUG` environment variable to enable debug output from Numba.
- Use `numba --sysinfo` to get details about your system for inclusion in bug reports or when seeking help.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **IDE:** VS Code with the Python extension, PyCharm, or Jupyter Notebook.
- **Profiler:** `cProfile` or `line_profiler` for identifying performance bottlenecks.
- **Debugger:** `pdb` or an IDE-integrated debugger for stepping through code and inspecting variables.
- **Linter:** `flake8` or `pylint` for enforcing code style and identifying potential errors.
- **Formatter:** `black` or `autopep8` for automatically formatting code according to PEP 8.
### 7.2. Build Configuration
- Use `setup.py` or `pyproject.toml` for managing project dependencies and build configuration.
- Specify Numba as a dependency in your project's configuration file.
- Consider using a virtual environment (e.g., `venv` or `conda`) to isolate project dependencies.
### 7.3. Linting and Formatting
- Use `flake8` or `pylint` to enforce code style and identify potential errors.
- Configure the linter to check for Numba-specific best practices, such as using `@njit` whenever possible.
- Use `black` or `autopep8` to automatically format code according to PEP 8.
### 7.4. Deployment Best Practices
- Package your application and its dependencies into a self-contained executable or container.
- Use a deployment platform that supports Numba and its dependencies (e.g., AWS Lambda, Google Cloud Functions, Docker).
- Optimize your application for the target deployment environment.
### 7.5. CI/CD Integration
- Integrate Numba into your Continuous Integration/Continuous Delivery (CI/CD) pipeline.
- Run unit tests, integration tests, and end-to-end tests automatically on every commit.
- Use a CI/CD tool like GitHub Actions, GitLab CI, or Jenkins to automate the build, test, and deployment process.
- Perform performance testing as part of the CI/CD pipeline to detect regressions.
+271
View File
@@ -0,0 +1,271 @@
---
description: This rule provides best practices for using NumPy in Python, covering coding standards, performance optimization, security, and testing strategies to enhance code quality and maintainability.
globs: **/*.py
---
# NumPy Library Best Practices and Coding Standards
This document outlines best practices for using the NumPy library in Python for scientific computing, data science, machine learning, and AI development. Adhering to these guidelines will improve code readability, maintainability, performance, security, and overall project success.
## 1. Code Organization and Structure
### 1.1. Directory Structure
* **`root_directory/`**: The project's root directory.
* **`data/`**: Stores datasets (e.g., CSV files, NumPy arrays in `.npy` format). Consider using subdirectories within `data/` to categorize datasets (e.g., `raw/`, `processed/`). Use version control (e.g., DVC) for larger datasets.
* **`notebooks/`**: Jupyter notebooks for exploration, prototyping, and EDA. Number notebooks sequentially (e.g., `01_data_loading.ipynb`, `02_feature_engineering.ipynb`). Keep notebooks clean and well-documented; move reusable code to modules.
* **`src/`** (or `package_name/`): Contains the Python source code.
* **`package_name/`**: The main package directory. Use your project's name as the package name.
* **`__init__.py`**: Marks the directory as a Python package. Can be empty or contain package-level initialization code.
* **`utils/`**: Utility functions and helper classes. Split into submodules if necessary (e.g., `utils/data_handling.py`, `utils/math_functions.py`).
* **`models/`**: Model definitions and training scripts (if applicable). Subdirectories can organize models further (e.g., `models/regression/`, `models/classification/`).
* **`preprocessing/`**: Data preprocessing functions and classes.
* **`visualization/`**: Functions for creating plots and visualizations.
* **`config.py`**: Configuration settings (e.g., file paths, hyperparameters). Use a library like `python-box` or `dynaconf` to manage configurations.
* **`main.py`**: The main entry point for the application (if applicable). Use `if __name__ == "__main__":` to control execution.
* **`tests/`**: Unit and integration tests. Mirror the `src/` structure. Use `pytest` or `unittest`.
* **`tests/utils/`**: Tests for the `utils/` module.
* **`tests/models/`**: Tests for the `models/` module.
* **`conftest.py`**: Configuration file for `pytest`. Can contain fixtures and hooks.
* **`docs/`**: Documentation for the project (e.g., using Sphinx).
* **`scripts/`**: Scripts for data downloading, processing, or model deployment.
* **`requirements.txt`**: Lists Python dependencies. Use `pip freeze > requirements.txt` to generate.
* **`.gitignore`**: Specifies files and directories to ignore in Git (e.g., `data/`, `notebooks/`, `__pycache__/`).
* **`README.md`**: Provides a high-level overview of the project.
* **`LICENSE`**: Specifies the license for the project.
* **`setup.py`** or **`pyproject.toml`**: Used for packaging and distribution.
### 1.2. File Naming Conventions
* **Python files**: Use lowercase with underscores (snake_case): `data_loader.py`, `feature_engineering.py`.
* **Class names**: Use CamelCase: `DataLoader`, `FeatureEngineer`.
* **Function and variable names**: Use snake_case: `load_data()`, `feature_names`.
* **Constants**: Use uppercase with underscores: `MAX_ITERATIONS`, `DEFAULT_LEARNING_RATE`.
### 1.3. Module Organization
* **Separate concerns**: Each module should have a single, well-defined purpose.
* **Avoid circular dependencies**: Design modules to minimize dependencies on each other.
* **Use relative imports**: Within a package, use relative imports to refer to other modules: `from . import utils`, `from ..models import BaseModel`.
* **Expose a clear API**: Each module should have a well-defined API (Application Programming Interface) of functions and classes that are intended for external use. Hide internal implementation details using leading underscores (e.g., `_helper_function()`).
### 1.4. Component Architecture
* **Layered architecture**: Divide the application into layers (e.g., data access, business logic, presentation) to promote separation of concerns.
* **Microservices**: For larger applications, consider breaking them down into smaller, independent microservices.
* **Design patterns**: Implement relevant design patterns to enhance flexibility and maintainability.
### 1.5. Code Splitting
* **Functions**: Break down large functions into smaller, more manageable functions.
* **Classes**: Use classes to encapsulate related data and behavior.
* **Modules**: Split code into multiple modules based on functionality.
* **Packages**: Organize modules into packages to create a hierarchical structure.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns
* **Strategy**: Use a Strategy pattern to encapsulate different algorithms or approaches for a specific task.
* **Factory**: Employ a Factory pattern to create objects without specifying their concrete classes.
* **Observer**: Use an Observer pattern to notify dependent objects when the state of an object changes.
### 2.2. Recommended Approaches
* **Vectorization**: Leverage NumPy's vectorized operations whenever possible to avoid explicit loops. Vectorization significantly improves performance.
* **Broadcasting**: Understand and utilize NumPy's broadcasting rules to perform operations on arrays with different shapes.
* **Ufuncs (Universal Functions)**: Use NumPy's built-in ufuncs (e.g., `np.sin`, `np.exp`, `np.add`) for element-wise operations. Ufuncs are highly optimized.
* **Masking**: Use boolean masks to select and modify specific elements in arrays.
* **Views vs. Copies**: Be aware of the difference between views and copies when slicing and manipulating arrays. Modifying a view affects the original array.
### 2.3. Anti-patterns and Code Smells
* **Explicit loops**: Avoid explicit loops for element-wise operations. Use vectorized operations instead.
* **Unnecessary copies**: Avoid creating unnecessary copies of arrays. Use views when possible.
* **Modifying arrays in place**: Be careful when modifying arrays in place, as it can lead to unexpected side effects.
* **Ignoring broadcasting rules**: Not understanding broadcasting rules can lead to incorrect results or errors.
* **Hardcoding array shapes**: Avoid hardcoding array shapes. Use `array.shape` to get the shape dynamically.
* **Relying on mutable default arguments**: Avoid using mutable default arguments (e.g., lists, dictionaries) in function definitions.
### 2.4. State Management
* **Immutable data structures**: When appropriate, use immutable data structures to prevent accidental modification of data. Consider libraries like `namedtuple` or `dataclasses` (with `frozen=True`).
* **Encapsulation**: Encapsulate state within classes to control access and modification.
* **Dependency injection**: Use dependency injection to decouple components and make them more testable.
### 2.5. Error Handling
* **Exceptions**: Use exceptions to handle errors and unexpected conditions. Raise specific exceptions (e.g., `ValueError`, `TypeError`) when appropriate.
* **Assertions**: Use assertions to check for conditions that should always be true. Assertions are helpful for debugging and validating data.
* **Logging**: Use logging to record errors, warnings, and informational messages. Configure logging to write to a file or stream.
* **`np.errstate`**: Use `np.errstate` context manager to handle floating-point exceptions (e.g., division by zero, overflow). You can configure how NumPy handles these exceptions (e.g., ignore, warn, raise).
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Vectorization**: As mentioned earlier, prioritize vectorized operations over explicit loops.
* **Memory Alignment**: NumPy arrays are typically aligned in memory, which can improve performance. Ensure that your data is aligned correctly.
* **Data Types**: Choose the smallest possible data type that can represent your data. Using smaller data types reduces memory usage and improves performance. For example, use `np.int8` instead of `np.int64` if the values are within the range of `np.int8`.
* **`np.einsum`**: Use `np.einsum` (Einstein summation) for complex array operations. `np.einsum` can often be more efficient than explicit loops or other NumPy functions.
* **Numba**: Use Numba to JIT (Just-In-Time) compile NumPy code. Numba can significantly improve the performance of computationally intensive code.
* **Cython**: Use Cython to write NumPy code in C. Cython allows you to take advantage of C's performance while still using Python's syntax.
* **BLAS/LAPACK**: NumPy relies on BLAS (Basic Linear Algebra Subprograms) and LAPACK (Linear Algebra Package) libraries for linear algebra operations. Ensure that you are using an optimized BLAS/LAPACK implementation (e.g., OpenBLAS, MKL).
* **`np.fft`**: For FFT (Fast Fourier Transform) operations, use the functions provided in NumPy's `np.fft` module. They're usually highly optimized.
### 3.2. Memory Management
* **Avoid creating large temporary arrays**: Minimize the creation of large temporary arrays, especially within loops. Use in-place operations when possible.
* **`np.empty`**: Use `np.empty` to create uninitialized arrays when you don't need to initialize the values immediately. This can be faster than `np.zeros` or `np.ones`.
* **`np.memmap`**: Use `np.memmap` to create memory-mapped arrays. Memory-mapped arrays allow you to work with large datasets that don't fit in memory.
* **Garbage collection**: Be mindful of Python's garbage collection. Explicitly delete large arrays when they are no longer needed to free up memory: `del my_array`.
### 3.3. Rendering Optimization (If Applicable)
* This is mainly relevant when NumPy arrays are used for image processing or other visualization tasks. Libraries like Matplotlib, Seaborn, or specialized rendering engines may offer specific optimizations for handling NumPy arrays.
### 3.4. Bundle Size Optimization (If Applicable)
* If you are deploying a web application or other application that includes NumPy, consider using tree shaking to remove unused code. Tools like Webpack or Parcel can help with tree shaking.
### 3.5. Lazy Loading
* If you are working with very large datasets, use lazy loading to load data only when it is needed. Libraries like Dask or Apache Arrow can help with lazy loading.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Arbitrary code execution**: Avoid using `np.fromstring` or `np.frombuffer` with untrusted input, as this can lead to arbitrary code execution.
* **Denial of service**: Be careful when using NumPy functions with user-supplied input, as this can lead to denial-of-service attacks. Validate input to prevent excessively large array allocations or computationally intensive operations.
* **Integer overflow**: Be aware of integer overflow issues when performing arithmetic operations on large arrays. Use appropriate data types to prevent overflow.
### 4.2. Input Validation
* **Data type validation**: Ensure that the input data has the expected data type.
* **Shape validation**: Ensure that the input data has the expected shape.
* **Range validation**: Ensure that the input data falls within the expected range.
* **Sanitize input**: Sanitize input data to prevent injection attacks.
* **Use `np.asarray`**: When receiving data from external sources, use `np.asarray` to convert it to a NumPy array. This ensures that you are working with a NumPy array and not some other type of object that might have unexpected behavior.
### 4.3. Authentication and Authorization (If Applicable)
* NumPy itself doesn't handle authentication or authorization. If your application requires these features, use appropriate authentication and authorization mechanisms (e.g., OAuth, JWT).
### 4.4. Data Protection
* **Encryption**: Encrypt sensitive data at rest and in transit.
* **Access control**: Restrict access to data based on user roles and permissions.
* **Data masking**: Mask sensitive data to protect it from unauthorized access.
* **Regular Security Audits**: Conduct regular security audits to identify and address potential vulnerabilities.
### 4.5. Secure API Communication (If Applicable)
* Use HTTPS for all API communication.
* Validate all API requests.
* Use rate limiting to prevent denial-of-service attacks.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test individual functions and classes**: Unit tests should focus on testing individual functions and classes in isolation.
* **Use `pytest` or `unittest`**: Use a testing framework like `pytest` or `unittest` to write and run unit tests.
* **Test edge cases**: Test edge cases and boundary conditions to ensure that your code handles them correctly.
* **Test for exceptions**: Test that your code raises the correct exceptions when errors occur.
* **Use parametrization**: Use parametrization to run the same test with multiple sets of inputs.
* **Assert almost equal**: Use `np.testing.assert_allclose` instead of `assert a == b` when comparing floating-point numbers. This accounts for potential floating-point precision errors.
### 5.2. Integration Testing
* **Test interactions between components**: Integration tests should focus on testing the interactions between different components of your application.
* **Use mock objects**: Use mock objects to isolate components during integration testing.
### 5.3. End-to-End Testing (If Applicable)
* **Test the entire application flow**: End-to-end tests should focus on testing the entire application flow from start to finish.
### 5.4. Test Organization
* **Mirror the source code structure**: Organize your tests in a directory structure that mirrors the source code structure.
* **Use descriptive test names**: Use descriptive test names that clearly indicate what the test is testing.
* **Keep tests small and focused**: Keep tests small and focused to make them easier to understand and maintain.
### 5.5. Mocking and Stubbing
* **Use mock objects to isolate components**: Use mock objects to isolate components during testing.
* **Use `unittest.mock` or `pytest-mock`**: Use a mocking library like `unittest.mock` or `pytest-mock` to create mock objects.
* **Mock external dependencies**: Mock external dependencies (e.g., databases, APIs) to avoid relying on them during testing.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Incorrect array indexing**: NumPy uses 0-based indexing, which can be confusing for developers who are used to other languages.
* **Incorrect array slicing**: Be careful when slicing arrays, as this can create views or copies depending on the slicing operation.
* **Incorrect broadcasting**: Not understanding broadcasting rules can lead to incorrect results or errors.
* **Modifying views**: Modifying a view affects the original array, which can lead to unexpected side effects.
* **Ignoring data types**: Not specifying the correct data type can lead to integer overflow or other issues.
### 6.2. Edge Cases
* **Empty arrays**: Be careful when working with empty arrays, as they can have unexpected behavior.
* **Arrays with NaN or Inf values**: Be aware that arrays can contain NaN (Not a Number) or Inf (Infinity) values, which can affect calculations.
* **Arrays with mixed data types**: NumPy arrays should typically have a single data type. Be cautious when working with arrays that have mixed data types (e.g., object arrays).
### 6.3. Version-Specific Issues
* Consult the NumPy release notes for information on version-specific issues and changes.
### 6.4. Compatibility Concerns
* **Python version**: Ensure that your code is compatible with the Python version you are using.
* **Other libraries**: Be aware of compatibility issues between NumPy and other libraries.
* **Operating system**: Be aware of potential differences in behavior across different operating systems.
### 6.5. Debugging Strategies
* **Print statements**: Use print statements to inspect the values of variables and arrays.
* **Debuggers**: Use a debugger (e.g., pdb, ipdb) to step through your code and inspect the state of the program.
* **Logging**: Use logging to record errors, warnings, and informational messages.
* **`np.seterr`**: Use `np.seterr` to configure how NumPy handles floating-point exceptions.
* **`np.info`**: Use `np.info` to get information about NumPy objects.
* **Visual Inspection**: Use visualization tools (Matplotlib, Seaborn, etc.) to visually inspect data and identify potential problems.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
* **IDE**: Use an IDE (Integrated Development Environment) like VS Code, PyCharm, or Spyder.
* **Jupyter Notebook**: Use Jupyter Notebook for exploration, prototyping, and EDA.
* **IPython**: Use IPython for interactive computing.
* **Debugging Tools**: Utilize debuggers like pdb or IDE-integrated debuggers for stepping through code and inspecting variables.
### 7.2. Build Configuration
* **`setup.py` or `pyproject.toml`**: Use `setup.py` or `pyproject.toml` to configure the build process.
* **`requirements.txt`**: Use `requirements.txt` to specify dependencies.
* **Virtual environments**: Use virtual environments to isolate dependencies.
* **Conda**: Consider using Conda for environment and package management, particularly for scientific computing workflows.
### 7.3. Linting and Formatting
* **PEP 8**: Follow PEP 8 style guidelines for Python code.
* **Linters**: Use a linter (e.g., pylint, flake8) to check for style violations and potential errors.
* **Formatters**: Use a formatter (e.g., black, autopep8) to automatically format your code.
* **Pre-commit hooks**: Use pre-commit hooks to run linters and formatters before committing code.
### 7.4. Deployment
* **Containerization (Docker)**: Use Docker to create a containerized environment for your application. This helps ensure consistency across different environments.
* **Cloud platforms**: Deploy your application to a cloud platform (e.g., AWS, Azure, GCP).
* **Serverless functions**: Consider using serverless functions (e.g., AWS Lambda, Azure Functions, Google Cloud Functions) for simple applications.
* **Model serving frameworks**: If deploying machine learning models, use a model serving framework like TensorFlow Serving or TorchServe.
### 7.5. CI/CD Integration
* **Continuous Integration (CI)**: Use a CI system (e.g., Jenkins, Travis CI, CircleCI, GitHub Actions) to automatically build and test your code when changes are made.
* **Continuous Delivery (CD)**: Use a CD system to automatically deploy your code to production after it has been tested.
* **Automated Testing**: Integrate automated tests into your CI/CD pipeline to ensure code quality and prevent regressions.
* **Infrastructure as Code (IaC)**: Define your infrastructure using code (e.g., Terraform, CloudFormation) to automate the provisioning and management of your environment.
By following these best practices, you can write high-quality, maintainable, and performant NumPy code.
+246
View File
@@ -0,0 +1,246 @@
---
description: Comprehensive best practices and coding standards for projects using the openai library, covering code structure, performance, security, and common pitfalls.
globs: **/*.py
---
# openai Library Best Practices and Coding Standards
This document outlines best practices and coding standards for developing applications using the `openai` library. Following these guidelines will lead to more maintainable, performant, and secure code.
## Library Information:
- Name: openai
- Tags: ai, ml, llm, api
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
Adopt a clear and consistent directory structure to improve code organization and maintainability. Here's a recommended structure for projects using the openai library:
project_root/
├── src/ # Source code directory
│ ├── models/ # Definitions for your models (e.g., data classes, schemas)
│ ├── services/ # Service layer for interacting with the OpenAI API
│ │ ├── openai_service.py # Encapsulates OpenAI API calls
│ ├── utils/ # Utility functions
│ ├── main.py # Entry point of your application
├── tests/ # Tests directory
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ ├── conftest.py # Pytest configuration file
├── data/ # Data storage (e.g., prompts, training data)
├── docs/ # Documentation
├── .env # Environment variables
├── requirements.txt # Dependencies
├── README.md # Project README
### 1.2 File Naming Conventions
- Use descriptive and consistent file names.
- Python files should use snake_case (e.g., `openai_service.py`).
- Class names should use CamelCase (e.g., `OpenAIService`).
- Variable names should use snake_case (e.g., `api_key`).
### 1.3 Module Organization
- Group related functionalities into modules.
- Avoid circular dependencies between modules.
- Use clear and concise module names.
- Use `__init__.py` files to define packages and control namespace.
### 1.4 Component Architecture
Consider using a layered architecture to separate concerns:
- **Presentation Layer:** Handles user interface or external API interactions.
- **Service Layer:** Encapsulates business logic and interacts with the OpenAI API.
- **Data Access Layer:** Handles data persistence and retrieval.
This separation makes testing and maintenance easier.
### 1.5 Code Splitting Strategies
- Split large files into smaller, more manageable modules based on functionality.
- Use abstract base classes and interfaces to define contracts between components.
- Apply the Single Responsibility Principle (SRP) to classes and functions.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
- **Factory Pattern:** Use a factory to create OpenAI API client instances with different configurations.
- **Strategy Pattern:** Implement different prompt strategies based on the task.
- **Decorator Pattern:** Add logging, caching, or rate limiting to OpenAI API calls.
### 2.2 Recommended Approaches
- **Prompt Engineering:** Follow best practices for prompt design. Place clear instructions at the beginning of prompts, be specific, and use examples.
- **Configuration:** Store API keys and other sensitive information in environment variables using a library like `python-dotenv`.
- **Asynchronous Calls:** Use `asyncio` and `aiohttp` for non-blocking API calls to improve performance.
- **Retries and Exponential Backoff:** Implement retry mechanisms with exponential backoff to handle transient API errors.
### 2.3 Anti-patterns
- **Hardcoding API Keys:** Never hardcode API keys directly into your code. Always use environment variables.
- **Ignoring Rate Limits:** Implement rate limiting to avoid exceeding OpenAI API limits.
- **Lack of Error Handling:** Always handle API errors gracefully and provide informative error messages.
- **Overly Complex Prompts:** Keep prompts simple and focused. Break down complex tasks into smaller steps.
- **Mixing Concerns:** Avoid mixing presentation, business logic, and data access in the same component.
### 2.4 State Management
- Use appropriate data structures to manage the state of your OpenAI interactions.
- Consider using a state management library if your application has complex state requirements.
- Avoid storing sensitive information in application state.
### 2.5 Error Handling
- Use `try-except` blocks to catch potential exceptions.
- Log errors with sufficient context for debugging.
- Implement custom exception classes for specific error conditions.
- Handle rate limit errors and implement retry logic.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Caching:** Cache API responses to reduce the number of API calls.
- **Batching:** Batch multiple API requests into a single request when possible.
- **Asynchronous Operations:** Use asynchronous programming to avoid blocking the main thread.
- **Token Optimization:** Reduce the number of tokens in your prompts to lower costs and improve response times.
### 3.2 Memory Management
- Be mindful of the size of your prompts and responses, especially when working with large language models.
- Use generators to process large datasets in chunks.
- Clean up resources (e.g., file handles, network connections) promptly.
### 3.3 Rendering Optimization (If Applicable)
- If your application involves rendering OpenAI-generated content, optimize the rendering process to minimize latency.
### 3.4 Bundle Size Optimization (If Applicable)
- For web applications, minimize bundle size by using tree shaking and code splitting.
### 3.5 Lazy Loading
- Use lazy loading to load modules or data only when they are needed.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
- **API Key Exposure:** Protect your OpenAI API key. Never commit it to version control or share it publicly.
- **Prompt Injection:** Validate and sanitize user inputs to prevent prompt injection attacks.
- **Data Leakage:** Avoid exposing sensitive data in prompts or API responses.
### 4.2 Input Validation
- Validate all user inputs to prevent malicious or unexpected data from being sent to the OpenAI API.
- Sanitize inputs to remove potentially harmful characters or code.
### 4.3 Authentication and Authorization
- Implement authentication and authorization mechanisms to protect your application and data.
- Use secure storage for API keys and other sensitive information.
### 4.4 Data Protection
- Encrypt sensitive data at rest and in transit.
- Follow data privacy regulations (e.g., GDPR, CCPA).
### 4.5 Secure API Communication
- Use HTTPS to encrypt communication with the OpenAI API.
- Verify the authenticity of the OpenAI API server using SSL certificates.
## 5. Testing Approaches
### 5.1 Unit Testing
- Write unit tests for individual components to ensure they function correctly in isolation.
- Use mocking and stubbing to isolate components from external dependencies (e.g., the OpenAI API).
### 5.2 Integration Testing
- Write integration tests to verify that different components work together correctly.
- Test the interaction between your application and the OpenAI API.
### 5.3 End-to-End Testing
- Write end-to-end tests to simulate user interactions and verify that the entire application works as expected.
### 5.4 Test Organization
- Organize your tests into a clear and consistent directory structure.
- Use descriptive test names.
- Follow a consistent testing style.
### 5.5 Mocking and Stubbing
- Use mocking libraries like `unittest.mock` or `pytest-mock` to mock the OpenAI API.
- Create stubs for API responses to control the behavior of the API during testing.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Not handling API errors:** Implement proper error handling for OpenAI API calls.
- **Exceeding rate limits:** Implement rate limiting and exponential backoff to avoid exceeding API limits.
- **Incorrect prompt formatting:** Follow OpenAI's prompt engineering guidelines to optimize model performance.
- **Not validating inputs:** Validate user inputs to prevent prompt injection attacks and unexpected behavior.
### 6.2 Edge Cases
- **Handling very long prompts:** Be aware of token limits and consider splitting long prompts into smaller chunks.
- **Dealing with ambiguous or unclear instructions:** Craft prompts carefully to provide clear and specific instructions.
- **Handling unexpected API responses:** Implement robust error handling to deal with unexpected API responses.
### 6.3 Version-Specific Issues
- Be aware of changes between different versions of the `openai` library.
- Consult the release notes and migration guides when upgrading to a new version.
### 6.4 Compatibility Concerns
- Ensure compatibility between the `openai` library and other libraries used in your project.
- Test your application thoroughly after upgrading any dependencies.
### 6.5 Debugging Strategies
- Use logging to track the flow of your application and identify potential issues.
- Use a debugger to step through your code and inspect variables.
- Use unit tests to isolate and debug individual components.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE:** VS Code, PyCharm
- **Virtual Environment Manager:** venv, conda, pipenv
- **Package Manager:** pip, poetry
- **Testing Framework:** pytest, unittest
- **Linting and Formatting:** pylint, flake8, black
### 7.2 Build Configuration
- Use a `requirements.txt` or `pyproject.toml` file to manage dependencies.
- Use a build system like `setuptools` or `poetry` to package your application.
### 7.3 Linting and Formatting
- Use a linter like `pylint` or `flake8` to enforce coding style guidelines.
- Use a formatter like `black` to automatically format your code.
### 7.4 Deployment Best Practices
- Use a containerization technology like Docker to package your application and its dependencies.
- Deploy your application to a cloud platform like AWS, Azure, or Google Cloud.
- Use a process manager like `systemd` or `supervisor` to manage your application.
### 7.5 CI/CD Integration
- Use a CI/CD pipeline to automate the build, test, and deployment process.
- Integrate your tests into the CI/CD pipeline to ensure that all changes are thoroughly tested before being deployed.
+199
View File
@@ -0,0 +1,199 @@
---
description: This rule outlines best practices for developing with the opencv-python library, focusing on code organization, performance, security, testing, and common pitfalls. It provides comprehensive guidelines for efficient and maintainable opencv-python projects.
globs: **/*.py
---
- Always use UV or Pipenv when installing dependencies for consistent environments.
- Always specify Python 3.10 or higher, as older versions may lack feature parity and security updates.
- Use type hints extensively for improved code readability and maintainability.
# Library Information:
- Name: opencv-python
- Tags: python, image-processing, computer-vision, opencv
## 1. Code Organization and Structure
- **Directory Structure:**
-
project_root/
├── data/ # Store image, video, and other data files.
├── src/ # Source code directory.
│ ├── modules/ # Reusable modules and utility functions.
│ │ ├── image_processing/ # Specific image processing functions.
│ │ │ ├── __init__.py
│ │ │ ├── filters.py # Implement filters as functions or classes
│ │ │ ├── transforms.py # Implement image transforms as functions or classes
│ │ ├── utils.py # Utility functions for data loading, etc.
│ ├── main.py # Entry point of your application.
├── tests/ # Test suite.
│ ├── unit/ # Unit tests for individual components.
│ ├── integration/ # Integration tests for combined components.
├── models/ # Saved model files
├── notebooks/ # Jupyter notebooks for experimentation.
├── requirements.txt # Project dependencies.
├── pyproject.toml # Project metadata and build configuration.
└── README.md # Project documentation.
- **File Naming Conventions:**
- Use descriptive and consistent naming.
- `module_name.py` (e.g., `image_utils.py`, `feature_extraction.py`).
- Class names: `PascalCase` (e.g., `ImageProcessor`, `FeatureDetector`).
- Function names: `snake_case` (e.g., `load_image`, `apply_filter`).
- **Module Organization:**
- Group related functions and classes into modules within the `src/modules/` directory.
- Use `__init__.py` files to make directories packages.
- Employ clear and concise module names.
- **Component Architecture:**
- Follow a layered architecture:
- **Data Access Layer:** Handles image loading, saving, and data source interactions.
- **Processing Layer:** Implements image processing algorithms and feature extraction.
- **Application Layer:** Orchestrates the processing and presents the results.
- **Code Splitting:**
- Decompose complex functions into smaller, well-defined units.
- Create separate modules for distinct functionalities (e.g., filtering, feature detection, object tracking).
- Utilize classes to encapsulate related state and behavior.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Strategy Pattern:** To swap image processing algorithms at runtime.
- **Factory Pattern:** To create different image processing objects based on configuration.
- **Observer Pattern:** To notify subscribers of image processing events.
- **Recommended Approaches:**
- **Image Loading:** Use `cv2.imread()` for loading images. Handle potential file errors gracefully.
- **Image Display:** Use `cv2.imshow()` for displaying images, and remember to call `cv2.waitKey()` to prevent freezing.
- **Video Processing:** Use `cv2.VideoCapture()` to capture video from a file or camera.
- **Iterating Pixels:** Access pixel values directly using NumPy array indexing for performance. Avoid slow Python loops when possible.
- **Anti-patterns and Code Smells:**
- **Deeply Nested Loops:** Indicate inefficient pixel-level operations. Consider vectorization using NumPy.
- **Global Variables:** Lead to unpredictable state. Encapsulate state within classes.
- **Hardcoded Paths:** Make code inflexible. Use relative paths and configurable settings.
- **Ignoring Errors:** Can lead to unexpected crashes. Implement robust error handling.
- **State Management:**
- Encapsulate state within classes.
- Minimize mutable state; favor immutable data structures where appropriate.
- Use dependency injection to manage external dependencies.
- **Error Handling:**
- Use `try...except` blocks to handle potential exceptions (e.g., file not found, invalid image format).
- Log errors for debugging and monitoring.
- Raise exceptions to propagate errors up the call stack.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Vectorization:** Use NumPy's vectorized operations instead of loops for faster processing.
- **Pre-allocation:** Pre-allocate NumPy arrays instead of repeatedly resizing them.
- **Caching:** Cache frequently accessed data (e.g., lookup tables) to avoid recalculation.
- **Multiprocessing/Multithreading:** Use `multiprocessing` or `threading` to parallelize independent image processing tasks.
- **Cython:** Implement performance-critical sections in Cython for C-like speeds.
- **GPU Acceleration:** Leverage OpenCV's CUDA module for GPU-accelerated processing (if applicable).
- **Memory Management:**
- Release unused memory by explicitly deleting large arrays or objects.
- Be mindful of memory copies. Use `view()` or `ascontiguousarray()` to avoid unnecessary copies.
- Use generators to process large images in chunks.
- **Rendering Optimization:**
- Minimize the number of draw calls.
- Use efficient drawing functions (e.g., `cv2.polylines()` instead of individual `cv2.line()` calls).
- **Bundle Size Optimization:**
- Not directly applicable to opencv-python. For applications that use opencv-python, dependencies should be managed effectively.
- **Lazy Loading:**
- Load images only when needed.
- Use lazy initialization for computationally expensive objects.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- **Denial of Service (DoS):** Prevent processing extremely large or malformed images that can consume excessive resources.
- **Code Injection:** Avoid executing arbitrary code based on user input (e.g., constructing file paths dynamically without proper sanitization).
- **Buffer Overflows:** Check image dimensions and data types to prevent buffer overflows when accessing pixel data directly.
- **Input Validation:**
- Validate image file extensions and formats.
- Check image dimensions and data types.
- Sanitize filenames to prevent path traversal attacks.
- **Authentication and Authorization:**
- Not typically applicable to core opencv-python functionality. These are relevant for applications leveraging opencv-python for tasks like facial recognition or video surveillance, requiring access control mechanisms.
- **Data Protection:**
- Encrypt sensitive image data at rest and in transit (if applicable).
- Implement access control mechanisms to restrict access to sensitive image data.
- Anonymize or redact personally identifiable information (PII) from images.
- **Secure API Communication:**
- Enforce HTTPS for all API communication.
- Use secure authentication mechanisms (e.g., API keys, OAuth).
- Validate all API requests and responses.
## 5. Testing Approaches
- **Unit Testing:**
- Test individual functions and classes in isolation.
- Use mocking to isolate components from external dependencies (e.g., file system, camera).
- Test edge cases and boundary conditions.
- Use libraries like `pytest` and `unittest`.
- **Integration Testing:**
- Test the interaction between different components.
- Verify that data flows correctly between modules.
- Use realistic test data.
- **End-to-End Testing:**
- Test the entire application workflow.
- Simulate user interactions.
- Verify that the application meets the requirements.
- **Test Organization:**
- Structure tests to mirror the source code organization.
- Use descriptive test names.
- Keep tests concise and focused.
- **Mocking and Stubbing:**
- Use `unittest.mock` or `pytest-mock` to create mock objects for external dependencies.
- Stub out functions that perform I/O operations or interact with hardware.
## 6. Common Pitfalls and Gotchas
- **BGR vs. RGB:** Be aware that OpenCV uses BGR color format by default, while other libraries (e.g., Matplotlib, PIL) use RGB. Convert between formats using `cv2.cvtColor()`.
- **Image Data Types:** Understand the different image data types (e.g., `uint8`, `float32`) and their implications for processing.
- **Memory Layout:** Be aware of the memory layout of NumPy arrays and use `ascontiguousarray()` when necessary.
- **`cv2.waitKey()`:** Remember to call `cv2.waitKey()` after `cv2.imshow()` to display the image and allow the window to respond to events. A value of 0 will wait indefinitely for a key press.
- **Incorrect File Paths:** Double-check file paths when loading images or videos.
- **Version Compatibility:** Be aware of compatibility issues between different versions of opencv-python.
- **Global Interpreter Lock (GIL):** Understand the implications of the GIL for multithreading in Python. Use multiprocessing for CPU-bound tasks.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **IDE:** VS Code, PyCharm, Jupyter Notebook.
- **Virtual Environment:** `venv`, `conda`.
- **Package Manager:** `pip`, `uv`.
- **Build Configuration:**
- Use `pyproject.toml` for project metadata and build configuration.
- Specify dependencies in `requirements.txt` or `pyproject.toml`.
- Use a build system like `setuptools` or `poetry`.
- **Linting and Formatting:**
- Use `flake8` for linting.
- Use `black` for formatting.
- Configure your IDE to automatically format code on save.
- **Deployment:**
- Containerize your application using Docker.
- Use a deployment platform like AWS, Azure, or Google Cloud.
- **CI/CD:**
- Integrate with a CI/CD system like Jenkins, GitLab CI, or GitHub Actions.
- Automate testing, linting, and deployment.
+243
View File
@@ -0,0 +1,243 @@
---
description: Comprehensive best practices for using pdoc to generate and maintain Python project documentation. Covers code structure, performance, security, testing, and tooling to ensure high-quality documentation and maintainable projects.
globs: **/*.py
---
# pdoc Best Practices: A Comprehensive Guide
This document outlines best practices for using `pdoc` to generate API documentation for Python projects. It covers code organization, performance considerations, security, testing, and common pitfalls, all tailored for effective documentation generation and maintainability.
## Library Information:
- Name: pdoc
- Tags: development, documentation, python, auto-generation
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
- **Clear Module Grouping:** Organize your code into logical modules and sub-packages. This makes it easier for `pdoc` to generate a navigable API.
- **`__init__.py` Files:** Ensure that each package directory contains an `__init__.py` file. This file can be empty, or it can contain initialization code and, importantly, the package-level docstring which `pdoc` will use.
- **Separate Concerns:** Isolate different functionalities into separate modules. For example, separate data models, business logic, and utility functions into distinct files.
Example:
my_project/
├── my_package/
│ ├── __init__.py # Package-level docstring here
│ ├── module_a.py # Contains functions and classes
│ ├── module_b.py # Contains more functions and classes
│ └── subpackage/
│ ├── __init__.py # Subpackage-level docstring here
│ └── module_c.py # Contains functions and classes
└── setup.py # Installation script
### 1.2 File Naming Conventions
- **Descriptive Names:** Use descriptive names for modules and packages. For example, `database_utils.py` is much better than `db.py`.
- **Lowercase with Underscores:** Follow the standard Python convention of using lowercase letters with underscores for module names (e.g., `my_module.py`).
### 1.3 Module Organization
- **Top-Level Docstrings:** Every module should have a top-level docstring that describes its purpose and lists the main classes, functions, and exceptions it defines.
- **`__all__` Variable:** Use the `__all__` variable to explicitly define the public API of a module. This tells `pdoc` (and other tools) which names should be included in the generated documentation.
Example:
python
# my_module.py
"""This module provides utility functions for data processing.
Classes:
DataProcessor: Processes data.
Functions:
clean_data: Cleans the data.
"""
__all__ = ['DataProcessor', 'clean_data']
class DataProcessor:
"""Processes data from various sources."""
...
def clean_data(data):
"""Cleans the input data."""
...
### 1.4 Component Architecture
- **Loose Coupling:** Design your components to be loosely coupled. This means that components should have minimal dependencies on each other.
- **Clear Interfaces:** Define clear interfaces for your components. This makes it easier to test and document your code.
- **Abstraction:** Use abstraction to hide the implementation details of your components. This makes your code more flexible and easier to maintain.
### 1.5 Code Splitting
- **Divide and Conquer:** Split large modules into smaller, more manageable files. This makes your code easier to understand and maintain.
- **By Functionality:** Split code based on functionality. For example, if you have a module that contains both database access code and business logic, split it into two separate modules.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
- **Factory Pattern:** Use the factory pattern to create objects. This makes it easier to switch between different implementations of a class.
- **Strategy Pattern:** Use the strategy pattern to encapsulate different algorithms. This makes it easier to switch between different algorithms at runtime.
- **Decorator Pattern:** Use the decorator pattern to add functionality to objects dynamically.
### 2.2 Recommended Approaches
- **Use Docstrings:** All modules, classes, functions, and methods must include docstrings. Docstrings are used by `pdoc` to create the API documentation.
- **Follow PEP 257:** Adhere to PEP 257 for docstring conventions. This ensures consistency and readability.
- **Choose a Style:** Consistently use a docstring style (Google, NumPy, reStructuredText) throughout your project.
- **Include Examples:** Provide simple, executable examples in your docstrings. This helps users understand how to use your code. These examples can be embedded directly within docstrings using the `doctest` module.
### 2.3 Anti-patterns
- **Missing Docstrings:** Failing to document modules, classes, functions, or methods.
- **Incomplete Docstrings:** Providing docstrings that are too brief or lack essential information.
- **Inconsistent Style:** Mixing different docstring styles within the same project.
- **Redundant Documentation:** Repeating information that is already clear from the code itself. Focus on the *why* rather than the *how*.
- **Ignoring `__all__`:** Not defining `__all__` or defining it incorrectly can lead to undocumented or wrongly documented API surfaces.
### 2.4 State Management
- **Minimize Global State:** Avoid using global variables as much as possible. If you must use global variables, document them clearly.
- **Use Classes to Encapsulate State:** Use classes to encapsulate state. This makes it easier to manage and reason about your code.
### 2.5 Error Handling
- **Raise Exceptions:** Raise exceptions when errors occur. This makes it easier to handle errors gracefully.
- **Use Try-Except Blocks:** Use try-except blocks to catch exceptions. This prevents your program from crashing when errors occur.
- **Document Exceptions:** Document the exceptions that your functions and methods can raise.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Profiling:** Use a profiler to identify performance bottlenecks in your code.
- **Caching:** Use caching to store frequently accessed data. Consider using `functools.lru_cache` for memoization.
- **Vectorization:** Use vectorized operations when working with numerical data. This is often faster than using loops.
### 3.2 Memory Management
- **Avoid Memory Leaks:** Be careful to avoid memory leaks. Free up memory when it is no longer needed.
- **Use Generators:** Use generators to process large amounts of data. This can reduce memory usage.
- **Use Data Structures Efficiently:** Use the right data structures for the job. For example, use sets for membership testing and dictionaries for lookups.
### 3.3 Rendering Optimization
- Not generally applicable to `pdoc` itself, as it mainly generates static HTML. However, the design of your code *can* affect how quickly `pdoc` can process it. Well-structured, easily-introspected code will be processed faster.
### 3.4 Bundle Size
- Not applicable to `pdoc` itself, as it is a documentation generator and not a web application framework.
### 3.5 Lazy Loading
- Not directly applicable to `pdoc`, but consider lazy loading modules within your own code to improve startup time if you have a large project that `pdoc` needs to process. This is done using `importlib.import_module`.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
- **Not Directly Applicable:** `pdoc` generates static documentation and does not execute arbitrary user-supplied code. Therefore, it is less vulnerable than many other types of applications. However, be mindful of the dependencies you use and keep them up to date.
### 4.2 Input Validation
- **Not Directly Applicable:** `pdoc` does not take direct user input.
### 4.3 Authentication and Authorization
- **Not Applicable:** `pdoc` is a documentation generation tool and does not require authentication or authorization.
### 4.4 Data Protection
- **Not Applicable:** `pdoc` does not handle sensitive data.
### 4.5 Secure API Communication
- **Not Applicable:** `pdoc` does not communicate with external APIs.
## 5. Testing Approaches
### 5.1 Unit Testing
- **Test Docstrings:** Use `doctest` to test examples embedded in your docstrings. This ensures that your examples are up-to-date and correct. `pdoc` renders these examples, making them executable directly from the documentation.
- **Focus on Public API:** Write unit tests for the public API of your modules, classes, and functions.
### 5.2 Integration Testing
- **Test Interactions:** Test the interactions between different components of your system.
### 5.3 End-to-End Testing
- **Test Complete Workflows:** Test complete workflows to ensure that your system is working correctly.
### 5.4 Test Organization
- **Separate Test Files:** Keep your tests in separate files from your code. This makes it easier to find and run your tests.
- **Organize by Module:** Organize your tests by module. This makes it easier to find the tests for a specific module.
### 5.5 Mocking and Stubbing
- **Use Mock Objects:** Use mock objects to isolate the code that you are testing from its dependencies. This makes it easier to test your code in isolation.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Incorrect Docstring Formatting:** Using the wrong docstring format or inconsistent formatting.
- **Omitting Parameters:** Failing to document all parameters of a function or method.
- **Not Updating Documentation:** Failing to update the documentation when the code changes.
- **Circular Imports:** Circular imports can confuse `pdoc`. Refactor your code to avoid them.
### 6.2 Edge Cases
- **Dynamic Code Generation:** If your code heavily uses dynamic code generation (`eval`, `exec`), `pdoc` may have difficulty introspecting it.
- **Metaclasses:** Complex metaclasses can also make it harder for `pdoc` to generate accurate documentation.
### 6.3 Version-Specific Issues
- **Check Compatibility:** Always check the compatibility of `pdoc` with your Python version. Refer to the official `pdoc` documentation for version-specific information.
### 6.4 Compatibility Concerns
- **Third-Party Libraries:** Ensure that `pdoc` is compatible with any third-party libraries that you are using.
### 6.5 Debugging Strategies
- **Verbose Mode:** Run `pdoc` in verbose mode to see more detailed output. This can help you identify errors.
- **Check for Errors:** Check the output of `pdoc` for any errors or warnings.
- **Inspect Generated HTML:** Inspect the generated HTML to see if the documentation looks correct.
## 7. Tooling and Environment
### 7.1 Recommended Tools
- **IDE:** Use a good IDE (e.g., VS Code, PyCharm) with Python support.
- **Linting:** Use a linter (e.g., pylint, flake8) to catch errors and enforce coding standards.
- **Formatting:** Use a code formatter (e.g., black, autopep8) to format your code.
### 7.2 Build Configuration
- **`setup.py` or `pyproject.toml`:** Use a `setup.py` file or `pyproject.toml` to define your project's dependencies and metadata.
- **Include Documentation Files:** Make sure to include documentation files in your build configuration.
### 7.3 Linting and Formatting
- **Consistent Style:** Enforce a consistent coding style using a linter and code formatter.
- **Follow PEP 8:** Follow the PEP 8 style guide for Python code.
- **Use Docstring Checks:** Configure your linter to check for missing or incomplete docstrings.
### 7.4 Deployment Best Practices
- **Generate Documentation Automatically:** Automate the generation of documentation as part of your build process.
- **Host Documentation:** Host the generated documentation on a web server or documentation hosting service (e.g., Read the Docs).
### 7.5 CI/CD Integration
- **Integrate with CI/CD:** Integrate `pdoc` with your CI/CD pipeline to automatically generate and deploy documentation on every commit.
By following these best practices, you can ensure that your Python projects have high-quality, well-maintained documentation that is easy for users to understand and use.

Some files were not shown because too many files have changed in this diff Show More