Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+206 -178
View File
@@ -1,196 +1,224 @@
---
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
description: This guide provides definitive best practices for developing, deploying, and operating applications on Google Cloud Platform (GCP), emphasizing security, performance, and maintainability.
globs: **/*
---
---
## GCP Library Best Practices
# gcp 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.
Adhering to these guidelines ensures your GCP applications are robust, secure, and performant. Treat these as non-negotiable standards.
### 1. Code Organization and Structure
## 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.
### 1. Adhere to Google's Language Style Guides
Consistency is paramount. Always follow the official Google Style Guides for your chosen language. This improves readability and maintainability across the team.
### 2. Common Patterns and Anti-patterns
**Guideline:** Integrate linting and formatting tools (e.g., Black for Python, Prettier for JS) configured with Google's style.
- **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.
### 2. Infrastructure as Code (IaC) is Mandatory
Provision and manage all GCP resources using IaC. This ensures declarative, version-controlled, and auditable infrastructure. Terraform is the default choice.
### 3. Performance Considerations
**Guideline:** Treat your infrastructure code with the same rigor as application code.
- **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.
❌ **BAD:** Manual console configuration, `gcloud` commands for provisioning.
✅ **GOOD:** Terraform for all resource definitions.
```terraform
# main.tf
resource "google_project_service" "compute_api" {
project = var.project_id
service = "compute.googleapis.com"
disable_on_destroy = false
}
### 4. Security Best Practices
resource "google_compute_instance" "default" {
project = var.project_id
zone = "us-central1-a"
name = "my-app-instance"
machine_type = "e2-medium"
boot_disk {
initialize_params {
image = "debian-cloud/debian-11"
}
}
network_interface {
network = "default"
}
}
```
- **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.
## Common Patterns and Anti-patterns
### 5. Testing Approaches
### 1. Write Idempotent Functions and Services
Your functions and services must produce the same result regardless of how many times they are called with the same input. This is critical for retries and distributed systems.
- **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.
❌ **BAD:** Non-idempotent operation.
```python
# Function that decrements a counter without checking state
def process_order(order_id):
# This will decrement the counter every time it's called
db.update_counter(order_id, -1)
```
✅ **GOOD:** Idempotent operation using a transaction or state check.
```python
# Function that processes an order idempotently
def process_order_idempotent(order_id):
# Use a transaction or check for existing processed state
if not db.order_processed(order_id):
db.process_order(order_id)
db.mark_order_processed(order_id)
else:
print(f"Order {order_id} already processed, skipping.")
```
### 6. Common Pitfalls and Gotchas
### 2. Ensure HTTP Functions Send a Response
HTTP-triggered Cloud Functions and Cloud Run services *must* send an HTTP response. Failing to do so results in timeouts and unnecessary billing.
- **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.
```python
# main.py
import functions_framework
### 7. Tooling and Environment
@functions_framework.http
def hello_http(request):
"""HTTP Cloud Function: Always sends a response."""
name = request.args.get("name", "World")
# ✅ GOOD: Explicitly send an HTTP response
return f"Hello {name}!"
```
- **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.
### 3. Least Privilege for Service Accounts
Service accounts must have the absolute minimum permissions required. Never embed service account keys in code. Use Workload Identity Federation or attach service accounts to resources.
By following these best practices, developers can build robust, secure, and scalable applications and infrastructure on Google Cloud Platform.
❌ **BAD:** Hardcoding service account keys or granting `roles/owner`.
```python
# Insecure: Embedding keys directly
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/key.json"
```
✅ **GOOD:** Attaching service account to Cloud Run/Functions/GKE or using Workload Identity.
```python
# Code running on GCP resource (e.g., Cloud Run) with attached SA
from google.cloud import storage
client = storage.Client() # Automatically uses attached SA credentials
```
### 4. Firestore Document IDs: Avoid Sequential Values
Monotonically increasing or decreasing document IDs (e.g., `item1`, `item2`) can lead to "hotspotting" and contention, severely impacting write performance.
❌ **BAD:** Sequential document IDs.
```python
db.collection('products').document('product_1').set({'name': 'Widget A'})
db.collection('products').document('product_2').set({'name': 'Widget B'})
```
✅ **GOOD:** Use automatic IDs or UUIDs.
```python
# Automatic ID generation
db.collection('products').add({'name': 'Widget A'})
# UUID generation
import uuid
product_id = str(uuid.uuid4())
db.collection('products').document(product_id).set({'name': 'Widget B'})
```
## Performance Considerations
### 1. Minimize Cold Start Latency for Serverless
For Cloud Functions and Cloud Run, optimize container startup time by minimizing dependencies and performing heavy computations in global scope.
❌ **BAD:** Heavy computation on every request.
```python
# main.py
import time
def expensive_init():
time.sleep(5) # Simulates heavy setup
return "Initialized"
def handler(request):
data = expensive_init() # Runs on every cold start AND every request
return f"Hello, {data}!"
```
✅ **GOOD:** Cache expensive operations in global scope.
```python
# main.py
import time
# Global scope: runs once per instance cold start
GLOBAL_DATA = "Initialized"
time.sleep(5) # Only runs once per cold start
def handler(request):
# Reuses GLOBAL_DATA for subsequent requests on the same instance
return f"Hello, {GLOBAL_DATA}!"
```
### 2. Configure Cloud Run for Background Activities
If your Cloud Run service performs background tasks *after* responding to an HTTP request, you *must* use instance-based billing. Otherwise, CPU access will be severely limited.
**Guideline:** For request-based billing, ensure all asynchronous operations complete before sending a response.
### 3. Optimize Firestore Indexing
Reduce write latency by setting collection-level index exemptions for fields not used in queries (e.g., large strings, sequential values, TTL fields, large arrays/maps).
**Guideline:** Only index what you query.
```python
# Example of a Firestore index exemption (conceptual, managed via console/gcloud/Terraform)
# For 'my_collection', exempt 'large_text_field' from indexing.
# This reduces storage costs and write latency.
```
## Common Pitfalls and Gotchas
### 1. Neglecting Temporary Files in Serverless
Files written to `/tmp` in Cloud Functions/Run consume memory and can persist between invocations. Always delete temporary files to prevent out-of-memory errors.
❌ **BAD:** Not cleaning up temporary files.
```python
import os
with open('/tmp/data.txt', 'w') as f:
f.write('some data')
# File persists, consumes memory
```
✅ **GOOD:** Explicitly delete temporary files.
```python
import os
temp_file_path = '/tmp/data.txt'
with open(temp_file_path, 'w') as f:
f.write('some data')
# ... use file ...
os.remove(temp_file_path) # Clean up immediately
```
### 2. Relying on Offsets for Firestore Pagination
Using `offset` in Firestore queries retrieves all skipped documents internally, billing you for reads and increasing latency.
❌ **BAD:** Using `offset`.
```python
query = db.collection('items').order_by('timestamp').offset(10).limit(10)
```
✅ **GOOD:** Use cursors for efficient pagination.
```python
# Get the last document from the previous page
last_doc_on_previous_page = ...
# Use start_after with a cursor
query = db.collection('items').order_by('timestamp').start_after(last_doc_on_previous_page).limit(10)
```
## Testing Approaches
### 1. Implement a Comprehensive CI/CD Pipeline
Adopt Google's "change safety" lifecycle: design, development, qualification, and rollout. This mandates automated testing (unit, integration, E2E), canary deployments, and post-deployment monitoring.
**Guideline:** Every code change must pass automated tests and be deployed through a controlled, staged release process.
### 2. Test Infrastructure as Code
Validate your Terraform or Config Connector configurations. Use tools like `terraform validate` and `terraform plan` in CI, and consider policy enforcement tools like OPA Gatekeeper.
```bash
# CI/CD pipeline step for Terraform validation
- name: Terraform Validate
run: terraform validate
- name: Terraform Plan
run: terraform plan -out=tfplan
```