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:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
@@ -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
@@ -0,0 +1,344 @@
---
description: Comprehensive rules and best practices for AWS development using Terraform, covering code organization, security, performance, and testing. Adherence to these guidelines ensures maintainable, secure, and efficient infrastructure code.
globs: **/*.tf
---
# AWS Development Best Practices using Terraform
This document outlines best practices for developing and maintaining AWS infrastructure using Terraform. Following these guidelines will help ensure your code is maintainable, secure, and efficient.
## 1. Code Organization and Structure
### 1.1 Directory Structure
- **Root Module**: The primary entry point for your infrastructure definition. Contains `main.tf`, `variables.tf`, `outputs.tf`, `providers.tf`, `versions.tf` and `locals.tf`.
- **Modules Directory**: Reusable components of your infrastructure. Each module should have its own directory under `modules/`.
- **Examples Directory**: Demonstrates how to use the modules. Each example should be a self-contained Terraform configuration.
- **Scripts Directory**: Custom scripts used by Terraform.
- **Templates Directory**: Templates for files that are read using the `templatefile` function, using the extension `.tftpl`.
- **Files Directory**: Contains static files referenced by Terraform (e.g., startup scripts).
- **Helpers Directory**: Contains utility scripts that are *not* directly called by Terraform.
- **.tfvars files**: Files containing variable definitions. Use `terraform.tfvars` for common values and create environment specific files in the `envs/` directory (e.g., `envs/dev/terraform.tfvars`, `envs/prod/terraform.tfvars`).
- **.gitignore**: Specifies intentionally untracked files that Git should ignore.
- **docs/**: Place any supplemental documentation in a `docs/` subdirectory.
- **CODEOWNERS**: File to document who is responsible for the module. Before any merge request is merged, an owner should approve it.
Example:
├── .terraform/ # Terraform working directory
├── modules/
│ ├── ec2/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── README.md
│ ├── s3/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── README.md
├── examples/
│ ├── ec2/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── README.md
│ ├── s3/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── README.md
├── scripts/
│ ├── configure_instance.sh
├── templates/
│ ├── user_data.tftpl
├── files/
│ ├── application.conf
├── helpers/
│ ├── backup_database.sh
├── terraform.tfvars
├── envs/
│ ├── dev/
│ │ ├── terraform.tfvars
│ ├── prod/
│ │ ├── terraform.tfvars
├── main.tf
├── variables.tf
├── outputs.tf
├── providers.tf
├── versions.tf
├── locals.tf
└── .gitignore
### 1.2 File Naming Conventions
- `main.tf`: Primary entry point for resource definitions.
- `variables.tf`: Variable declarations.
- `outputs.tf`: Output declarations.
- `providers.tf`: Provider configuration.
- `versions.tf`: Terraform and provider version constraints.
- `locals.tf`: Local variable definitions.
- `*.tfvars`: Variable value files. Use `terraform.tfvars` for default values and `env/<environment>.tfvars` for environment-specific values.
### 1.3 Module Organization
- **Reusable Modules**: Create modules for common infrastructure components (e.g., EC2 instances, S3 buckets, VPCs).
- **Module Composition**: Compose complex infrastructure by combining smaller, reusable modules.
- **Module Versioning**: Use version control (e.g., Git tags) to manage module versions.
- **Module Naming**: Module repositories must use the format `terraform-<PROVIDER>-<NAME>`. For example: `terraform-aws-ec2`
- **Module sources**: When referencing another module on a public registry, pin the Git commit hash by pointing directly to the underlying Git repo URL. Example:
terraform
module "lambda" {
source = "github.com/terraform-aws-modules/terraform-aws-lambda.git?ref=e78cdf1f82944897ca6e30d6489f43cf24539374" # --> v4.18.0
}
### 1.4 Component Architecture
- **Layered Architecture**: Separate infrastructure into logical layers (e.g., network, compute, data).
- **Loose Coupling**: Design components to be loosely coupled, minimizing dependencies between them.
- **Clear Abstractions**: Use modules to create clear abstractions for complex infrastructure components.
### 1.5 Code Splitting Strategies
- **Functional Decomposition**: Split code into smaller, manageable functions.
- **Resource Grouping**: Group related resources into separate files or modules.
- **Environment Separation**: Use separate files or modules for environment-specific configurations.
- **Service-Based Separation**: Separate resources by service (e.g., `iam.tf`, `ec2.tf`, `s3.tf`) only if they exceed 150 lines in `main.tf`.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to AWS
- **Immutable Infrastructure**: Deploy new infrastructure components instead of modifying existing ones.
- **Infrastructure as Code (IaC)**: Manage infrastructure through code, using tools like Terraform.
- **Blue/Green Deployments**: Deploy new versions of applications alongside existing ones, then switch traffic.
- **Canary Deployments**: Deploy new versions of applications to a small subset of users before rolling them out to everyone.
### 2.2 Recommended Approaches for Common Tasks
- **Creating VPCs**: Use the `terraform-aws-modules/vpc/aws` module for creating VPCs.
- **Creating EC2 Instances**: Use the `terraform-aws-modules/ec2-instance/aws` module for creating EC2 instances.
- **Creating S3 Buckets**: Use the `terraform-aws-modules/s3-bucket/aws` module for creating S3 buckets.
- **Managing IAM Roles**: Use the `aws_iam_role` and `aws_iam_policy` resources to manage IAM roles and policies.
- **Using Data Sources**: Utilize data sources (e.g., `aws_ami`, `aws_vpc`) to fetch information about existing AWS resources.
- **Resource Tagging**: Tag all AWS resources for cost allocation, automation, and identification.
- **State File Storage**: Use a remote backend (e.g., S3 with DynamoDB locking) for storing Terraform state.
### 2.3 Anti-patterns and Code Smells to Avoid
- **Hardcoding Values**: Avoid hardcoding values in your code. Use variables instead.
- **Storing Secrets in Code**: Never store secrets (e.g., passwords, API keys) in your code. Use AWS Secrets Manager or other secret management solutions.
- **Overly Complex Modules**: Avoid creating modules that are too complex and difficult to understand.
- **Ignoring Errors**: Always handle errors gracefully.
- **Manual Infrastructure Changes**: Avoid making manual changes to infrastructure outside of Terraform.
- **Using embedded resource attributes**: avoid using these embedded resource attributes and instead you should use the unique resource to attach that pseudo-resource. These resource relationships can cause chicken/egg issues that are unique per resource.
### 2.4 State Management Best Practices
- **Remote Backend**: Use a remote backend (e.g., S3 with DynamoDB locking) for storing Terraform state. This allows for collaboration and prevents data loss.
- **State Locking**: Enable state locking to prevent concurrent modifications to the state file.
- **State Encryption**: Encrypt the state file at rest and in transit.
- **Workspace Management**: Use Terraform workspaces to manage multiple environments (e.g., development, staging, production).
- **Secure State Access**: Restrict access to the state file to authorized users and systems only. Consider implementing least privilege principles.
- **Versioning**: Implement a mechanism for versioning your state files, which could include frequent backups and using version control systems.
- **Avoid local state**: Never store Terraform state locally.
### 2.5 Error Handling Patterns
- **Validation Rules**: Use validation rules within variable definitions to check input values.
- **Error Propagation**: Propagate errors up the call stack to be handled at a higher level.
- **Retry Logic**: Implement retry logic for transient errors (e.g., network errors, API throttling).
- **Logging**: Log errors and warnings to aid in debugging.
- **Custom Error Messages**: Provide clear and informative error messages to users.
- **Panic Handling**: Avoid using `panic()` function that stops the execution, implement error handling.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Efficient Resource Usage**: Use the appropriate instance types and storage classes for your workloads.
- **Caching**: Implement caching to reduce latency and improve performance.
- **Load Balancing**: Use load balancing to distribute traffic across multiple instances.
- **Content Delivery Networks (CDNs)**: Use CDNs to deliver static content closer to users.
- **Database Optimization**: Optimize database queries and indexing for faster performance.
- **Parallelization**: Use `for_each` and `count` to parallelize resource creation and modification.
### 3.2 Memory Management
- **Resource Limits**: Set resource limits on EC2 instances and other AWS resources.
- **Memory Profiling**: Use memory profiling tools to identify memory leaks and optimize memory usage.
- **Garbage Collection**: Configure garbage collection settings for your applications.
### 3.3 Rendering Optimization
- **Minimize Rendering**: Minimize the amount of data that needs to be rendered.
- **Efficient Templates**: Use efficient templates to generate configuration files.
### 3.4 Bundle Size Optimization
- **Code Splitting**: Split code into smaller bundles that can be loaded on demand.
- **Tree Shaking**: Remove unused code from your bundles.
- **Minification**: Minify your code to reduce bundle sizes.
- **Compression**: Compress your bundles to reduce download times.
### 3.5 Lazy Loading Strategies
- **Lazy Loading of Resources**: Load resources only when they are needed.
- **Virtualization**: Use virtualization to reduce the number of resources that need to be loaded.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **IAM Misconfiguration**: Prevent IAM misconfiguration by following the principle of least privilege.
- **Unsecured S3 Buckets**: Secure S3 buckets by enabling encryption, access logging, and versioning.
- **Security Group Misconfiguration**: Configure security groups to allow only necessary traffic.
- **SQL Injection**: Prevent SQL injection by using parameterized queries and input validation.
- **Cross-Site Scripting (XSS)**: Prevent XSS by sanitizing user input and output.
- **Cross-Site Request Forgery (CSRF)**: Prevent CSRF by using anti-CSRF tokens.
- **Exposed Secrets**: Avoid exposing secrets by using AWS Secrets Manager and IAM roles.
### 4.2 Input Validation
- **Validate User Input**: Validate user input to prevent malicious code from being injected into your application.
- **Use Data Types**: Use appropriate data types for your variables to prevent type-related errors.
- **Regular Expressions**: Use regular expressions to validate complex input patterns.
### 4.3 Authentication and Authorization Patterns
- **IAM Roles**: Use IAM roles to grant permissions to AWS resources.
- **Multi-Factor Authentication (MFA)**: Enable MFA for all user accounts.
- **Principle of Least Privilege**: Grant users only the permissions they need to perform their tasks.
- **AWS Cognito**: Use AWS Cognito to manage user authentication and authorization.
- **API Gateway Authorization**: Implement authorization at the API Gateway level to control access to your APIs.
### 4.4 Data Protection Strategies
- **Encryption at Rest**: Encrypt data at rest using AWS KMS, S3 encryption, or other encryption solutions.
- **Encryption in Transit**: Encrypt data in transit using HTTPS, TLS, or other encryption protocols.
- **Data Masking**: Mask sensitive data to prevent unauthorized access.
- **Data Redaction**: Redact sensitive data from logs and other output.
### 4.5 Secure API Communication
- **HTTPS**: Use HTTPS for all API communication.
- **API Keys**: Use API keys to authenticate API requests.
- **OAuth 2.0**: Use OAuth 2.0 for authorization.
- **Rate Limiting**: Implement rate limiting to prevent abuse.
- **Web Application Firewall (WAF)**: Use a WAF to protect your APIs from common web attacks.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test Individual Modules**: Unit test individual Terraform modules to ensure they are working correctly.
- **Mock AWS Resources**: Mock AWS resources to isolate your modules from external dependencies.
- **Test Variable Validation**: Verify variable validation rules work as expected.
- **Test Output Values**: Check that module outputs are correct.
### 5.2 Integration Testing
- **Test Module Integration**: Test how modules interact with each other.
- **Deploy to Test Environment**: Deploy your infrastructure to a test environment and verify that it is working correctly.
- **Automated Tests**: Write automated tests to verify that your infrastructure is working correctly.
### 5.3 End-to-End Testing
- **Test Full Infrastructure**: Test the entire infrastructure from end to end.
- **Simulate User Behavior**: Simulate user behavior to verify that your infrastructure is working correctly.
- **Monitor Performance**: Monitor performance to identify any performance bottlenecks.
### 5.4 Test Organization
- **Separate Test Directory**: Create a separate directory for your tests.
- **Test Naming Conventions**: Use clear naming conventions for your tests.
- **Test Documentation**: Document your tests to explain what they are testing.
### 5.5 Mocking and Stubbing
- **Use Mock Objects**: Use mock objects to isolate your code from external dependencies.
- **Use Stub Objects**: Use stub objects to provide canned responses to external dependencies.
- **Terratest**: Utilize Terratest for creating test environments and performing infrastructure tests.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Forgetting to Enable State Locking**: Enabling state locking is crucial for preventing corruption and ensuring integrity when multiple users work on the same Terraform project.
- **Overlooking IAM Permissions**: Ensuring the Terraform service account has the necessary IAM permissions to create, modify, and delete resources is vital.
- **Incorrect Resource Dependencies**: Managing resource dependencies correctly to prevent errors during creation or deletion.
- **Handling Sensitive Data Insecurely**: Implementing robust measures for managing sensitive data, such as API keys and passwords, by using AWS Secrets Manager or other appropriate services.
- **Neglecting to Monitor Infrastructure**: Setting up comprehensive monitoring and alerting to detect and respond to infrastructure issues promptly.
- **Using hardcoded values**: Always use variables
### 6.2 Edge Cases to be Aware Of
- **Resource Limits**: Be aware of AWS resource limits and plan accordingly.
- **Availability Zones**: Understand the implications of availability zones and design your infrastructure to be resilient to AZ failures.
- **Data Consistency**: Understand the consistency models of different AWS services and design your applications accordingly.
- **API Throttling**: Be aware of API throttling limits and implement retry logic.
### 6.3 Version-Specific Issues
- **Terraform Version Compatibility**: Ensure that your Terraform code is compatible with the version of Terraform you are using.
- **Provider Version Compatibility**: Ensure that your Terraform providers are compatible with the version of Terraform you are using.
- **AWS API Version Compatibility**: Be aware of changes to the AWS API and update your code accordingly.
### 6.4 Compatibility Concerns
- **Backwards Compatibility**: Ensure that your changes are backwards compatible.
- **Cross-Region Compatibility**: Ensure that your infrastructure is compatible across different AWS regions.
- **Cross-Account Compatibility**: Ensure that your infrastructure is compatible across different AWS accounts.
### 6.5 Debugging Strategies
- **Terraform Plan**: Use `terraform plan` to preview changes before applying them.
- **Terraform Show**: Use `terraform show` to inspect the current state of your infrastructure.
- **Terraform Graph**: Use `terraform graph` to visualize the dependencies between resources.
- **Terraform Console**: Use `terraform console` to evaluate Terraform expressions.
- **AWS CloudTrail**: Use AWS CloudTrail to audit API calls and identify errors.
- **CloudWatch Logs**: Use CloudWatch Logs to collect and analyze application logs.
- **Enable Debug Logging**: Enable debug logging to get more detailed information about what Terraform is doing.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **Terraform CLI**: The Terraform command-line interface.
- **IDE with Terraform Support**: Use an IDE with Terraform support (e.g., VS Code with the Terraform extension).
- **tfenv**: Use tfenv to manage multiple versions of Terraform.
- **AWS CLI**: The AWS command-line interface.
- **jq**: A command-line JSON processor.
### 7.2 Build Configuration
- **Makefile**: Use a Makefile to automate common build tasks (e.g., `terraform init`, `terraform plan`, `terraform apply`).
- **.terraformignore**: Create a `.terraformignore` to prevent files from being included in the Terraform package.
### 7.3 Linting and Formatting
- **terraform fmt**: Use `terraform fmt` to automatically format your Terraform code.
- **terraform validate**: Use `terraform validate` to validate your Terraform code.
- **tflint**: Use `tflint` to lint your Terraform code.
- **pre-commit hooks**: Enforce code quality standards using pre-commit hooks.
### 7.4 Deployment Best Practices
- **Automated Deployments**: Use automated deployments to reduce errors and improve consistency.
- **Infrastructure as Code (IaC)**: Manage infrastructure as code using tools like Terraform.
- **Immutable Infrastructure**: Deploy new infrastructure components instead of modifying existing ones.
- **Blue/Green Deployments**: Deploy new versions of applications alongside existing ones, then switch traffic.
- **Canary Deployments**: Deploy new versions of applications to a small subset of users before rolling them out to everyone.
### 7.5 CI/CD Integration
- **Integrate with CI/CD Pipeline**: Integrate Terraform with your CI/CD pipeline.
- **Automated Testing**: Run automated tests as part of your CI/CD pipeline.
- **Automated Deployments**: Automatically deploy your infrastructure as part of your CI/CD pipeline.
- **Version Control**: Store your Terraform code in version control.
- **Terraform Cloud/Enterprise**: Use Terraform Cloud/Enterprise for remote state management and collaboration.
This document provides a comprehensive set of best practices for AWS development using Terraform. By following these guidelines, you can ensure your code is maintainable, secure, and efficient.
@@ -0,0 +1,347 @@
---
description: This rule provides comprehensive best practices for developing Azure applications, covering code organization, security, performance, testing, and common pitfalls. It aims to improve code quality, security posture, and overall efficiency when working with the Azure ecosystem.
globs: **/*.{az,tf,bicep,py,js,ts,json,yml,yaml,ps1,sh,cs,java}
---
# Azure Library Best Practices and Coding Standards
This document outlines the recommended best practices for developing applications and infrastructure using Azure services. It covers various aspects including code organization, security, performance, testing, and tooling to ensure robust, scalable, and secure solutions.
## 1. Code Organization and Structure
A well-organized codebase is crucial for maintainability, scalability, and collaboration. The following guidelines provide a structured approach to organizing your Azure projects.
### Directory Structure Best Practices
Adopt a modular and logical directory structure based on the application's architecture and components.
* **`src/`**: Contains the source code of your application.
* **`modules/`**: Groups related functionalities into independent modules.
* **`components/`**: Contains reusable UI or logical components.
* **`services/`**: Encapsulates external service integrations (e.g., Azure Storage, Cosmos DB).
* **`models/`**: Defines data models and schemas.
* **`utils/`**: Contains utility functions and helper classes.
* **`infra/` or `terraform/` or `bicep/`**: Infrastructure-as-Code definitions (Terraform, Bicep, Azure Resource Manager templates).
* **`config/`**: Configuration files for different environments (development, staging, production).
* **`scripts/`**: Automation scripts for deployment, build processes, etc.
* **`tests/`**: Unit, integration, and end-to-end tests.
* **`docs/`**: Documentation for the project and its components.
Example:
my-azure-project/
├── src/
│ ├── modules/
│ │ ├── user-management/
│ │ │ ├── ...
│ │ ├── data-processing/
│ │ │ ├── ...
│ ├── components/
│ │ ├── button/
│ │ │ ├── ...
│ ├── services/
│ │ ├── storage-service.js
│ │ ├── cosmosdb-service.js
│ ├── models/
│ │ ├── user.js
│ ├── utils/
│ │ ├── logger.js
├── infra/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
├── config/
│ ├── development.json
│ ├── production.json
├── scripts/
│ ├── deploy.sh
│ ├── build.sh
├── tests/
│ ├── unit/
│ ├── integration/
│ ├── e2e/
├── docs/
│ ├── README.md
├── .gitignore
├── package.json
### File Naming Conventions
Maintain consistency in file naming to improve readability and searchability.
* Use descriptive names that reflect the file's purpose.
* Use a consistent case (e.g., camelCase or kebab-case).
* Use appropriate file extensions (e.g., `.js`, `.ts`, `.py`, `.tf`, `.bicep`).
* For React components, use `ComponentName.jsx` or `ComponentName.tsx`.
Example:
* `user-service.js` (for a user service module)
* `UserProfile.jsx` (for a user profile component)
* `storage-account.tf` (for a Terraform file defining a storage account)
### Module Organization
Divide the application into independent and reusable modules based on functionality.
* Each module should have a clear responsibility and a well-defined interface.
* Minimize dependencies between modules to promote loose coupling.
* Consider using a module bundler (e.g., Webpack, Parcel) to manage dependencies and optimize the build process.
Example:
A `user-management` module could contain components and services related to user authentication, authorization, and profile management.
### Component Architecture
For UI-based applications, adopt a component-based architecture (e.g., React, Angular, Vue.js).
* Divide the UI into reusable components with clear inputs and outputs.
* Follow the principles of single responsibility and separation of concerns.
* Use a component library (e.g., Material UI, Ant Design) to accelerate development and maintain consistency.
### Code Splitting Strategies
Improve initial load time by splitting the application into smaller chunks that can be loaded on demand.
* Use dynamic imports to load modules only when they are needed.
* Configure your module bundler to create separate chunks for different parts of the application.
* Consider using route-based code splitting for single-page applications.
## 2. Common Patterns and Anti-patterns
Understanding common patterns and anti-patterns is essential for building efficient, maintainable, and reliable Azure applications.
### Design Patterns Specific to Azure
* **Retry Pattern:** Implement retry logic to handle transient failures when interacting with Azure services.
* **Circuit Breaker Pattern:** Prevent cascading failures by temporarily blocking access to a service that is experiencing problems.
* **Queue-Based Load Leveling:** Use queues (e.g., Azure Queue Storage, Azure Service Bus) to decouple components and handle bursts of traffic.
* **Cache-Aside Pattern:** Use a cache (e.g., Azure Cache for Redis) to improve performance by storing frequently accessed data.
* **Gateway Aggregation Pattern:** Expose multiple backend services through a single API gateway (e.g., Azure API Management).
### Recommended Approaches for Common Tasks
* **Configuration Management:** Use Azure App Configuration to manage application settings and feature flags.
* **Secret Management:** Use Azure Key Vault to securely store and manage secrets, keys, and certificates.
* **Logging and Monitoring:** Use Azure Monitor to collect and analyze logs, metrics, and traces.
* **Identity and Access Management:** Use Azure Active Directory (Azure AD) for authentication and authorization.
* **Data Storage:** Choose the appropriate Azure storage service based on your data requirements (e.g., Azure Blob Storage for unstructured data, Azure Cosmos DB for NoSQL data, Azure SQL Database for relational data).
### Anti-Patterns and Code Smells to Avoid
* **Hardcoding Secrets:** Never hardcode secrets or API keys in your code. Use Azure Key Vault to manage them securely.
* **Ignoring Errors:** Always handle errors gracefully and log relevant information for debugging.
* **Over-Engineering:** Avoid unnecessary complexity and focus on delivering business value.
* **Long-Running Transactions:** Keep transactions short and avoid holding resources for extended periods.
* **Tight Coupling:** Design components and modules to be loosely coupled to improve maintainability and testability.
* **Monolithic Functions:** Avoid creating large, complex functions. Break them down into smaller, more manageable units.
### State Management Best Practices
* For serverless functions, design for statelessness whenever possible. Store state in external storage services like Azure Cosmos DB or Azure Storage.
* For web applications, use appropriate state management techniques (e.g., cookies, sessions, local storage, or dedicated state management libraries like Redux or Zustand).
* Consider using distributed caching (e.g., Azure Cache for Redis) to improve performance and scalability.
### Error Handling Patterns
* Use try-catch blocks to handle exceptions gracefully.
* Log errors with sufficient detail to aid in debugging.
* Implement a centralized error handling mechanism to catch and handle unhandled exceptions.
* Provide meaningful error messages to the user.
* Use Polly library for implementing resilience policies like retry, circuit breaker, and timeout.
## 3. Performance Considerations
Optimizing performance is crucial for delivering a responsive and scalable Azure application.
### Optimization Techniques
* **Caching:** Implement caching at various levels (e.g., browser, server, database) to reduce latency and improve performance.
* **Compression:** Enable compression (e.g., Gzip) to reduce the size of HTTP responses.
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead.
* **Content Delivery Network (CDN):** Use Azure CDN to cache static assets closer to users.
* **Database Optimization:** Optimize database queries and indexes to improve query performance.
* **Asynchronous Operations:** Use asynchronous operations to avoid blocking the main thread.
### Memory Management
* **Dispose Resources:** Dispose of disposable resources (e.g., database connections, file streams) properly to avoid memory leaks.
* **Garbage Collection:** Be aware of garbage collection behavior and avoid creating unnecessary objects.
* **Large Object Heap (LOH):** Be mindful of the LOH and avoid allocating large objects frequently.
### Rendering Optimization
* **Virtualization:** Use virtualization techniques (e.g., React Virtualized, Angular CDK Virtual Scroll) to efficiently render large lists of data.
* **Debouncing and Throttling:** Use debouncing and throttling to limit the frequency of event handlers.
* **Lazy Loading:** Load images and other resources only when they are visible on the screen.
### Bundle Size Optimization
* **Tree Shaking:** Use tree shaking to remove unused code from your bundles.
* **Code Splitting:** Split your code into smaller chunks that can be loaded on demand.
* **Minification:** Minify your code to reduce its size.
* **Image Optimization:** Optimize images by compressing them and using appropriate formats.
### Lazy Loading Strategies
* **Component-Based Lazy Loading:** Load components only when they are needed.
* **Route-Based Lazy Loading:** Load modules associated with specific routes only when those routes are accessed.
* **Image Lazy Loading:** Load images only when they are scrolled into view.
## 4. Security Best Practices
Security should be a top priority when developing Azure applications.
### Common Vulnerabilities and How to Prevent Them
* **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
* **Cross-Site Scripting (XSS):** Sanitize user input and output to prevent XSS attacks.
* **Cross-Site Request Forgery (CSRF):** Use anti-CSRF tokens to prevent CSRF attacks.
* **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms.
* **Insecure Direct Object References (IDOR):** Validate that users have access to the resources they are requesting.
* **Security Misconfiguration:** Follow security best practices for configuring Azure services.
* **Sensitive Data Exposure:** Protect sensitive data by encrypting it at rest and in transit.
### Input Validation
* Validate all user input on both the client and server sides.
* Use a schema validation library (e.g., Joi, Yup) to define and enforce data validation rules.
* Sanitize user input to remove potentially malicious characters.
### Authentication and Authorization Patterns
* Use Azure Active Directory (Azure AD) for authentication and authorization.
* Implement role-based access control (RBAC) to restrict access to resources based on user roles.
* Use multi-factor authentication (MFA) to enhance security.
* Follow the principle of least privilege.
* Leverage Managed Identities for Azure resources to securely access other Azure services.
### Data Protection Strategies
* Encrypt sensitive data at rest using Azure Storage Service Encryption (SSE) or Azure Disk Encryption.
* Encrypt data in transit using TLS/SSL.
* Use Azure Key Vault to store and manage encryption keys.
* Implement data masking and tokenization to protect sensitive data.
### Secure API Communication
* Use HTTPS for all API communication.
* Implement API authentication using API keys, tokens, or OAuth 2.0.
* Use rate limiting to prevent abuse.
* Use Azure API Management to manage and secure your APIs.
## 5. Testing Approaches
Thorough testing is essential for ensuring the quality and reliability of your Azure applications.
### Unit Testing Strategies
* Write unit tests for individual components and functions.
* Use a unit testing framework (e.g., Jest, Mocha, JUnit, pytest).
* Aim for high code coverage.
* Follow the Arrange-Act-Assert pattern.
* Use mocks and stubs to isolate the code under test.
### Integration Testing
* Write integration tests to verify the interaction between different components and services.
* Test the integration with Azure services (e.g., Azure Storage, Cosmos DB).
* Use a testing environment that closely resembles the production environment.
### End-to-End Testing
* Write end-to-end tests to verify the entire application workflow.
* Use a testing framework (e.g., Cypress, Selenium, Playwright).
* Automate end-to-end tests as part of your CI/CD pipeline.
### Test Organization
* Organize tests into a clear directory structure.
* Use descriptive test names.
* Group related tests together.
### Mocking and Stubbing
* Use mocks to simulate the behavior of external dependencies.
* Use stubs to provide predefined responses for API calls.
* Use a mocking framework (e.g., Mockito, Jest Mocks).
## 6. Common Pitfalls and Gotchas
Be aware of common pitfalls and gotchas to avoid making mistakes when developing Azure applications.
### Frequent Mistakes Developers Make
* **Insufficient Resource Sizing:** Underestimating the required resources can lead to performance issues.
* **Ignoring Azure Service Limits:** Being unaware of Azure service limits can cause unexpected errors.
* **Improper Error Handling:** Inadequate error handling can make it difficult to diagnose and resolve issues.
* **Lack of Monitoring:** Failing to monitor the application's performance and health can lead to undetected problems.
* **Neglecting Security:** Overlooking security best practices can expose the application to vulnerabilities.
### Edge Cases to Be Aware Of
* **Network Latency:** Be aware of network latency when interacting with Azure services.
* **Transient Faults:** Implement retry logic to handle transient faults.
* **Resource Contention:** Be aware of resource contention and design the application to handle it gracefully.
* **Data Consistency:** Understand the data consistency models of Azure storage services.
### Version-Specific Issues
* Be aware of breaking changes in Azure SDKs and APIs.
* Keep your dependencies up to date.
* Test your application with different versions of Azure services.
### Compatibility Concerns
* Ensure that your application is compatible with the target Azure environment.
* Test your application on different browsers and devices.
### Debugging Strategies
* Use Azure Monitor to collect and analyze logs, metrics, and traces.
* Use remote debugging to debug your application running in Azure.
* Use logging to track the flow of execution and identify errors.
* Use breakpoints to pause execution and inspect variables.
## 7. Tooling and Environment
Choosing the right tools and environment can significantly improve your development experience.
### Recommended Development Tools
* **Visual Studio Code:** A popular code editor with excellent support for Azure development.
* **Azure CLI:** A command-line tool for managing Azure resources.
* **Azure PowerShell:** A PowerShell module for managing Azure resources.
* **Terraform:** An infrastructure-as-code tool for provisioning and managing Azure resources.
* **Bicep:** A declarative language for deploying Azure resources.
* **Azure SDKs:** Libraries for interacting with Azure services from various programming languages.
### Build Configuration
* Use a build automation tool (e.g., Azure DevOps, Jenkins, GitHub Actions) to automate the build process.
* Configure your build process to run tests, linters, and code formatters.
* Use environment variables to configure your application for different environments.
### Linting and Formatting
* Use a linter (e.g., ESLint, Pylint) to enforce code style guidelines.
* Use a code formatter (e.g., Prettier, Black) to automatically format your code.
* Configure your editor to automatically run the linter and formatter on save.
### Deployment Best Practices
* Use Infrastructure-as-Code (IaC) to automate the deployment of Azure resources.
* Use a deployment pipeline (e.g., Azure Pipelines, GitHub Actions) to automate the deployment process.
* Use blue-green deployments or canary deployments to minimize downtime.
* Implement rollback strategies to quickly revert to a previous version if necessary.
### CI/CD Integration
* Integrate your CI/CD pipeline with Azure DevOps, GitHub Actions, or other CI/CD tools.
* Automate the build, test, and deployment processes.
* Use environment variables to configure your application for different environments.
* Implement automated testing to catch errors early in the development cycle.
By following these best practices, you can build robust, scalable, secure, and maintainable Azure applications.
@@ -0,0 +1,196 @@
---
description: This rule provides best practices for developing and managing infrastructure and applications on Google Cloud Platform (GCP), encompassing code organization, security, performance, and deployment strategies.
globs: **/*.{tf,py,js,go,java,proto,sh,yaml,yml}
---
---
## GCP Library Best Practices
This document outlines best practices for developing and managing applications and infrastructure on Google Cloud Platform (GCP). It covers various aspects, including code organization, common patterns, performance, security, testing, common pitfalls, and tooling.
### 1. Code Organization and Structure
- **Follow a Standard Module Structure (especially for Terraform)**:
- Start every module with a `main.tf` file. This file contains the primary resources defined in the module.
- Include a `README.md` file for module documentation. This should explain the module's purpose, usage, inputs, and outputs.
- Group related resources logically in separate files (e.g., `network.tf`, `compute.tf`, `storage.tf`).
- Use folders to logically group files.
- **Directory Structure Best Practices:**
- `modules/`: Contains reusable Terraform modules. Each module should encapsulate a specific set of resources or functionality.
- `environments/`: Contains environment-specific configurations (e.g., `dev/`, `staging/`, `prod/`). Each environment directory should contain its own `terraform.tfvars` and `backend.tf` (or equivalent).
- `scripts/`: Contains utility scripts (e.g., Python, Bash) for automation.
- `docs/`: Contains documentation for the project.
- `examples/`: Contains example configurations or usage scenarios.
- **File Naming Conventions:**
- Use descriptive names for Terraform files (e.g., `vpc.tf`, `firewall.tf`, `iam.tf`).
- Use underscores for resource names and avoid repeating resource types in names (e.g., `instance_web_server` instead of `web_server_instance`).
- Use consistent naming conventions for variables and outputs.
- **Module Organization:**
- Keep modules small and focused. Each module should have a single responsibility.
- Use input variables to parameterize modules. This makes them reusable and configurable.
- Define outputs for modules to expose important information. This allows other modules or configurations to consume the module's results.
- **Component Architecture (for application code):**
- Adopt a layered architecture (e.g., presentation, business logic, data access).
- Use dependency injection to decouple components and improve testability.
- Design components for reusability and maintainability.
- Use well-defined interfaces between components.
- **Code Splitting Strategies (especially for client-side code):**
- Split code into logical chunks based on functionality or features.
- Use lazy loading to load code only when it's needed. This can improve initial page load time.
- Consider using code splitting tools like Webpack or Parcel.
### 2. Common Patterns and Anti-patterns
- **Design Patterns Specific to GCP:**
- **Service Facade:** Abstract complex GCP service interactions behind a simple interface.
- **Pub/Sub Fanout:** Use Cloud Pub/Sub to distribute messages to multiple subscribers for parallel processing.
- **Cloud Functions Chaining:** Chain Cloud Functions together to create complex workflows.
- **Idempotent Operations:** Ensure operations can be safely retried without unintended side effects, especially crucial in distributed systems like GCP.
- **Recommended Approaches for Common Tasks:**
- **Configuration Management:** Use environment variables or Cloud KMS for storing sensitive configuration data.
- **Secret Management:** Use Cloud Secret Manager to securely store and manage secrets.
- **Data Storage:** Choose the appropriate storage solution based on the data type and access patterns (e.g., Cloud Storage for objects, Cloud SQL for relational data, Cloud Datastore for NoSQL data).
- **Logging:** Use Cloud Logging for centralized logging and monitoring.
- **Monitoring:** Utilize Cloud Monitoring and Cloud Trace for performance monitoring and troubleshooting.
- **Identity and Access Management (IAM):** Adopt the principle of least privilege. Grant users and service accounts only the necessary permissions.
- **Anti-patterns and Code Smells to Avoid:**
- **Hardcoding Credentials:** Never hardcode credentials in code or configuration files. Use environment variables, secret management, or IAM roles.
- **Overly Complex IAM Roles:** Avoid creating overly complex IAM roles with too many permissions. This can lead to security vulnerabilities.
- **Ignoring Error Handling:** Always handle errors gracefully and provide informative error messages.
- **Long-Running Processes in Cloud Functions:** Cloud Functions have time limits. Offload long-running processes to other services like Cloud Run or Compute Engine.
- **Lack of Monitoring:** Failing to monitor your application can lead to undetected performance issues and errors.
- **Ignoring Security Updates:** Regularly update your dependencies and software to address security vulnerabilities.
- **State Management Best Practices:**
- **Use Terraform State:** Store Terraform state remotely in Cloud Storage for collaboration and version control.
- **Stateless Applications:** Design applications to be stateless whenever possible. If state is required, store it in a persistent storage solution like Cloud SQL or Cloud Datastore.
- **Avoid Local Storage:** Do not rely on local storage for persistent data. Use Cloud Storage or other persistent storage solutions.
- **Error Handling Patterns:**
- **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions consistently.
- **Logging and Monitoring:** Log all errors to Cloud Logging and set up alerts for critical errors in Cloud Monitoring.
- **Retry Mechanisms:** Implement retry mechanisms for transient errors.
- **Circuit Breaker Pattern:** Use the circuit breaker pattern to prevent cascading failures in distributed systems.
### 3. Performance Considerations
- **Optimization Techniques:**
- **Caching:** Implement caching at various levels (e.g., browser, CDN, server-side) to reduce latency and improve performance. Consider using Cloud CDN or Memorystore.
- **Load Balancing:** Use Cloud Load Balancing to distribute traffic across multiple instances for high availability and scalability.
- **Database Optimization:** Optimize database queries and indexing to improve performance. Consider using Cloud SQL Insights for query analysis.
- **Asynchronous Operations:** Use asynchronous operations for long-running tasks to prevent blocking the main thread.
- **Memory Management (for application code):**
- **Efficient Data Structures:** Choose appropriate data structures to minimize memory usage.
- **Garbage Collection:** Understand how garbage collection works in your chosen language and optimize code to minimize memory leaks.
- **Resource Pooling:** Use resource pooling to reuse expensive resources like database connections.
- **Rendering Optimization (for web applications):**
- **Minimize DOM Manipulation:** Minimize DOM manipulation to improve rendering performance.
- **Use Virtual DOM:** Use a virtual DOM library like React or Vue.js to optimize rendering updates.
- **Optimize Images:** Optimize images for web use by compressing them and using appropriate formats (e.g., WebP).
- **Bundle Size Optimization (for web applications):**
- **Code Splitting:** Split code into smaller chunks to reduce initial bundle size.
- **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
- **Minification:** Minify code to reduce bundle size.
- **Lazy Loading Strategies (for web applications):**
- **Lazy Load Images:** Lazy load images that are not initially visible on the page.
- **Lazy Load Modules:** Lazy load modules that are not immediately required.
- **Intersection Observer:** Use the Intersection Observer API to detect when elements are visible in the viewport.
### 4. Security Best Practices
- **Common Vulnerabilities and How to Prevent Them:**
- **SQL Injection:** Prevent SQL injection by using parameterized queries or object-relational mappers (ORMs).
- **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user inputs and encoding outputs.
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using anti-CSRF tokens.
- **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data.
- **Input Validation:**
- **Validate All Inputs:** Validate all user inputs on both the client-side and server-side.
- **Use Regular Expressions:** Use regular expressions to validate input formats.
- **Sanitize Inputs:** Sanitize inputs to remove potentially malicious characters.
- **Authentication and Authorization Patterns:**
- **Identity-Aware Proxy (IAP):** Use IAP to control access to applications running on Compute Engine, GKE, and App Engine.
- **Firebase Authentication:** Use Firebase Authentication to easily implement authentication in web and mobile applications.
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
- **Service Accounts:** Use service accounts to authenticate applications running on GCP.
- **Data Protection Strategies:**
- **Encryption at Rest:** Encrypt data at rest using Cloud KMS or Cloud Storage encryption.
- **Encryption in Transit:** Encrypt data in transit using HTTPS (TLS).
- **Data Loss Prevention (DLP):** Use Cloud DLP to prevent sensitive data from being leaked.
- **Secure API Communication:**
- **HTTPS:** Always use HTTPS for API communication.
- **API Keys:** Use API keys to authenticate API clients.
- **JWTs:** Use JWTs for secure API authorization.
- **Rate Limiting:** Implement rate limiting to prevent abuse.
### 5. Testing Approaches
- **Unit Testing Strategies:**
- **Test Individual Units:** Test individual units of code (e.g., functions, classes) in isolation.
- **Use Mocking:** Use mocking to isolate units of code from dependencies.
- **Test Edge Cases:** Test edge cases and boundary conditions.
- **Integration Testing:**
- **Test Interactions:** Test the interactions between different units of code or components.
- **Test Database Interactions:** Test interactions with databases and other external systems.
- **Use Test Databases:** Use test databases to avoid affecting production data.
- **End-to-End Testing:**
- **Test Complete Workflows:** Test complete workflows from start to finish.
- **Simulate User Interactions:** Simulate user interactions to ensure the application behaves as expected.
- **Use Automated Testing Tools:** Use automated testing tools to automate end-to-end tests.
- **Test Organization:**
- **Organize Tests by Component:** Organize tests by component or module.
- **Use a Consistent Naming Convention:** Use a consistent naming convention for test files and test cases.
- **Keep Tests Separate from Code:** Keep tests separate from production code.
- **Mocking and Stubbing:**
- **Use Mocking Libraries:** Use mocking libraries to create mock objects and stubs.
- **Mock External Dependencies:** Mock external dependencies like APIs and databases.
- **Stub Responses:** Stub responses from external services to control test behavior.
### 6. Common Pitfalls and Gotchas
- **Frequent Mistakes Developers Make:**
- **Incorrect IAM Permissions:** Assigning overly broad IAM permissions.
- **Misconfiguring Network Settings:** Misconfiguring firewall rules or VPC settings.
- **Ignoring Cost Optimization:** Failing to optimize resource usage and costs.
- **Not Using Managed Services:** Trying to manage infrastructure manually instead of using GCP managed services.
- **Lack of Automation:** Not automating deployments and infrastructure management.
- **Edge Cases to be Aware of:**
- **Network Latency:** Account for network latency in distributed systems.
- **Concurrency Issues:** Handle concurrency issues correctly in multi-threaded applications.
- **Data Consistency:** Ensure data consistency across distributed systems.
- **Version-Specific Issues:**
- **API Compatibility:** Be aware of API compatibility issues when upgrading GCP SDKs or services.
- **Deprecated Features:** Avoid using deprecated features.
- **Compatibility Concerns:**
- **Cross-Browser Compatibility:** Ensure web applications are compatible with different browsers.
- **Mobile Compatibility:** Ensure web applications are responsive and compatible with mobile devices.
- **Debugging Strategies:**
- **Use Cloud Debugger:** Use Cloud Debugger to debug applications running on GCP.
- **Use Logging:** Use Cloud Logging to log debug information.
- **Use Monitoring:** Use Cloud Monitoring to monitor application performance and identify issues.
- **Local Debugging:** Debug applications locally before deploying them to GCP.
### 7. Tooling and Environment
- **Recommended Development Tools:**
- **Google Cloud SDK (gcloud):** Command-line tool for interacting with GCP services.
- **Terraform:** Infrastructure as code tool for managing GCP resources.
- **IDE with GCP Support:** Use an IDE with GCP support (e.g., VS Code with the Google Cloud Code extension).
- **Docker:** Containerization platform for building and deploying applications.
- **Build Configuration:**
- **Use Build Automation Tools:** Use build automation tools like Maven, Gradle, or npm.
- **Define Build Steps:** Define clear build steps for compiling, testing, and packaging applications.
- **Manage Dependencies:** Manage dependencies using dependency management tools like Maven, Gradle, or npm.
- **Linting and Formatting:**
- **Use Linters:** Use linters to enforce code style and identify potential issues.
- **Use Formatters:** Use formatters to automatically format code.
- **Configure Linters and Formatters:** Configure linters and formatters to match project coding standards.
- **Deployment Best Practices:**
- **Automate Deployments:** Automate deployments using CI/CD pipelines.
- **Use Infrastructure as Code:** Use infrastructure as code (e.g., Terraform) to manage infrastructure.
- **Blue/Green Deployments:** Use blue/green deployments to minimize downtime.
- **Canary Deployments:** Use canary deployments to gradually roll out new features.
- **Rollback Strategy:** Have a rollback strategy in place to revert to a previous version if necessary.
- **CI/CD Integration:**
- **Use Cloud Build:** Use Cloud Build for CI/CD pipelines on GCP.
- **Integrate with Version Control:** Integrate CI/CD pipelines with version control systems (e.g., GitHub, GitLab, Cloud Source Repositories).
- **Automate Testing:** Automate testing as part of the CI/CD pipeline.
- **Automate Deployments:** Automate deployments as part of the CI/CD pipeline.
By following these best practices, developers can build robust, secure, and scalable applications and infrastructure on Google Cloud Platform.
@@ -0,0 +1,220 @@
---
description: Comprehensive guide for AWS Lambda development, covering best practices for code organization, performance, security, testing, and common pitfalls. Focuses on building robust, scalable, and secure serverless applications using AWS Lambda.
globs: **/*.{js,ts,jsx,tsx,py,java,go,c#,cs,ps1,sh}
---
- **Use Documented APIs Only:** Rely solely on AWS Lambda's documented APIs to ensure compatibility and avoid unexpected behavior. Do not use undocumented or internal APIs.
- **Single Responsibility Principle:** Design Lambda functions to perform a single, well-defined task. This promotes modularity, testability, and maintainability.
- **Native AWS Integrations:** Prefer native AWS integrations (e.g., SQS, SNS, Kinesis) for passing data between services instead of custom code, which enhances scalability and reduces complexity.
- **Local Dependencies:** Store and reference dependencies locally within the Lambda function package to minimize latency and improve cold start times.
- **Limit Variable Re-initialization:** Initialize variables outside the function handler to leverage execution context reuse and reduce initialization overhead.
- **Thorough Testing:** Implement a comprehensive testing strategy including unit, integration, and end-to-end tests to ensure function correctness and reliability.
## 1. Code Organization and Structure:
- **Directory Structure:**
- Organize code into logical directories based on functionality (e.g., `src`, `tests`, `utils`).
- Separate handler logic from core business logic.
- Example:
my-lambda-function/
├── src/
│ ├── handler.js # Lambda handler function
│ ├── business-logic.js # Core business logic
│ └── utils.js # Utility functions
├── tests/
│ ├── handler.test.js # Unit tests for handler.js
│ └── ...
├── package.json # Dependencies and scripts
└── ...
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- Follow a naming convention (e.g., `kebab-case`, `PascalCase`) consistently.
- Example: `user-service.js`, `UserService.java`.
- **Module Organization:**
- Break down large functions into smaller, reusable modules.
- Use appropriate module systems (e.g., ES modules in JavaScript, packages in Python, modules in Go).
- Example (JavaScript):
javascript
// src/user-service.js
export function createUser(userData) { ... }
export function getUser(userId) { ... }
- **Component Architecture:**
- Design Lambda functions as part of a larger component-based architecture.
- Decouple functions from specific triggers (e.g., API Gateway, SQS) to increase reusability.
- Implement interfaces or contracts to define interactions between components.
- **Code Splitting Strategies:**
- Use code splitting techniques to reduce Lambda function package size.
- Implement dynamic imports or lazy loading for infrequently used modules (where supported by the runtime).
- Leverage layers for shared dependencies across multiple functions.
## 2. Common Patterns and Anti-patterns:
- **Design Patterns:**
- **Event-Driven Architecture:** Design functions to respond to events from various AWS services.
- **Command Pattern:** Encapsulate requests as objects to decouple request processing from the handler.
- **Dependency Injection:** Inject dependencies into functions to improve testability and maintainability.
- **Recommended Approaches:**
- **Configuration Management:** Use environment variables or AWS Systems Manager Parameter Store for configuration data.
- **Logging:** Implement structured logging with timestamps, request IDs, and relevant context.
- **Idempotency:** Ensure functions are idempotent to handle potential retry scenarios gracefully.
- **Anti-patterns:**
- **Monolithic Functions:** Avoid creating large, complex functions that perform multiple unrelated tasks.
- **Hardcoding Secrets:** Never hardcode sensitive information (e.g., API keys, passwords) in code. Use AWS Secrets Manager or environment variables.
- **Excessive Dependencies:** Minimize the number of dependencies to reduce package size and improve cold start times.
- **State Management:**
- Use external services (e.g., DynamoDB, Redis) for persistent state management.
- Leverage Lambda layers for caching frequently accessed data.
- Design functions to be stateless whenever possible.
- **Error Handling:**
- Implement robust error handling mechanisms, including try-catch blocks and error logging.
- Use custom exceptions for specific error scenarios.
- Return meaningful error messages to the caller.
- Implement dead-letter queues (DLQs) for asynchronous invocations to handle failed events.
## 3. Performance Considerations:
- **Optimization Techniques:**
- **Minimize Package Size:** Reduce the size of the deployment package by removing unnecessary files and dependencies.
- **Optimize Dependencies:** Use lightweight dependencies and avoid importing entire libraries when only specific functions are needed.
- **Code Optimization:** Profile and optimize code for performance bottlenecks.
- **Connection Reuse:** Reuse database connections, HTTP clients, and other resources to minimize overhead.
- **Memory Management:**
- Allocate sufficient memory to Lambda functions based on their needs.
- Monitor memory usage and adjust the memory allocation accordingly.
- Clean up resources (e.g., closing file streams, releasing memory) to avoid memory leaks.
- **Cold Starts:**
- Minimize cold start times by reducing package size, optimizing dependencies, and using provisioned concurrency.
- Use initilization logic outside the handler to take advantage of container reuse
- **Bundle Size Optimization:**
- Use tools like Webpack or esbuild to bundle and optimize code for production.
- Minify code and remove unused code (dead code elimination).
- **Lazy Loading Strategies:**
- Implement lazy loading or dynamic imports for infrequently used modules to reduce initial load time.
## 4. Security Best Practices:
- **Common Vulnerabilities:**
- **Injection Attacks:** Prevent SQL injection, command injection, and other injection attacks by validating and sanitizing input.
- **Cross-Site Scripting (XSS):** Protect against XSS vulnerabilities by encoding output properly.
- **Insecure Deserialization:** Avoid deserializing untrusted data to prevent arbitrary code execution.
- **Broken Authentication:** Implement strong authentication and authorization mechanisms.
- **Input Validation:**
- Validate all input data to prevent malicious or invalid data from being processed.
- Use schema validation libraries to enforce data types and formats.
- Sanitize input data to remove potentially harmful characters or code.
- **Authentication and Authorization:**
- Use AWS Identity and Access Management (IAM) roles to grant Lambda functions the necessary permissions.
- Implement authentication and authorization mechanisms to protect sensitive resources.
- Use AWS Cognito for user authentication and authorization.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use AWS Key Management Service (KMS) to manage encryption keys.
- Mask or redact sensitive data in logs.
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Implement API authentication and authorization using API keys, JWT tokens, or other secure mechanisms.
- Protect against common web application attacks (e.g., CSRF, DDoS).
## 5. Testing Approaches:
- **Unit Testing:**
- Write unit tests to verify the correctness of individual functions or modules.
- Use mocking or stubbing to isolate units of code from external dependencies.
- Use testing frameworks (e.g., Jest, Mocha, pytest) to automate unit testing.
- **Integration Testing:**
- Write integration tests to verify the interactions between different components or services.
- Test the integration of Lambda functions with other AWS services (e.g., SQS, DynamoDB).
- Use tools like AWS SAM Local to run integration tests locally.
- **End-to-End Testing:**
- Write end-to-end tests to verify the entire application flow from end to end.
- Simulate user interactions to test the application's functionality.
- Use tools like Selenium or Cypress to automate end-to-end testing.
- **Test Organization:**
- Organize tests into separate directories based on the type of test (e.g., unit, integration, e2e).
- Use descriptive test names to clearly identify the purpose of each test.
- Follow a consistent testing strategy across all projects.
- **Mocking and Stubbing:**
- Use mocking or stubbing to replace external dependencies with controlled test doubles.
- Mock AWS SDK calls to isolate Lambda functions from AWS services.
- Use mocking frameworks (e.g., Jest, Sinon.js) to simplify mocking and stubbing.
## 6. Common Pitfalls and Gotchas:
- **Frequent Mistakes:**
- **Incorrect IAM Permissions:** Ensure that Lambda functions have the necessary IAM permissions to access required AWS resources.
- **Timeout Errors:** Increase the Lambda function timeout if it takes longer than expected to complete.
- **Memory Exhaustion:** Allocate sufficient memory to Lambda functions to avoid memory exhaustion errors.
- **Unclosed Connections:** Close database connections, HTTP clients, and other resources properly to avoid resource leaks.
- **Edge Cases:**
- **Concurrent Invocations:** Handle concurrent invocations gracefully to avoid race conditions or data corruption.
- **Throttling:** Implement retry mechanisms to handle throttling errors from AWS services.
- **Error Retries:** Design functions to be idempotent to handle potential retry scenarios gracefully.
- **Version-Specific Issues:**
- Be aware of version-specific issues or compatibility concerns when upgrading Lambda function runtimes or dependencies.
- Test Lambda functions thoroughly after upgrading to ensure they still function correctly.
- **Compatibility Concerns:**
- Ensure that Lambda functions are compatible with the supported runtime environment.
- Use compatible versions of dependencies to avoid compatibility issues.
- **Debugging Strategies:**
- Use CloudWatch Logs to debug Lambda function execution.
- Use AWS X-Ray to trace and analyze Lambda function performance.
- Use local debugging tools (e.g., AWS SAM Local) to debug Lambda functions locally.
## 7. Tooling and Environment:
- **Recommended Tools:**
- **AWS SAM:** Use AWS SAM (Serverless Application Model) to define and deploy Lambda functions and other serverless resources.
- **AWS CLI:** Use the AWS CLI (Command Line Interface) to manage AWS resources from the command line.
- **Terraform/CloudFormation:** Use Infrastructure as Code (IaC) tools like Terraform or CloudFormation to provision and manage AWS infrastructure.
- **IDE:** Use an IDE with support for Lambda development (e.g., VS Code with the AWS Toolkit extension).
- **Build Configuration:**
- Use build tools (e.g., npm, yarn, Maven, Gradle) to manage dependencies and build Lambda function packages.
- Configure build scripts to automate common tasks (e.g., linting, testing, bundling).
- **Linting and Formatting:**
- Use linters (e.g., ESLint, Pylint) to enforce coding standards and identify potential code quality issues.
- Use formatters (e.g., Prettier, Black) to automatically format code consistently.
- **Deployment:**
- Use AWS SAM CLI or other deployment tools to deploy Lambda functions to AWS.
- Implement blue/green deployments or canary deployments to minimize downtime during deployments.
- Automate deployments using CI/CD pipelines.
- **CI/CD Integration:**
- Integrate Lambda function deployments with CI/CD pipelines to automate testing and deployment.
- Use CI/CD tools (e.g., Jenkins, CircleCI, GitHub Actions) to build, test, and deploy Lambda functions.
@file aws-lambda-security.mdc
@file aws-lambda-performance.mdc
@@ -0,0 +1,210 @@
---
description: This rule outlines best practices for developing and maintaining modal libraries, covering aspects from code organization and performance to security and testing. It aims to guide developers in creating robust, efficient, and user-friendly modal components.
globs: **/*.{js,jsx,ts,tsx,mjs,cjs}
---
- **Library Information:**
- Name: modal
- Category: cloud_platforms
- Subcategory: serverless
- **General Principles:**
- **Clarity and Purpose:** Modals should have a clear and concise purpose, conveyed through a descriptive title. Content should be helpful and action-oriented.
- **User Control:** Prioritize user control by using modals sparingly and providing visible, intuitive close options (e.g., close button, overlay click).
- **Accessibility:** Ensure modals are accessible to all users by testing with assistive technologies and adhering to accessibility standards (e.g., ARIA attributes).
- **Code Organization and Structure:**
- **Directory Structure:**
- `src/`: Contains the source code of the modal library.
- `components/`: Reusable modal components (e.g., `Modal.jsx`, `ModalHeader.jsx`, `ModalBody.jsx`, `ModalFooter.jsx`).
- `hooks/`: Custom hooks for managing modal state and logic (e.g., `useModal.js`).
- `utils/`: Utility functions (e.g., validation, formatting).
- `styles/`: CSS or styling components.
- `types/`: TypeScript type definitions.
- `examples/`: Example usage of the modal library.
- `tests/`: Unit and integration tests.
- `docs/`: Documentation for the library.
- **File Naming Conventions:**
- Use descriptive names for components (e.g., `ConfirmationModal.jsx`, `InputModal.jsx`).
- Follow a consistent naming convention (e.g., PascalCase for components, camelCase for variables and functions).
- **Module Organization:**
- Organize code into logical modules and submodules. Each module should have a specific responsibility.
- Use ES modules (import/export) for modularity and tree-shaking.
- **Component Architecture:**
- Favor a component-based architecture. Each modal element (header, body, footer) should be a reusable component.
- Use composition to create complex modals from smaller, reusable components.
- **Code Splitting Strategies:**
- Consider code splitting for large modal libraries to improve initial load time.
- Lazy load modal content or components that are not immediately needed.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:**
- **Controlled Components:** Use controlled components for modal content to manage state effectively.
- **Render Props or Hooks:** Provide flexibility in rendering modal content using render props or custom hooks.
- **Provider Pattern:** Use a context provider to manage global modal state and configuration.
- **Recommended Approaches:**
- Use a state management library (e.g., Zustand, Jotai) for complex modal state.
- Implement a modal queue to manage multiple modals efficiently.
- Provide a consistent API for opening and closing modals.
- **Anti-patterns:**
- **Overusing Modals:** Avoid using modals for non-critical information or actions.
- **Deeply Nested Components:** Minimize deeply nested components within modals to improve performance.
- **Ignoring Accessibility:** Neglecting accessibility can make the modal unusable for some users.
- **State Management Best Practices:**
- Choose a state management solution that fits the complexity of the modal library.
- Keep state minimal and derive values when possible.
- Use immutable data structures to prevent unexpected side effects.
- **Error Handling Patterns:**
- Implement error boundaries to catch errors within modals.
- Provide informative error messages to the user.
- Log errors for debugging purposes.
- **Performance Considerations:**
- **Optimization Techniques:**
- Memoize components to prevent unnecessary re-renders.
- Use virtualization for long lists of modal content.
- Debounce or throttle event handlers to improve responsiveness.
- **Memory Management:**
- Clean up event listeners and timers when the modal is closed.
- Avoid creating large data structures within modals.
- Release resources when the modal is unmounted.
- **Rendering Optimization:**
- Use CSS transforms for animations instead of modifying layout properties.
- Minimize the number of DOM updates.
- Use techniques like `requestAnimationFrame` for smoother animations.
- **Bundle Size Optimization:**
- Use tree-shaking to remove unused code from the bundle.
- Minify and compress the code.
- Use code splitting to reduce the initial bundle size.
- **Lazy Loading Strategies:**
- Lazy load modal content or components that are not immediately visible.
- Use dynamic imports to load modules on demand.
- **Security Best Practices:**
- **Common Vulnerabilities:**
- **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks.
- **Injection Attacks:** Protect against injection attacks by validating user inputs.
- **Input Validation:**
- Validate all user inputs within the modal.
- Use appropriate data types and formats.
- Sanitize inputs to remove malicious code.
- **Authentication and Authorization Patterns:**
- Implement authentication and authorization mechanisms to protect sensitive data.
- Use secure cookies or tokens to store user credentials.
- Enforce access control policies.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms to protect data.
- Implement data loss prevention measures.
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Validate API responses.
- Protect API keys and secrets.
- **Testing Approaches:**
- **Unit Testing Strategies:**
- Test individual components and functions in isolation.
- Use mocking and stubbing to isolate dependencies.
- Test edge cases and error conditions.
- **Integration Testing:**
- Test the interaction between components and modules.
- Verify that the modal works correctly with other parts of the application.
- **End-to-End Testing:**
- Test the entire modal workflow from start to finish.
- Use automated testing tools to simulate user interactions.
- **Test Organization:**
- Organize tests into logical groups based on functionality.
- Use descriptive test names.
- Keep tests concise and focused.
- **Mocking and Stubbing:**
- Use mocking to simulate external dependencies.
- Use stubbing to replace complex functions with simpler versions.
- Avoid over-mocking, as it can lead to brittle tests.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:**
- Forgetting to handle focus management when opening/closing modal
- Not properly managing the stacking context of modals.
- Ignoring keyboard navigation.
- **Edge Cases:**
- Handling modals within modals.
- Supporting different screen sizes and orientations.
- Handling modals in server-side rendered applications.
- **Version-Specific Issues:**
- Be aware of compatibility issues with different versions of dependencies.
- Test the modal library with different browsers and devices.
- **Compatibility Concerns:**
- Ensure the modal library is compatible with different JavaScript frameworks and libraries.
- Test with different browsers and devices.
- **Debugging Strategies:**
- Use browser developer tools to inspect the modal's HTML and CSS.
- Use logging to track the flow of execution.
- Use a debugger to step through the code.
- **Tooling and Environment:**
- **Recommended Development Tools:**
- VS Code with extensions for React/TypeScript/ESLint.
- Chrome DevTools for debugging.
- **Build Configuration:**
- Use a build tool like webpack, Parcel, or Rollup.
- Configure the build tool to optimize the bundle size.
- **Linting and Formatting:**
- Use ESLint to enforce code style and detect potential errors.
- Use Prettier to automatically format the code.
- **Deployment Best Practices:**
- Deploy the modal library to a CDN for fast and reliable delivery.
- Use version control to track changes to the code.
- Automate the deployment process.
- **CI/CD Integration:**
- Integrate the modal library with a CI/CD pipeline for automated testing and deployment.
- Use a CI/CD tool like Jenkins, Travis CI, or CircleCI.
- **Accessibility Considerations (WCAG Compliance):**
- **Keyboard Navigation:** Ensure all interactive elements within the modal are reachable and operable using the keyboard. Use tab index appropriately.
- **Focus Management:** Trap focus within the modal when it's open. Return focus to the previously focused element when the modal is closed. Prevent focus leaking to elements behind the modal.
- **ARIA Attributes:**
- Use `role="dialog"` or `role="alertdialog"` to indicate the modal's purpose.
- Use `aria-labelledby` to associate the modal's title with the modal element.
- Use `aria-describedby` to associate the modal's content with the modal element.
- Implement `aria-modal="true"` to signify the modal is blocking interaction with the rest of the page.
- **Color Contrast:** Ensure sufficient color contrast between text and background elements.
- **Screen Reader Compatibility:** Test the modal with screen readers to ensure content is read correctly and controls are accessible.
- **Visual Cues:** Provide clear visual cues to indicate the active element.
- **Alternative Text:** Ensure images have descriptive alternative text.
- **UI/UX Best Practices:**
- **Modal Size and Positioning:** Ensure the modal is appropriately sized and positioned on the screen. Avoid modals that are too large or obstruct important content.
- **Animation and Transitions:** Use subtle animations and transitions to enhance the user experience. Avoid excessive or distracting animations.
- **Responsiveness:** Ensure the modal is responsive and adapts to different screen sizes and orientations.
- **Dark Overlay:** Use a dark overlay to dim the background and focus the user's attention on the modal. The overlay should be semi-transparent.
- **Clear Calls to Action:** Use clear and concise button labels for calls to action. Avoid ambiguous or confusing labels.
- **Example Snippets (Illustrative):**
- **React Component:**
jsx
import React, { useState } from 'react';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return (
{children}
<button onClick={onClose}>Close</button>
);
};
export default Modal;
- **TypeScript Type Definitions:**
typescript
interface ModalProps {
isOpen: boolean;
onClose: () => void;
children: React.ReactNode;
}
By adhering to these best practices, you can create robust, accessible, and user-friendly modal libraries that enhance the overall user experience of your applications.