mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,292 @@
|
||||
---
|
||||
description: This rule provides a comprehensive set of best practices and coding standards for developing with the Cloudflare library, specifically focusing on Terraform configurations. It aims to guide developers in creating efficient, secure, and maintainable infrastructure code.
|
||||
globs: **/*.tf
|
||||
---
|
||||
# Cloudflare Terraform Best Practices
|
||||
|
||||
This document outlines the recommended best practices and coding standards for working with Cloudflare resources using Terraform. Following these guidelines will help you create robust, scalable, and maintainable infrastructure code.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
|
||||
* **Account-Based Segregation:** Organize your Terraform projects by Cloudflare accounts. This allows for clear separation of resources and access control.
|
||||
* **Zone-Based Grouping:** Within each account, further group resources by zones. This makes it easier to manage resources associated with specific domains.
|
||||
* **Product/Feature-Based Organization:** Within each zone, create subdirectories for individual Cloudflare products or features (e.g., `dns`, `page_rules`, `rulesets`, `waf`). This promotes modularity and maintainability.
|
||||
* **Environment Separation:** While not strictly enforced within a single repository, using separate Cloudflare accounts for different environments (development, staging, production) is *strongly* recommended for complete isolation.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
example-tf/
|
||||
├── demo_account_a # Per account segregation of resources
|
||||
│ ├── users # Top level directory for account members as they are "zoneless"
|
||||
│ │ ├── provider.tf # `provider.tf` is for configuring the providers
|
||||
│ │ ├── users.tf # `<subject>.tf` (users.tf) is for managing the individual resources
|
||||
│ │ └── vars.tf # Manage all variables for this component
|
||||
│ ├── zone_a # Group all zone based features together
|
||||
│ │ ├── dns # Individual (or grouped, your choice) of products or features to manage together
|
||||
│ │ │ ├── dns.tf # `<subject>.tf` (dns.tf) is for managing the individual resources
|
||||
│ │ │ ├── provider.tf # `provider.tf` is for configuring the providers
|
||||
│ │ │ └── vars.tf # Manage all variables for this component
|
||||
│ │ └── page_rules # ... same as above but for Page Rules (legacy)
|
||||
│ │ ├── page_rules.tf
|
||||
│ │ ├── provider.tf
|
||||
│ │ └── vars.tf
|
||||
│ ├── zone_b
|
||||
│ │ ├── dns
|
||||
│ │ │ ├── dns.tf
|
||||
│ │ │ ├── provider.tf
|
||||
│ │ │ └── vars.tf
|
||||
│ │ └── page_rules
|
||||
│ │ ├── page_rules.tf
|
||||
│ │ ├── provider.tf
|
||||
│ │ └── vars.tf
|
||||
│ └── zone_c
|
||||
│ ├── dns
|
||||
│ │ ├── dns.tf
|
||||
│ │ ├── provider.tf
|
||||
│ │ └── vars.tf
|
||||
│ └── page_rules
|
||||
│ ├── page_rules.tf
|
||||
│ ├── provider.tf
|
||||
│ └── vars.tf
|
||||
└── demo_account_b
|
||||
├── users
|
||||
│ ├── provider.tf
|
||||
│ ├── users.tf
|
||||
│ └── vars.tf
|
||||
├── zone_a
|
||||
│ ├── dns
|
||||
│ │ ├── dns.tf
|
||||
│ │ ├── provider.tf
|
||||
│ │ └── vars.tf
|
||||
│ └── page_rules
|
||||
│ ├── page_rules.tf
|
||||
│ ├── provider.tf
|
||||
│ └── vars.tf
|
||||
├── zone_b
|
||||
│ ├── dns
|
||||
│ │ ├── dns.tf
|
||||
│ │ ├── provider.tf
|
||||
│ │ └── vars.tf
|
||||
│ └── page_rules
|
||||
│ ├── page_rules.tf
|
||||
│ ├── provider.tf
|
||||
│ └── vars.tf
|
||||
└── zone_c
|
||||
├── dns
|
||||
│ ├── dns.tf
|
||||
│ ├── provider.tf
|
||||
│ └── vars.tf
|
||||
└── page_rules
|
||||
├── page_rules.tf
|
||||
├── provider.tf
|
||||
└── vars.tf
|
||||
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* `provider.tf`: Contains provider configuration (e.g., Cloudflare provider settings).
|
||||
* `variables.tf`: Defines input variables for the module/component.
|
||||
* `outputs.tf`: Declares output values that can be used by other modules/components.
|
||||
* `<resource_type>.tf`: Contains resource definitions for a specific Cloudflare resource type (e.g., `dns_records.tf`, `page_rules.tf`, `waf_rules.tf`).
|
||||
* `data.tf`: Contains Terraform data sources.
|
||||
* `main.tf`: If `provider.tf` and `outputs.tf` are not required, `main.tf` should contain your main resource and data source definitions.
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
* **Avoid Modules (or Use Sparingly):** While modules can provide abstraction, they can also introduce complexity and make debugging more difficult. Carefully consider whether a module is truly necessary before creating one. If you do use modules, keep them small and well-defined.
|
||||
* **Module Structure:** If using modules, follow a consistent internal structure, including `variables.tf`, `outputs.tf`, and `main.tf`.
|
||||
* **Versioning:** If you share Terraform modules (internal or public), ensure you practice module versioning best practices. A well-defined versioning strategy, such as semantic versioning is recommended.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Small, Focused Components:** Design your Terraform code as a collection of small, focused components, each responsible for a specific aspect of your Cloudflare configuration.
|
||||
* **Loose Coupling:** Minimize dependencies between components to improve reusability and reduce the impact of changes.
|
||||
* **Well-Defined Interfaces:** Clearly define the input variables and output values for each component to create well-defined interfaces.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Resource Type:** Split code based on resource type (e.g., DNS records, Page Rules).
|
||||
* **Functionality:** Split code based on logical functionality (e.g., WAF rules for specific types of attacks).
|
||||
* **Environment:** While *strongly* recommending separate Cloudflare accounts for environments, you can also use Terraform workspaces to manage different environments within the same codebase, though this is generally discouraged due to potential blast radius of changes.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to Cloudflare
|
||||
|
||||
* **Data Source-Driven Configuration:** Use data sources to dynamically fetch information about existing Cloudflare resources (e.g., zone ID, account ID) rather than hardcoding them.
|
||||
* **Looping with `for_each` and `count`:** Use `for_each` or `count` to create multiple similar resources (e.g., multiple DNS records) based on variables or data sources. Favor `for_each` over `count` when possible, as it provides more explicit resource naming and updating behaviors.
|
||||
* **Dynamic Blocks:** Leverage dynamic blocks to conditionally create resource attributes based on variables or data sources. This allows for more flexible and reusable code.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Creating DNS Records:** Use `cloudflare_record` resource to manage DNS records. Utilize `for_each` to create multiple records based on a variable containing a list of record definitions.
|
||||
* **Managing Page Rules:** Use the `cloudflare_page_rule` resource to create and manage page rules. Consider using a module to encapsulate common page rule configurations.
|
||||
* **Configuring WAF Rules:** Use the `cloudflare_ruleset` and related resources to create and manage WAF rulesets. Organize rulesets into logical groups based on functionality.
|
||||
* **Setting up Load Balancers:** Use `cloudflare_load_balancer`, `cloudflare_load_balancer_pool`, and `cloudflare_load_balancer_monitor` resources to create and manage load balancers.
|
||||
* **Worker Deployment**: Use `cloudflare_worker` to manage Cloudflare Workers.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Hardcoding Values:** Avoid hardcoding values such as API keys, account IDs, and zone IDs in your code. Use variables and data sources instead.
|
||||
* **Managing Resources Outside of Terraform:** Terraform works best when it manages all changes to and the lifecycle of a resource. Avoid making manual changes to Cloudflare resources outside of Terraform, as this can lead to inconsistencies and drift. If external changes are unavoidable, plan to re-import the resources or reconcile the differences.
|
||||
* **Overly Complex Modules:** Avoid creating overly complex modules that perform too many tasks. Break down complex configurations into smaller, more manageable components.
|
||||
* **Ignoring `terraform fmt` and `terraform validate`:** Always run `terraform fmt` to format your code and `terraform validate` to check for syntax errors and other issues before committing changes.
|
||||
* **Storing Secrets in Code:** Never store API tokens or other secrets directly in your Terraform code or version control. Use a secure secret management solution like Vault or environment variables.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Remote State:** Always use remote state management (e.g., Terraform Cloud, AWS S3, Azure Blob Storage) to store your Terraform state file. This ensures that your state is stored securely and is accessible to all members of your team.
|
||||
* **State Locking:** Enable state locking to prevent concurrent modifications to your state file.
|
||||
* **Encryption:** Encrypt your state file at rest to protect sensitive information.
|
||||
* **Backup:** Regularly back up your state file to prevent data loss.
|
||||
* **Consider Terraform Cloud:** For teams, consider using Terraform Cloud for state management, collaboration, and automation. It offers features like remote state storage, state locking, plan previews, and automated runs.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **Use `try` and `catch` in Expressions:** Use `try` and `catch` to handle errors in Terraform expressions gracefully.
|
||||
* **Validate Input Variables:** Validate input variables to ensure that they are in the correct format and within the expected range.
|
||||
* **Use `depends_on` Sparingly:** Use `depends_on` only when necessary to explicitly define dependencies between resources. Overuse of `depends_on` can lead to performance issues and deadlocks.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Minimize Resource Dependencies:** Reduce the number of dependencies between resources to improve plan and apply times.
|
||||
* **Use Data Sources Effectively:** Use data sources to retrieve information about existing resources rather than creating new resources when possible.
|
||||
* **Targeted Applies:** Use targeted applies (`terraform apply -target=resource`) to apply changes to specific resources rather than applying the entire configuration.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Large State Files:** Be mindful of large state files. Break down large configurations into smaller, more manageable components to reduce state file size. Review state files periodically and consider refactoring if they become unwieldy.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Exposed API Keys:** Never expose your Cloudflare API keys in your code or version control. Use environment variables or a secure secret management solution instead.
|
||||
* **Insufficient Input Validation:** Validate all input variables to prevent injection attacks and other security vulnerabilities.
|
||||
* **Overly Permissive Permissions:** Grant only the necessary permissions to your Cloudflare API keys and Terraform service accounts.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Variable Validation:** Use the `validation` block in variable definitions to enforce constraints on input values. This is crucial for preventing unexpected behavior and security vulnerabilities.
|
||||
* **Regular Expressions:** Use regular expressions to validate input strings.
|
||||
* **Type Checking:** Use Terraform's type system to ensure that variables are of the correct type.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **API Tokens vs. Global API Key:** Prefer using API tokens with specific permissions over the global API key, as API tokens can be scoped to specific resources and actions.
|
||||
* **Least Privilege Principle:** Grant only the necessary permissions to your Terraform service accounts.
|
||||
* **Secure Storage:** Store API tokens and other secrets securely using a secret management solution.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
* **Data Masking:** Mask sensitive data in logs and error messages.
|
||||
* **Access Control:** Implement strict access control policies to protect sensitive data.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Always use HTTPS to communicate with the Cloudflare API.
|
||||
* **TLS:** Use TLS 1.2 or higher.
|
||||
* **Certificate Validation:** Validate the Cloudflare API certificate.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Validate Resource Attributes:** Write unit tests to validate the attributes of individual resources.
|
||||
* **Check for Expected Errors:** Write unit tests to check for expected errors.
|
||||
* **Use `terraform show`:** Use `terraform show` to inspect the generated Terraform configuration and verify that it is correct.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Deploy to a Test Environment:** Deploy your Terraform code to a test environment and verify that it works as expected.
|
||||
* **Automated Testing:** Automate your integration tests using a CI/CD pipeline.
|
||||
* **Check Cloudflare Resources:** After applying a Terraform configuration in a test environment, use the Cloudflare API or UI to verify that the resources have been created and configured correctly.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Simulate Real-World Traffic:** Simulate real-world traffic to your Cloudflare resources to verify that they are functioning correctly.
|
||||
* **Monitor Performance:** Monitor the performance of your Cloudflare resources to identify any bottlenecks or issues.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Separate Test Directory:** Create a separate directory for your Terraform tests.
|
||||
* **Test Naming Conventions:** Follow consistent naming conventions for your tests.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Mock Data Sources:** Mock data sources to isolate your tests from external dependencies.
|
||||
* **Stub API Calls:** Stub API calls to control the behavior of the Cloudflare API during testing.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
* **Rate Limiting:** Be aware of Cloudflare's API rate limits. Implement retry logic to handle rate limit errors.
|
||||
* **Resource Dependencies:** Understand the dependencies between Cloudflare resources. Create resources in the correct order to avoid errors.
|
||||
* **State Drift:** Regularly check for state drift and reconcile any differences between your Terraform state and your Cloudflare resources.
|
||||
* **Idempotency:** Ensure that your Terraform code is idempotent. Applying the same configuration multiple times should have the same result.
|
||||
* **Cloudflare Provider Version:** Lock the Cloudflare provider version in your `terraform` block in `main.tf`. Upgrading the provider can sometimes introduce breaking changes, so testing the upgrade in a non-production environment is suggested first.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **Terraform CLI:** The official Terraform command-line interface.
|
||||
* **Terraform Language Server:** Provides code completion, syntax highlighting, and other features for Terraform code in your IDE.
|
||||
* **IDE Extensions:** Use IDE extensions for Terraform to improve your development experience (e.g., VS Code Terraform extension).
|
||||
* **cf-terraforming:** Use `cf-terraforming` tool to import existing Cloudflare resources into Terraform state.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Terraform Block:** Configure the required providers and Terraform version in the `terraform` block in `main.tf`.
|
||||
* **Provider Configuration:** Configure the Cloudflare provider with your API key and account ID.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **`terraform fmt`:** Use `terraform fmt` to automatically format your Terraform code.
|
||||
* **`terraform validate`:** Use `terraform validate` to check for syntax errors and other issues.
|
||||
* **`tflint`:** Consider using `tflint` or other linting tools to enforce coding standards and best practices.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **CI/CD Pipeline:** Automate your Terraform deployments using a CI/CD pipeline.
|
||||
* **Plan Previews:** Always review the Terraform plan before applying changes.
|
||||
* **Apply with Auto-Approve (Carefully):** Use the `-auto-approve` flag with caution. Only use it in automated environments where you have a high degree of confidence in your code.
|
||||
* **Blue/Green Deployments:** Consider using blue/green deployments to minimize downtime during deployments.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Terraform Cloud/Enterprise:** Use Terraform Cloud or Enterprise to manage your Terraform workflows and collaborate with your team.
|
||||
* **GitHub Actions:** Use GitHub Actions to automate your Terraform deployments.
|
||||
* **GitLab CI:** Use GitLab CI to automate your Terraform deployments.
|
||||
* **Jenkins:** Use Jenkins to automate your Terraform deployments.
|
||||
|
||||
## 8. Angle Brackets, Square Brackets, and Curly Braces
|
||||
|
||||
* **Angle Brackets (`<` and `>`):** Use angle brackets as placeholders for variables that the user must enter, except in URLs, where you should use curly braces.
|
||||
* Example: `https://<user-specified domain>.cloudflare.com`
|
||||
* **Square Brackets (`[` and `]`):** Use square brackets to enclose optional items.
|
||||
* Example: `tag=dns query [search tag=malware]`
|
||||
* **Curly Braces (`{` and `}`):** Use curly braces in code samples or string literals, such as placeholders in URLs.
|
||||
* Example: `https://api.cloudflare.com/client/v4/organizations/{organization_identifier}/invites`
|
||||
|
||||
## 9. Cloudflare's Convention Symbols
|
||||
|
||||
* The `>` symbol leads you through nested menu items and dialog box options to a final action.
|
||||
* Example: `Options > Settings > General` directs you to pull down the Options menu, select the Settings item, and select General from the last dialog box. Do not use bold formatting for the `>` symbol.
|
||||
* Tip icon: This icon denotes a tip, which alerts you to advisory information.
|
||||
* Note icon: This icon denotes a note, which alerts you to important information.
|
||||
* Info icon: This icon denotes info, which alerts you to important information.
|
||||
* Notice icon: This icon denotes a notice, which alerts you to take precautions to avoid data loss, loss of signal integrity, or degradation of performance.
|
||||
* Caution icon: This icon denotes a caution, which advises you to take precautions to avoid injury.
|
||||
* Blue text: Text in this color indicates a link.
|
||||
* Bold: Use bold when referring to a clickable action or to highlight a title or name in the UI. Bold text denotes items that you must select or click in the software, identifiers in the UI, or parameter names. Do not use bold for programs. In nested menus, use bold for the word not the symbol.
|
||||
* Example: `Dashboard > This > That`
|
||||
* Italics: Use italics when referring to an option that customers can select from, like in dropdown menus. Do not use italics when referring to the state of a toggle - for example, enabled/disabled should not be italicized.
|
||||
* Monospace: Text in this font denotes text or characters that you should enter from the keyboard, sections of code, programming examples, and syntax examples. This font is also used for the proper names of drives, paths, directories, programs, subprograms, devices, functions, operations, variables, files, API commands, and extensions.
|
||||
|
||||
By adhering to these best practices, you can create more efficient, secure, and maintainable Terraform code for managing your Cloudflare infrastructure.
|
||||
@@ -0,0 +1,227 @@
|
||||
---
|
||||
description: This rule outlines best practices for developing and maintaining the Modal library, covering code organization, performance, security, and testing. It aims to ensure high-quality, maintainable, and scalable cloud deployment solutions.
|
||||
globs: **/*.py
|
||||
---
|
||||
# Modal Library Best Practices
|
||||
|
||||
This document outlines the best practices for developing and maintaining the Modal library. These guidelines cover various aspects of the library, including code organization, performance, security, testing, and deployment. Following these guidelines will ensure the Modal library remains a high-quality, maintainable, and scalable cloud deployment solution.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- Adopt a modular directory structure based on functionality or component type.
|
||||
- Use clear and descriptive directory names.
|
||||
- Example:
|
||||
|
||||
modal/
|
||||
├── api/
|
||||
│ ├── __init__.py
|
||||
│ ├── routes.py
|
||||
│ └── models.py
|
||||
├── config/
|
||||
│ ├── __init__.py
|
||||
│ └── settings.py
|
||||
├── deployment/
|
||||
│ ├── __init__.py
|
||||
│ ├── deploy.py
|
||||
│ └── utils.py
|
||||
├── exceptions/
|
||||
│ ├── __init__.py
|
||||
│ └── custom_exceptions.py
|
||||
├── security/
|
||||
│ ├── __init__.py
|
||||
│ ├── auth.py
|
||||
│ └── permissions.py
|
||||
├── testing/
|
||||
│ ├── __init__.py
|
||||
│ ├── unit/
|
||||
│ └── integration/
|
||||
├── utils/
|
||||
│ ├── __init__.py
|
||||
│ └── helpers.py
|
||||
├── __init__.py
|
||||
└── core.py
|
||||
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent file names.
|
||||
- Follow a consistent naming convention (e.g., `snake_case` for Python).
|
||||
- Example: `user_authentication.py`, `database_connection.py`
|
||||
|
||||
- **Module Organization:**
|
||||
- Group related functions, classes, and data into modules.
|
||||
- Use `__init__.py` files to define package structure.
|
||||
- Ensure clear separation of concerns between modules.
|
||||
- Each module should have a clearly defined purpose.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Design the library using a component-based architecture.
|
||||
- Each component should be self-contained and reusable.
|
||||
- Components should have well-defined interfaces.
|
||||
- Use dependency injection to manage component dependencies.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Divide large modules into smaller, more manageable files.
|
||||
- Split code based on functionality or feature.
|
||||
- Consider using lazy loading for infrequently used modules.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns Specific to Modal:**
|
||||
- **Singleton:** For managing global resources (e.g., configuration).
|
||||
- **Factory:** For creating Modal clients with different configurations.
|
||||
- **Observer:** For notifying subscribers of Modal state changes.
|
||||
- **Strategy:** For different deployment strategies (e.g., different cloud providers).
|
||||
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Configuration Management:** Use a dedicated configuration module to manage settings.
|
||||
- **Logging:** Implement a robust logging system for debugging and monitoring.
|
||||
- **Error Handling:** Use exception handling to gracefully handle errors.
|
||||
- **Asynchronous Operations:** Use `asyncio` or similar libraries for handling asynchronous tasks.
|
||||
- **Resource Management:** Use context managers (`with` statement) to ensure proper resource cleanup.
|
||||
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **God Classes:** Avoid creating classes that are too large and complex.
|
||||
- **Spaghetti Code:** Maintain a clear and well-structured codebase.
|
||||
- **Magic Numbers:** Use constants instead of hardcoded values.
|
||||
- **Duplicated Code:** Refactor duplicated code into reusable functions or classes.
|
||||
- **Ignoring Errors:** Always handle exceptions appropriately.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Prefer immutable data structures to avoid unintended side effects.
|
||||
- Use a centralized state management system (if needed) for complex state.
|
||||
- Consider using libraries like `attrs` or `dataclasses` for managing data objects.
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Use try-except blocks to handle potential exceptions.
|
||||
- Define custom exception classes for specific error conditions.
|
||||
- Log exceptions with relevant information for debugging.
|
||||
- Implement retry mechanisms for transient errors.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Profile code to identify performance bottlenecks.
|
||||
- Optimize database queries and data access patterns.
|
||||
- Use caching to reduce the load on external services.
|
||||
- Avoid unnecessary computations and memory allocations.
|
||||
|
||||
- **Memory Management:**
|
||||
- Use generators and iterators to process large datasets efficiently.
|
||||
- Avoid creating large objects in memory unnecessarily.
|
||||
- Use memory profiling tools to identify memory leaks.
|
||||
|
||||
- **Rendering Optimization (if applicable):**
|
||||
- N/A (Modal library is primarily backend-focused).
|
||||
|
||||
- **Bundle Size Optimization (if applicable):**
|
||||
- N/A (Modal library is primarily backend-focused).
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use lazy loading to load modules and resources only when they are needed.
|
||||
- This can reduce startup time and memory usage.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Injection Attacks:** Sanitize user inputs to prevent SQL injection, command injection, etc.
|
||||
- **Cross-Site Scripting (XSS):** N/A (Modal library is primarily backend-focused).
|
||||
- **Cross-Site Request Forgery (CSRF):** N/A (Modal library is primarily backend-focused).
|
||||
- **Authentication and Authorization Flaws:** Implement secure authentication and authorization mechanisms.
|
||||
- **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate all user inputs to prevent malicious data from entering the system.
|
||||
- Use data validation libraries (e.g., `marshmallow`, `pydantic`) to enforce data types and constraints.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a strong authentication mechanism (e.g., OAuth 2.0, JWT).
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive resources.
|
||||
- Avoid storing passwords in plain text; use password hashing algorithms (e.g., bcrypt, Argon2).
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between clients and servers.
|
||||
- Implement data masking and anonymization techniques to protect sensitive data.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use API keys or tokens to authenticate API requests.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Use input validation to prevent malicious data from entering the system.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for all critical functions and classes.
|
||||
- Use mocking and stubbing to isolate units of code.
|
||||
- Aim for high test coverage.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify the interaction between different components.
|
||||
- Test the integration with external services (e.g., databases, APIs).
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to verify the entire system functionality.
|
||||
- Simulate real-world scenarios.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on functionality or component.
|
||||
- Use a consistent naming convention for test files and functions.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to isolate units of code.
|
||||
- Create stubs for external dependencies.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- Improper error handling.
|
||||
- Lack of input validation.
|
||||
- Security vulnerabilities.
|
||||
- Performance bottlenecks.
|
||||
- Inadequate testing.
|
||||
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- Handling of large datasets.
|
||||
- Concurrent access to shared resources.
|
||||
- Network failures and timeouts.
|
||||
- Unexpected input values.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility issues between different versions of the library and its dependencies.
|
||||
- Test the library with different versions of Python and other dependencies.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure the library is compatible with different operating systems and environments.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use logging to trace the execution flow and identify errors.
|
||||
- Use debuggers to step through the code and inspect variables.
|
||||
- Use profiling tools to identify performance bottlenecks.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- IDE: VS Code, PyCharm
|
||||
- Debugger: pdb, ipdb
|
||||
- Profiler: cProfile, line_profiler
|
||||
- Testing Framework: pytest, unittest
|
||||
- Mocking Library: unittest.mock, pytest-mock
|
||||
- Linting and Formatting: pylint, flake8, black
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use a build system (e.g., `setuptools`, `poetry`) to manage dependencies and build the library.
|
||||
- Define a clear build process.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use linters (e.g., `pylint`, `flake8`) to enforce code style and identify potential errors.
|
||||
- Use formatters (e.g., `black`) to automatically format the code.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use a deployment automation tool (e.g., Ansible, Terraform) to automate the deployment process.
|
||||
- Use infrastructure-as-code (IaC) to manage infrastructure.
|
||||
- Monitor the deployment process for errors.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate the library with a CI/CD pipeline to automate testing and deployment.
|
||||
- Use tools like Jenkins, GitLab CI, or GitHub Actions.
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
description: Enforces Vercel's recommended coding style, optimization strategies, and security best practices. This guide helps developers build performant, secure, and maintainable applications on the Vercel platform.
|
||||
globs: **/*.{js,jsx,ts,tsx,md,mdx,json,yml,yaml,html,css,scss,sass}
|
||||
---
|
||||
- Adhere to Vercel's Style Guide: Utilize linting and styling tools configured according to the Vercel Style Guide for consistent code formatting and style. Use `@file vercel_style_guide.mdc` to include style guide details.
|
||||
- Enforce Consistent Coding Style: Integrate ESLint, Prettier, and TypeScript to automatically enforce coding style and prevent stylistic inconsistencies. Refer to [Vercel's documentation](https://vercel.com/docs) for setup instructions.
|
||||
- Optimize Codebase Performance: Focus on optimizing the codebase for faster loading times and improved user experience. Includes optimizing cache, assets, and serverless functions.
|
||||
- Implement Conformance Checks: Utilize Vercel's Conformance tools to automatically check for performance, security, and code health issues.
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure:**
|
||||
- Adopt a clear and consistent directory structure (e.g., `components`, `pages`, `lib`, `api`, `styles`, `public`). Group related files logically to improve maintainability.
|
||||
- Use a `src` directory to encapsulate all source code, separating it from configuration files and other project assets.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent file names (e.g., `Button.tsx`, `useUser.ts`, `api/products.js`).
|
||||
- Prefer camelCase for JavaScript/TypeScript files and kebab-case for CSS/SCSS files.
|
||||
- **Module Organization:**
|
||||
- Organize code into reusable modules or components. Favor small, focused modules with well-defined interfaces.
|
||||
- Use ES modules (`import`/`export`) for modularity and dependency management.
|
||||
- **Component Architecture:**
|
||||
- Employ a component-based architecture (e.g., using React, Vue, or Svelte) to build reusable UI elements.
|
||||
- Follow the principles of separation of concerns and single responsibility.
|
||||
- Consider using a design system or component library to maintain consistency across the application.
|
||||
- **Code Splitting Strategies:**
|
||||
- Implement code splitting to reduce the initial bundle size and improve loading times. Use dynamic imports for route-based or component-based splitting.
|
||||
- Analyze bundle size using tools like `webpack-bundle-analyzer` to identify large dependencies.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to Vercel:**
|
||||
- Serverless Functions: Use serverless functions for API endpoints and background tasks. Optimize function size and execution time to minimize cold starts.
|
||||
- Edge Functions: Use edge functions to perform operations closer to the user, reducing latency for geographically distributed users.
|
||||
- Incremental Static Regeneration (ISR): Use ISR to combine the benefits of static generation and server-side rendering.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- Data Fetching: Use `getStaticProps` or `getServerSideProps` in Next.js for data fetching in pages.
|
||||
- API Routes: Create API routes in the `pages/api` directory of a Next.js project for handling API requests.
|
||||
- Environment Variables: Use environment variables to store sensitive information and configuration settings.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- Large components: Break down large components into smaller, more manageable pieces.
|
||||
- Deeply nested components: Avoid excessive nesting of components, which can make code harder to read and maintain.
|
||||
- Over-fetching data: Fetch only the data that is needed by a component.
|
||||
- Mutating state directly: Avoid mutating state directly, which can lead to unexpected behavior.
|
||||
- **State Management Best Practices:**
|
||||
- Choose a state management solution (e.g., Redux, Zustand, Recoil, React Context) that is appropriate for the application's complexity.
|
||||
- Follow recommended patterns for managing state (e.g., reducers, actions, selectors).
|
||||
- Avoid storing too much data in the global state.
|
||||
- **Error Handling Patterns:**
|
||||
- Implement comprehensive error handling throughout the application.
|
||||
- Use try-catch blocks to catch exceptions.
|
||||
- Log errors to a monitoring service.
|
||||
- Display user-friendly error messages.
|
||||
|
||||
## 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- Minimize bundle size by removing unused code and dependencies (tree shaking).
|
||||
- Compress images and other assets.
|
||||
- Use a content delivery network (CDN) to serve static assets.
|
||||
- Optimize database queries.
|
||||
- Cache frequently accessed data.
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly releasing resources.
|
||||
- Use garbage collection to reclaim unused memory.
|
||||
- Profile application memory usage to identify potential issues.
|
||||
- **Rendering Optimization:**
|
||||
- Use memoization techniques (e.g., `React.memo`, `useMemo`) to prevent unnecessary re-renders.
|
||||
- Virtualize long lists to improve rendering performance.
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- **Bundle Size Optimization:**
|
||||
- Analyze bundle size with tools like `webpack-bundle-analyzer` or `source-map-explorer`.
|
||||
- Remove unused dependencies.
|
||||
- Minify code.
|
||||
- Compress code with gzip or Brotli.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Implement lazy loading for images, components, and routes.
|
||||
- Use the `IntersectionObserver` API to detect when an element is visible in the viewport.
|
||||
|
||||
## 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- Cross-site scripting (XSS): Sanitize user input to prevent XSS attacks. Use a library like DOMPurify.
|
||||
- Cross-site request forgery (CSRF): Use CSRF tokens to protect against CSRF attacks.
|
||||
- SQL injection: Use parameterized queries or an ORM to prevent SQL injection attacks.
|
||||
- Authentication and authorization vulnerabilities: Implement strong authentication and authorization mechanisms.
|
||||
- **Input Validation:**
|
||||
- Validate all user input on both the client and server sides.
|
||||
- Use a validation library to simplify the validation process.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a secure authentication protocol (e.g., OAuth 2.0, JWT).
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive resources.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication between the client and server.
|
||||
- Protect against data breaches by implementing appropriate security measures.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS to encrypt API traffic.
|
||||
- Authenticate and authorize API requests.
|
||||
- Limit API rate to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual components, functions, and modules.
|
||||
- Use a unit testing framework (e.g., Jest, Mocha, Jasmine).
|
||||
- Mock external dependencies.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to verify that different parts of the application work together correctly.
|
||||
- Test interactions between components, modules, and APIs.
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to simulate user interactions and verify that the application works as expected.
|
||||
- Use an end-to-end testing framework (e.g., Cypress, Playwright).
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on the type of test (e.g., unit, integration, e2e).
|
||||
- Use descriptive test names.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate components and functions during testing.
|
||||
- Mock external dependencies to avoid making real API calls.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- Over-reliance on client-side rendering.
|
||||
- Neglecting performance optimization.
|
||||
- Ignoring security vulnerabilities.
|
||||
- Not writing enough tests.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- Handling errors gracefully.
|
||||
- Supporting different browsers and devices.
|
||||
- Dealing with slow network connections.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes in Vercel and its dependencies.
|
||||
- Test application thoroughly after upgrading Vercel or any dependencies.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that the application is compatible with different browsers, devices, and operating systems.
|
||||
- **Debugging Strategies:**
|
||||
- Use browser developer tools to debug client-side code.
|
||||
- Use server-side logging to debug server-side code.
|
||||
- Use a debugger to step through code and inspect variables.
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- VS Code with extensions for ESLint, Prettier, and TypeScript.
|
||||
- Chrome DevTools for debugging.
|
||||
- Vercel CLI for deploying and managing applications.
|
||||
- **Build Configuration:**
|
||||
- Configure build scripts to optimize code and assets.
|
||||
- Use environment variables to configure the build process.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier to enforce consistent code style.
|
||||
- Configure linting and formatting rules to match the Vercel Style Guide.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy application to Vercel using the Vercel CLI or Git integration.
|
||||
- Configure environment variables for production.
|
||||
- Monitor application performance and logs.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate with a CI/CD pipeline (e.g., GitHub Actions, CircleCI) to automate the build, test, and deployment process.
|
||||
- Run tests and linters as part of the CI/CD pipeline.
|
||||
|
||||
@file vercel_style_guide.mdc
|
||||
Reference in New Issue
Block a user