From d96d9ab8c8ef8d127843e50e40ccc940d7b38b85 Mon Sep 17 00:00:00 2001 From: sanjeed5 Date: Fri, 28 Feb 2025 19:31:47 +0530 Subject: [PATCH] Add comprehensive MDC rule files for various technologies - Add 150+ MDC rule files covering a wide range of programming languages, frameworks, and tools - Include best practices, coding standards, and guidelines for technologies like Python, JavaScript, React, AWS, CI/CD, and more - Implement consistent formatting and structure across rule files - Add concluding sections with recommendations for maintainability, security, and performance - Enhance project documentation with comprehensive technology-specific guidelines --- .gitignore | 3 +- rules-mdc/aiohttp.mdc | 338 +++++++++++++++++ rules-mdc/amazon-ec2.mdc | 317 ++++++++++++++++ rules-mdc/amazon-s3.mdc | 367 ++++++++++++++++++ rules-mdc/android-sdk.mdc | 311 ++++++++++++++++ rules-mdc/ansible.mdc | 553 +++++++++++++++++++++++++++ rules-mdc/ant-design.mdc | 311 ++++++++++++++++ rules-mdc/anyio.mdc | 169 +++++++++ rules-mdc/apollo-graphql.mdc | 217 +++++++++++ rules-mdc/asp-net.mdc | 363 ++++++++++++++++++ rules-mdc/astro.mdc | 168 +++++++++ rules-mdc/asyncio.mdc | 371 +++++++++++++++++++ rules-mdc/auth0.mdc | 195 ++++++++++ rules-mdc/autogen.mdc | 166 +++++++++ rules-mdc/aws-amplify.mdc | 286 ++++++++++++++ rules-mdc/aws-cli.mdc | 349 +++++++++++++++++ rules-mdc/aws-dynamodb.mdc | 182 +++++++++ rules-mdc/aws-ecs.mdc | 210 +++++++++++ rules-mdc/aws-rds.mdc | 324 ++++++++++++++++ rules-mdc/azure-pipelines.mdc | 176 +++++++++ rules-mdc/bash.mdc | 292 +++++++++++++++ rules-mdc/beautifulsoup4.mdc | 5 + rules-mdc/behave.mdc | 4 + rules-mdc/black.mdc | 134 +++++++ rules-mdc/boto3.mdc | 349 +++++++++++++++++ rules-mdc/bottle.mdc | 279 ++++++++++++++ rules-mdc/c-sharp.mdc | 368 ++++++++++++++++++ rules-mdc/cheerio.mdc | 265 +++++++++++++ rules-mdc/circleci.mdc | 231 ++++++++++++ rules-mdc/clerk.mdc | 236 ++++++++++++ rules-mdc/click.mdc | 356 ++++++++++++++++++ rules-mdc/codemirror.mdc | 240 ++++++++++++ rules-mdc/crewai.mdc | 179 +++++++++ rules-mdc/customtkinter.mdc | 230 ++++++++++++ rules-mdc/cypress.mdc | 345 +++++++++++++++++ rules-mdc/d3.mdc | 5 + rules-mdc/dask.mdc | 268 ++++++++++++++ rules-mdc/datadog.mdc | 180 +++++++++ rules-mdc/deno.mdc | 268 ++++++++++++++ rules-mdc/digitalocean.mdc | 278 ++++++++++++++ rules-mdc/discord-api.mdc | 190 ++++++++++ rules-mdc/django-orm.mdc | 306 +++++++++++++++ rules-mdc/django-rest-framework.mdc | 336 +++++++++++++++++ rules-mdc/drizzle.mdc | 274 ++++++++++++++ rules-mdc/elasticsearch.mdc | 272 ++++++++++++++ rules-mdc/elk-stack.mdc | 168 +++++++++ rules-mdc/emacs.mdc | 220 +++++++++++ rules-mdc/esbuild.mdc | 282 ++++++++++++++ rules-mdc/eslint.mdc | 5 + rules-mdc/fabric-js.mdc | 299 +++++++++++++++ rules-mdc/ffmpeg.mdc | 331 +++++++++++++++++ rules-mdc/firebase.mdc | 303 +++++++++++++++ rules-mdc/flake8.mdc | 276 ++++++++++++++ rules-mdc/flask-restful.mdc | 314 ++++++++++++++++ rules-mdc/fontawesome.mdc | 163 ++++++++ rules-mdc/gcp-cli.mdc | 85 +++++ rules-mdc/gensim.mdc | 285 ++++++++++++++ rules-mdc/gitlab-ci.mdc | 239 ++++++++++++ rules-mdc/go.mdc | 556 ++++++++++++++++++++++++++++ rules-mdc/godot.mdc | 358 ++++++++++++++++++ rules-mdc/google-maps-js.mdc | 262 +++++++++++++ rules-mdc/gradle.mdc | 141 +++++++ rules-mdc/grafana.mdc | 5 + rules-mdc/heroku.mdc | 118 ++++++ rules-mdc/httpx.mdc | 255 +++++++++++++ rules-mdc/hypothesis.mdc | 164 ++++++++ rules-mdc/insomnia.mdc | 91 +++++ rules-mdc/ionic.mdc | 339 +++++++++++++++++ rules-mdc/isort.mdc | 223 +++++++++++ rules-mdc/java.mdc | 296 +++++++++++++++ rules-mdc/jax.mdc | 267 +++++++++++++ rules-mdc/jenkins.mdc | 194 ++++++++++ rules-mdc/jquery.mdc | 410 ++++++++++++++++++++ rules-mdc/junit.mdc | 256 +++++++++++++ rules-mdc/keras.mdc | 323 ++++++++++++++++ rules-mdc/kivy.mdc | 347 +++++++++++++++++ rules-mdc/langchain-js.mdc | 179 +++++++++ rules-mdc/langgraph.mdc | 312 ++++++++++++++++ rules-mdc/lightgbm.mdc | 297 +++++++++++++++ rules-mdc/llama-index.mdc | 158 ++++++++ rules-mdc/llamaindex-js.mdc | 294 +++++++++++++++ rules-mdc/llvm.mdc | 131 +++++++ rules-mdc/matplotlib.mdc | 306 +++++++++++++++ rules-mdc/maven.mdc | 177 +++++++++ rules-mdc/microsoft-teams.mdc | 241 ++++++++++++ rules-mdc/mlx.mdc | 282 ++++++++++++++ rules-mdc/mockito.mdc | 249 +++++++++++++ rules-mdc/mypy.mdc | 101 +++++ rules-mdc/neo4j.mdc | 278 ++++++++++++++ rules-mdc/netlify.mdc | 293 +++++++++++++++ rules-mdc/next-js.mdc | 437 ++++++++++++++-------- rules-mdc/nginx.mdc | 406 ++++++++++++++++++++ rules-mdc/nltk.mdc | 304 +++++++++++++++ rules-mdc/nose2.mdc | 316 ++++++++++++++++ rules-mdc/notion-api.mdc | 263 +++++++++++++ rules-mdc/numba.mdc | 299 +++++++++++++++ rules-mdc/numpy.mdc | 271 ++++++++++++++ rules-mdc/openai.mdc | 246 ++++++++++++ rules-mdc/opencv-python.mdc | 199 ++++++++++ rules-mdc/pdoc.mdc | 243 ++++++++++++ rules-mdc/peewee.mdc | 365 ++++++++++++++++++ rules-mdc/phoenix.mdc | 270 ++++++++++++++ rules-mdc/php.mdc | 334 +++++++++++++++++ rules-mdc/pillow.mdc | 169 +++++++++ rules-mdc/plotly.mdc | 343 +++++++++++++++++ rules-mdc/poetry.mdc | 333 +++++++++++++++++ rules-mdc/pony.mdc | 275 ++++++++++++++ rules-mdc/postman.mdc | 100 +++++ rules-mdc/puppeteer.mdc | 284 ++++++++++++++ rules-mdc/pydantic.mdc | 207 +++++++++++ rules-mdc/pygame.mdc | 321 ++++++++++++++++ rules-mdc/pylint.mdc | 324 ++++++++++++++++ rules-mdc/pyqt.mdc | 120 ++++++ rules-mdc/pyramid.mdc | 176 +++++++++ rules-mdc/pyright.mdc | 291 +++++++++++++++ rules-mdc/pyside.mdc | 237 ++++++++++++ rules-mdc/pytest.mdc | 335 +++++++++++++++++ rules-mdc/python.mdc | 347 +++++++++++++++++ rules-mdc/railway.mdc | 289 +++++++++++++++ rules-mdc/react.mdc | 415 +++++++++++++-------- rules-mdc/remix.mdc | 315 ++++++++++++++++ rules-mdc/requests.mdc | 267 +++++++++++++ rules-mdc/rich.mdc | 160 ++++++++ rules-mdc/ros.mdc | 277 ++++++++++++++ rules-mdc/ruby.mdc | 478 ++++++++++++++++++++++++ rules-mdc/rust.mdc | 417 +++++++++++++++++++++ rules-mdc/sanic.mdc | 223 +++++++++++ rules-mdc/scikit-image.mdc | 295 +++++++++++++++ rules-mdc/scipy.mdc | 56 +++ rules-mdc/scrapy.mdc | 288 ++++++++++++++ rules-mdc/seaborn.mdc | 5 + rules-mdc/selenium.mdc | 328 ++++++++++++++++ rules-mdc/sentry.mdc | 146 ++++++++ rules-mdc/setuptools.mdc | 239 ++++++++++++ rules-mdc/smolagents.mdc | 286 ++++++++++++++ rules-mdc/socket-io.mdc | 302 +++++++++++++++ rules-mdc/spacy.mdc | 317 ++++++++++++++++ rules-mdc/sphinx.mdc | 170 +++++++++ rules-mdc/spring.mdc | 208 +++++++++++ rules-mdc/sqlalchemy.mdc | 261 +++++++++++++ rules-mdc/sqlite.mdc | 342 +++++++++++++++++ rules-mdc/statsmodels.mdc | 289 +++++++++++++++ rules-mdc/streamlit.mdc | 74 ++++ rules-mdc/stripe.mdc | 284 ++++++++++++++ rules-mdc/three-js.mdc | 311 ++++++++++++++++ rules-mdc/tinygrad.mdc | 175 +++++++++ rules-mdc/tkinter.mdc | 292 +++++++++++++++ rules-mdc/tornado.mdc | 308 +++++++++++++++ rules-mdc/tortoise-orm.mdc | 235 ++++++++++++ rules-mdc/tqdm.mdc | 182 +++++++++ rules-mdc/transformers.mdc | 174 +++++++++ rules-mdc/trio.mdc | 224 +++++++++++ rules-mdc/typer.mdc | 276 ++++++++++++++ rules-mdc/unittest.mdc | 266 +++++++++++++ rules-mdc/unity.mdc | 471 +++++++++++++++++++++++ rules-mdc/unreal-engine.mdc | 363 ++++++++++++++++++ rules-mdc/vim.mdc | 247 ++++++++++++ rules-mdc/xgboost.mdc | 287 ++++++++++++++ rules-mdc/zsh.mdc | 200 ++++++++++ 159 files changed, 40387 insertions(+), 309 deletions(-) create mode 100644 rules-mdc/aiohttp.mdc create mode 100644 rules-mdc/amazon-ec2.mdc create mode 100644 rules-mdc/amazon-s3.mdc create mode 100644 rules-mdc/android-sdk.mdc create mode 100644 rules-mdc/ansible.mdc create mode 100644 rules-mdc/ant-design.mdc create mode 100644 rules-mdc/anyio.mdc create mode 100644 rules-mdc/apollo-graphql.mdc create mode 100644 rules-mdc/asp-net.mdc create mode 100644 rules-mdc/astro.mdc create mode 100644 rules-mdc/asyncio.mdc create mode 100644 rules-mdc/auth0.mdc create mode 100644 rules-mdc/autogen.mdc create mode 100644 rules-mdc/aws-amplify.mdc create mode 100644 rules-mdc/aws-cli.mdc create mode 100644 rules-mdc/aws-dynamodb.mdc create mode 100644 rules-mdc/aws-ecs.mdc create mode 100644 rules-mdc/aws-rds.mdc create mode 100644 rules-mdc/azure-pipelines.mdc create mode 100644 rules-mdc/bash.mdc create mode 100644 rules-mdc/beautifulsoup4.mdc create mode 100644 rules-mdc/behave.mdc create mode 100644 rules-mdc/black.mdc create mode 100644 rules-mdc/boto3.mdc create mode 100644 rules-mdc/bottle.mdc create mode 100644 rules-mdc/c-sharp.mdc create mode 100644 rules-mdc/cheerio.mdc create mode 100644 rules-mdc/circleci.mdc create mode 100644 rules-mdc/clerk.mdc create mode 100644 rules-mdc/click.mdc create mode 100644 rules-mdc/codemirror.mdc create mode 100644 rules-mdc/crewai.mdc create mode 100644 rules-mdc/customtkinter.mdc create mode 100644 rules-mdc/cypress.mdc create mode 100644 rules-mdc/d3.mdc create mode 100644 rules-mdc/dask.mdc create mode 100644 rules-mdc/datadog.mdc create mode 100644 rules-mdc/deno.mdc create mode 100644 rules-mdc/digitalocean.mdc create mode 100644 rules-mdc/discord-api.mdc create mode 100644 rules-mdc/django-orm.mdc create mode 100644 rules-mdc/django-rest-framework.mdc create mode 100644 rules-mdc/drizzle.mdc create mode 100644 rules-mdc/elasticsearch.mdc create mode 100644 rules-mdc/elk-stack.mdc create mode 100644 rules-mdc/emacs.mdc create mode 100644 rules-mdc/esbuild.mdc create mode 100644 rules-mdc/eslint.mdc create mode 100644 rules-mdc/fabric-js.mdc create mode 100644 rules-mdc/ffmpeg.mdc create mode 100644 rules-mdc/firebase.mdc create mode 100644 rules-mdc/flake8.mdc create mode 100644 rules-mdc/flask-restful.mdc create mode 100644 rules-mdc/fontawesome.mdc create mode 100644 rules-mdc/gcp-cli.mdc create mode 100644 rules-mdc/gensim.mdc create mode 100644 rules-mdc/gitlab-ci.mdc create mode 100644 rules-mdc/go.mdc create mode 100644 rules-mdc/godot.mdc create mode 100644 rules-mdc/google-maps-js.mdc create mode 100644 rules-mdc/gradle.mdc create mode 100644 rules-mdc/grafana.mdc create mode 100644 rules-mdc/heroku.mdc create mode 100644 rules-mdc/httpx.mdc create mode 100644 rules-mdc/hypothesis.mdc create mode 100644 rules-mdc/insomnia.mdc create mode 100644 rules-mdc/ionic.mdc create mode 100644 rules-mdc/isort.mdc create mode 100644 rules-mdc/java.mdc create mode 100644 rules-mdc/jax.mdc create mode 100644 rules-mdc/jenkins.mdc create mode 100644 rules-mdc/jquery.mdc create mode 100644 rules-mdc/junit.mdc create mode 100644 rules-mdc/keras.mdc create mode 100644 rules-mdc/kivy.mdc create mode 100644 rules-mdc/langchain-js.mdc create mode 100644 rules-mdc/langgraph.mdc create mode 100644 rules-mdc/lightgbm.mdc create mode 100644 rules-mdc/llama-index.mdc create mode 100644 rules-mdc/llamaindex-js.mdc create mode 100644 rules-mdc/llvm.mdc create mode 100644 rules-mdc/matplotlib.mdc create mode 100644 rules-mdc/maven.mdc create mode 100644 rules-mdc/microsoft-teams.mdc create mode 100644 rules-mdc/mlx.mdc create mode 100644 rules-mdc/mockito.mdc create mode 100644 rules-mdc/mypy.mdc create mode 100644 rules-mdc/neo4j.mdc create mode 100644 rules-mdc/netlify.mdc create mode 100644 rules-mdc/nginx.mdc create mode 100644 rules-mdc/nltk.mdc create mode 100644 rules-mdc/nose2.mdc create mode 100644 rules-mdc/notion-api.mdc create mode 100644 rules-mdc/numba.mdc create mode 100644 rules-mdc/numpy.mdc create mode 100644 rules-mdc/openai.mdc create mode 100644 rules-mdc/opencv-python.mdc create mode 100644 rules-mdc/pdoc.mdc create mode 100644 rules-mdc/peewee.mdc create mode 100644 rules-mdc/phoenix.mdc create mode 100644 rules-mdc/php.mdc create mode 100644 rules-mdc/pillow.mdc create mode 100644 rules-mdc/plotly.mdc create mode 100644 rules-mdc/poetry.mdc create mode 100644 rules-mdc/pony.mdc create mode 100644 rules-mdc/postman.mdc create mode 100644 rules-mdc/puppeteer.mdc create mode 100644 rules-mdc/pydantic.mdc create mode 100644 rules-mdc/pygame.mdc create mode 100644 rules-mdc/pylint.mdc create mode 100644 rules-mdc/pyqt.mdc create mode 100644 rules-mdc/pyramid.mdc create mode 100644 rules-mdc/pyright.mdc create mode 100644 rules-mdc/pyside.mdc create mode 100644 rules-mdc/pytest.mdc create mode 100644 rules-mdc/python.mdc create mode 100644 rules-mdc/railway.mdc create mode 100644 rules-mdc/remix.mdc create mode 100644 rules-mdc/requests.mdc create mode 100644 rules-mdc/rich.mdc create mode 100644 rules-mdc/ros.mdc create mode 100644 rules-mdc/ruby.mdc create mode 100644 rules-mdc/rust.mdc create mode 100644 rules-mdc/sanic.mdc create mode 100644 rules-mdc/scikit-image.mdc create mode 100644 rules-mdc/scipy.mdc create mode 100644 rules-mdc/scrapy.mdc create mode 100644 rules-mdc/seaborn.mdc create mode 100644 rules-mdc/selenium.mdc create mode 100644 rules-mdc/sentry.mdc create mode 100644 rules-mdc/setuptools.mdc create mode 100644 rules-mdc/smolagents.mdc create mode 100644 rules-mdc/socket-io.mdc create mode 100644 rules-mdc/spacy.mdc create mode 100644 rules-mdc/sphinx.mdc create mode 100644 rules-mdc/spring.mdc create mode 100644 rules-mdc/sqlalchemy.mdc create mode 100644 rules-mdc/sqlite.mdc create mode 100644 rules-mdc/statsmodels.mdc create mode 100644 rules-mdc/streamlit.mdc create mode 100644 rules-mdc/stripe.mdc create mode 100644 rules-mdc/three-js.mdc create mode 100644 rules-mdc/tinygrad.mdc create mode 100644 rules-mdc/tkinter.mdc create mode 100644 rules-mdc/tornado.mdc create mode 100644 rules-mdc/tortoise-orm.mdc create mode 100644 rules-mdc/tqdm.mdc create mode 100644 rules-mdc/transformers.mdc create mode 100644 rules-mdc/trio.mdc create mode 100644 rules-mdc/typer.mdc create mode 100644 rules-mdc/unittest.mdc create mode 100644 rules-mdc/unity.mdc create mode 100644 rules-mdc/unreal-engine.mdc create mode 100644 rules-mdc/vim.mdc create mode 100644 rules-mdc/xgboost.mdc create mode 100644 rules-mdc/zsh.mdc diff --git a/.gitignore b/.gitignore index a7532e3..e5dc047 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,5 @@ wheels/ awesome-cursorrules/ .env exa_results/ -logs/ \ No newline at end of file +logs/ +.cache/ diff --git a/rules-mdc/aiohttp.mdc b/rules-mdc/aiohttp.mdc new file mode 100644 index 0000000..6d1d1f7 --- /dev/null +++ b/rules-mdc/aiohttp.mdc @@ -0,0 +1,338 @@ +--- +description: Comprehensive guide for aiohttp development covering code organization, performance, security, testing, and deployment best practices. Provides actionable guidance for developers to build robust and maintainable aiohttp applications. +globs: **/*.py +--- +# Aiohttp Best Practices + +This document provides a comprehensive guide to aiohttp development, covering code organization, performance, security, testing, and deployment. + +Library Information: +- Name: aiohttp +- Tags: web, python, http-client, async + +## 1. Code Organization and Structure + +### 1.1. Directory Structure Best Practices: + +* **Project Root:** + * `src/`: Contains the main application code. + * `main.py`: Entry point of the application. + * `app.py`: Application factory and setup. + * `routes.py`: Defines application routes. + * `handlers/`: Contains request handlers. + * `user_handlers.py`: User-related handlers. + * `product_handlers.py`: Product-related handlers. + * `middlewares/`: Custom middleware components. + * `logging_middleware.py`: Logging middleware. + * `auth_middleware.py`: Authentication middleware. + * `utils/`: Utility modules. + * `db.py`: Database connection and utilities. + * `config.py`: Configuration management. + * `tests/`: Contains unit and integration tests. + * `conftest.py`: Pytest configuration file. + * `unit/`: Unit tests. + * `integration/`: Integration tests. + * `static/`: Static files (CSS, JavaScript, images). + * `templates/`: Jinja2 or other template files. + * `docs/`: Project documentation. + * `requirements.txt`: Python dependencies. + * `Dockerfile`: Docker configuration file. + * `docker-compose.yml`: Docker Compose configuration. + * `.env`: Environment variables. + * `README.md`: Project description and instructions. + * `.gitignore`: Specifies intentionally untracked files that Git should ignore. + * `.cursor/rules/`: Project specific Cursor AI rules. + +### 1.2. File Naming Conventions: + +* Python files: `snake_case.py` (e.g., `user_handlers.py`, `database_utils.py`). +* Class names: `CamelCase` (e.g., `UserHandler`, `DatabaseConnection`). +* Function names: `snake_case` (e.g., `get_user`, `create_product`). +* Variables: `snake_case` (e.g., `user_id`, `product_name`). +* Constants: `UPPER_SNAKE_CASE` (e.g., `DEFAULT_PORT`, `MAX_CONNECTIONS`). + +### 1.3. Module Organization: + +* Group related functionality into modules. +* Use clear and descriptive module names. +* Avoid circular dependencies. +* Keep modules focused and concise. +* Use packages to organize modules into a hierarchical structure. + +### 1.4. Component Architecture: + +* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access). +* **Microservices Architecture:** Decompose the application into small, independent services. +* **Hexagonal Architecture (Ports and Adapters):** Decouple the application core from external dependencies. +* **MVC (Model-View-Controller):** Organize the application into models (data), views (presentation), and controllers (logic). + +### 1.5. Code Splitting Strategies: + +* **Route-based splitting:** Load modules based on the requested route. +* **Feature-based splitting:** Divide the application into feature modules. +* **Component-based splitting:** Split the application into reusable components. +* **On-demand loading:** Load modules only when they are needed. +* **Asynchronous loading:** Use `asyncio.gather` or similar techniques to load modules concurrently. + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns: + +* **Singleton:** For managing shared resources like database connections or configuration objects. +* **Factory:** For creating instances of classes with complex initialization logic. +* **Strategy:** For implementing different algorithms or behaviors. +* **Observer:** For implementing event-driven systems. +* **Middleware:** For handling cross-cutting concerns like logging, authentication, and error handling. + +### 2.2. Recommended Approaches for Common Tasks: + +* **Request Handling:** Use request handlers to process incoming requests. +* **Routing:** Use `aiohttp.web.RouteTableDef` for defining routes. +* **Middleware:** Implement middleware for request pre-processing and response post-processing. +* **Data Serialization:** Use `aiohttp.web.json_response` for serializing data to JSON. +* **Error Handling:** Implement custom error handlers to handle exceptions gracefully. +* **Session Management:** Use `aiohttp-session` for managing user sessions. +* **WebSockets:** Utilize `aiohttp.web.WebSocketResponse` for handling WebSocket connections. + +### 2.3. Anti-patterns and Code Smells: + +* **Creating a new `ClientSession` for each request:** This is a performance bottleneck. Reuse a single `ClientSession`. +* **Blocking operations in asynchronous code:** Avoid using blocking operations (e.g., `time.sleep`) in asynchronous code. +* **Ignoring exceptions:** Always handle exceptions properly to prevent unexpected behavior. +* **Overusing global variables:** Avoid using global variables as much as possible to maintain code clarity and testability. +* **Tight coupling:** Decouple components to improve maintainability and reusability. +* **Hardcoding configuration:** Use environment variables or configuration files to manage configuration settings. + +### 2.4. State Management: + +* **Application State:** Store application-level state in the `aiohttp.web.Application` instance. +* **Request State:** Store request-specific state in the `aiohttp.web.Request` instance. +* **Session State:** Use `aiohttp-session` to manage user session data. +* **Database:** Use a database like PostgreSQL, MySQL, or MongoDB to store persistent state. +* **Redis/Memcached:** Use in-memory data stores for caching frequently accessed data. + +### 2.5. Error Handling: + +* **Use `try-except` blocks:** Wrap code that may raise exceptions in `try-except` blocks. +* **Handle specific exceptions:** Catch specific exception types instead of using a generic `except Exception`. +* **Log exceptions:** Log exceptions with detailed information for debugging. +* **Return informative error responses:** Return appropriate HTTP status codes and error messages to the client. +* **Implement custom error handlers:** Create custom error handlers to handle specific exception types. +* **Use `aiohttp.web.HTTPException`:** Raise `aiohttp.web.HTTPException` to return HTTP error responses. + +## 3. Performance Considerations + +### 3.1. Optimization Techniques: + +* **Reuse `ClientSession`:** Always reuse a single `ClientSession` instance for making multiple requests. +* **Connection Pooling:** aiohttp automatically uses connection pooling, so reuse your session. +* **Keep-Alive Connections:** Keep-alive connections are enabled by default, reducing connection overhead. +* **Gzip Compression:** Enable Gzip compression for responses to reduce bandwidth usage. +* **Caching:** Implement caching for frequently accessed data to reduce database load. +* **Optimize Database Queries:** Optimize database queries to improve response times. +* **Use Indexes:** Use indexes in your database tables to speed up queries. +* **Limit Payload Size:** Keep request and response payloads as small as possible. +* **Background Tasks:** Use `asyncio.create_task` to offload long-running tasks to the background. +* **Profiling:** Use profiling tools to identify performance bottlenecks. + +### 3.2. Memory Management: + +* **Avoid Memory Leaks:** Ensure that all resources are properly released to prevent memory leaks. +* **Use Generators:** Use generators to process large datasets in chunks. +* **Limit Object Creation:** Minimize the creation of objects to reduce memory overhead. +* **Use Data Structures Efficiently:** Choose appropriate data structures to optimize memory usage. +* **Garbage Collection:** Understand how Python's garbage collection works and optimize your code accordingly. + +### 3.3. Rendering Optimization: + +* **Template Caching:** Cache templates to reduce rendering time. +* **Minimize Template Logic:** Keep template logic simple and move complex logic to request handlers. +* **Use Asynchronous Templates:** Use asynchronous template engines like `aiohttp-jinja2`. +* **Optimize Static Files:** Optimize static files (CSS, JavaScript, images) to reduce page load times. + +### 3.4. Bundle Size Optimization: + +* **Minimize Dependencies:** Reduce the number of dependencies in your project. +* **Tree Shaking:** Use tree shaking to remove unused code from your bundles. +* **Code Minification:** Minify your code to reduce bundle sizes. +* **Code Compression:** Compress your code to further reduce bundle sizes. + +### 3.5. Lazy Loading: + +* **Lazy Load Modules:** Load modules only when they are needed. +* **Lazy Load Images:** Load images only when they are visible in the viewport. +* **Use Asynchronous Loading:** Use `asyncio.gather` or similar techniques to load resources concurrently. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities: + +* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM. +* **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates. +* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens. +* **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms. +* **Denial-of-Service (DoS) Attacks:** Implement rate limiting and other measures to prevent DoS attacks. +* **Insecure Dependencies:** Keep your dependencies up to date to prevent vulnerabilities. + +### 4.2. Input Validation: + +* **Validate all user input:** Validate all user input to prevent malicious data from entering your application. +* **Use a validation library:** Use a validation library like `marshmallow` or `voluptuous` to simplify input validation. +* **Sanitize user input:** Sanitize user input to remove potentially harmful characters. +* **Limit input length:** Limit the length of input fields to prevent buffer overflows. +* **Use regular expressions:** Use regular expressions to validate input patterns. + +### 4.3. Authentication and Authorization: + +* **Use a strong authentication scheme:** Use a strong authentication scheme like OAuth 2.0 or JWT. +* **Store passwords securely:** Store passwords securely using a hashing algorithm like bcrypt. +* **Implement role-based access control (RBAC):** Use RBAC to control access to resources based on user roles. +* **Use secure cookies:** Use secure cookies to protect session data. +* **Implement multi-factor authentication (MFA):** Use MFA to add an extra layer of security. + +### 4.4. Data Protection: + +* **Encrypt sensitive data:** Encrypt sensitive data at rest and in transit. +* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server. +* **Store data securely:** Store data in a secure location with appropriate access controls. +* **Regularly back up data:** Regularly back up data to prevent data loss. +* **Comply with data privacy regulations:** Comply with data privacy regulations like GDPR and CCPA. + +### 4.5. Secure API Communication: + +* **Use HTTPS:** Always use HTTPS for API communication. +* **Implement API authentication:** Use API keys or tokens to authenticate API requests. +* **Rate limit API requests:** Implement rate limiting to prevent abuse. +* **Validate API requests:** Validate API requests to prevent malicious data from entering your application. +* **Log API requests:** Log API requests for auditing and debugging. + +## 5. Testing Approaches + +### 5.1. Unit Testing: + +* **Test individual components:** Unit tests should test individual components in isolation. +* **Use a testing framework:** Use a testing framework like `pytest` or `unittest`. +* **Write clear and concise tests:** Write clear and concise tests that are easy to understand. +* **Test edge cases:** Test edge cases and boundary conditions. +* **Use mocks and stubs:** Use mocks and stubs to isolate components under test. + +### 5.2. Integration Testing: + +* **Test interactions between components:** Integration tests should test interactions between different components. +* **Test with real dependencies:** Integration tests should use real dependencies whenever possible. +* **Test the entire application flow:** Integration tests should test the entire application flow. +* **Use a testing database:** Use a testing database to isolate integration tests from the production database. + +### 5.3. End-to-End Testing: + +* **Test the entire system:** End-to-end tests should test the entire system from end to end. +* **Use a testing environment:** Use a testing environment that mimics the production environment. +* **Automate end-to-end tests:** Automate end-to-end tests to ensure that the system is working correctly. +* **Use a browser automation tool:** Use a browser automation tool like Selenium or Puppeteer. + +### 5.4. Test Organization: + +* **Organize tests by module:** Organize tests by module to improve test discovery and maintainability. +* **Use descriptive test names:** Use descriptive test names that clearly indicate what the test is verifying. +* **Use test fixtures:** Use test fixtures to set up and tear down test environments. +* **Use test markers:** Use test markers to categorize tests and run specific test suites. + +### 5.5. Mocking and Stubbing: + +* **Use mocks to simulate dependencies:** Use mocks to simulate the behavior of dependencies. +* **Use stubs to provide predefined responses:** Use stubs to provide predefined responses to API calls. +* **Use mocking libraries:** Use mocking libraries like `unittest.mock` or `pytest-mock`. +* **Avoid over-mocking:** Avoid over-mocking, as it can make tests less reliable. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes: + +* **Not handling exceptions properly:** Always handle exceptions to prevent unexpected behavior. +* **Using blocking operations in asynchronous code:** Avoid using blocking operations in asynchronous code. +* **Not closing `ClientSession`:** Always close the `ClientSession` to release resources. +* **Not validating user input:** Always validate user input to prevent security vulnerabilities. +* **Not using HTTPS:** Always use HTTPS for secure communication. + +### 6.2. Edge Cases: + +* **Handling timeouts:** Implement proper timeout handling to prevent requests from hanging indefinitely. +* **Handling connection errors:** Handle connection errors gracefully to prevent application crashes. +* **Handling large payloads:** Handle large payloads efficiently to prevent memory issues. +* **Handling concurrent requests:** Handle concurrent requests properly to prevent race conditions. +* **Handling Unicode encoding:** Be aware of Unicode encoding issues when processing text data. + +### 6.3. Version-Specific Issues: + +* **aiohttp version compatibility:** Be aware of compatibility issues between different aiohttp versions. +* **asyncio version compatibility:** Be aware of compatibility issues between aiohttp and different asyncio versions. +* **Python version compatibility:** Be aware of compatibility issues between aiohttp and different Python versions. + +### 6.4. Compatibility Concerns: + +* **Compatibility with other libraries:** Be aware of compatibility issues between aiohttp and other libraries. +* **Compatibility with different operating systems:** Be aware of compatibility issues between aiohttp and different operating systems. +* **Compatibility with different web servers:** Be aware of compatibility issues between aiohttp and different web servers. + +### 6.5. Debugging Strategies: + +* **Use logging:** Use logging to track application behavior and identify issues. +* **Use a debugger:** Use a debugger to step through code and examine variables. +* **Use a profiler:** Use a profiler to identify performance bottlenecks. +* **Use error reporting tools:** Use error reporting tools to track and fix errors in production. +* **Use a network analyzer:** Use a network analyzer like Wireshark to capture and analyze network traffic. + +## 7. Tooling and Environment + +### 7.1. Recommended Development Tools: + +* **IDE:** Use an IDE like VS Code, PyCharm, or Sublime Text. +* **Virtual Environment:** Use a virtual environment to isolate project dependencies. +* **Package Manager:** Use a package manager like pip or poetry to manage dependencies. +* **Testing Framework:** Use a testing framework like pytest or unittest. +* **Linting Tool:** Use a linting tool like pylint or flake8 to enforce code style. +* **Formatting Tool:** Use a formatting tool like black or autopep8 to format code automatically. + +### 7.2. Build Configuration: + +* **Use a build system:** Use a build system like Make or tox to automate build tasks. +* **Define dependencies in `requirements.txt` or `pyproject.toml`:** Specify all project dependencies in a `requirements.txt` or `pyproject.toml` file. +* **Use a Dockerfile:** Use a Dockerfile to create a containerized build environment. +* **Use Docker Compose:** Use Docker Compose to manage multi-container applications. + +### 7.3. Linting and Formatting: + +* **Use a consistent code style:** Use a consistent code style throughout the project. +* **Configure linting tools:** Configure linting tools to enforce code style rules. +* **Configure formatting tools:** Configure formatting tools to format code automatically. +* **Use pre-commit hooks:** Use pre-commit hooks to run linters and formatters before committing code. + +### 7.4. Deployment: + +* **Use a web server:** Use a web server like Nginx or Apache to serve the application. +* **Use a process manager:** Use a process manager like Supervisor or systemd to manage the application process. +* **Use a reverse proxy:** Use a reverse proxy to improve security and performance. +* **Use a load balancer:** Use a load balancer to distribute traffic across multiple servers. +* **Use a monitoring system:** Use a monitoring system to track application health and performance. +* **Standalone Server:** aiohttp.web.run_app(), simple but doesn't utilize all CPU cores. +* **Nginx + Supervisord:** Nginx prevents attacks, allows utilizing all CPU cores, and serves static files faster. +* **Nginx + Gunicorn:** Gunicorn launches the app as worker processes, simplifying deployment compared to bare Nginx. + +### 7.5. CI/CD Integration: + +* **Use a CI/CD pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process. +* **Use a CI/CD tool:** Use a CI/CD tool like Jenkins, GitLab CI, or GitHub Actions. +* **Run tests in the CI/CD pipeline:** Run tests in the CI/CD pipeline to ensure that code changes don't break the application. +* **Automate deployment:** Automate deployment to reduce manual effort and improve consistency. + +## Additional Best Practices: + +* **Session Management:** Always create a `ClientSession` for making requests and reuse it across multiple requests to benefit from connection pooling. Avoid creating a new session for each request, as this can lead to performance issues. +* **Error Handling:** Implement robust error handling in your request handlers. Use try-except blocks to manage exceptions, particularly for network-related errors. For example, handle `ConnectionResetError` to manage client disconnections gracefully. +* **Middleware Usage:** Utilize middleware for cross-cutting concerns such as logging, error handling, and modifying requests/responses. Define middleware functions that accept a request and a handler, allowing you to process requests before they reach your main handler. +* **Graceful Shutdown:** Implement graceful shutdown procedures for your server to ensure that ongoing requests are completed before the application exits. This can be achieved by registering shutdown signals and cleaning up resources. +* **Security Practices:** When deploying, consider using a reverse proxy like Nginx for added security and performance. Configure SSL/TLS correctly to secure your application. +* **Character Set Detection:** If a response does not include the charset needed to decode the body, use `ClientSession` accepts a `fallback_charset_resolver` parameter which can be used to introduce charset guessing functionality. +* **Persistent Session:** Use `Cleanup Context` when creating a persistent session. + +By adhering to these practices, developers can enhance the reliability, performance, and security of their `aiohttp` applications. \ No newline at end of file diff --git a/rules-mdc/amazon-ec2.mdc b/rules-mdc/amazon-ec2.mdc new file mode 100644 index 0000000..777235c --- /dev/null +++ b/rules-mdc/amazon-ec2.mdc @@ -0,0 +1,317 @@ +--- +description: This rule file provides best practices, coding standards, and security guidelines for developing, deploying, and maintaining applications using the amazon-ec2 library within the AWS ecosystem. It focuses on infrastructure as code (IaC), resource management, performance, and security considerations for robust and scalable EC2-based solutions. +globs: **/*.{tf,json,yml,yaml,py,js,ts,sh,java,go,rb,m} +--- +- ## General Principles + - **Infrastructure as Code (IaC):** Treat your infrastructure as code. Define and provision AWS resources (EC2 instances, security groups, networks) using code (e.g., AWS CloudFormation, AWS CDK, Terraform). This ensures consistency, repeatability, and version control. + - **Security First:** Integrate security best practices into every stage of development, from IaC template creation to instance configuration. Implement the principle of least privilege, regularly patch instances, and utilize security assessment tools. + - **Modularity and Reusability:** Design your infrastructure and application code in modular components that can be reused across multiple projects or environments. + - **Automation:** Automate as much of the infrastructure provisioning, deployment, and management processes as possible. Use CI/CD pipelines for automated testing and deployment. + - **Monitoring and Logging:** Implement comprehensive monitoring and logging to track the health, performance, and security of your EC2 instances and applications. + +- ## 1. Code Organization and Structure + + - **Directory Structure Best Practices:** + - Adopt a logical directory structure that reflects the architecture of your application and infrastructure. + - Example: + + project-root/ + ├── modules/ # Reusable infrastructure modules (e.g., VPC, security groups) + │ ├── vpc/ # VPC module + │ │ ├── main.tf # Terraform configuration for the VPC + │ │ ├── variables.tf # Input variables for the VPC module + │ │ ├── outputs.tf # Output values for the VPC module + │ ├── security_group/ # Security Group module + │ │ ├── ... + ├── environments/ # Environment-specific configurations + │ ├── dev/ # Development environment + │ │ ├── main.tf # Terraform configuration for the Dev environment + │ │ ├── variables.tf # Environment specific variables + │ ├── prod/ # Production environment + │ │ ├── ... + ├── scripts/ # Utility scripts (e.g., deployment scripts, automation scripts) + │ ├── deploy.sh # Deployment script + │ ├── update_ami.py # Python script to update AMI + ├── application/ # Application code + │ ├── src/ # Source code + │ ├── tests/ # Unit and integration tests + ├── README.md + └── ... + + - **File Naming Conventions:** + - Use consistent and descriptive file names. + - Examples: + - `main.tf`: Main Terraform configuration file + - `variables.tf`: Terraform variables file + - `outputs.tf`: Terraform output values file + - `deploy.sh`: Deployment script + - `instance.py`: Python module for instance management + - **Module Organization:** + - Encapsulate reusable infrastructure components into modules (e.g., VPC, security groups, load balancers). + - Each module should have: + - A clear purpose. + - Well-defined input variables and output values. + - Comprehensive documentation. + - Keep modules small and focused. + - **Component Architecture:** + - Design your application as a collection of loosely coupled components. + - Each component should have: + - A well-defined interface. + - Clear responsibilities. + - Independent deployment lifecycle. + - **Code Splitting:** + - Break down large application codebases into smaller, manageable modules. + - Use lazy loading to load modules on demand, reducing initial load time. + - Example (Python): + python + # main.py + import importlib + + def load_module(module_name): + module = importlib.import_module(module_name) + return module + + # Load the module when needed + my_module = load_module('my_module') + my_module.my_function() + + +- ## 2. Common Patterns and Anti-patterns + + - **Design Patterns:** + - **Singleton:** Use when exactly one instance of a class is needed (e.g., a configuration manager). + - **Factory:** Use to create objects without specifying their concrete classes (e.g., creating different types of EC2 instances). + - **Strategy:** Use to define a family of algorithms, encapsulate each one, and make them interchangeable (e.g., different instance termination strategies). + - **Common Tasks:** + - **Creating an EC2 Instance (AWS CLI):** + bash + aws ec2 run-instances --image-id ami-xxxxxxxxxxxxxxxxx --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-xxxxxxxxxxxxxxxxx + + - **Creating an EC2 Instance (AWS CDK): + typescript + import * as ec2 from 'aws-cdk-lib/aws-ec2'; + + const vpc = new ec2.Vpc(this, 'TheVPC', { maxAzs: 3 }); + + const instance = new ec2.Instance(this, 'EC2Instance', { + vpc: vpc, + instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO), + machineImage: new ec2.AmazonLinux2023Image({generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2}), + }); + + - **Attaching an EBS Volume:** + - Ensure the EBS volume is in the same Availability Zone as the EC2 instance. + - Use the `aws ec2 attach-volume` command or the equivalent SDK call. + - **Anti-patterns:** + - **Hardcoding AWS Credentials:** Never hardcode AWS credentials in your code. Use IAM roles for EC2 instances and IAM users with restricted permissions for local development. + - **Creating Publicly Accessible S3 Buckets:** Avoid creating S3 buckets that are publicly accessible without proper security controls. + - **Ignoring Error Handling:** Always handle exceptions and errors gracefully. Provide meaningful error messages and logging. + - **Over-Permissive Security Groups:** Implement the principle of least privilege. Grant only the minimum necessary permissions to your security groups. + - **State Management:** + - Use state files (e.g., Terraform state) to track the current state of your infrastructure. + - Store state files securely (e.g., in an S3 bucket with encryption and versioning). + - Use locking mechanisms to prevent concurrent modifications to the state file. + - **Error Handling:** + - Implement robust error handling to catch exceptions and prevent application crashes. + - Use try-except blocks to handle potential errors. + - Log error messages with sufficient detail for debugging. + +- ## 3. Performance Considerations + + - **Optimization Techniques:** + - **Instance Type Selection:** Choose the appropriate EC2 instance type based on your application's requirements (CPU, memory, network). + - **EBS Optimization:** Use Provisioned IOPS (PIOPS) EBS volumes for high-performance applications. + - **Caching:** Implement caching mechanisms to reduce database load and improve response times (e.g., using Amazon ElastiCache). + - **Load Balancing:** Distribute traffic across multiple EC2 instances using an Elastic Load Balancer (ELB). + - **Auto Scaling:** Use Auto Scaling groups to automatically scale your EC2 instances based on demand. + - **Memory Management:** + - Monitor memory usage on your EC2 instances. + - Optimize application code to reduce memory consumption. + - Use memory profiling tools to identify memory leaks. + - **Bundle Size Optimization:** + - Minimize the size of your application's deployment package. + - Remove unnecessary dependencies. + - Use code minification and compression. + - Example (Python): + bash + # Create a virtual environment + python3 -m venv .venv + source .venv/bin/activate + + # Install only necessary dependencies + pip install --no-cache-dir -r requirements.txt + + # Create deployment package + zip -r deployment_package.zip * + + - **Lazy Loading:** + - Load application modules on demand to reduce initial load time. + - Use code splitting to break down large modules into smaller chunks. + - Example (JavaScript): + javascript + // main.js + async function loadModule() { + const module = await import('./my_module.js'); + module.myFunction(); + } + + loadModule(); + + +- ## 4. Security Best Practices + + - **Common Vulnerabilities:** + - **SQL Injection:** Prevent SQL injection by using parameterized queries and input validation. + - **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and encoding output. + - **Remote Code Execution (RCE):** Prevent RCE by validating user input and using secure coding practices. + - **Unsecured API endpoints:** Secure API endpoints using authentication and authorization mechanisms. + - **Input Validation:** + - Validate all user input to prevent malicious code from being injected into your application. + - Use regular expressions and data type validation. + - **Authentication and Authorization:** + - Use strong authentication mechanisms (e.g., multi-factor authentication). + - Implement role-based access control (RBAC) to restrict access to sensitive resources. + - Use AWS IAM roles for EC2 instances to grant access to AWS resources. + - **Data Protection:** + - Encrypt sensitive data at rest and in transit. + - Use HTTPS for all API communication. + - Store sensitive data in secure storage (e.g., AWS Secrets Manager). + - **Secure API Communication:** + - Use HTTPS for all API communication. + - Validate API requests and responses. + - Implement rate limiting to prevent abuse. + - Use AWS API Gateway to manage and secure your APIs. + +- ## 5. Testing Approaches + + - **Unit Testing:** + - Write unit tests for individual components to verify their functionality. + - Use mocking and stubbing to isolate components from external dependencies. + - Example (Python): + python + import unittest + from unittest.mock import Mock + + class MyComponent: + def __init__(self, external_dependency): + self.dependency = external_dependency + + def my_function(self, input_data): + result = self.dependency.process_data(input_data) + return result + + class TestMyComponent(unittest.TestCase): + def test_my_function(self): + # Create a mock for the external dependency + mock_dependency = Mock() + mock_dependency.process_data.return_value = "Mocked Result" + + # Create an instance of MyComponent with the mock dependency + component = MyComponent(mock_dependency) + + # Call the function to be tested + result = component.my_function("Test Input") + + # Assert the expected behavior + self.assertEqual(result, "Mocked Result") + mock_dependency.process_data.assert_called_once_with("Test Input") + + if __name__ == '__main__': + unittest.main() + + - **Integration Testing:** + - Write integration tests to verify the interaction between components. + - Test the integration of your application with AWS services. + - **End-to-End Testing:** + - Write end-to-end tests to verify the entire application flow. + - Simulate real user scenarios. + - **Test Organization:** + - Organize your tests into a logical directory structure. + - Use meaningful test names. + - Keep tests independent of each other. + - **Mocking and Stubbing:** + - Use mocking and stubbing to isolate components from external dependencies. + - Example (AWS CDK): + typescript + // Mocking AWS SDK calls in Jest + jest.mock('aws-sdk', () => { + const mEC2 = { + describeInstances: jest.fn().mockReturnValue({ + promise: jest.fn().mockResolvedValue({ Reservations: [] }), + }), + }; + return { + EC2: jest.fn().mockImplementation(() => mEC2), + }; + }); + + +- ## 6. Common Pitfalls and Gotchas + + - **Frequent Mistakes:** + - **Incorrect Security Group Configuration:** Incorrectly configured security groups can expose your EC2 instances to security risks. + - **Insufficient Resource Limits:** Exceeding AWS resource limits can cause application failures. + - **Not Using Auto Scaling:** Not using Auto Scaling can lead to performance bottlenecks and outages during periods of high demand. + - **Forgetting to Terminate Unused Instances:** Forgetting to terminate unused EC2 instances can lead to unnecessary costs. + - **Edge Cases:** + - **Spot Instance Interruptions:** Spot instances can be interrupted with short notice. Design your application to handle spot instance interruptions gracefully. + - **Network Connectivity Issues:** Network connectivity issues can prevent your application from accessing AWS services or other resources. + - **Version-Specific Issues:** + - Be aware of version-specific issues with the amazon-ec2 library or AWS services. + - Consult the documentation for the specific versions you are using. + - **Compatibility Concerns:** + - Ensure compatibility between your application and the underlying operating system and libraries. + - Test your application on different operating systems and browsers. + - **Debugging Strategies:** + - Use logging and monitoring to track the behavior of your application. + - Use debugging tools to identify and fix errors. + - Consult the AWS documentation and community forums for help. + +- ## 7. Tooling and Environment + + - **Recommended Tools:** + - **AWS CLI:** Command-line interface for interacting with AWS services. + - **AWS Management Console:** Web-based interface for managing AWS resources. + - **AWS CloudFormation:** Infrastructure as code service for provisioning and managing AWS resources. + - **AWS CDK:** Cloud Development Kit for defining cloud infrastructure in code. + - **Terraform:** Infrastructure as code tool for provisioning and managing cloud resources. + - **Packer:** Tool for creating machine images. + - **Ansible:** Configuration management tool. + - **Build Configuration:** + - Use a build tool (e.g., Make, Gradle, Maven) to automate the build process. + - Define dependencies and build steps in a build file. + - Example (Python): + makefile + # Makefile + venv: + python3 -m venv .venv + . .venv/bin/activate + pip install -r requirements.txt + + deploy: + zip -r deployment_package.zip * + aws s3 cp deployment_package.zip s3://my-bucket/deployment_package.zip + aws lambda update-function-code --function-name my-function --s3-bucket my-bucket --s3-key deployment_package.zip + + - **Linting and Formatting:** + - Use a linter (e.g., pylint, eslint) to enforce code style and identify potential errors. + - Use a formatter (e.g., black, prettier) to automatically format your code. + - **Deployment Best Practices:** + - Use a deployment pipeline to automate the deployment process. + - Deploy to a staging environment before deploying to production. + - Use blue/green deployments to minimize downtime. + - **CI/CD Integration:** + - Integrate your application with a CI/CD system (e.g., Jenkins, CircleCI, GitLab CI). + - Automate testing, building, and deployment. + +- ## Additional Considerations + + - **Cost Optimization:** Regularly review your AWS resource usage and identify opportunities for cost savings. Consider using Reserved Instances or Spot Instances to reduce costs. + - **Disaster Recovery:** Implement a disaster recovery plan to ensure business continuity in the event of an outage. Use AWS Backup or other backup solutions to protect your data. + - **Compliance:** Ensure that your application complies with relevant regulations and standards (e.g., PCI DSS, HIPAA). + +- ## References + + - [AWS EC2 Best Practices](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-best-practices.html) + - [AWS CDK Best Practices](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html) + - [Terraform AWS Provider Best Practices](https://docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/structure.html) \ No newline at end of file diff --git a/rules-mdc/amazon-s3.mdc b/rules-mdc/amazon-s3.mdc new file mode 100644 index 0000000..94a315a --- /dev/null +++ b/rules-mdc/amazon-s3.mdc @@ -0,0 +1,367 @@ +--- +description: This rule file provides comprehensive best practices, coding standards, and security guidelines for developing applications using Amazon S3. It aims to ensure secure, performant, and maintainable S3 integrations. +globs: **/*S3*.{js,ts,jsx,tsx,py,java,go,csharp} +--- +- Always disable public access to S3 buckets unless explicitly needed. Use AWS Identity and Access Management (IAM) policies and bucket policies for access control instead of Access Control Lists (ACLs), which are now generally deprecated. +- Implement encryption for data at rest using Server-Side Encryption (SSE), preferably with AWS Key Management Service (KMS) for enhanced security. +- Use S3 Transfer Acceleration for faster uploads over long distances and enable versioning to protect against accidental deletions. Monitor performance using Amazon CloudWatch and enable logging for auditing. Additionally, consider using S3 Storage Lens for insights into storage usage and activity trends. +- Leverage S3's lifecycle policies to transition objects to cheaper storage classes based on access patterns, and regularly review your storage usage to optimize costs. Utilize S3 Intelligent-Tiering for automatic cost savings based on changing access patterns. + +## Amazon S3 Best Practices and Coding Standards + +This document provides comprehensive best practices, coding standards, and security guidelines for developing applications using Amazon S3. Following these guidelines will help ensure that your S3 integrations are secure, performant, maintainable, and cost-effective. + +### 1. Code Organization and Structure + +#### 1.1. Directory Structure Best Practices + +Organize your code related to Amazon S3 into logical directories based on functionality. + + +project/ +├── src/ +│ ├── s3/ +│ │ ├── utils.js # Utility functions for S3 operations +│ │ ├── uploader.js # Handles uploading files to S3 +│ │ ├── downloader.js # Handles downloading files from S3 +│ │ ├── config.js # Configuration for S3 (bucket name, region, etc.) +│ │ ├── errors.js # Custom error handling for S3 operations +│ │ └── index.js # Entry point for S3 module +│ ├── ... +│ └── tests/ +│ ├── s3/ +│ │ ├── uploader.test.js # Unit tests for uploader.js +│ │ └── ... +│ └── ... +├── ... + + +#### 1.2. File Naming Conventions + +Use descriptive and consistent file names. + +* `uploader.js`: Module for uploading files to S3. +* `downloader.js`: Module for downloading files from S3. +* `s3_service.py`: (Python Example) Defines S3 related services. +* `S3Manager.java`: (Java Example) Manages S3 client and configurations. + +#### 1.3. Module Organization + +* **Single Responsibility Principle:** Each module should have a clear and specific purpose (e.g., uploading, downloading, managing bucket lifecycle). +* **Abstraction:** Hide complex S3 operations behind simpler interfaces. +* **Configuration:** Store S3 configuration details (bucket name, region, credentials) in a separate configuration file. + +Example (JavaScript): +javascript +// s3/uploader.js +import AWS from 'aws-sdk'; +import config from './config'; + +const s3 = new AWS.S3(config.s3); + +export const uploadFile = async (file, key) => { + const params = { + Bucket: config.s3.bucketName, + Key: key, + Body: file + }; + try { + await s3.upload(params).promise(); + console.log(`File uploaded successfully: ${key}`); + } catch (error) { + console.error('Error uploading file:', error); + throw error; // Re-throw for handling in the caller. + } +}; + + +#### 1.4. Component Architecture + +For larger applications, consider a component-based architecture. This can involve creating distinct components for different S3-related tasks. For example: + +* **Upload Component:** Handles file uploads, progress tracking, and error handling. +* **Download Component:** Handles file downloads, progress tracking, and caching. +* **Management Component:** Manages bucket creation, deletion, and configuration. + +#### 1.5. Code Splitting + +If you have a large application using S3, consider using code splitting to reduce the initial load time. This involves breaking your code into smaller chunks that can be loaded on demand. This is especially relevant for front-end applications using S3 for asset storage. + +* **Dynamic Imports:** Use dynamic imports to load S3-related modules only when needed. +* **Webpack/Rollup:** Configure your bundler to create separate chunks for S3 code. + +### 2. Common Patterns and Anti-patterns + +#### 2.1. Design Patterns + +* **Strategy Pattern:** Use a strategy pattern to handle different storage classes or encryption methods. +* **Factory Pattern:** Use a factory pattern to create S3 clients with different configurations. +* **Singleton Pattern:** Use a singleton pattern if you want to use one s3 instance for all the s3 interactions. + +#### 2.2. Recommended Approaches for Common Tasks + +* **Uploading large files:** Use multipart upload for files larger than 5 MB. This allows you to upload files in parallel and resume interrupted uploads. +* **Downloading large files:** Use byte-range fetches to download files in chunks. This is useful for resuming interrupted downloads and for accessing specific portions of a file. +* **Deleting multiple objects:** Use the `deleteObjects` API to delete multiple objects in a single request. This is more efficient than deleting objects one by one. + +#### 2.3. Anti-patterns and Code Smells + +* **Hardcoding credentials:** Never hardcode AWS credentials in your code. Use IAM roles or environment variables. +* **Insufficient error handling:** Always handle errors from S3 operations gracefully. Provide informative error messages and retry failed operations. +* **Ignoring bucket access control:** Properly configure bucket policies and IAM roles to restrict access to your S3 buckets. +* **Overly permissive bucket policies:** Avoid granting overly broad permissions in your bucket policies. Follow the principle of least privilege. +* **Not using versioning:** Failing to enable versioning can lead to data loss if objects are accidentally deleted or overwritten. +* **Assuming immediate consistency:** S3 provides eventual consistency for some operations. Be aware of this and design your application accordingly. +* **Polling for object existence:** Instead of polling, use S3 events to trigger actions when objects are created or modified. +* **Inefficient data retrieval:** Avoid retrieving entire objects when only a portion of the data is needed. Use byte-range fetches or S3 Select to retrieve only the necessary data. + +#### 2.4. State Management + +* **Stateless operations:** Design your S3 operations to be stateless whenever possible. This makes your application more scalable and resilient. +* **Caching:** Use caching to reduce the number of requests to S3. Consider using a CDN (Content Delivery Network) to cache frequently accessed objects. +* **Session management:** If you need to maintain state, store session data in a separate database or cache, not in S3. + +#### 2.5. Error Handling + +* **Retry mechanism:** Implement retry logic with exponential backoff for transient errors. +* **Specific error handling:** Handle different S3 errors differently (e.g., retry 503 errors, log 403 errors). +* **Centralized error logging:** Log all S3 errors to a centralized logging system for monitoring and analysis. + +Example (Python): +python +import boto3 +from botocore.exceptions import ClientError +import time + +s3 = boto3.client('s3') + +def upload_file(file_name, bucket, object_name=None): + """Upload a file to an S3 bucket""" + if object_name is None: + object_name = file_name + + for attempt in range(3): # Retry up to 3 times + try: + response = s3.upload_file(file_name, bucket, object_name) + return True + except ClientError as e: + if e.response['Error']['Code'] == 'NoSuchBucket': + print(f"The bucket {bucket} does not exist.") + return False + elif e.response['Error']['Code'] == 'AccessDenied': + print("Access denied. Check your credentials and permissions.") + return False + else: + print(f"An error occurred: {e}") + if attempt < 2: # Wait and retry + time.sleep(2 ** attempt) + else: + return False + except Exception as e: + print(f"An unexpected error occurred: {e}") + return False + return False # Reached max retries and failed + + +### 3. Performance Considerations + +#### 3.1. Optimization Techniques + +* **Use S3 Transfer Acceleration:** If you are uploading or downloading files from a geographically distant location, use S3 Transfer Acceleration to improve performance. S3 Transfer Acceleration utilizes Amazon CloudFront's globally distributed edge locations. +* **Use multipart upload:** For large files, use multipart upload to upload files in parallel. The documentation states the best practice is to use this for files larger than 5MB. +* **Enable gzip compression:** Compress objects before uploading them to S3 to reduce storage costs and improve download times. Set the `Content-Encoding` header to `gzip` when uploading compressed objects. +* **Use HTTP/2:** Enable HTTP/2 on your S3 bucket to improve performance. +* **Optimize object sizes:** Store related data in a single object to reduce the number of requests to S3. + +#### 3.2. Memory Management + +* **Stream data:** Avoid loading entire files into memory. Use streams to process data in chunks. +* **Release resources:** Release S3 client objects when they are no longer needed. + +#### 3.3. Bundle Size Optimization + +* **Tree shaking:** Use a bundler that supports tree shaking to remove unused code from your bundle. +* **Code splitting:** Split your code into smaller chunks that can be loaded on demand. + +#### 3.4. Lazy Loading + +* **Load images on demand:** Load images from S3 only when they are visible on the screen. +* **Lazy load data:** Load data from S3 only when it is needed. + +### 4. Security Best Practices + +#### 4.1. Common Vulnerabilities + +* **Publicly accessible buckets:** Ensure that your S3 buckets are not publicly accessible. +* **Insufficient access control:** Properly configure bucket policies and IAM roles to restrict access to your S3 buckets. +* **Cross-site scripting (XSS):** Sanitize user input to prevent XSS attacks if you are serving content directly from S3. +* **Data injection:** Validate all data before storing it in S3 to prevent data injection attacks. + +#### 4.2. Input Validation + +* **Validate file types:** Validate the file types of uploaded objects to prevent malicious files from being stored in S3. +* **Validate file sizes:** Limit the file sizes of uploaded objects to prevent denial-of-service attacks. +* **Sanitize file names:** Sanitize file names to prevent directory traversal attacks. + +#### 4.3. Authentication and Authorization + +* **Use IAM roles:** Use IAM roles to grant permissions to applications running on EC2 instances or other AWS services. +* **Use temporary credentials:** Use temporary credentials for applications that need to access S3 from outside of AWS. You can use AWS STS (Security Token Service) to generate temporary credentials. +* **Principle of least privilege:** Grant only the minimum permissions required for each user or application. + +#### 4.4. Data Protection + +* **Encrypt data at rest:** Use server-side encryption (SSE) or client-side encryption to encrypt data at rest in S3. +* **Encrypt data in transit:** Use HTTPS to encrypt data in transit between your application and S3. +* **Enable versioning:** Enable versioning to protect against accidental data loss. +* **Enable MFA Delete:** Require multi-factor authentication to delete objects from S3. +* **Object locking:** Use S3 Object Lock to prevent objects from being deleted or overwritten for a specified period of time. + +#### 4.5. Secure API Communication + +* **Use HTTPS:** Always use HTTPS to communicate with the S3 API. +* **Validate certificates:** Validate the SSL/TLS certificates of the S3 endpoints. +* **Restrict access:** Restrict access to the S3 API using IAM policies and bucket policies. + +### 5. Testing Approaches + +#### 5.1. Unit Testing + +* **Mock S3 client:** Mock the S3 client to isolate your unit tests. +* **Test individual functions:** Test individual functions that interact with S3. +* **Verify error handling:** Verify that your code handles S3 errors correctly. + +Example (JavaScript with Jest): +javascript +// s3/uploader.test.js +import { uploadFile } from './uploader'; +import AWS from 'aws-sdk'; + +jest.mock('aws-sdk', () => { + const mS3 = { + upload: jest.fn().mockReturnThis(), + promise: jest.fn(), + }; + return { + S3: jest.fn(() => mS3), + }; +}); + +describe('uploadFile', () => { + it('should upload file successfully', async () => { + const mockS3 = new AWS.S3(); + mockS3.promise.mockResolvedValue({}); + const file = 'test file content'; + const key = 'test.txt'; + + await uploadFile(file, key); + + expect(AWS.S3).toHaveBeenCalledTimes(1); + expect(mockS3.upload).toHaveBeenCalledWith({ + Bucket: 'your-bucket-name', + Key: key, + Body: file + }); + }); + + it('should handle upload error', async () => { + const mockS3 = new AWS.S3(); + mockS3.promise.mockRejectedValue(new Error('Upload failed')); + const file = 'test file content'; + const key = 'test.txt'; + + await expect(uploadFile(file, key)).rejects.toThrow('Upload failed'); + }); +}); + + +#### 5.2. Integration Testing + +* **Test with real S3 buckets:** Create a dedicated S3 bucket for integration tests. +* **Test end-to-end flows:** Test complete workflows that involve S3 operations. +* **Verify data integrity:** Verify that data is correctly stored and retrieved from S3. + +#### 5.3. End-to-End Testing + +* **Simulate user scenarios:** Simulate real user scenarios to test your application's S3 integration. +* **Monitor performance:** Monitor the performance of your S3 integration under load. + +#### 5.4. Test Organization + +* **Separate test directories:** Create separate test directories for unit tests, integration tests, and end-to-end tests. +* **Descriptive test names:** Use descriptive test names that clearly indicate what is being tested. + +#### 5.5. Mocking and Stubbing + +* **Mock S3 client:** Use a mocking library (e.g., Jest, Mockito) to mock the S3 client. +* **Stub S3 responses:** Stub S3 API responses to simulate different scenarios. +* **Use dependency injection:** Use dependency injection to inject mocked S3 clients into your components. + +### 6. Common Pitfalls and Gotchas + +#### 6.1. Frequent Mistakes + +* **Forgetting to handle errors:** Failing to handle S3 errors can lead to unexpected behavior and data loss. +* **Using incorrect region:** Using the wrong region can result in connection errors and data transfer costs. +* **Exposing sensitive data:** Storing sensitive data in S3 without proper encryption can lead to security breaches. +* **Not cleaning up temporary files:** Failing to delete temporary files after uploading them to S3 can lead to storage waste. +* **Overusing public read access:** Granting public read access to S3 buckets can expose sensitive data to unauthorized users. + +#### 6.2. Edge Cases + +* **Eventual consistency:** S3 provides eventual consistency for some operations. Be aware of this and design your application accordingly. +* **Object size limits:** Be aware of the object size limits for S3. +* **Request rate limits:** Be aware of the request rate limits for S3. +* **Special characters in object keys:** Handle special characters in object keys correctly. + +#### 6.3. Version-Specific Issues + +* **SDK compatibility:** Ensure that your AWS SDK is compatible with the S3 API version. +* **API changes:** Be aware of any API changes that may affect your application. + +#### 6.4. Compatibility Concerns + +* **Browser compatibility:** Ensure that your application is compatible with different browsers if you are using S3 directly from the browser. +* **Serverless environments:** Be aware of any limitations when using S3 in serverless environments (e.g., Lambda). + +#### 6.5. Debugging Strategies + +* **Enable logging:** Enable logging to track S3 API calls and errors. +* **Use S3 monitoring tools:** Use S3 monitoring tools to monitor the performance and health of your S3 buckets. +* **Check S3 access logs:** Analyze S3 access logs to identify potential security issues. +* **Use AWS CloudTrail:** Use AWS CloudTrail to track API calls to S3. +* **Use AWS X-Ray:** Use AWS X-Ray to trace requests through your application and identify performance bottlenecks. + +### 7. Tooling and Environment + +#### 7.1. Recommended Development Tools + +* **AWS CLI:** The AWS Command Line Interface (CLI) is a powerful tool for managing S3 resources. +* **AWS SDK:** The AWS SDK provides libraries for interacting with S3 from various programming languages. +* **S3 Browser:** S3 Browser is a Windows client for managing S3 buckets and objects. +* **Cyberduck:** Cyberduck is a cross-platform client for managing S3 buckets and objects. +* **Cloudberry Explorer:** Cloudberry Explorer is a Windows client for managing S3 buckets and objects. + +#### 7.2. Build Configuration + +* **Use environment variables:** Store S3 configuration details (bucket name, region, credentials) in environment variables. +* **Use a build tool:** Use a build tool (e.g., Maven, Gradle, Webpack) to manage your project dependencies and build your application. + +#### 7.3. Linting and Formatting + +* **Use a linter:** Use a linter (e.g., ESLint, PyLint) to enforce code style and best practices. +* **Use a formatter:** Use a code formatter (e.g., Prettier, Black) to automatically format your code. + +#### 7.4. Deployment + +* **Use infrastructure as code:** Use infrastructure as code (e.g., CloudFormation, Terraform) to automate the deployment of your S3 resources. +* **Use a deployment pipeline:** Use a deployment pipeline to automate the deployment of your application. +* **Use blue/green deployments:** Use blue/green deployments to minimize downtime during deployments. + +#### 7.5. CI/CD Integration + +* **Integrate with CI/CD tools:** Integrate your S3 deployment process with CI/CD tools (e.g., Jenkins, CircleCI, Travis CI). +* **Automate testing:** Automate your unit tests, integration tests, and end-to-end tests as part of your CI/CD pipeline. +* **Automate deployments:** Automate the deployment of your application to S3 as part of your CI/CD pipeline. + +By following these best practices and coding standards, you can ensure that your Amazon S3 integrations are secure, performant, maintainable, and cost-effective. \ No newline at end of file diff --git a/rules-mdc/android-sdk.mdc b/rules-mdc/android-sdk.mdc new file mode 100644 index 0000000..349e5b9 --- /dev/null +++ b/rules-mdc/android-sdk.mdc @@ -0,0 +1,311 @@ +--- +description: This rule file provides comprehensive best practices for Android SDK development, encompassing code organization, performance, security, testing, and common pitfalls. It aims to guide developers in creating robust, maintainable, and efficient Android applications and libraries. +globs: **/*.{java,kt,xml,gradle,properties} +--- +- MUST be under source control management (SCM). RECOMMENDED source control management is git +- If you intend your source repo to be public ensure you have received the necessary management and legal approval +- MUST use a .gitignore configuration tailored for Android projects (e.g., ignoring `local.properties`, `build/`, `.gradle/`) +- Source code repositories SHOULD follow the naming convention `[platform]-[library name]`, e.g., `android-analytics`, `java-datastore` +- MUST NOT restrict read access to source code repositories unnecessarily +- RECOMMEND to not have source file header comment blocks as these easily get out of date + +## Code Organization and Structure + +- SHOULD follow the standard project layout for Android projects. Key directories: + - `src/main/java`: Java/Kotlin source code + - `src/main/res`: Resources (layouts, drawables, strings, etc.) + - `src/test/java`: Unit tests + - `src/androidTest/java`: Instrumentation tests +- MUST prefix all exported resources (layout files, XML files, drawable IDs, color IDs, dimension IDs, string IDs, etc.) with a unique prefix for the library using `resourcePrefix` in the Gradle build file. Example: `sug` for a Suggestion Module. This avoids naming conflicts when the library is used in other projects. +- Use package names that are descriptive and follow the reverse domain name convention (e.g., `com.example.myapp.feature`). +- Organize code into logical modules or features. Each module should have a clear responsibility and be loosely coupled with other modules. +- Use Kotlin for new projects. If working with Java, target Java 8 or higher to utilize modern language features. +- Consider using a multi-module project structure for larger projects to improve build times and code organization. Modules can represent different features, libraries, or build variants. +- Employ a layered architecture (e.g., presentation, domain, data) to separate concerns and improve testability. + +### Directory Structure Best Practices: + + +root/ +├── app/ +│ ├── build.gradle +│ └── src/ +│ ├── androidTest/ +│ │ └── java/ +│ ├── main/ +│ │ ├── AndroidManifest.xml +│ │ ├── java/ +│ │ │ └── com/example/app/ +│ │ │ ├── MainActivity.kt +│ │ │ ├── model/ +│ │ │ ├── view/ +│ │ │ └── viewmodel/ +│ │ └── res/ +│ │ ├── layout/ +│ │ ├── drawable/ +│ │ ├── values/ +│ │ └── mipmap-xxhdpi/ +│ └── test/ +│ └── java/ +├── library_module/ +│ ├── build.gradle +│ └── src/ +│ ├── main/ +│ │ ├── java/ +│ │ └── res/ +│ └── test/ +├── build.gradle +├── settings.gradle + + +### File Naming Conventions: + +- **Kotlin/Java:** `PascalCase` for class names (e.g., `MainActivity`), `camelCase` for variables and method names (e.g., `userName`, `calculateTotal`). +- **Layout XML:** `snake_case` (e.g., `activity_main.xml`). Use descriptive names reflecting the layout's purpose. +- **Drawable XML:** `snake_case` (e.g., `ic_launcher.xml`). Prefix icons with `ic_`, backgrounds with `bg_`, and other drawables accordingly. +- **Values XML:** `snake_case` (e.g., `strings.xml`, `colors.xml`, `dimens.xml`). +- **Gradle:** `build.gradle` (module-level), `settings.gradle` (project-level). + +### Component Architecture Recommendations: + +- MVVM (Model-View-ViewModel) is the recommended architecture pattern. Use Android Architecture Components (LiveData, ViewModel, Room) to implement it effectively. +- For complex UI logic, consider using a ViewBindingDelegate to simplify view access and reduce boilerplate. +- Use dependency injection (Hilt or Dagger) to manage dependencies and improve testability. + +## Common Patterns and Anti-patterns + +- Use `LiveData` and `Flow` for reactive data streams. +- Utilize coroutines for asynchronous operations to simplify threading and avoid callback hell. +- Avoid performing long-running operations on the main thread (UI thread). Use `Dispatchers.IO` or `Dispatchers.Default` with coroutines or `AsyncTask` for background tasks. +- Don't use `AsyncTask` if possible, prefer coroutines. +- Prefer `ConstraintLayout` over other layout types for complex UIs as it is more flexible and performant. +- Use `RecyclerView` for displaying large lists of data efficiently. Implement view holder pattern correctly for optimal performance. +- Apply data binding to reduce boilerplate code in UI updates. +- Use sealed classes for representing state to ensure exhaustive handling of all possible states. +- Implement proper error handling with try-catch blocks and report errors gracefully to the user. +- Log errors and exceptions using a logging framework (Timber) for debugging and analysis. + +### Anti-patterns and Code Smells to Avoid: + +- **God Classes:** Classes that are too large and have too many responsibilities. Break them down into smaller, more focused classes. +- **Spaghetti Code:** Code that is difficult to read and understand due to complex control flow. Refactor it to improve readability and maintainability. +- **Copy-Paste Programming:** Duplicating code across multiple locations. Extract the common code into reusable functions or classes. +- **Hardcoding Values:** Avoid hardcoding values directly in the code. Use resources (strings, colors, dimensions) for better maintainability and localization. +- **Leaking Context:** Holding onto `Activity` or `Context` instances for longer than necessary, leading to memory leaks. + +### State Management Best Practices: + +- Use `ViewModel` to store UI-related data that survives configuration changes. +- Utilize `SavedStateHandle` in `ViewModel` to persist data across process death. +- Consider using a state management library (e.g., Redux, MVI) for complex applications with complex state. +- Implement appropriate caching strategies to reduce network requests and improve performance. + +### Error Handling Patterns: + +- Use try-catch blocks to handle potential exceptions and prevent app crashes. +- Report errors gracefully to the user with informative error messages. +- Log errors and exceptions using a logging framework (Timber) for debugging and analysis. +- Implement retry mechanisms for transient errors (e.g., network connection issues). + +## Performance Considerations + +- Optimize image loading using libraries like Glide or Coil. Resize images to the required dimensions before loading them into `ImageViews`. +- Use efficient data structures (e.g., `SparseArray` instead of `HashMap` for integer keys). +- Avoid creating unnecessary objects, especially in loops or frequently called methods. +- Use `StringBuilder` instead of string concatenation for building strings efficiently. +- Minimize network requests and optimize data transfer using compression and pagination. +- Analyze app performance using profiling tools (Android Profiler) to identify bottlenecks. +- Utilize the LeakCanary library to detect memory leaks during development. +- Use ProGuard or R8 to shrink, obfuscate, and optimize the code for release builds. + +### Memory Management Considerations: + +- Avoid creating memory leaks by properly managing object lifecycles and releasing resources when they are no longer needed. +- Use `WeakReference` to hold references to objects that may be garbage collected to prevent memory leaks. +- Monitor memory usage using the Android Profiler and identify potential memory leaks. + +### Rendering Optimization: + +- Minimize overdraw by reducing the number of layers that are drawn on top of each other. +- Use hardware acceleration to improve rendering performance. +- Optimize custom views by implementing `onDraw()` method efficiently and avoiding unnecessary allocations. + +### Bundle Size Optimization: + +- Remove unused resources using `shrinkResources` in the Gradle build file. +- Use vector drawables instead of raster images for icons and other simple graphics. +- Enable code shrinking and obfuscation using ProGuard or R8. +- Compress images using tools like TinyPNG or ImageOptim. +- Use app bundles to deliver optimized APKs for different device configurations. +- Utilize dynamic feature modules to defer the download of non-essential features. + +### Lazy Loading Strategies: + +- Implement lazy loading for images and other resources that are not immediately visible on the screen. +- Use pagination or infinite scrolling to load data in chunks as the user scrolls down the list. + +## Security Best Practices + +- MUST use Kotlin or Java. Kotlin is RECOMMENDED +- SHOULD use static code analysis, such as detekt or SwiftLint to minimise errors and minimise debates and formatting fix-up commits in PRs. It is RECOMMENDED to integrate these tools with the CI workflow. SHOULD use quality tools available in common config: Android and iOS +- Android: MUST use the Android Support Annotations for public APIs. Non-Android Java code MUST use the Jetbrains Annotations for public APIs +- Secure API communication and proper permission handling are vital to protect user data. +- MUST use a `consumerProguardFiles` file if obfuscation breaks the libraries function. +- SHOULD NOT have unnecessary exported dependencies, in particular SHOULD NOT leak networking library to consumers. SHOULD NOT leak serialization library to consumers. An exception to this rule are optional adapters for popular libraries. + +### Common Vulnerabilities and Prevention: + +- **SQL Injection:** Avoid using raw SQL queries. Use parameterized queries or an ORM like Room to prevent SQL injection attacks. +- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. +- **Man-in-the-Middle (MITM) Attacks:** Use HTTPS for all network communication to encrypt data in transit and prevent MITM attacks. +- **Insecure Data Storage:** Encrypt sensitive data before storing it on the device. +- **Improper Platform Usage:** Ensure that permissions are properly requested and handled. Review and minimize the permissions your app requests. + +### Input Validation: + +- Validate all user input on both the client and server sides to prevent malicious data from being processed. +- Use regular expressions or validation libraries to enforce input constraints. + +### Authentication and Authorization: + +- Use secure authentication protocols (e.g., OAuth 2.0, OpenID Connect) for user authentication. +- Implement proper authorization mechanisms to control access to resources based on user roles. +- Store user credentials securely using hashing and salting. + +### Data Protection: + +- Encrypt sensitive data at rest using AES or other strong encryption algorithms. +- Securely transmit data over the network using HTTPS. +- Implement data masking or anonymization techniques to protect user privacy. + +### Secure API Communication: + +- Use HTTPS for all API communication. +- Verify the server's SSL certificate to prevent MITM attacks. +- Implement API rate limiting to prevent denial-of-service attacks. + +## Testing Approaches + +- All library (sub-)projects MUST generate coverage test reports (e.g. jacoco, Xcode/slather). +- Unit test coverage MUST be at least 80% and SHOULD be above 85% +- Unit tests MUST NOT rely on reflection to expose otherwise private/internal classes or members. +- Tests SHOULD use JUnit, and MAY use helper libraries such as Mockito or Robolectric + +### Unit Testing Strategies: + +- Write unit tests for all critical components, including `ViewModels`, repositories, and use cases. +- Use mocking frameworks (Mockito) to isolate units under test and mock dependencies. +- Follow the AAA (Arrange, Act, Assert) pattern for writing clear and concise unit tests. + +### Integration Testing Approaches: + +- Write integration tests to verify the interaction between different components, such as `ViewModels` and repositories. +- Use dependency injection to provide mock dependencies for integration tests. + +### End-to-End Testing: + +- Use UI testing frameworks (Espresso, UI Automator) to write end-to-end tests that simulate user interactions. + +### Test Organization: + +- Organize tests into separate directories based on the type of tests (unit, integration, UI). +- Use descriptive names for test classes and methods to clearly indicate what is being tested. + +### Mocking and Stubbing: + +- Use mocking frameworks (Mockito) to create mock objects for dependencies. +- Use stubbing to define the behavior of mock objects for specific test cases. + +## Common Pitfalls and Gotchas + +- Frequent mistakes developers make when using android-sdk +- Edge cases to be aware of when using android-sdk +- Version-specific issues with android-sdk +- Compatibility concerns between android-sdk and other technologies +- Debugging strategies for android-sdk applications + +### Frequent Mistakes: + +- Not handling configuration changes properly, leading to data loss or unexpected behavior. +- Performing long-running operations on the main thread, causing the UI to freeze. +- Leaking `Context` objects, leading to memory leaks. +- Not properly validating user input, leading to security vulnerabilities. +- Not handling exceptions properly, leading to app crashes. +- Overusing `AsyncTask` and not managing thread pools correctly. + +### Edge Cases: + +- Handling network connectivity issues gracefully. +- Managing different screen sizes and densities. +- Dealing with low-memory conditions. +- Handling background tasks properly to avoid ANRs (Application Not Responding). +- Handling different Android versions and API levels. + +### Version-Specific Issues: + +- Be aware of API level differences and use `@TargetApi` and `@RequiresApi` annotations to handle them correctly. +- Test your app on different Android versions to ensure compatibility. + +### Compatibility Concerns: + +- Ensure compatibility with different device manufacturers and hardware configurations. +- Test your app on different screen sizes and densities. + +### Debugging Strategies: + +- Use the Android Debug Bridge (ADB) to connect to devices and emulators for debugging. +- Use the Android Profiler to analyze app performance and identify bottlenecks. +- Use logging statements to track the flow of execution and identify errors. +- Use the debugger to step through the code and inspect variables. + +## Tooling and Environment + +### Recommended Tools: + +- Android Studio: The official IDE for Android development. +- Gradle: The build system for Android projects. +- ADB (Android Debug Bridge): A command-line tool for communicating with Android devices and emulators. +- Android Profiler: A tool for analyzing app performance. +- LeakCanary: A library for detecting memory leaks. +- Timber: A logging library for Android. + +### Build Configuration: + +- MUST use gradle with gradle wrapper to build Android library or Java library +- MUST have consistent minSdk and supportLib versions with other SDKs +- SHOULD use shared build configuration for consistent version with other SDKs/libraries +- MAY use manual configuration with values (same as in shared build configuration), if so SHOULD use a recent minSdk version unless there is an engineering or product decision to support older versions +- SHOULD use latest versions of Android X libraries (if required) + +- Configure build variants for different environments (debug, release, staging). +- Use ProGuard or R8 to shrink, obfuscate, and optimize the code for release builds. +- Configure signing configurations to sign the APK for distribution. + +### Linting and Formatting: + +- Enforce code style guidelines using lint and code formatters (e.g., ktlint for Kotlin). +- Configure lint to run automatically during the build process. +- Resolve lint warnings and errors to improve code quality. + +### Deployment: + +- Publish libraries to a Maven repository (Maven Central or a private repository). +- Deploy apps to the Google Play Store. +- Implement beta testing using Google Play Console. + +### CI/CD Integration: + +- Integrate the build process with a CI/CD system (e.g., Jenkins, CircleCI, GitHub Actions). +- Automate testing, linting, and code formatting as part of the CI/CD pipeline. +- Automate deployment to the Google Play Store. + +## Additional Considerations +- Limit impact on consumers. SHOULD limit dependencies as much as possible primarily due to risk of version clashes +- RECOMMENDED not to have any exported dependency on other SDK modules e.g. if your module needs authentication, do not depend on Authentication SDK. Instead, require your library consumer to pass an access token string to your API instead. +- Expose minimal Surface area. Keep everything private unless it needs to be public. Every public class, method, property & resource MUST have a strong reason for being public. MAY keep internal source code in a /Private folder to allow tools to more easily ignore those files +- MUST hide classes from generated API documentation that are required to be public solely for technical reasons and are not intended for SDK consumers +- SHOULD declare classes as final to avoid unexpected high-jacking of SDK behavior by subclasses +- For better testability of your library it is RECOMMENDED to use dependency injection +- MUST follow Semantic Versioning +- MUST tag source control management revision/commit that is published +- RECOMMENDED For Android: Use gradle-versions-plugin for automated versioning by git tag \ No newline at end of file diff --git a/rules-mdc/ansible.mdc b/rules-mdc/ansible.mdc new file mode 100644 index 0000000..99f9b60 --- /dev/null +++ b/rules-mdc/ansible.mdc @@ -0,0 +1,553 @@ +--- +description: This rule file provides comprehensive best practices and coding standards for Ansible projects, covering code organization, common patterns, performance, security, testing, pitfalls, and tooling. It aims to improve maintainability, reusability, and efficiency in Ansible automation. +globs: **/*.{yml,yaml,j2} +--- +- Adopt and adhere to the following Ansible best practices to ensure maintainable, reusable, and efficient automation code. This guide provides standards for code organization, common patterns, performance optimization, security, testing, tooling, and common pitfalls to avoid. + +## 1. Code Organization and Structure + +- Structure your Ansible projects in a clear and consistent manner to enhance readability and maintainability. + +### 1.1 Directory Structure Best Practices + +- **Root Directory:** + - `ansible.cfg`: Ansible configuration file. This should live in the root directory of your project. + - `inventory/`: Contains your inventory files (hosts, groups, and variables). + - `hosts`: Main inventory file. + - `group_vars/`: Directory for group-specific variables. + - `all/`: Contains variables that apply to all hosts. + - `vars.yml`: Primary file for common variables. + - `vault.yml`: Encrypted variables. + - `/`: Directory for variables specific to a group. + - `vars.yml`: Group-specific variables. + - `vault.yml`: Encrypted group variables. + - `host_vars/`: Directory for host-specific variables. + - `/`: Directory for a specific host. + - `vars.yml`: Host-specific variables. + - `vault.yml`: Encrypted host variables. + - `playbooks/`: Directory for your Ansible playbooks. + - `site.yml`: Main playbook, orchestrating other playbooks. + - `.yml`: Playbooks tailored to different environments (e.g., staging.yml, production.yml). + - `.yml`: Playbooks for specific components (e.g., webservers.yml, databases.yml). + - `roles/`: Directory for reusable Ansible roles. + - `/`: + - `tasks/`: Contains tasks for the role. + - `main.yml`: Entry point for the role's tasks. + - `handlers/`: Contains handlers for the role. + - `main.yml`: Entry point for the role's handlers. + - `defaults/`: Contains default variable values for the role. + - `main.yml`: Default variable values. + - `vars/`: Contains role-specific variables. + - `main.yml`: Role-specific variables. + - `meta/`: Contains metadata about the role. + - `main.yml`: Role metadata (e.g., dependencies, author). + - `templates/`: Contains Jinja2 templates for the role. + - `files/`: Contains static files used by the role. + - `library/`: (Optional) Custom Ansible modules. + - `filter_plugins/`: (Optional) Custom Jinja2 filter plugins. + - `lookup_plugins/`: (Optional) Custom lookup plugins. + - `plugins/`: All of the above (library, filter, lookup, etc) should be placed in respective subfolders in this directory + - `requirements.yml`: Lists roles to be downloaded from Ansible Galaxy. + - `README.md`: Project documentation. + +### 1.2 File Naming Conventions + +- **Playbooks:** + - Use lowercase with hyphens for readability (e.g., `webservers.yml`, `database-setup.yml`). + - Name your main playbook `site.yml` for consistency. +- **Roles:** + - Use lowercase with underscores (e.g., `common_setup`, `nginx_configuration`). + - Role names should be descriptive and concise. +- **Variables Files:** + - Use `vars.yml` for general variables and `defaults.yml` for role defaults. + - Use `vault.yml` for encrypted variables. + - Group-specific variables: `.yml`. + - Host-specific variables: `.yml`. +- **Tasks and Handlers:** + - `main.yml` as the entry point for tasks and handlers within roles. +- **Templates:** + - Give descriptive names to templates, using the `.j2` extension (e.g., `nginx.conf.j2`, `application.properties.j2`). +- **Inventory:** + - Name your inventory file `hosts` or follow a consistent naming convention, such as `_hosts` (e.g., `staging_hosts`, `production_hosts`). + +### 1.3 Module Organization + +- Keep custom modules in the `library/` directory at the project root. +- Organize modules into subdirectories based on functionality (e.g., `library/custom_modules/database`, `library/custom_modules/monitoring`). +- Document each custom module with clear usage examples and return values. +- Utilize `module_utils` to create shared code used by multiple modules. +- Follow a consistent naming convention for custom modules (e.g., `my_custom_module.py`). +- All modules should contain argument spec and proper return values (changed, failed, original_message, message, etc). + +### 1.4 Component Architecture Recommendations + +- **Roles as Building Blocks:** + - Divide your infrastructure into logical components (e.g., web servers, databases, load balancers) and create roles for each. + - Keep roles single-purposed and focused on specific functionality to promote reusability. +- **Playbooks for Orchestration:** + - Use playbooks to orchestrate roles and define the desired state of your infrastructure. + - The main `site.yml` playbook should act as the entry point, calling other component-specific playbooks. +- **Variables for Configuration:** + - Externalize configuration data using variables in `group_vars/` and `host_vars/`. + - Use default variables within roles to provide sane defaults and allow for customization. +- **Handlers for Event-Driven Configuration:** + - Use handlers to manage service restarts and other event-driven tasks. + - Ensure handlers are idempotent and only triggered when necessary. + +### 1.5 Code Splitting Strategies + +- **Role Decomposition:** + - Break down complex roles into smaller, more manageable roles to improve reusability and maintainability. +- **Task Includes:** + - Use `include_tasks` to split long task lists into smaller, more focused files. +- **Dynamic Includes:** + - Employ `include_vars`, `include_role`, and `include_tasks` with dynamic variables to load configuration data or tasks based on conditions. +- **Blocks for Logical Grouping:** + - Use blocks to group related tasks, providing better error handling and readability. + +## 2. Common Patterns and Anti-patterns + +- Learn and apply common Ansible design patterns to solve infrastructure automation problems efficiently while avoiding pitfalls. + +### 2.1 Design Patterns + +- **Idempotency:** + - Design tasks to be idempotent, meaning they should produce the same result regardless of how many times they are executed. + - Use the `changed_when` and `failed_when` directives to customize task result conditions. +- **Variable Prioritization:** + - Understand Ansible's variable precedence and use it effectively to override default values. + - Variable precedence order (highest to lowest): extra vars (-e), command line arguments (-e), role vars, include vars, block vars, task vars, role defaults, inventory vars, registered vars, facts. +- **Handlers for Service Management:** + - Utilize handlers to restart services when configuration files change. Use `notify` directive in tasks to trigger handlers. +- **Template Management:** + - Use the `template` module to manage configuration files. Keep templates simple and focused on configuration logic. +- **Looping with `with_items`:** + - Use `with_items` or `loop` to iterate over lists of items, such as packages to install or users to create. +- **Conditions with `when`:** + - Use the `when` directive to conditionally execute tasks based on variables or facts. +- **Delegation with `delegate_to`:** + - Use the `delegate_to` directive to run tasks on a specific host, such as when managing a load balancer or database server. +- **Error Handling with `block` and `rescue`:** + - Wrap tasks in `block` directives and use `rescue` to handle errors gracefully. +- **Register variables for complex tasks:** + - Register variables to capture output from a task and use it in subsequent tasks. +- **Meta Tasks for Role Management:** + - Use meta tasks (e.g., `meta: clear_host_errors`, `meta: end_play`) to manage role execution and handle errors. +- **Facts for dynamic configuration:** + - Utilize facts to gather system information and dynamically configure tasks. +- **Loops for repetitive tasks:** + - Use loops to perform repetitive tasks, such as creating multiple users or installing multiple packages. Always name the loop so the end user can identify the tasks better. + +### 2.2 Recommended Approaches for Common Tasks + +- **Package Management:** + - Use the appropriate package manager module (e.g., `apt`, `yum`, `dnf`, `homebrew`) for the target system. + - Always specify the `state` (e.g., `present`, `latest`, `absent`) when managing packages. +- **File Management:** + - Use the `file` module to create, modify, or delete files and directories. + - Use the `copy` module to copy files from the control node to the target nodes. + - Use the `template` module to manage configuration files with Jinja2 templates. +- **Service Management:** + - Use the `service` or `systemd` module to manage services. + - Always specify the `state` (e.g., `started`, `stopped`, `restarted`) when managing services. + - Use handlers to restart services when configuration files change. +- **User Management:** + - Use the `user` module to create, modify, or delete users. + - Use the `group` module to manage groups. + - Use the `authorized_key` module to manage SSH keys. +- **Cron Job Management:** + - Use the `cron` module to create, modify, or delete cron jobs. +- **Firewall Management:** + - Use the `firewalld` or `ufw` module to manage firewalls. +- **SELinux Management:** + - Use the `selinux` module to manage SELinux policies. +- **Line-in-File management:** + - Use the `lineinfile` module to ensure a specific line exists in a file. + - Use the `blockinfile` module to ensure a block of lines exist in a file. + +### 2.3 Anti-patterns and Code Smells + +- **Shell and Command Modules:** + - Avoid using the `shell` and `command` modules unless absolutely necessary. + - Prefer Ansible's built-in modules for specific tasks, as they provide idempotency and better error handling. +- **Hardcoded Values:** + - Avoid hardcoding values in your playbooks or roles. + - Use variables in `group_vars/` and `host_vars/` to externalize configuration data. +- **Inconsistent Naming Conventions:** + - Follow a consistent naming convention for variables, tasks, roles, and files. + - This improves readability and maintainability. +- **Unnecessary Complexity:** + - Keep your playbooks and roles as simple as possible. + - Avoid over-engineering or introducing unnecessary complexity. +- **Lack of Idempotency:** + - Ensure your tasks are idempotent to avoid unintended side effects. + - Use the `changed_when` and `failed_when` directives to customize task result conditions. +- **Ignoring Errors:** + - Always handle errors gracefully by using `block` and `rescue` directives. + - Use the `fail` module to explicitly fail a playbook when a critical error occurs. +- **Storing Secrets in Plain Text:** + - Never store sensitive data in plain text. + - Use Ansible Vault to encrypt variables and files. +- **Lack of Documentation:** + - Always document your playbooks, roles, and custom modules. + - This improves collaboration and makes it easier to maintain your automation code. +- **Copying the same block of code:** + - Refactor and call the common tasks using `include_tasks` to improve readability and maintainability +- **Using loops when a module can handle multiple arguments:** + - Some modules can perform multiple tasks by passing a list of arguments (e.g. `yum` module), so avoid using loops as much as possible. +- **Creating complex templates:** + - Templates should be simple and contain logic that is easy to read and maintain. + - Avoid implementing complex functionality that increases maintenance cost and reduces code readability. +- **Writing unoptimized Jinja expressions:** + - Use Jinja filters for data manipulation, rather than implementing the logic using Ansible modules + +### 2.4 State Management + +- **Use Ansible to manage the desired state of your infrastructure.** Avoid manual changes outside of Ansible. +- **Leverage facts to gather system information and dynamically configure tasks.** +- **Use handlers to react to state changes and ensure services are restarted or reconfigured when necessary.** +- **Use variables to store configuration data and customize the desired state for different environments.** + +### 2.5 Error Handling Patterns + +- **Use `block` and `rescue` to handle errors gracefully.** +- **Use the `fail` module to explicitly fail a playbook when a critical error occurs.** +- **Register variables to capture the output of tasks and use the output in error handling logic.** +- **Use the `ignore_errors` directive to continue playbook execution even when a task fails (use with caution).** +- **Use the `meta: clear_host_errors` task to clear errors on a host and continue playbook execution.** +- **Implement rollback mechanisms to revert changes in case of failures.** + +## 3. Performance Considerations + +- Optimize your Ansible code to improve execution speed and resource utilization. + +### 3.1 Optimization Techniques + +- **Use SSH multiplexing:** + - Enable SSH multiplexing in your `ansible.cfg` file to reduce the overhead of establishing SSH connections. + - `pipelining = True` +- **Use ControlPersist:** + - Enable ControlPersist in your SSH configuration to keep SSH connections alive for longer periods of time. +- **Optimize Inventory:** + - Use a dynamic inventory to manage large numbers of hosts. + - Cache the inventory data to reduce the time it takes to load the inventory. +- **Minimize Fact Gathering:** + - Disable fact gathering for tasks that don't require them. + - Use the `gather_facts: false` directive in your playbooks or tasks. +- **Parallel Execution:** + - Increase the number of forks to execute tasks in parallel. + - Use the `-f` or `--forks` option when running Ansible playbooks. + - Be mindful of resource limitations and avoid overloading your control node or target hosts. +- **Avoid Loops When Possible:** + - Prefer modules that can handle lists of items instead of using loops. + - For example, use the `yum` or `apt` module with a list of packages to install instead of using a loop with the `package` module. +- **Optimize Jinja2 Templates:** + - Use Jinja2 filters to perform data manipulation instead of using Ansible modules. + - Cache the results of Jinja2 filters to avoid recomputing them repeatedly. +- **Use Async Tasks:** + - Use async tasks with poll to execute tasks in the background and reduce the time it takes to run your playbooks. +- **Use Connection Type `smart` or `persistent`:** + - These connection types are optimized for performance, especially for larger deployments. +- **Use Caching:** + - Utilize Ansible's fact caching to avoid gathering the same facts repeatedly. +- **Use strategy plugins:** + - Use plugins such as free, debug and host_pinned in your Ansible configuration file to maximize execution performance and concurrency. + +### 3.2 Memory Management + +- **Limit the number of forks:** + - Reduce the number of forks if your control node is running out of memory. +- **Use smaller inventories:** + - Split large inventories into smaller inventories to reduce memory usage. +- **Avoid loading large files into variables:** + - Use the `slurp` module to read large files into variables only when necessary. +- **Compress large files before transferring them:** + - Use the `compress` module to compress large files before transferring them to target hosts. + +### 3.3 Rendering Optimization + +- **Cache Jinja2 templates:** + - Enable Jinja2 template caching to reduce the time it takes to render templates. +- **Use filters and tests:** + - Instead of modules, use filters and tests to avoid calling Ansible tasks. +- **Limit Variable Scope:** + - Declare variables in the narrowest scope possible to minimize memory usage and improve performance. + +## 4. Security Best Practices + +- Secure your Ansible environment and protect sensitive data. + +### 4.1 Common Vulnerabilities and Prevention + +- **Plaintext Secrets:** + - *Vulnerability:* Storing passwords, API keys, and other sensitive data in plaintext in playbooks or variable files. + - *Prevention:* Use Ansible Vault to encrypt sensitive data. + - Example: + + # Encrypt a variable file + ansible-vault encrypt group_vars/all/vault.yml + + # Use the variable in a playbook + - name: Deploy application with secret key + template: + src: app.conf.j2 + dest: /etc/app/app.conf + +- **Unprotected SSH Keys:** + - *Vulnerability:* Leaving private SSH keys unprotected on the control node or target hosts. + - *Prevention:* Restrict access to the control node and use SSH key-based authentication with proper permissions. +- **Command Injection:** + - *Vulnerability:* Using user-supplied data directly in shell commands without proper sanitization. + - *Prevention:* Avoid using the `shell` and `command` modules unless absolutely necessary. + - Use Ansible's built-in modules whenever possible. + - If you must use `shell` or `command`, sanitize user input properly. +- **Privilege Escalation:** + - *Vulnerability:* Granting unnecessary privileges to Ansible users or tasks. + - *Prevention:* Use the `become` directive only when necessary. + - Grant the minimum required privileges to Ansible users. +- **Unvalidated Input:** + - *Vulnerability:* Using unvalidated input from external sources (e.g., APIs, user input) without proper sanitization. + - *Prevention:* Validate all input from external sources before using it in your playbooks or tasks. + - Use the `assert` module to validate input. +- **Insecure Communication:** + - *Vulnerability:* Using insecure communication protocols (e.g., HTTP) to transfer sensitive data. + - *Prevention:* Use HTTPS for all communication with APIs and other external services. +- **Weak SSH Keys:** + - *Vulnerability:* Using weak or compromised SSH keys. + - *Prevention:* Generate strong SSH keys with a key length of at least 2048 bits. + - Rotate SSH keys regularly. +- **Unauthorized Access:** + - *Vulnerability:* Allowing unauthorized access to the control node or target hosts. + - *Prevention:* Use strong passwords and multi-factor authentication. + - Restrict access to the control node and target hosts to authorized users only. + +### 4.2 Input Validation + +- **Validate all input from external sources before using it in your playbooks or tasks.** +- **Use the `assert` module to validate input.** +- **Use regular expressions to validate input strings.** +- **Use the `int` and `float` filters to validate numeric input.** +- **Use the `bool` filter to validate boolean input.** +- **Use the `list` and `dict` filters to validate list and dictionary input.** + +### 4.3 Authentication and Authorization + +- **Use SSH key-based authentication instead of passwords.** +- **Restrict access to the control node and target hosts to authorized users only.** +- **Use the `become` directive to escalate privileges only when necessary.** +- **Use the `sudo` module to execute tasks with elevated privileges.** +- **Use the `acl` module to manage access control lists (ACLs) on files and directories.** +- **Integrate with external authentication providers (e.g., LDAP, Active Directory) for centralized user management.** + +### 4.4 Data Protection + +- **Use Ansible Vault to encrypt sensitive data.** +- **Use HTTPS for all communication with APIs and other external services.** +- **Use the `slurp` module to read sensitive data from files into variables only when necessary.** +- **Use the `compress` module to compress sensitive data before transferring it to target hosts.** +- **Use the `hash` filter to hash sensitive data before storing it in files or databases.** +- **Implement data masking and tokenization techniques to protect sensitive data at rest and in transit.** + +### 4.5 Secure API Communication + +- **Use HTTPS for all communication with APIs.** +- **Use strong authentication mechanisms (e.g., API keys, OAuth 2.0) to protect your APIs.** +- **Validate all input from APIs before using it in your playbooks or tasks.** +- **Use the `uri` module to interact with APIs securely.** +- **Implement rate limiting and throttling to protect your APIs from abuse.** +- **Monitor your APIs for security vulnerabilities and performance issues.** + +## 5. Testing Approaches + +- Implement a comprehensive testing strategy to ensure your Ansible code is reliable and error-free. + +### 5.1 Unit Testing + +- **Unit test custom modules, filter plugins, and lookup plugins.** +- **Use a testing framework such as `pytest` to write and run unit tests.** +- **Mock external dependencies to isolate the code being tested.** +- **Write tests for all possible scenarios, including edge cases and error conditions.** +- **Use continuous integration to run unit tests automatically on every commit.** +- **Test modules for different possible input arguments and check their results.** + +### 5.2 Integration Testing + +- **Integration test your playbooks and roles to ensure they work together correctly.** +- **Use a testing framework such as `Molecule` to automate integration testing.** +- **Create a test environment that closely resembles your production environment.** +- **Test all critical functionality, including package installation, configuration management, and service management.** +- **Use continuous integration to run integration tests automatically on every commit.** +- **Use an ephemeral infrastructure using Vagrant or Docker to test the playbooks on a fresh machine.** +- **Test for idempotency by running the same playbook multiple times.** + +### 5.3 End-to-End Testing + +- **End-to-end test your entire infrastructure to ensure all components work together correctly.** +- **Use a testing framework such as `Testinfra` or `Inspec` to write and run end-to-end tests.** +- **Create a test environment that is as close as possible to your production environment.** +- **Test all critical business processes to ensure they work as expected.** +- **Use continuous integration to run end-to-end tests automatically on every commit.** + +### 5.4 Test Organization + +- **Organize your tests into a directory structure that mirrors your Ansible code.** +- **Create separate directories for unit tests, integration tests, and end-to-end tests.** +- **Use descriptive names for your test files and test functions.** +- **Document your tests with clear explanations of what they are testing.** +- **Use a consistent naming convention for your tests to improve readability and maintainability.** + +### 5.5 Mocking and Stubbing Techniques + +- **Use mocking and stubbing to isolate your code during unit testing.** +- **Mock external dependencies such as APIs, databases, and operating system commands.** +- **Use a mocking framework such as `unittest.mock` (Python) to create mocks and stubs.** +- **Write tests that verify that your code interacts with the mocked dependencies correctly.** +- **Avoid mocking Ansible modules, instead create a module that is a wrapper around it.** + +## 6. Common Pitfalls and Gotchas + +- Be aware of common mistakes and edge cases when working with Ansible. + +### 6.1 Frequent Mistakes + +- **Incorrect YAML Syntax:** + - YAML is whitespace-sensitive. Incorrect indentation or missing colons can cause syntax errors. + - Use a YAML linter to validate your syntax. +- **Variable Scope Issues:** + - Variables can be defined at different levels (e.g., playbook, role, inventory). Understanding variable precedence is crucial. + - Use the `vars_prompt` directive to prompt users for variables. +- **Incorrect Module Usage:** + - Using the wrong module for a task can lead to unexpected results or errors. + - Refer to the Ansible documentation for module usage examples and best practices. +- **Lack of Idempotency:** + - Tasks that are not idempotent can cause unintended side effects when run repeatedly. + - Use the `changed_when` and `failed_when` directives to customize task result conditions. +- **Ignoring Errors:** + - Ignoring errors can lead to cascading failures or inconsistent state. + - Use the `block` and `rescue` directives to handle errors gracefully. +- **Misunderstanding Facts:** + - Facts are variables that contain information about the target hosts. Misunderstanding or misusing facts can lead to incorrect behavior. + - Use the `ansible_facts` variable to access all available facts. +- **Over-reliance on the `shell` module:** + - Avoid the shell module unless absolutely necessary as using it hinders the playbook's idempotency. +- **Not testing playbooks:** + - Always test your playbooks before running them in production to avoid any unexpected issues. + +### 6.2 Edge Cases + +- **Handling Large Files:** + - Transferring large files can be slow and consume a lot of resources. Use the `synchronize` module or the `archive` and `unarchive` modules to optimize file transfers. +- **Managing Complex Dependencies:** + - Managing complex dependencies between tasks and roles can be challenging. Use the `block` and `rescue` directives to handle errors gracefully. +- **Working with Dynamic Inventories:** + - Dynamic inventories can be complex to set up and maintain. Use a dynamic inventory plugin or script to manage your inventory automatically. +- **Handling Network Latency:** + - Network latency can affect the performance of your playbooks. Use the `async` directive to execute tasks asynchronously. +- **Special characters in variables:** + - Avoid using special characters that can interfere with playbook's execution. + +### 6.3 Version-Specific Issues + +- **Module Compatibility:** + - Some modules may not be compatible with all versions of Ansible. + - Check the module documentation for compatibility information. +- **Deprecated Features:** + - Some features may be deprecated in newer versions of Ansible. + - Be aware of deprecated features and migrate to the recommended alternatives. +- **Behavioral Changes:** + - Some modules may have different behavior in different versions of Ansible. + - Test your playbooks with different versions of Ansible to ensure they behave as expected. + +### 6.4 Compatibility Concerns + +- **Operating System Compatibility:** + - Some playbooks and roles may only be compatible with specific operating systems. + - Check the playbook or role documentation for compatibility information. +- **Python Version Compatibility:** + - Ansible requires Python to be installed on the target hosts. Ensure that the target hosts have a compatible version of Python installed. +- **Module Dependencies:** + - Some modules may have external dependencies that need to be installed on the target hosts. + - Check the module documentation for dependency information. + +### 6.5 Debugging Strategies + +- **Use the `-v` or `--verbose` option to increase the verbosity of Ansible output.** +- **Use the `-C` or `--check` option to perform a dry run of your playbook.** +- **Use the `--diff` option to see the changes that will be made to the target hosts.** +- **Use the `debug` module to print variables and facts.** +- **Use the `assert` module to validate variables and facts.** +- **Use the `pause` module to pause playbook execution and inspect the target hosts.** +- **Use the `register` directive to capture the output of tasks and use the output in debugging logic.** +- **Check the Ansible logs on the control node and the target hosts for error messages.** + +## 7. Tooling and Environment + +- Utilize recommended tools and environment configurations to streamline your Ansible development and deployment processes. + +### 7.1 Recommended Development Tools + +- **Text Editor or IDE:** + - Use a text editor or IDE with YAML and Jinja2 syntax highlighting and auto-completion. + - Popular options include VS Code, Sublime Text, Atom, and PyCharm. + - Install Ansible-specific plugins for improved code completion and linting. +- **Ansible Lint:** + - Use `ansible-lint` to check your playbooks and roles for common errors and best practices violations. + - Configure `ansible-lint` to use a custom style guide or to enforce specific rules. +- **Molecule:** + - Use `Molecule` to test your roles in a Docker or Vagrant environment. + - Molecule provides a framework for writing and running integration tests for your roles. +- **Vagrant:** + - Use `Vagrant` to create virtual machines for testing your playbooks and roles. + - Vagrant allows you to easily create and destroy test environments. +- **Docker:** + - Use `Docker` to containerize your Ansible control node and target hosts. + - Docker provides a lightweight and portable environment for running your Ansible code. +- **Testinfra:** + - Use `Testinfra` to write and run end-to-end tests for your infrastructure. + - Testinfra allows you to verify the state of your target hosts after running your playbooks. + +### 7.2 Build Configuration + +- **Use a build tool such as `Make` or `Grunt` to automate your build process.** +- **Create a `Makefile` or `Gruntfile.js` that defines the tasks for linting, testing, and deploying your Ansible code.** +- **Use environment variables to configure your build process.** +- **Use a version control system such as `Git` to track changes to your build configuration.** +- **Keep your build configuration simple and easy to understand.** + +### 7.3 Linting and Formatting + +- **Use `ansible-lint` to check your playbooks and roles for common errors and best practices violations.** +- **Configure `ansible-lint` to use a custom style guide or to enforce specific rules.** +- **Use a YAML linter to validate your YAML syntax.** +- **Use a Jinja2 linter to validate your Jinja2 syntax.** +- **Automate linting and formatting as part of your build process.** +- **Use auto-formatting tools such as `Prettier` to automatically format your YAML and Jinja2 code.** +- **Follow a consistent naming convention for your variables, tasks, roles, and files.** + +### 7.4 Deployment Best Practices + +- **Use a deployment tool such as `Ansible Tower` or `AWX` to manage your deployments.** +- **Use a continuous integration and continuous delivery (CI/CD) pipeline to automate your deployments.** +- **Use a version control system such as `Git` to track changes to your playbooks and roles.** +- **Use a rollback mechanism to revert changes in case of failures.** +- **Use a monitoring tool such as `Nagios` or `Zabbix` to monitor your infrastructure.** +- **Use a logging tool such as `ELK Stack` or `Splunk` to collect and analyze your logs.** +- **Always test your playbooks in a staging environment before deploying them to production.** + +### 7.5 CI/CD Integration + +- **Integrate your Ansible code into your CI/CD pipeline to automate testing and deployment.** +- **Use a CI/CD tool such as `Jenkins`, `GitLab CI`, or `Travis CI` to automate your pipeline.** +- **Create a CI/CD pipeline that includes linting, testing, and deployment steps.** +- **Use environment variables to configure your CI/CD pipeline.** +- **Use a version control system such as `Git` to trigger your CI/CD pipeline on every commit.** +- **Use automated testing to verify that your infrastructure changes work as expected.** +- **Use automated deployment to deploy your infrastructure changes to your target environment.** +- **Automate configuration management:** + - Ensure consistent configurations for servers and applications. +- **Implement infrastructure as code:** + - Track and manage infrastructure in source control. +- **Automate application deployments:** + - Deploy new versions of software reliably and efficiently. +- **Orchestrate multi-tier deployments:** + - Coordinate deployments across various layers of infrastructure. \ No newline at end of file diff --git a/rules-mdc/ant-design.mdc b/rules-mdc/ant-design.mdc new file mode 100644 index 0000000..a3fef47 --- /dev/null +++ b/rules-mdc/ant-design.mdc @@ -0,0 +1,311 @@ +--- +description: This rule enforces best practices and coding standards for projects using the Ant Design (antd) UI library within React applications. It covers code organization, performance, security, testing, and common pitfalls to ensure maintainable and efficient applications. +globs: **/*.{js,jsx,ts,tsx} +--- +# Ant Design (antd) Best Practices and Coding Standards + +This document outlines the recommended best practices for developing React applications using the Ant Design (antd) UI library. Following these guidelines will lead to more maintainable, performant, and secure applications. + +## 1. Code Organization and Structure + +### 1.1. Directory Structure + +- **`src/components/`**: Contains reusable React components, including those utilizing antd components. +- **`src/pages/`**: Contains components representing different application routes or pages. +- **`src/layouts/`**: Contains layout components that provide a consistent structure across pages. +- **`src/services/`**: Contains modules for interacting with APIs and handling data fetching. +- **`src/utils/`**: Contains utility functions and helper modules. +- **`src/styles/`**: Contains global styles, theme customizations, and component-specific stylesheets. +- **`src/assets/`**: Contains static assets such as images, fonts, and icons. +- **`src/context/`**: (Optional) If using context API, store all context definition files here. + +Example: + + +my-app/ +├── src/ +│ ├── components/ +│ │ ├── Button.jsx +│ │ ├── Input.jsx +│ │ └── ... +│ ├── pages/ +│ │ ├── HomePage.jsx +│ │ ├── LoginPage.jsx +│ │ └── ... +│ ├── layouts/ +│ │ ├── MainLayout.jsx +│ │ └── ... +│ ├── services/ +│ │ ├── api.js +│ │ └── ... +│ ├── utils/ +│ │ ├── date-formatter.js +│ │ └── ... +│ ├── styles/ +│ │ ├── global.css +│ │ ├── theme.js +│ │ └── ... +│ ├── App.jsx +│ └── index.js +└── ... + + +### 1.2. File Naming Conventions + +- **Components**: Use PascalCase for component file names (e.g., `MyComponent.jsx`, `UserProfile.tsx`). +- **Styles**: Use kebab-case for style file names (e.g., `my-component.css`, `user-profile.module.scss`). +- **Modules**: Use camelCase for module file names (e.g., `api.js`, `dateFormatter.ts`). + +### 1.3. Module Organization + +- Group related components, styles, and assets within the same directory. +- Create separate modules for API interactions, data transformations, and utility functions. + +### 1.4. Component Architecture + +- **Presentational Components**: Focus on rendering UI elements and receiving data via props. +- **Container Components**: Handle data fetching, state management, and logic, passing data to presentational components. +- Use functional components with hooks whenever possible for simplicity and reusability. + +### 1.5. Code Splitting + +- Utilize React.lazy and Suspense to load components on demand, improving initial load time. +- Split routes into separate chunks to minimize the initial bundle size. +- Consider using dynamic imports for less frequently used components or modules. + +Example: + +jsx +import React, { Suspense } from 'react'; + +const MyComponent = React.lazy(() => import('./MyComponent')); + +function MyPage() { + return ( + Loading...}> + + + ); +} + + +## 2. Common Patterns and Anti-patterns + +### 2.1. Design Patterns + +- **Higher-Order Components (HOCs)**: Use for cross-cutting concerns like authentication or data fetching. Prefer hooks where possible. +- **Render Props**: An alternative to HOCs for sharing code between components. Prefer hooks where possible. +- **Compound Components**: Create reusable components with implicit state sharing (e.g., `Tabs` and `Tab` components). + +### 2.2. Recommended Approaches + +- **Form Handling**: Use `antd`'s `Form` component for managing form state, validation, and submission. +- **Data Display**: Leverage `antd`'s `Table`, `List`, and `Card` components for structured data presentation. +- **Navigation**: Use `antd`'s `Menu` and `Breadcrumb` components for creating intuitive navigation. + +### 2.3. Anti-patterns and Code Smells + +- **Direct DOM Manipulation**: Avoid directly manipulating the DOM; let React manage updates. +- **Over-reliance on `any` type**: Using `any` in TypeScript defeats the purpose of static typing. Provide explicit types. +- **Mutating Props**: Treat props as read-only and avoid modifying them directly. +- **Inline Styles**: Keep styles in CSS files or use styled-components for better organization and maintainability. Prefer CSS Modules or Styled Components for component specific styles. + +### 2.4. State Management + +- **Component State**: Use `useState` for simple, local component state. +- **Context API**: Use for sharing state across multiple components without prop drilling. +- **Redux/Zustand**: Consider for complex applications with global state and predictable state transitions. +- **MobX**: Consider for complex applications where you want to observe changes in your data and derive calculations from that data. + +### 2.5. Error Handling + +- **Try-Catch Blocks**: Use for handling synchronous errors. +- **Error Boundaries**: Use to catch errors during rendering and prevent the entire application from crashing. +- **Global Error Handling**: Implement a global error handler to log errors and provide user feedback. + +Example (Error Boundary): + +jsx +class ErrorBoundary extends React.Component { + constructor(props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error) { + return { hasError: true }; + } + + componentDidCatch(error, errorInfo) { + console.error('Caught error: ', error, errorInfo); + } + + render() { + if (this.state.hasError) { + return

Something went wrong.

; + } + + return this.props.children; + } +} + +export default ErrorBoundary; + +// Usage: + + + + + +## 3. Performance Considerations + +### 3.1. Optimization Techniques + +- **Memoization**: Use `React.memo` to prevent unnecessary re-renders of components with the same props. +- **Pure Components**: Extend `React.PureComponent` for class components to perform shallow prop comparisons. +- **Virtualization**: Use `antd`'s `Table` and `List` components with virtualization for large datasets. +- **Debouncing/Throttling**: Use for event handlers that trigger frequent updates (e.g., search input). + +### 3.2. Memory Management + +- **Avoid Memory Leaks**: Properly clean up event listeners and timers in `useEffect` hooks. +- **Release Resources**: Release unused objects and data structures to free up memory. + +### 3.3. Rendering Optimization + +- **ShouldComponentUpdate**: Implement `shouldComponentUpdate` (for class components) or use `React.memo` (for functional components) to prevent unnecessary re-renders. +- **Immutable Data**: Use immutable data structures to simplify change detection. + +### 3.4. Bundle Size Optimization + +- **Modular Imports**: Import only the necessary components from `antd` to reduce bundle size (e.g., `import { Button } from 'antd';`). Use `babel-plugin-import` for automatic modular imports. +- **Tree Shaking**: Ensure your build process supports tree shaking to remove unused code. +- **Code Splitting**: As mentioned earlier, split your code into smaller chunks to reduce the initial bundle size. + +### 3.5. Lazy Loading + +- Use `React.lazy` and `Suspense` to load components on demand. +- Implement lazy loading for images and other assets using libraries like `react-lazyload`. + +## 4. Security Best Practices + +### 4.1. Common Vulnerabilities + +- **Cross-Site Scripting (XSS)**: Prevent XSS by sanitizing user input and encoding output. +- **Cross-Site Request Forgery (CSRF)**: Protect against CSRF attacks by implementing CSRF tokens. +- **SQL Injection**: Avoid directly embedding user input in SQL queries; use parameterized queries or ORMs. + +### 4.2. Input Validation + +- **Server-Side Validation**: Always validate user input on the server-side. +- **Client-Side Validation**: Use `antd`'s `Form` component for client-side validation to provide immediate feedback to the user. +- **Sanitize Input**: Sanitize user input to remove potentially harmful characters or code. + +### 4.3. Authentication and Authorization + +- **Secure Authentication**: Use secure authentication mechanisms like JWT (JSON Web Tokens) or OAuth. +- **Role-Based Access Control (RBAC)**: Implement RBAC to control access to different parts of the application based on user roles. + +### 4.4. Data Protection + +- **Encryption**: Encrypt sensitive data both in transit and at rest. +- **Data Masking**: Mask sensitive data in the UI to prevent unauthorized access. + +### 4.5. Secure API Communication + +- **HTTPS**: Use HTTPS to encrypt communication between the client and the server. +- **API Rate Limiting**: Implement rate limiting to prevent abuse and denial-of-service attacks. + +## 5. Testing Approaches + +### 5.1. Unit Testing + +- Test individual components in isolation to ensure they function correctly. +- Use testing libraries like Jest and React Testing Library. +- Mock dependencies to isolate the component being tested. + +### 5.2. Integration Testing + +- Test the interaction between multiple components or modules. +- Use testing libraries like React Testing Library and Cypress. + +### 5.3. End-to-End Testing + +- Test the entire application from the user's perspective. +- Use testing frameworks like Cypress or Playwright. + +### 5.4. Test Organization + +- Create a `tests/` directory at the root of your project. +- Place test files alongside the components or modules they test (e.g., `MyComponent.test.jsx`). +- Use descriptive test names to clearly indicate what is being tested. + +### 5.5. Mocking and Stubbing + +- Use mocking libraries like Jest's `jest.mock()` to mock external dependencies. +- Use stubbing to replace functions or methods with predefined behavior. + +## 6. Common Pitfalls and Gotchas + +### 6.1. Frequent Mistakes + +- **Not using modular imports**: Importing the entire `antd` library can significantly increase bundle size. +- **Ignoring TypeScript errors**: Failing to address TypeScript errors can lead to runtime issues. +- **Not handling asynchronous operations correctly**: Failing to handle promises or async/await can lead to unhandled rejections and unexpected behavior. +- **Not localizing strings correctly**: Hardcoding strings instead of using `antd` i18n features. + +### 6.2. Edge Cases + +- **Handling different screen sizes and devices**: Ensuring responsive design using `antd` grid system. +- **Accessibility**: Consider accessibility when using components, making sure to include `aria` attributes. +- **Browser compatibility**: Test the app on various browsers (Chrome, Firefox, Safari, Edge, etc). + +### 6.3. Version-Specific Issues + +- **Breaking changes**: Be aware of breaking changes when upgrading `antd` versions. +- **Deprecated APIs**: Avoid using deprecated APIs and migrate to the recommended alternatives. +- **CSS class conflicts:** Potential issues with CSS specificity or conflicts with global styles. Use CSS Modules or Styled Components for more robust style isolation. + +### 6.4. Compatibility Concerns + +- **React version**: Ensure compatibility between `antd` and your React version. +- **Other UI libraries**: Avoid conflicts with other UI libraries by using consistent styling and naming conventions. + +### 6.5. Debugging + +- **Use browser developer tools**: Inspect the DOM, network requests, and console output. +- **Use React DevTools**: Inspect the component tree, props, and state. +- **Use logging and debugging statements**: Add `console.log` statements to trace the execution flow and inspect variable values. + +## 7. Tooling and Environment + +### 7.1. Recommended Tools + +- **IDE**: VS Code, WebStorm. +- **Build Tool**: Webpack, Parcel, Rollup, esbuild. +- **Testing Libraries**: Jest, React Testing Library, Cypress. +- **Linting**: ESLint, Prettier. + +### 7.2. Build Configuration + +- **Optimize for production**: Use production-specific build configurations to minimize bundle size and improve performance. +- **Configure code splitting**: Set up code splitting to load components on demand. +- **Enable tree shaking**: Ensure your build process supports tree shaking to remove unused code. + +### 7.3. Linting and Formatting + +- **ESLint**: Use ESLint with recommended React and `antd` plugins to enforce coding standards and detect potential errors. +- **Prettier**: Use Prettier to automatically format your code for consistency. +- **Stylelint:** Use Stylelint to enforce consistent style practices. + +### 7.4. Deployment + +- **Choose a hosting platform**: Netlify, Vercel, AWS, Google Cloud, Azure. +- **Configure environment variables**: Set up environment variables for API keys, database credentials, and other sensitive information. +- **Use a CDN**: Use a Content Delivery Network (CDN) to cache static assets and improve loading times. + +### 7.5. CI/CD Integration + +- **Set up a CI/CD pipeline**: Use tools like Jenkins, Travis CI, CircleCI, or GitHub Actions to automate testing, building, and deployment. +- **Automate testing**: Run unit, integration, and end-to-end tests in your CI/CD pipeline. +- **Automate deployment**: Automate the deployment process to reduce manual effort and errors. \ No newline at end of file diff --git a/rules-mdc/anyio.mdc b/rules-mdc/anyio.mdc new file mode 100644 index 0000000..2ebb326 --- /dev/null +++ b/rules-mdc/anyio.mdc @@ -0,0 +1,169 @@ +--- +description: This rule provides best practices and coding standards for developing with the AnyIO library, focusing on structured concurrency, task management, and proper use of synchronization primitives to create robust, cross-backend asynchronous applications. +globs: **/*.py +--- +# AnyIO Best Practices and Coding Standards + +This document provides comprehensive guidelines for developing with the AnyIO library, covering code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and recommended tooling. + +## Library Information: +- Name: anyio +- Tags: python, async, compatibility-layer + +## 1. Code Organization and Structure + +- **Directory Structure:** Organize your project to separate concerns clearly. + - `src/`: Contains the main application code. + - `tests/`: Contains unit, integration, and end-to-end tests. + - `examples/`: Contains example code showcasing AnyIO features. + - `docs/`: Contains project documentation (using Sphinx, for example). + - `tasks.py`: Invoke tasks for building, testing, and deploying (using Invoke). +- **File Naming Conventions:** + - Use descriptive and consistent file names. + - `my_component.py` for a component's source code. + - `my_component_test.py` for its tests. + - `conftest.py` in the `tests/` directory for test fixtures. +- **Module Organization:** + - Group related functionality into modules. + - Use packages to further structure your code. + - Employ clear and concise module-level docstrings. +- **Component Architecture:** + - Design components with clear responsibilities. + - Use interfaces or abstract base classes for decoupling. + - Consider using dependency injection to improve testability. +- **Code Splitting:** + - Break down large functions into smaller, more manageable ones. + - Decompose complex modules into simpler sub-modules. + - Consider lazy-loading modules or components to improve startup time. + +## 2. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Task Groups (Nurseries):** Use task groups (`anyio.create_task_group()`) for structured concurrency. This is the most crucial pattern in AnyIO. + - **Resource Acquisition Is Initialization (RAII):** Use `async with` statements for managing resources (e.g., sockets, files) to ensure proper cleanup, even in case of exceptions or cancellations. + - **Observer Pattern:** Use AnyIO's `Event` or `Condition` primitives to implement observer patterns for asynchronous communication. + - **Producer-Consumer Pattern:** Use `anyio.Queue` for implementing producer-consumer patterns with asynchronous tasks. +- **Recommended Approaches:** + - Use `anyio.sleep()` for non-blocking delays. + - Employ `anyio.to_thread.run_sync()` to run blocking code in a separate thread to avoid blocking the event loop. + - Utilize `anyio.Path` for asynchronous file I/O operations. +- **Anti-patterns:** + - **Blocking the Event Loop:** Avoid performing long-running synchronous operations in the main event loop. Use `anyio.to_thread.run_sync()` to offload such tasks to worker threads. + - **Ignoring Exceptions:** Always handle exceptions gracefully within tasks and task groups. Unhandled exceptions can crash your application. + - **Unstructured Concurrency:** Avoid creating tasks without a task group. This can lead to resource leaks and difficult-to-debug issues. + - **Spin Locks:** Do not use busy-waiting or spin locks in asynchronous code. Use synchronization primitives like `Lock` or `Condition` instead. +- **State Management:** + - Use immutable data structures whenever possible to avoid race conditions. + - Employ `Lock` or `Condition` objects to protect shared mutable state. + - Consider using atomic operations for simple state updates. +- **Error Handling:** + - Wrap code in `try...except` blocks to catch exceptions. + - Use `try...finally` blocks to ensure cleanup, even in case of exceptions. + - Leverage task groups to handle exceptions across multiple tasks. + - Implement retry mechanisms for transient errors. + +## 3. Performance Considerations + +- **Optimization Techniques:** + - **Asynchronous I/O:** Utilize AnyIO's asynchronous I/O functions (e.g., `anyio.Path`, `anyio.open_file`) for optimal performance when dealing with I/O-bound operations. + - **Connection Pooling:** Implement connection pooling for database connections or other network resources to reduce overhead. + - **Caching:** Cache frequently accessed data to minimize I/O operations. + - **Minimize Context Switching:** Reduce unnecessary context switching by batching operations and avoiding excessive `await` calls. +- **Memory Management:** + - Avoid creating large, unnecessary data structures. + - Use generators or iterators to process large datasets in a memory-efficient manner. + - Properly close resources (e.g., sockets, files) to release memory. + - Use the `del` statement or `weakref` to break circular references and allow garbage collection. +- **Rendering Optimization:** N/A (AnyIO is not directly involved in rendering). +- **Bundle Size Optimization:** N/A (AnyIO itself is a dependency, not a frontend bundle). +- **Lazy Loading:** + - Use lazy loading to defer the initialization of components until they are needed. + - Implement code splitting to load modules on demand. + +## 4. Security Best Practices + +- **Common Vulnerabilities:** + - **Denial of Service (DoS):** Protect against DoS attacks by limiting the number of concurrent connections or requests. + - **Injection Attacks:** Sanitize user inputs to prevent injection attacks (e.g., SQL injection, command injection). + - **Cross-Site Scripting (XSS):** N/A (AnyIO is not directly involved in front-end development). +- **Input Validation:** + - Validate all user inputs to ensure they conform to expected formats and ranges. + - Use input validation libraries to simplify the process. + - Escape or sanitize user inputs before using them in database queries or system commands. +- **Authentication and Authorization:** + - Implement authentication to verify the identity of users. + - Implement authorization to control access to resources based on user roles. + - Use secure password hashing algorithms (e.g., bcrypt, Argon2). +- **Data Protection:** + - Use encryption to protect sensitive data at rest and in transit. + - Store cryptographic keys securely. + - Comply with relevant data privacy regulations (e.g., GDPR, CCPA). +- **Secure API Communication:** + - Use HTTPS for all API communication to encrypt data in transit. + - Implement proper authentication and authorization mechanisms for API endpoints. + - Protect against Cross-Site Request Forgery (CSRF) attacks if your API is used by web applications. + +## 5. Testing Approaches + +- **Unit Testing:** + - Write unit tests for individual components to verify their functionality. + - Use mocking or stubbing to isolate components from their dependencies. + - Aim for high test coverage to ensure that all code paths are tested. +- **Integration Testing:** + - Write integration tests to verify the interaction between different components. + - Test the integration with external services (e.g., databases, APIs). +- **End-to-End Testing:** + - Write end-to-end tests to verify the entire application flow. + - Simulate real user interactions to test the application from a user's perspective. +- **Test Organization:** + - Organize tests into separate modules based on the components or features they test. + - Use a consistent naming convention for test files and functions. + - Employ test fixtures to set up and tear down test environments. +- **Mocking and Stubbing:** + - Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to replace dependencies with mock objects. + - Stub external services or APIs to simulate different scenarios. + - Verify that mock objects are called with the expected arguments. + +## 6. Common Pitfalls and Gotchas + +- **Frequent Mistakes:** + - **Not using `async with` for resources:** Forgetting to use `async with` for resources that require asynchronous cleanup can lead to resource leaks. + - **Mixing asyncio and Trio idioms:** Avoid mixing idioms from different asynchronous frameworks. Stick to AnyIO's API. + - **Incorrectly using `to_thread.run_sync`:** Ensure that the code passed to `to_thread.run_sync` is actually blocking. +- **Edge Cases:** + - **Cancellation:** Be aware of how cancellation works in AnyIO and handle it gracefully. + - **Timeouts:** Implement timeouts to prevent tasks from running indefinitely. + - **Signal Handling:** Properly handle signals (e.g., `SIGINT`, `SIGTERM`) to ensure graceful shutdown. +- **Version-Specific Issues:** + - Consult the AnyIO changelog for known issues and breaking changes in different versions. +- **Compatibility Concerns:** + - Ensure that AnyIO is compatible with the versions of asyncio or Trio you are using. + - Be aware of potential compatibility issues with other libraries that use asynchronous programming. +- **Debugging Strategies:** + - Use logging to trace the execution flow of your code. + - Employ debuggers (e.g., `pdb`, `ipdb`) to step through your code and inspect variables. + - Use asynchronous debugging tools to debug asynchronous code. + +## 7. Tooling and Environment + +- **Recommended Development Tools:** + - **Python:** Use the latest stable version of Python (3.10+ recommended). + - **Poetry/Pip:** Use Poetry or Pip for dependency management. + - **Pytest:** Use Pytest for testing. + - **Black/Ruff:** Use Black and Ruff for code formatting and linting. + - **VS Code/PyCharm:** Use VS Code or PyCharm as your IDE. +- **Build Configuration:** + - Use a `pyproject.toml` file to configure Poetry or Pip. + - Specify dependencies and build settings in the `pyproject.toml` file. + - Use a `setup.py` file for projects that need to be installed with `pip install -e .` +- **Linting and Formatting:** + - Configure Black and Ruff to enforce consistent code formatting and style. + - Use a pre-commit hook to automatically format and lint code before committing. +- **Deployment:** + - Package your application into a Docker container for easy deployment. + - Use a process manager (e.g., systemd, Supervisor) to manage your application. + - Deploy your application to a cloud platform (e.g., AWS, Azure, GCP). +- **CI/CD Integration:** + - Use a CI/CD pipeline to automate the build, test, and deployment process. + - Integrate your CI/CD pipeline with your version control system (e.g., GitHub, GitLab, Bitbucket). + - Use automated testing to ensure that code changes do not introduce regressions. \ No newline at end of file diff --git a/rules-mdc/apollo-graphql.mdc b/rules-mdc/apollo-graphql.mdc new file mode 100644 index 0000000..9e3a0a0 --- /dev/null +++ b/rules-mdc/apollo-graphql.mdc @@ -0,0 +1,217 @@ +--- +description: This rule provides comprehensive best practices and coding standards for developing with Apollo GraphQL. It covers schema design, security, performance, testing, and deployment. +globs: **/*.{js,jsx,ts,tsx,graphql} +--- +- Always use UV when installing dependencies +- Always use python 3.12 +- Always use classes instead of function + +# Apollo GraphQL Best Practices + +This document provides a comprehensive guide to best practices and coding standards for developing GraphQL APIs and applications using the Apollo ecosystem. + +## Library Information: +- Name: apollo-graphql +- Tags: web, api, graphql, javascript + +## 1. Schema Design + +- **Clarity and Consistency:** + - Use descriptive naming conventions for types, fields, and arguments (e.g., `getUserById` instead of `getUser`). + - Maintain consistency across the schema in terms of naming and structure. + - Define a clear schema that reflects your business domain and data model. + +- **Interfaces and Unions:** + - Implement interfaces and unions for shared features and common data structures. + - Use interfaces to define contracts for types that implement shared behaviors. + - Use unions when a field can return different object types that don't share a common interface. + +- **Nullability:** + - Every field is nullable by default unless explicitly marked as non-null using `!`. Carefully consider nullability for each field. + - Use non-null types (`!`) only when you can guarantee that the field will always return a value. + - Handle potential errors gracefully and return `null` for nullable fields when appropriate. + +- **Demand-Driven Schema Design:** + - Design your schema to serve client use cases and product requirements. + - Intentionally design your schema to serve client use cases and product requirements. + +- **Avoid Autogenerated Schemas:** + - Avoid autogenerating schemas, especially the fields on the root operation types + +## 2. Security + +- **Disable Introspection in Production:** + - Disable introspection in production environments to prevent unauthorized access to your schema. + - Restrict access to staging environments where introspection is enabled. + +- **Input Validation:** + - Validate all user inputs to prevent injection attacks and data corruption. + - Use custom scalars or directives to enforce validation rules on input types. + - Sanitize and escape user inputs before using them in resolvers. + +- **Authentication and Authorization:** + - Implement robust authentication and authorization mechanisms to protect your API. + - Use industry-standard protocols like OAuth 2.0 or JWT for authentication. + - Implement fine-grained authorization checks at the field level. + - Enforcing authentication and authorization in the router protects your underlying APIs from malicious operations + +- **Rate Limiting and Depth Limiting:** + - Implement rate limiting to prevent abuse and denial-of-service attacks. + - Limit query depth to prevent complex queries from overwhelming your server. + +- **Whitelisting Queries:** + - Consider whitelisting queries to restrict the operations that can be executed against your API. + +- **Obfuscate Error Details:** + - Remove verbose error details from API responses in your production graph. + - Only selectively expose error details to clients in production. + +- **Data Validation and Sanitization:** + - As a schema design best practice, you should deliberately design your schema to serve client use cases and product requirements. + +## 3. Performance Optimization + +- **Batching and Caching:** + - Utilize batching techniques (e.g., DataLoader) to reduce the number of requests to backend data sources. + - Implement caching at different levels (e.g., server-side, client-side) to improve response times. + +- **Pagination:** + - Implement pagination strategies to manage large datasets effectively. + - Use cursor-based pagination for efficient retrieval of paginated data. + +- **N+1 Problem:** + - Use tools like DataLoader to address the N+1 query problem and ensure efficient data fetching. + +- **Server-Side Batching & Caching:** + - GraphQL is designed in a way that allows you to write clean code on the server, where every field on every type has a focused single-purpose function for resolving that value. + +- **Automatic Persisted Queries (APQ):** + - Consider implementing automatic persisted queries (APQ) to optimize network usage and improve security + +## 4. Code Organization and Structure + +- **Directory Structure:** + + src/ + schema/ + types/ + *.graphql + resolvers/ + *.js + dataSources/ + *.js + utils/ + *.js + index.js // Entry point + + +- **File Naming Conventions:** + - Use PascalCase for type definitions (e.g., `UserType.graphql`). + - Use camelCase for resolver functions (e.g., `getUserById.js`). + +- **Module Organization:** + - Organize your code into reusable modules based on functionality (e.g., user management, product catalog). + - Create separate modules for schema definitions, resolvers, and data sources. + +- **Component Architecture:** + - Follow a component-based architecture for building GraphQL applications. + - Create reusable components for common UI elements and data fetching logic. + +- **Code Splitting:** + - Use code splitting to reduce the initial bundle size and improve page load times. + - Consider splitting your application into smaller chunks based on routes or features. + +## 5. Common Patterns and Anti-patterns + +- **Design Patterns:** + - **Data Source Pattern:** Decouple data fetching logic from resolvers using data sources. + - **Schema Stitching:** Combine multiple GraphQL APIs into a single, unified schema. + +- **Recommended Approaches:** + - Use a GraphQL client library (e.g., Apollo Client, Relay) for efficient data fetching and caching. + - Implement custom directives to add additional functionality to your schema. + +- **Anti-patterns:** + - **Over-fetching/Under-fetching:** Avoid returning more or less data than required by the client. + - **Chatty APIs:** Reduce the number of round trips between the client and the server. + - **God Objects:** Avoid creating large, monolithic types with too many fields. + +- **State Management:** + - Use a state management library (e.g., Redux, Zustand, Jotai) to manage client-side state. + - Consider using Apollo Client's local state management features for simple state requirements. + +- **Error Handling:** + - Use a consistent error handling mechanism across your application. + - Return informative error messages to the client. + - Log errors on the server for debugging purposes. + +## 6. Testing Approaches + +- **Unit Testing:** + - Unit test individual resolvers and data sources. + - Mock external dependencies to isolate the code under test. + +- **Integration Testing:** + - Integrate test your GraphQL API with your database and other backend services. + - Use a testing framework like Jest or Mocha for writing integration tests. + +- **End-to-End Testing:** + - Use end-to-end testing to verify the entire application flow. + - Use a testing tool like Cypress or Puppeteer for writing end-to-end tests. + +- **Test Organization:** + - Organize your tests into separate directories based on functionality. + - Use descriptive names for your test files and test cases. + +- **Mocking and Stubbing:** + - Use mocking and stubbing techniques to isolate the code under test and simulate external dependencies. + +## 7. Common Pitfalls and Gotchas + +- **N+1 Problem:** Be aware of the N+1 query problem and use DataLoader or other batching techniques to solve it. +- **Schema Evolution:** Plan for schema evolution and use techniques like adding new fields and deprecating old ones to avoid breaking changes. +- **Performance Bottlenecks:** Monitor your API for performance bottlenecks and use profiling tools to identify slow resolvers. +- **Nullability:** Ensure that non-null fields never return `null` to avoid unexpected errors. + +## 8. Tooling and Environment + +- **Development Tools:** + - Use a GraphQL IDE like GraphiQL or Apollo Studio for exploring and testing your API. + - Use code generation tools to generate types and resolvers from your schema. + +- **Build Configuration:** + - Use a build tool like Webpack or Parcel to bundle your code for production. + - Configure your build tool to optimize your code and reduce bundle size. + +- **Linting and Formatting:** + - Use a linter like ESLint or Prettier to enforce code style and prevent errors. + +- **Deployment:** + - Deploy your GraphQL API to a production environment like AWS Lambda, Google Cloud Functions, or a Node.js server. + - Use a serverless platform for easy scaling and management. + +- **CI/CD Integration:** + - Integrate your GraphQL API with a CI/CD pipeline for automated testing and deployment. + +## 9. Additional Best Practices + +- **Versioning:** While GraphQL promotes continuous evolution, consider versioning your API if you need to make breaking changes. +- **Documentation:** Provide comprehensive documentation for your GraphQL API using tools like GraphQL Docs. +- **Monitoring:** Monitor your GraphQL API for performance and errors using tools like Apollo Studio or New Relic. +- **Error Messages and Notifications:** You can also opt for union types to represent an error and to prompt suggestions to users, though this is a more expensive choice. + +## 10. Global Identification + +- Another way to organize components, besides Pagination, is by using a global identification. Originally proposed on Relay and similar to URIs, this method has become a more general good practice though it is not considered mandatory — especially if you are not planning on supporting Relay in your application + +## 11. Rate Limiting + +- Like any other web API, setting limits is a good strategy to avoid, for example, an overload of requests per minute. There are a few ways this can be done in GraphQL + +## 12. Authentication and Authorization + +- Often interchanged in their meaning, authentication is the act of determining who a user is and whether they are logged in or not. Authorization, on the other hand, is the act of determining if a user is allowed to do an action or see something. + +## 13. Safelisting with Persisted queries + +- Beyond operation limits, GraphOS enables first-party apps to register trusted operations in a persisted query list ( PQL) or safelist. \ No newline at end of file diff --git a/rules-mdc/asp-net.mdc b/rules-mdc/asp-net.mdc new file mode 100644 index 0000000..e0c65ff --- /dev/null +++ b/rules-mdc/asp-net.mdc @@ -0,0 +1,363 @@ +--- +description: This rule file provides best practices and coding standards for ASP.NET Core development, covering various aspects from code organization to security and performance optimization. +globs: **/*.cs +--- +# ASP.NET Core Best Practices and Coding Standards + +This document outlines recommended best practices and coding standards for developing ASP.NET Core applications. Following these guidelines will help ensure code clarity, maintainability, performance, and security. + +## 1. Code Organization and Structure + +### Directory Structure Best Practices: + +A well-defined directory structure is crucial for maintaining a scalable and organized ASP.NET Core project. Here's a suggested structure: + + +ProjectName/ +├── src/ +│ ├── ProjectName.Web/ +│ │ ├── Controllers/ +│ │ ├── Models/ +│ │ ├── Views/ +│ │ ├── Pages/ (for Razor Pages) +│ │ ├── wwwroot/ +│ │ ├── appsettings.json +│ │ ├── Program.cs +│ │ ├── Startup.cs +│ ├── ProjectName.Data/ +│ │ ├── Models/ +│ │ ├── Contexts/ +│ │ ├── Repositories/ +│ │ ├── Migrations/ +│ ├── ProjectName.Services/ +│ │ ├── Interfaces/ +│ │ ├── Implementations/ +│ ├── ProjectName.Models/ (if different from Data Models) +├── tests/ +│ ├── ProjectName.UnitTests/ +│ ├── ProjectName.IntegrationTests/ +├── artifacts/ +├── .editorconfig +├── .gitignore +├── ProjectName.sln + + +* **src:** Contains the source code of the application. +* **ProjectName.Web:** The main web application project. This can also be named `API` for web API projects. +* **Controllers:** Contains ASP.NET Core controllers. +* **Models:** Contains view models and other data transfer objects (DTOs) specific to the web layer. +* **Views:** Contains Razor views (.cshtml files). +* **Pages:** Contains Razor Pages (if using Razor Pages model). +* **wwwroot:** Contains static files like CSS, JavaScript, and images. +* **ProjectName.Data:** Contains data access logic, Entity Framework Core contexts, and models representing database entities. +* **Models (Data):** Defines entity models that correspond to database tables. +* **Contexts:** Contains the DbContext class. +* **Repositories:** Contains repositories for data access. +* **Migrations:** Contains Entity Framework Core migrations. +* **ProjectName.Services:** Contains business logic and application services. +* **Interfaces:** Defines interfaces for services. +* **Implementations:** Contains concrete implementations of service interfaces. +* **ProjectName.Models:** (Optional) Contains domain models that are shared across multiple layers. This layer promotes separation of concerns if your data layer models should not be exposed at the API or Web layer. +* **tests:** Contains unit and integration tests. +* **ProjectName.UnitTests:** Contains unit tests. +* **ProjectName.IntegrationTests:** Contains integration tests. +* **artifacts:** Contains build artifacts. +* **.editorconfig:** Defines code style rules. +* **.gitignore:** Specifies intentionally untracked files that Git should ignore. +* **ProjectName.sln:** The solution file. + +### File Naming Conventions: + +* **Classes:** PascalCase (e.g., `UserController`, `ProductService`) +* **Interfaces:** IPascalCase (e.g., `IProductService`, `IUserRepository`) +* **Methods:** PascalCase (e.g., `GetProduct`, `CreateUser`) +* **Variables (local):** camelCase (e.g., `productName`, `userId`) +* **Parameters:** camelCase (e.g., `productId`, `userName`) +* **Constants:** PascalCase (e.g., `DefaultPageSize`, `MaxRetries`) +* **Enums:** PascalCase (e.g., `OrderStatus`, `UserRole`) +* **Namespaces:** PascalCase, mirroring the directory structure (e.g., `ProjectName.Web.Controllers`, `ProjectName.Services.Implementations`) +* **Files:** Match the class/interface name (e.g., `UserController.cs`, `IProductService.cs`) + +### Module Organization: + +* **Feature-based Modules:** Group related functionality into modules based on features (e.g., `Authentication`, `Products`, `Orders`). Each feature can have its own folder within the `src` directory, containing its own controllers, models, services, and data access components. This enhances cohesion and reduces coupling. +* **Vertical Slices:** Organize modules around specific use cases or user stories. Each slice contains all the code necessary to implement a particular feature, from the UI to the data access layer. This promotes faster development and easier maintenance. + +### Component Architecture: + +* **Layered Architecture:** Divide the application into layers (e.g., Presentation, Application, Domain, Infrastructure) to separate concerns and promote testability. Each layer has a specific responsibility and interacts with other layers through well-defined interfaces. +* **Microservices:** For larger applications, consider breaking down the application into smaller, independent microservices. Each microservice handles a specific business capability and can be deployed and scaled independently. + +### Code Splitting Strategies: + +* **Feature-based Splitting:** Split code based on features, loading modules only when they are needed. This can improve initial load time and reduce memory consumption. +* **Route-based Splitting:** Load code only when a specific route is accessed. This is especially useful for large applications with many routes. +* **On-Demand Loading:** Load code dynamically when a user interacts with a specific component. This can improve perceived performance and reduce the initial download size. + +## 2. Common Patterns and Anti-patterns + +### Design Patterns: + +* **Dependency Injection (DI):** Use the built-in DI container to manage dependencies and promote loose coupling. +* **Repository Pattern:** Abstract data access logic behind repositories to improve testability and maintainability. Avoid exposing EF Core `IQueryable` outside of the repository. +* **Unit of Work Pattern:** Encapsulate multiple operations into a single transaction to ensure data consistency. +* **CQRS (Command Query Responsibility Segregation):** Separate read and write operations into separate models to optimize performance and scalability. +* **Mediator Pattern:** Decouple components by routing messages through a central mediator. Libraries like MediatR are excellent for this. +* **Specification Pattern:** Encapsulate complex query logic into reusable specification objects. +* **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable. + +### Recommended Approaches for Common Tasks: + +* **Configuration:** Use the `IOptions` pattern to access configuration settings in a strongly-typed manner. +* **Logging:** Use the `ILogger` interface for logging. Configure logging providers in `appsettings.json` and leverage structured logging. +* **Exception Handling:** Implement global exception handling middleware to handle unhandled exceptions and return appropriate error responses. +* **Data Validation:** Use data annotations and the `ModelState` property for validating user input. Implement custom validation attributes for complex validation rules. +* **Asynchronous Programming:** Use `async` and `await` for I/O-bound operations to avoid blocking threads. +* **HTTP Requests:** Utilize `HttpClientFactory` for creating and managing `HttpClient` instances. +* **Background Tasks:** Use hosted services or background worker services for running long-running tasks asynchronously. + +### Anti-patterns and Code Smells: + +* **Tight Coupling:** Avoid tight coupling between components. Use interfaces and dependency injection to promote loose coupling. +* **God Classes:** Avoid creating large classes with too many responsibilities. Break down large classes into smaller, more manageable classes. +* **Shotgun Surgery:** Avoid making changes to multiple classes when a single responsibility changes. This indicates poor separation of concerns. +* **Primitive Obsession:** Avoid using primitive types to represent domain concepts. Create value objects to encapsulate domain logic and validation rules. +* **Feature Envy:** Avoid classes that access the data of another class more than their own. Move the method to the class where the data resides. +* **Sync-over-Async:** Avoid using `Task.Wait()` or `Task.Result` in asynchronous methods, as this can lead to thread pool starvation. Always use `await`. +* **Ignoring Exceptions:** Avoid catching exceptions and not logging or handling them appropriately. +* **Magic Strings/Numbers:** Avoid hardcoding values directly in the code. Use constants or configuration settings instead. +* **Returning raw Entities:** Do not expose EF Core entities directly to the client. Create DTOs or View Models to represent the data that needs to be returned. + +### State Management Best Practices: + +* **Stateless Controllers:** Design controllers to be stateless. Avoid storing state in controller fields. +* **Session State:** Use session state sparingly. Session state can impact scalability. Consider using a distributed cache for session state. +* **Cookies:** Use cookies for storing small amounts of non-sensitive data. Be mindful of cookie size limits and security concerns. +* **TempData:** Use TempData for passing data between redirects. TempData is stored in session or cookies. +* **Caching:** Use caching (memory cache, distributed cache, response caching) to improve performance and reduce database load. Cache aggressively, but invalidate appropriately. + +### Error Handling Patterns: + +* **Global Exception Handling:** Implement global exception handling middleware to catch unhandled exceptions and return consistent error responses. +* **Exception Filters:** Use exception filters to handle exceptions at the controller level. +* **Try-Catch Blocks:** Use try-catch blocks for handling expected exceptions. +* **Problem Details:** Return problem details (RFC 7807) in error responses to provide more detailed information about the error. +* **Idempotency:** Design APIs to be idempotent where possible, so that retries are safe. + +## 3. Performance Considerations + +### Optimization Techniques: + +* **Asynchronous Programming:** Use `async` and `await` for I/O-bound operations. +* **Caching:** Implement caching strategies to reduce database load and improve response times. +* **Response Compression:** Enable response compression to reduce the size of HTTP responses. +* **Minification and Bundling:** Minify and bundle CSS and JavaScript files to reduce the number of HTTP requests and improve load times. +* **Image Optimization:** Optimize images to reduce their file size without sacrificing quality. +* **Database Optimization:** Optimize database queries and indexing to improve data access performance. +* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead. +* **HTTP/2:** Use HTTP/2 for improved performance and reduced latency. +* **Precompiled Views:** Precompile Razor views to improve startup time. +* **Use Span and Memory:** Utilize these types for efficient memory manipulation, reducing allocations and copies. +* **Object Pooling:** Employ object pooling for frequently created and destroyed objects to reduce garbage collection overhead. `ArrayPool` is especially effective for large arrays. +* **Optimize LINQ Usage:** Use LINQ effectively, avoiding unnecessary iterations and allocations. Utilize `AsNoTracking()` for read-only queries and be mindful of client-side evaluation. +* **Use System.Text.Json:** Prefer `System.Text.Json` over `Newtonsoft.Json` where possible, as it offers better performance and is designed for UTF-8 text. + +### Memory Management: + +* **Minimize Object Allocations:** Reduce object allocations, especially in hot code paths. Consider using object pooling and value types. +* **Avoid Large Objects:** Avoid allocating large objects (>= 85,000 bytes) as they are stored on the large object heap and can cause performance issues. +* **Dispose of Resources:** Dispose of disposable resources (e.g., database connections, file streams) properly to prevent memory leaks. +* **Garbage Collection:** Understand how the garbage collector works and avoid patterns that trigger frequent garbage collections. + +### Rendering Optimization: + +* **Partial Views:** Use partial views to reuse code and reduce code duplication. +* **View Components:** Use view components to encapsulate complex rendering logic. +* **Tag Helpers:** Use tag helpers to create reusable UI components. +* **Client-Side Rendering:** Consider using client-side rendering frameworks (e.g., React, Angular, Vue.js) for complex UI interactions. +* **Lazy Loading:** Implement lazy loading for images and other assets to improve initial load time. + +### Bundle Size Optimization: + +* **Tree Shaking:** Use tree shaking to remove unused code from JavaScript bundles. +* **Code Splitting:** Split code into smaller chunks that can be loaded on demand. +* **Compression:** Compress JavaScript and CSS files using gzip or Brotli. +* **Dead Code Elimination:** Remove unused code from the application. + +### Lazy Loading Strategies: + +* **Lazy Loading of Images:** Load images only when they are visible in the viewport. +* **Lazy Loading of Modules:** Load modules only when they are needed. +* **Lazy Loading of Data:** Load data only when it is requested. + +## 4. Security Best Practices + +### Common Vulnerabilities and Prevention: + +* **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks. +* **Cross-Site Scripting (XSS):** Sanitize user input and encode output to prevent XSS attacks. +* **Cross-Site Request Forgery (CSRF):** Use anti-forgery tokens to prevent CSRF attacks. +* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data and functionality. +* **Clickjacking:** Protect against clickjacking attacks by using the X-Frame-Options header. +* **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks. +* **Open Redirects:** Validate redirect URLs to prevent open redirect vulnerabilities. +* **Insecure Direct Object References (IDOR):** Implement proper authorization checks to prevent unauthorized access to resources. + +### Input Validation: + +* **Server-Side Validation:** Always validate user input on the server-side. +* **Whitelisting:** Use whitelisting to allow only valid characters and data formats. +* **Data Annotations:** Use data annotations to validate model properties. +* **Custom Validation:** Implement custom validation attributes for complex validation rules. +* **Sanitization:** Sanitize user input to remove potentially harmful characters. + +### Authentication and Authorization: + +* **Authentication Schemes:** Choose an appropriate authentication scheme (e.g., cookies, JWT, OAuth2) based on the application requirements. +* **Authorization Policies:** Use authorization policies to define access control rules. +* **Role-Based Access Control (RBAC):** Implement RBAC to grant users access to specific resources based on their roles. +* **Claims-Based Authorization:** Use claims-based authorization to grant users access to specific resources based on their claims. +* **Secure Password Storage:** Use strong password hashing algorithms (e.g., bcrypt, Argon2) to store passwords securely. +* **Multi-Factor Authentication (MFA):** Implement MFA to enhance security. +* **Implement OWASP Recommendations:** Follow the OWASP (Open Web Application Security Project) guidelines for secure authentication and authorization. + +### Data Protection: + +* **Encryption:** Encrypt sensitive data at rest and in transit. +* **Data Protection API:** Use the Data Protection API to protect sensitive data. +* **Key Management:** Implement proper key management practices to protect encryption keys. +* **HTTPS:** Use HTTPS to encrypt communication between the client and the server. + +### Secure API Communication: + +* **API Keys:** Use API keys to authenticate API clients. +* **OAuth 2.0:** Use OAuth 2.0 to authorize API clients. +* **JWT (JSON Web Tokens):** Use JWT for secure API authentication and authorization. +* **Rate Limiting:** Implement rate limiting to prevent API abuse. +* **Input Validation:** Implement proper input validation on the server-side to prevent injection attacks. +* **Output Encoding:** Encode API responses to prevent XSS attacks. +* **CORS (Cross-Origin Resource Sharing):** Configure CORS to allow only authorized domains to access the API. + +## 5. Testing Approaches + +### Unit Testing: + +* **Test-Driven Development (TDD):** Write unit tests before writing the code. +* **Arrange, Act, Assert (AAA):** Follow the AAA pattern in unit tests. +* **Mocking:** Use mocking frameworks (e.g., Moq, NSubstitute) to isolate the code being tested. +* **Code Coverage:** Aim for high code coverage. +* **Focus on Business Logic:** Unit test the business logic of the application. + +### Integration Testing: + +* **Test Data Access:** Test the interaction between the application and the database. +* **Test External Services:** Test the interaction between the application and external services. +* **Use a Test Database:** Use a separate test database for integration tests. +* **Seed the Database:** Seed the test database with test data before running integration tests. + +### End-to-End Testing: + +* **Test the Entire Application Flow:** Test the entire application flow from the user interface to the database. +* **Use Automation Tools:** Use automation tools (e.g., Selenium, Cypress) to automate end-to-end tests. +* **Test in a Production-Like Environment:** Test in a production-like environment to ensure that the application works as expected in production. + +### Test Organization: + +* **Separate Test Projects:** Create separate test projects for unit tests, integration tests, and end-to-end tests. +* **Organize Tests by Feature:** Organize tests by feature or module. +* **Use Naming Conventions:** Use consistent naming conventions for test classes and methods. + +### Mocking and Stubbing: + +* **Use Mocking Frameworks:** Use mocking frameworks to create mock objects and stubs. +* **Mock Dependencies:** Mock external dependencies to isolate the code being tested. +* **Verify Interactions:** Verify that the code being tested interacts with its dependencies as expected. +* **Avoid Over-Mocking:** Avoid mocking too many dependencies. Focus on mocking external dependencies and complex objects. + +## 6. Common Pitfalls and Gotchas + +### Frequent Mistakes: + +* **Incorrect Dependency Injection Configuration:** Incorrectly configuring dependency injection can lead to runtime errors. +* **Not Handling Exceptions Properly:** Not handling exceptions properly can lead to application crashes. +* **Blocking Calls:** Making blocking calls in asynchronous methods can lead to thread pool starvation. +* **Incorrect Data Validation:** Incorrect data validation can lead to security vulnerabilities and data corruption. +* **Over-Engineering:** Over-engineering the application can lead to unnecessary complexity. +* **Premature Optimization:** Optimizing the application too early can lead to wasted effort and code that is difficult to maintain. +* **Ignoring Security Best Practices:** Ignoring security best practices can lead to security vulnerabilities. +* **Not Writing Tests:** Not writing tests can lead to code that is difficult to maintain and prone to errors. +* **Leaking Database Connections:** Failing to properly dispose of database connections can exhaust connection resources and cause performance issues. +* **Using Sync over Async:** Blocking asynchronous operations can lead to thread pool starvation and performance degradation. +* **Not using HttpClientFactory correctly:** Improper disposal of `HttpClient` instances leads to socket exhaustion. Always use `HttpClientFactory`. + +### Edge Cases: + +* **Handling Null Values:** Handle null values properly to prevent null reference exceptions. +* **Handling Empty Collections:** Handle empty collections properly to prevent unexpected behavior. +* **Handling Large Data Sets:** Handle large data sets efficiently to prevent performance issues. +* **Handling Time Zones:** Handle time zones correctly to prevent data inconsistencies. + +### Version-Specific Issues: + +* **Breaking Changes:** Be aware of breaking changes between different versions of ASP.NET Core. +* **Deprecated Features:** Be aware of deprecated features and plan to migrate to newer features. +* **Performance Improvements:** Take advantage of performance improvements in newer versions of ASP.NET Core. +* **Security Patches:** Stay up-to-date with security patches to protect against vulnerabilities. + +### Compatibility Concerns: + +* **.NET Framework vs .NET Core:** Be aware of the differences between .NET Framework and .NET Core and choose the appropriate framework for the application. +* **Operating System Compatibility:** Ensure that the application is compatible with the target operating system. +* **Browser Compatibility:** Ensure that the application is compatible with the target browsers. + +### Debugging Strategies: + +* **Logging:** Use logging to track down errors and unexpected behavior. +* **Debugging Tools:** Use debugging tools (e.g., Visual Studio debugger) to step through the code and examine variables. +* **Profiling Tools:** Use profiling tools to identify performance bottlenecks. +* **Remote Debugging:** Use remote debugging to debug applications running on remote servers. +* **Diagnostic Tools:** Use diagnostic tools (e.g., Application Insights) to monitor the health and performance of the application. + +## 7. Tooling and Environment + +### Recommended Development Tools: + +* **Visual Studio:** A comprehensive IDE for developing ASP.NET Core applications. +* **Visual Studio Code:** A lightweight and versatile code editor for developing ASP.NET Core applications. +* **.NET CLI:** A command-line tool for creating, building, and running ASP.NET Core applications. +* **NuGet Package Manager:** A package manager for managing dependencies in ASP.NET Core applications. +* **Postman:** A tool for testing APIs. +* **Fiddler:** A tool for debugging HTTP traffic. + +### Build Configuration: + +* **Use a Build Server:** Use a build server (e.g., Azure DevOps, Jenkins) to automate the build process. +* **Configure Build Configurations:** Configure build configurations (e.g., Debug, Release) to optimize the application for different environments. +* **Use NuGet Package Restore:** Use NuGet package restore to automatically download dependencies during the build process. +* **Version Control:** Use version control (e.g., Git) to track changes to the code. + +### Linting and Formatting: + +* **.editorconfig:** Use an .editorconfig file to define code style rules. +* **Code Analyzers:** Use code analyzers to enforce code style rules and detect potential errors. +* **StyleCop:** Use StyleCop to enforce coding style guidelines. +* **ReSharper:** Use ReSharper to improve code quality and productivity. +* **Format on Save:** Configure the IDE to format code on save. + +### Deployment Best Practices: + +* **Choose a Hosting Environment:** Choose an appropriate hosting environment (e.g., Azure, AWS, on-premises server) based on the application requirements. +* **Configure Application Settings:** Configure application settings (e.g., connection strings, API keys) for the production environment. +* **Use HTTPS:** Use HTTPS to encrypt communication between the client and the server. +* **Enable Logging:** Enable logging to track errors and unexpected behavior in the production environment. +* **Monitor the Application:** Monitor the health and performance of the application in the production environment. +* **Use a Deployment Pipeline:** Automate the deployment process with a CI/CD pipeline. +* **Consider Containerization:** Deploy your application using containers (e.g., Docker) to ensure consistency across environments. +* **Implement Health Checks:** Use ASP.NET Core's built-in health checks endpoint to monitor the health of your application. + +### CI/CD Integration: + +* **Use a CI/CD Pipeline:** Use a CI/CD pipeline (e.g., Azure DevOps, GitHub Actions, GitLab CI) to automate the build, test, and deployment process. +* **Automate Testing:** Automate unit tests, integration tests, and end-to-end tests in the CI/CD pipeline. +* **Automate Deployment:** Automate the deployment process in the CI/CD pipeline. +* **Implement Rollbacks:** Implement rollbacks to quickly revert to a previous version of the application if there are problems with the new deployment. \ No newline at end of file diff --git a/rules-mdc/astro.mdc b/rules-mdc/astro.mdc new file mode 100644 index 0000000..68647f9 --- /dev/null +++ b/rules-mdc/astro.mdc @@ -0,0 +1,168 @@ +--- +description: Comprehensive best practices and coding standards for Astro projects, including code organization, performance considerations, security, and testing. +globs: **/*.astro +--- +- # Code Organization and Structure + - ## Directory Structure Best Practices + - `src/`: This is the heart of your Astro project. + - `components/`: Reusable UI elements. Organize components into subdirectories based on functionality or feature. + - `layouts/`: Components that define the overall page structure. Use a `BaseLayout.astro` to provide common elements like `` and `