[
  {
    "path": ".github/ISSUE_TEMPLATE/PULL_REQUEST_TEMPLATE.md",
    "content": "# Pull Request Template for FastAPI-boilerplate\n\n## Description\nPlease provide a clear and concise description of what your pull request is about.\n\n## Changes\nBriefly list the changes you've made. If applicable, also link any relevant issues or pull requests.\n\n## Tests\nDescribe the tests you added or modified to cover your changes, if applicable.\n\n## Checklist\n- [ ] I have read the [CONTRIBUTING](CONTRIBUTING.md) document.\n- [ ] My code follows the code style of this project.\n- [ ] I have added necessary documentation (if appropriate).\n- [ ] I have added tests that cover my changes (if applicable).\n- [ ] All new and existing tests passed.\n\n## Additional Notes\nInclude any additional information that you think is important for reviewers to know.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/fastapi-boilerplate-feature-request.md",
    "content": "---\nname: FastAPI-boilerplate Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/fastapi-boilerplate-issue.md",
    "content": "---\nname: FastAPI-boilerplate Issue\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug or question**\nA clear and concise description of what the bug or question is.\n\n**To Reproduce**\nPlease provide a self-contained, minimal, and reproducible example of your use case\n```python\n# Your code here\n```\n\n**Description**\nDescribe the problem, question, or error you are facing. Include both the expected output for your input and the actual output you're observing.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\npoetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\npoetry.lock\nsrc/poetry.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n\n# Macos\n.DS_Store\n\n.ruff_cache"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "default_language_version:\n  python: python3.11\n\nrepos:\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.1.0\n    hooks:\n      - id: end-of-file-fixer\n      - id: trailing-whitespace\n      - id: check-yaml\n      - id: check-docstring-first\n      - id: check-executables-have-shebangs\n      - id: check-case-conflict\n      - id: check-added-large-files\n        exclude: ^(.*\\/dummy.*|.*\\.json)$\n        args: [\"--maxkb=750\", \"--enforce-all\"]\n      - id: detect-private-key\n      - id: check-merge-conflict\n\n  - repo: https://github.com/asottile/pyupgrade\n    rev: v3.15.0\n    hooks:\n      - id: pyupgrade\n        args: [--py310-plus]\n        name: Upgrade code to Python 3.10+\n\n  - repo: https://github.com/myint/docformatter\n    rev: v1.7.5\n    hooks:\n      - id: docformatter\n        args: [--in-place, --wrap-summaries=115, --wrap-descriptions=120]\n\n  - repo: https://github.com/asottile/yesqa\n    rev: v1.5.0\n    hooks:\n      - id: yesqa\n        name: Unused noqa\n\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.1.9\n    hooks:\n      - id: ruff\n        args: [ --fix ]\n      - id: ruff-format\n\n  - repo: https://github.com/asottile/blacken-docs\n    rev: 1.16.0\n    hooks:\n      - id: blacken-docs\n        args: [--line-length=120]\n        additional_dependencies: [black==22.1.0]\n\n  - repo: https://github.com/executablebooks/mdformat\n    rev: 0.7.17\n    hooks:\n      - id: mdformat\n        additional_dependencies:\n          - mdformat-gfm\n          - mdformat_frontmatter\n        exclude: CHANGELOG.md\n\n  - repo: local\n    hooks:\n    - id: unit_test\n      name: Unit test\n      language: system\n      entry: poetry run pytest\n      pass_filenames: false\n      always_run: true\n      types: [python]\n      stages: [manual]\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\nigor.magalhaes.r@gmail.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to FastAPI-boilerplate\n\nThank you for your interest in contributing to FastAPI-boilerplate! This guide is meant to make it easy for you to get started.\nContributions are appreciated, even if just reporting bugs, documenting stuff or answering questions. To contribute with a feature:\n\n## Setting Up Your Development Environment\n\n### Cloning the Repository\nStart by forking and cloning the FastAPI-boilerplate repository:\n\n1. **Fork the Repository**: Begin by forking the project repository. You can do this by visiting https://github.com/igormagalhaesr/FastAPI-boilerplate and clicking the \"Fork\" button.\n1. **Create a Feature Branch**: Once you've forked the repo, create a branch for your feature by running `git checkout -b feature/fooBar`.\n1. **Testing Changes**: Ensure that your changes do not break existing functionality by running tests. In the root folder, execute poetry run `python -m pytest` to run the tests.\n\n### Using Poetry for Dependency Management\nFastAPI-boilerplate uses Poetry for managing dependencies. If you don't have Poetry installed, follow the instructions on the [official Poetry website](https://python-poetry.org/docs/).\n\nOnce Poetry is installed, navigate to the cloned repository and install the dependencies:\n```sh\ncd FastAPI-boilerplate\npoetry install\n```\n\n### Activating the Virtual Environment\nPoetry creates a virtual environment for your project. Activate it using:\n\n```sh\npoetry shell\n```\n\n## Making Contributions\n\n### Coding Standards\n- Follow PEP 8 guidelines.\n- Write meaningful tests for new features or bug fixes.\n\n### Testing with Pytest\nFastAPI-boilerplate uses pytest for testing. Run tests using:\n```sh\npoetry run pytest\n```\n\n### Linting\nUse mypy for type checking:\n```sh\nmypy src\n```\n\nUse ruff for style:\n```sh\nruff check --fix\nruff format\n```\n\nEnsure your code passes linting before submitting.\n\n### Using pre-commit for Better Code Quality\n\nIt helps in identifying simple issues before submission to code review. By running automated checks, pre-commit can ensure code quality and consistency.\n\n1. **Install Pre-commit**:\n   - **Installation**: Install pre-commit in your development environment. Use the command `pip install pre-commit`.\n   - **Setting Up Hooks**: After installing pre-commit, set up the hooks with `pre-commit install`. This command will install hooks into your .git/ directory which will automatically check your commits for issues.\n1. **Committing Your Changes**:\n   After making your changes, use `git commit -am 'Add some fooBar'` to commit them. Pre-commit will run automatically on your files when you commit, ensuring that they meet the required standards.\n   Note: If pre-commit identifies issues, it may block your commit. Fix these issues and commit again. This ensures that all contributions are of high quality.\n1. **Pushing Changes and Creating Pull Request**:\n   Push your changes to the branch using `git push origin feature/fooBar`.\n   Visit your fork on GitHub and create a new Pull Request to the main repository.\n\n### Additional Notes\n\n**Stay Updated**: Keep your fork updated with the main repository to avoid merge conflicts. Regularly fetch and merge changes from the upstream repository.\n**Adhere to Project Conventions**: Follow the coding style, conventions, and commit message guidelines of the project.\n**Open Communication**: Feel free to ask questions or discuss your ideas by opening an issue or in discussions.\n\n## Submitting Your Contributions\n\n### Creating a Pull Request\nAfter making your changes:\n\n- Push your changes to your fork.\n- Open a pull request with a clear description of your changes.\n- Update the README.md if necessary.\n\n\n### Code Reviews\n- Address any feedback from code reviews.\n- Once approved, your contributions will be merged into the main branch.\n\n## Code of Conduct\nPlease adhere to our [Code of Conduct](CODE_OF_CONDUCT.md) to maintain a welcoming and inclusive environment.\n\nThank you for contributing to FastAPI-boilerplate🚀\n"
  },
  {
    "path": "Dockerfile",
    "content": "# --------- requirements ---------\n\nFROM python:3.11 as requirements-stage\n\nWORKDIR /tmp\n\nRUN pip install poetry poetry-plugin-export\n\nCOPY ./pyproject.toml ./poetry.lock* /tmp/\n\nRUN poetry export -f requirements.txt --output requirements.txt --without-hashes\n\n\n# --------- final image build ---------\nFROM python:3.11\n\nWORKDIR /code\n\nCOPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt\n\nRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt\n\nCOPY ./src/app /code/app\n\n# -------- replace with comment to run with gunicorn --------\nCMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\", \"--reload\"]\n# CMD [\"gunicorn\", \"app.main:app\", \"-w\", \"4\", \"-k\", \"uvicorn.workers.UvicornWorker\". \"-b\", \"0.0.0.0:8000\"]\n"
  },
  {
    "path": "LICENSE.md",
    "content": "MIT License\n\nCopyright (c) 2023 Igor Magalhães\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\"> Fast FastAPI boilerplate (SQLmodel version)</h1>\n<p align=\"center\" markdown=1>\n  <i>Yet another template to speed your FastAPI development up. This time, using SQLModel.</i>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://github.com/igormagalhaesr/SQLModel-boilerplate\">\n    <img src=\"https://raw.githubusercontent.com/igorbenav/docs-images/main/sqlmodelboilerplate.png?raw=true\" alt=\"Purple Rocket with FastAPI Logo as its window. There is a word FAST written\" width=\"35%\" height=\"auto\">\n  </a>\n</p>\n\n<p align=\"center\">\n  <a href=\"\">\n      <img src=\"https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white\" alt=\"Python\">\n  </a>\n  <a href=\"https://fastapi.tiangolo.com\">\n      <img src=\"https://img.shields.io/badge/FastAPI-005571?style=for-the-badge&logo=fastapi\" alt=\"FastAPI\">\n  </a>\n  <a href=\"https://www.postgresql.org\">\n      <img src=\"https://img.shields.io/badge/PostgreSQL-316192?style=for-the-badge&logo=postgresql&logoColor=white\" alt=\"PostgreSQL\">\n  </a>\n  <a href=\"https://redis.io\">\n      <img src=\"https://img.shields.io/badge/Redis-DC382D?logo=redis&logoColor=fff&style=for-the-badge\" alt=\"Redis\">\n  </a>\n  <a href=\"https://docs.docker.com/compose/\">\n      <img src=\"https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=fff&style=for-the-badge\" alt=\"Docker\">\n  </a>\n  <a href=\"https://nginx.org/en/\">\n      <img src=\"https://img.shields.io/badge/NGINX-009639?logo=nginx&logoColor=fff&style=for-the-badge\" alt=NGINX>\n  </a>\n</p>\n\n## 0. About\n\n**FastAPI boilerplate** creates an extendable async API using FastAPI, SQLModel and PostgreSQL:\n\n- [`FastAPI`](https://fastapi.tiangolo.com): modern Python web framework for building APIs\n- [`SQLModel`](https://sqlmodel.tiangolo.com): SQL databases in Python, designed for simplicity, compatibility, and robustness.\n- [`PostgreSQL`](https://www.postgresql.org): The World's Most Advanced Open Source Relational Database\n- [`Redis`](https://redis.io): Source Available, in-memory data store used by millions as a cache, message broker and more.\n- [`ARQ`](https://arq-docs.helpmanual.io) Job queues and RPC in python with asyncio and redis.\n- [`Docker Compose`](https://docs.docker.com/compose/) With a single command, create and start all the services from your configuration.\n- [`NGINX`](https://nginx.org/en/) High-performance low resource consumption web server used for Reverse Proxy and Load Balancing.\n\n<br>\n<a href=\"https://fastro.ai\">\n  <img width=\"1394\" height=\"403\" alt=\"fastroai-banner\" src=\"https://github.com/user-attachments/assets/53db61f8-2fa7-46a2-ae91-8d131e0166d4\" />\n</a>\n<br>\n\n## 1. Features\n\n- ⚡️ Fully async\n- 🚀 SQLModel with Pydantic V2 and SQLAlchemy 2.0 support\n- 🔐 User authentication with JWT\n- 🍪 Cookie based refresh token\n- 🏬 Easy redis caching\n- 👜 Easy client-side caching\n- 🚦 ARQ integration for task queue\n- ⚙️ Efficient and robust queries with <a href=\"https://github.com/igorbenav/fastcrud\">fastcrud</a>\n- ⎘ Out of the box offset and cursor pagination support with <a href=\"https://github.com/igorbenav/fastcrud\">fastcrud</a>\n- 🛑 Rate Limiter dependency\n- 👮 FastAPI docs behind authentication and hidden based on the environment\n- 🦾 Easily extendable\n- 🤸‍♂️ Flexible\n- 🚚 Easy running with docker compose\n- ⚖️ NGINX Reverse Proxy and Load Balancing\n\n## 2. Contents\n\n0. [About](#0-about)\n1. [Features](#1-features)\n1. [Contents](#2-contents)\n1. [Prerequisites](#3-prerequisites)\n   1. [Environment Variables (.env)](#31-environment-variables-env)\n   1. [Docker Compose](#32-docker-compose-preferred)\n   1. [From Scratch](#33-from-scratch)\n1. [Usage](#4-usage)\n   1. [Docker Compose](#41-docker-compose)\n   1. [From Scratch](#42-from-scratch)\n      1. [Packages](#421-packages)\n      1. [Running PostgreSQL With Docker](#422-running-postgresql-with-docker)\n      1. [Running Redis with Docker](#423-running-redis-with-docker)\n      1. [Running the API](#424-running-the-api)\n   1. [Creating the first superuser](#43-creating-the-first-superuser)\n   1. [Database Migrations](#44-database-migrations)\n1. [Extending](#5-extending)\n   1. [Project Structure](#51-project-structure)\n   1. [Database Model](#52-database-model)\n   1. [DB Models](#53-db-models)\n   1. [Validation Models](#54-validation-models)\n   1. [Alembic Migrations](#55-alembic-migrations)\n   1. [CRUD](#56-crud)\n   1. [Routes](#57-routes)\n      1. [Paginated Responses](#571-paginated-responses)\n      1. [HTTP Exceptions](#572-http-exceptions)\n   1. [Caching](#58-caching)\n   1. [More Advanced Caching](#59-more-advanced-caching)\n   1. [ARQ Job Queues](#510-arq-job-queues)\n   1. [Rate Limiting](#511-rate-limiting)\n   1. [JWT Authentication](#512-jwt-authentication)\n   1. [Running](#513-running)\n   1. [Create Application](#514-create-application)\n   2. [Opting Out of Services](#515-opting-out-of-services)\n1. [Running in Production](#6-running-in-production)\n   1. [Uvicorn Workers with Gunicorn](#61-uvicorn-workers-with-gunicorn)\n   1. [Running With NGINX](#62-running-with-nginx)\n      1. [One Server](#621-one-server)\n      1. [Multiple Servers](#622-multiple-servers)\n1. [Testing](#7-testing)\n1. [Contributing](#8-contributing)\n1. [References](#9-references)\n1. [License](#10-license)\n1. [Contact](#11-contact)\n\n______________________________________________________________________\n\n## 3. Prerequisites\n\n### 3.0 Start\n\nStart by using the template, and naming the repository to what you want.\n\n<p align=\"left\">\n    <img src=\"https://user-images.githubusercontent.com/43156212/277866726-975d1c98-b1c9-4c8e-b4bd-001c8a5728cb.png\" alt=\"clicking use this template button, then create a new repository option\" width=\"35%\" height=\"auto\">\n</p>\n\nThen clone your created repository (I'm using the base for the example)\n\n```sh\ngit clone https://github.com/igormagalhaesr/SQLModel-boilerplate\n```\n\n> \\[!TIP\\]\n> If you are in a hurry, you may use one of the following templates (containing a `.env`, `docker-compose.yml` and `Dockerfile`):\n\n- [Running locally with uvicorn](https://gist.github.com/igorbenav/48ad745120c3f77817e094f3a609111a)\n- [Runing in staging with gunicorn managing uvicorn workers](https://gist.github.com/igorbenav/d0518d4f6bdfb426d4036090f74905ee)\n- [Running in production with NGINX](https://gist.github.com/igorbenav/232c3b73339d6ca74e2bf179a5ef48a1)\n\n> \\[!WARNING\\]\n> Do not forget to place `docker-compose.yml` and `Dockerfile` in the `root` folder, while `.env` should be in the `src` folder.\n\n### 3.1 Environment Variables (.env)\n\nThen create a `.env` file inside `src` directory:\n\n```sh\ntouch .env\n```\n\nInside of `.env`, create the following app settings variables:\n\n```\n# ------------- app settings -------------\nAPP_NAME=\"Your app name here\"\nAPP_DESCRIPTION=\"Your app description here\"\nAPP_VERSION=\"0.1\"\nCONTACT_NAME=\"Your name\"\nCONTACT_EMAIL=\"Your email\"\nLICENSE_NAME=\"The license you picked\"\n```\n\nFor the database ([`if you don't have a database yet, click here`](#422-running-postgresql-with-docker)), create:\n\n```\n# ------------- database -------------\nPOSTGRES_USER=\"your_postgres_user\"\nPOSTGRES_PASSWORD=\"your_password\"\nPOSTGRES_SERVER=\"your_server\" # default \"localhost\", if using docker compose you should use \"db\"\nPOSTGRES_PORT=5432 # default \"5432\", if using docker compose you should use \"5432\"\nPOSTGRES_DB=\"your_db\"\n```\n\nFor database administration using PGAdmin create the following variables in the .env file\n\n```\n# ------------- pgadmin -------------\nPGADMIN_DEFAULT_EMAIL=\"your_email_address\"\nPGADMIN_DEFAULT_PASSWORD=\"your_password\"\nPGADMIN_LISTEN_PORT=80\n```\n\nTo connect to the database, log into the PGAdmin console with the values specified in `PGADMIN_DEFAULT_EMAIL` and `PGADMIN_DEFAULT_PASSWORD`.\n\nOnce in the main PGAdmin screen, click Add Server:\n\n![pgadmin-connect](https://github.com/igorbenav/docs-images/blob/main/289698727-e15693b6-fae9-4ec6-a597-e70ab6f44133-3.png?raw=true)\n\n1. Hostname/address is `db` (if using containers)\n1. Is the value you specified in `POSTGRES_PORT`\n1. Leave this value as `postgres`\n1. is the value you specified in `POSTGRES_USER`\n1. Is the value you specified in `POSTGRES_PASSWORD`\n\nFor crypt:\nStart by running\n\n```sh\nopenssl rand -hex 32\n```\n\nAnd then create in `.env`:\n\n```\n# ------------- crypt -------------\nSECRET_KEY= # result of openssl rand -hex 32\nALGORITHM= # pick an algorithm, default HS256\nACCESS_TOKEN_EXPIRE_MINUTES= # minutes until token expires, default 30\nREFRESH_TOKEN_EXPIRE_DAYS= # days until token expires, default 7\n```\n\nThen for the first admin user:\n\n```\n# ------------- admin -------------\nADMIN_NAME=\"your_name\"\nADMIN_EMAIL=\"your_email\"\nADMIN_USERNAME=\"your_username\"\nADMIN_PASSWORD=\"your_password\"\n```\n\nFor redis caching:\n\n```\n# ------------- redis cache-------------\nREDIS_CACHE_HOST=\"your_host\" # default \"localhost\", if using docker compose you should use \"redis\"\nREDIS_CACHE_PORT=6379 # default \"6379\", if using docker compose you should use \"6379\"\n```\n\nAnd for client-side caching:\n\n```\n# ------------- redis client-side cache -------------\nCLIENT_CACHE_MAX_AGE=30 # default \"30\"\n```\n\nFor ARQ Job Queues:\n\n```\n# ------------- redis queue -------------\nREDIS_QUEUE_HOST=\"your_host\" # default \"localhost\", if using docker compose you should use \"redis\"\nREDIS_QUEUE_PORT=6379 # default \"6379\", if using docker compose you should use \"6379\"\n```\n\n> \\[!WARNING\\]\n> You may use the same redis for both caching and queue while developing, but the recommendation is using two separate containers for production.\n\nTo create the first tier:\n\n```\n# ------------- first tier -------------\nTIER_NAME=\"free\"\n```\n\nFor the rate limiter:\n\n```\n# ------------- redis rate limit -------------\nREDIS_RATE_LIMIT_HOST=\"localhost\"   # default=\"localhost\", if using docker compose you should use \"redis\"\nREDIS_RATE_LIMIT_PORT=6379          # default=6379, if using docker compose you should use \"6379\"\n\n\n# ------------- default rate limit settings -------------\nDEFAULT_RATE_LIMIT_LIMIT=10         # default=10\nDEFAULT_RATE_LIMIT_PERIOD=3600      # default=3600\n```\n\nFor tests (optional to run):\n\n```\n# ------------- test -------------\nTEST_NAME=\"Tester User\"\nTEST_EMAIL=\"test@tester.com\"\nTEST_USERNAME=\"testeruser\"\nTEST_PASSWORD=\"Str1ng$t\"\n```\n\nAnd Finally the environment:\n\n```\n# ------------- environment -------------\nENVIRONMENT=\"local\"\n```\n\n`ENVIRONMENT` can be one of `local`, `staging` and `production`, defaults to local, and changes the behavior of api `docs` endpoints:\n\n- **local:** `/docs`, `/redoc` and `/openapi.json` available\n- **staging:** `/docs`, `/redoc` and `/openapi.json` available for superusers\n- **production:** `/docs`, `/redoc` and `/openapi.json` not available\n\n### 3.2 Docker Compose (preferred)\n\nTo do it using docker compose, ensure you have docker and docker compose installed, then:\nWhile in the base project directory (FastAPI-boilerplate here), run:\n\n```sh\ndocker compose up\n```\n\nYou should have a `web` container, `postgres` container, a `worker` container and a `redis` container running.\nThen head to `http://127.0.0.1:8000/docs`.\n\n### 3.3 From Scratch\n\nInstall poetry:\n\n```sh\npip install poetry\n```\n\n## 4. Usage\n\n### 4.1 Docker Compose\n\nIf you used docker compose, your setup is done. You just need to ensure that when you run (while in the base folder):\n\n```sh\ndocker compose up\n```\n\nYou get the following outputs (in addition to many other outputs):\n\n```sh\nfastapi-boilerplate-worker-1  | ... redis_version=x.x.x mem_usage=999K clients_connected=1 db_keys=0\n...\nfastapi-boilerplate-db-1      | ... [1] LOG:  database system is ready to accept connections\n...\nfastapi-boilerplate-web-1     | INFO:     Application startup complete.\n```\n\nSo you may skip to [5. Extending](#5-extending).\n\n### 4.2 From Scratch\n\n#### 4.2.1. Packages\n\nIn the `root` directory (`FastAPI-boilerplate` if you didn't change anything), run to install required packages:\n\n```sh\npoetry install\n```\n\nEnsuring it ran without any problem.\n\n#### 4.2.2. Running PostgreSQL With Docker\n\n> \\[!NOTE\\]\n> If you already have a PostgreSQL running, you may skip this step.\n\nInstall docker if you don't have it yet, then run:\n\n```sh\ndocker pull postgres\n```\n\nAnd pick the port, name, user and password, replacing the fields:\n\n```sh\ndocker run -d \\\n    -p {PORT}:{PORT} \\\n    --name {NAME} \\\n    -e POSTGRES_PASSWORD={PASSWORD} \\\n    -e POSTGRES_USER={USER} \\\n    postgres\n```\n\nSuch as:\n\n```sh\ndocker run -d \\\n    -p 5432:5432 \\\n    --name postgres \\\n    -e POSTGRES_PASSWORD=1234 \\\n    -e POSTGRES_USER=postgres \\\n    postgres\n```\n\n#### 4.2.3. Running redis With Docker\n\n> \\[!NOTE\\]\n> If you already have a redis running, you may skip this step.\n\nInstall docker if you don't have it yet, then run:\n\n```sh\ndocker pull redis:alpine\n```\n\nAnd pick the name and port, replacing the fields:\n\n```sh\ndocker run -d \\\n  --name {NAME}  \\\n  -p {PORT}:{PORT} \\\nredis:alpine\n```\n\nSuch as\n\n```sh\ndocker run -d \\\n  --name redis  \\\n  -p 6379:6379 \\\nredis:alpine\n```\n\n#### 4.2.4. Running the API\n\nWhile in the `root` folder, run to start the application with uvicorn server:\n\n```sh\npoetry run uvicorn src.app.main:app --reload\n```\n\n> \\[!TIP\\]\n> The --reload flag enables auto-reload once you change (and save) something in the project\n\n### 4.3 Creating the first superuser\n\n#### 4.3.1 Docker Compose\n\n> \\[!WARNING\\]\n> Make sure DB and tables are created before running create_superuser (db should be running and the api should run at least once before)\n\nIf you are using docker compose, you should uncomment this part of the docker-compose.yml:\n\n```\n  #-------- uncomment to create first superuser --------\n  # create_superuser:\n  #   build:\n  #     context: .\n  #     dockerfile: Dockerfile\n  #   env_file:\n  #     - ./src/.env\n  #   depends_on:\n  #     - db\n  #   command: python -m src.scripts.create_first_superuser\n  #   volumes:\n  #     - ./src:/code/src\n```\n\nGetting:\n\n```\n  #-------- uncomment to create first superuser --------\n  create_superuser:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    env_file:\n      - ./src/.env\n    depends_on:\n      - db\n    command: python -m src.scripts.create_first_superuser\n    volumes:\n      - ./src:/code/src\n```\n\nWhile in the base project folder run to start the services:\n\n```sh\ndocker-compose up -d\n```\n\nIt will automatically run the create_superuser script as well, but if you want to rerun eventually:\n\n```sh\ndocker-compose run --rm create_superuser\n```\n\nto stop the create_superuser service:\n\n```sh\ndocker-compose stop create_superuser\n```\n\n#### 4.3.2 From Scratch\n\nWhile in the `root` folder, run (after you started the application at least once to create the tables):\n\n```sh\npoetry run python -m src.scripts.create_first_superuser\n```\n\n### 4.3.3 Creating the first tier\n\n> \\[!WARNING\\]\n> Make sure DB and tables are created before running create_tier (db should be running and the api should run at least once before)\n\nTo create the first tier it's similar, you just replace `create_superuser` for `create_tier` service or `create_first_superuser` to `create_first_tier` for scripts. If using `docker compose`, do not forget to uncomment the `create_tier` service in `docker-compose.yml`.\n\n### 4.4 Database Migrations\n\n> \\[!WARNING\\]\n> To create the tables if you did not create the endpoints, ensure that you import the models in src/app/models/__init__.py. This step is crucial to create the new tables.\n\nIf you are using the db in docker, you need to change this in `docker-compose.yml` to run migrations:\n\n```sh\n  db:\n    image: postgres:13\n    env_file:\n      - ./src/.env\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    # -------- replace with comment to run migrations with docker --------\n    expose:\n      - \"5432\"\n    # ports:\n    #  - 5432:5432\n```\n\nGetting:\n\n```sh\n  db:\n    ...\n    # expose:\n    #  - \"5432\"\n    ports:\n      - 5432:5432\n```\n\nWhile in the `src` folder, run Alembic migrations:\n\n```sh\npoetry run alembic revision --autogenerate\n```\n\nAnd to apply the migration\n\n```sh\npoetry run alembic upgrade head\n```\n\n> [!NOTE]\n> If you do not have poetry, you may run it without poetry after running `pip install alembic`\n\n## 5. Extending\n\n### 5.1 Project Structure\n\nFirst, you may want to take a look at the project structure and understand what each file is doing.\n\n```sh\n.\n├── Dockerfile                        # Dockerfile for building the application container.\n├── docker-compose.yml                # Docker Compose file for defining multi-container applications.\n├── pyproject.toml                    # Poetry configuration file with project metadata and dependencies.\n├── README.md                         # Project README providing information and instructions.\n├── LICENSE.md                        # License file for the project.\n│\n├── tests                             # Unit and integration tests for the application.\n│   ├── __init__.py\n│   ├── conftest.py                   # Configuration and fixtures for pytest.\n│   ├── helper.py                     # Helper functions for tests.\n│   └── test_user.py                  # Test cases for user-related functionality.\n│\n└── src                               # Source code directory.\n    ├── __init__.py                   # Initialization file for the src package.\n    ├── alembic.ini                   # Configuration file for Alembic (database migration tool).\n    ├── poetry.lock                   # Poetry lock file specifying exact versions of dependencies.\n    │\n    ├── app                           # Main application directory.\n    │   ├── __init__.py               # Initialization file for the app package.\n    │   ├── main.py                   # Main entry point of the FastAPI application.\n    │   │\n    │   │\n    │   ├── api                       # Folder containing API-related logic.\n    │   │   ├── __init__.py\n    │   │   ├── dependencies.py       # Defines dependencies for use across API endpoints.\n    │   │   │\n    │   │   └── v1                    # Version 1 of the API.\n    │   │       ├── __init__.py\n    │   │       ├── login.py          # API route for user login.\n    │   │       ├── logout.py         # API route for user logout.\n    │   │       ├── posts.py          # API routes for post operations.\n    │   │       ├── rate_limits.py    # API routes for rate limiting functionalities.\n    │   │       ├── tasks.py          # API routes for task management.\n    │   │       ├── tiers.py          # API routes for user tier functionalities.\n    │   │       └── users.py          # API routes for user management.\n    │   │\n    │   ├── core                      # Core utilities and configurations for the application.\n    │   │   ├── __init__.py\n    │   │   ├── config.py             # Configuration settings for the application.\n    │   │   ├── logger.py             # Configuration for application logging.\n    │   │   ├── schemas.py            # Pydantic schemas for data validation.\n    │   │   ├── security.py           # Security utilities, such as password hashing.\n    │   │   ├── setup.py              # Setup file for the FastAPI app instance.\n    │   │   │\n    │   │   ├── db                    # Core Database related modules.\n    │   │   │   ├── __init__.py\n    │   │   │   ├── crud_token_blacklist.py  # CRUD operations for token blacklist.\n    │   │   │   ├── database.py       # Database connectivity and session management.\n    │   │   │   ├── models.py         # Core Database models.\n    │   │   │   └── token_blacklist.py  # Model for token blacklist functionality.\n    │   │   │\n    │   │   ├── exceptions            # Custom exception classes.\n    │   │   │   ├── __init__.py\n    │   │   │   ├── cache_exceptions.py   # Exceptions related to cache operations.\n    │   │   │   └── http_exceptions.py    # HTTP-related exceptions.\n    │   │   │\n    │   │   ├── utils                 # Utility functions and helpers.\n    │   │   │   ├── __init__.py\n    │   │   │   ├── cache.py          # Cache-related utilities.\n    │   │   │   ├── queue.py          # Utilities for task queue management.\n    │   │   │   └── rate_limit.py     # Rate limiting utilities.\n    │   │   │\n    │   │   └── worker                # Worker script for background tasks.\n    │   │       ├── __init__.py\n    │   │       ├── settings.py       # Worker configuration and settings.\n    │   │       └── functions.py      # Async task definitions and management.\n    │   │\n    │   ├── crud                      # CRUD operations for the application.\n    │   │   ├── __init__.py\n    │   │   ├── crud_base.py          # Base class for CRUD operations.\n    │   │   ├── crud_posts.py         # CRUD operations for posts.\n    │   │   ├── crud_rate_limit.py    # CRUD operations for rate limiting.\n    │   │   ├── crud_tier.py          # CRUD operations for user tiers.\n    │   │   ├── crud_users.py         # CRUD operations for users.\n    │   │   └── helper.py             # Helper functions for CRUD operations.\n    │   │\n    │   ├── logs                      # Directory for log files.\n    │   │   └── app.log               # Log file for the application.\n    │   │\n    │   ├── middleware                # Middleware components for the application.\n    │   │   └── client_cache_middleware.py  # Middleware for client-side caching.\n    │   │\n    │   └── models                    # SQLModel db and validation models for the application.\n    │       ├── __init__.py\n    │       ├── post.py               # SQLModel models for posts.\n    │       ├── rate_limit.py         # SQLModel models for rate limiting.\n    │       ├── tier.py               # SQLModel models for user tiers.\n    │       └── user.py               # SQLModel models for users.\n    │\n    ├── migrations                    # Alembic migration scripts for database changes.\n    │   ├── README\n    │   ├── env.py                    # Environment configuration for Alembic.\n    │   ├── script.py.mako            # Template script for Alembic migrations.\n    │   │\n    │   └── versions                  # Individual migration scripts.\n    │       └── README.MD\n    │\n    └── scripts                       # Utility scripts for the application.\n        ├── __init__.py\n        ├── create_first_superuser.py # Script to create the first superuser.\n        └── create_first_tier.py      # Script to create the first user tier.\n```\n\n### 5.2 Database Model\n\nCreate the new entities and relationships and add them to the model <br>\n![diagram](https://user-images.githubusercontent.com/43156212/284426387-bdafc637-0473-4b71-890d-29e79da288cf.png)\n\n#### 5.2.1 Token Blacklist\n\nNote that this table is used to blacklist the `JWT` tokens (it's how you log a user out) <br>\n![diagram](https://user-images.githubusercontent.com/43156212/284426382-b2f3c0ca-b8ea-4f20-b47e-de1bad2ca283.png)\n\n### 5.3 DB Models\n\nInside `app/models`, create a new `entity.py` for each new entity (replacing entity with the name) and define the attributes according to [SQLModel standards](https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/):\n\n```python\nfrom sqlmodel import Field, SQLModel\n\n\nclass Entity(SQLModel, table=True):\n    __tablename__ = \"entity\"\n\n    id: int | None = Field(default=None, primary_key=True)\n    name: str = Field(max_digits=30)\n    ...\n```\n\n### 5.4 Validation Models\n\nInside each `entity.py` in `app/models`, create your SQLModel data validation models for each new entity, you'll now use `table=False` (or just leave it blank, as it's the default):\n\n```python\nfrom sqlmodel import Field, SQLModel\n\n# this should be here already\nclass Entity(SQLModel, table=True):\n    __tablename__ = \"entity\"\n\n    id: int | None = Field(default=None, primary_key=True)\n    name: str = Field(max_digits=30)\n    ...\n\n# now we'll create the other validation models\nclass EntityBase(SQLModel):\n    name: str\n    ...\n\n\nclass EntityRead(EntityBase):\n    ...\n\n\nclass EntityCreate(EntityBase):\n    ...\n\n\nclass EntityCreateInternal(EntityCreate):\n    ...\n\n\nclass EntityUpdate(SQLModel):\n    ...\n\n\nclass EntityUpdateInternal(SQLModel):\n    ...\n\n\nclass EntityDelete(SQLModel):\n    model_config = {\"extra\": \"forbid\"}\n\n    is_deleted: bool\n    deleted_at: datetime\n```\n\n### 5.5 Alembic Migrations\n\n> \\[!WARNING\\]\n> To create the tables if you did not create the endpoints, ensure that you import the models in src/app/models/__init__.py. This step is crucial to create the new models.\n\nThen, while in the `src` folder, run Alembic migrations:\n\n```sh\npoetry run alembic revision --autogenerate\n```\n\nAnd to apply the migration\n\n```sh\npoetry run alembic upgrade head\n```\n\n### 5.6 CRUD\n\nInside `app/crud`, create a new `crud_entities.py` inheriting from `FastCRUD` for each new entity:\n\n```python\nfrom fastcrud import FastCRUD\n\nfrom app.models.entity import Entity, EntityCreateInternal, EntityUpdate, EntityUpdateInternal, EntityDelete\n\nCRUDEntity = FastCRUD[Entity, EntityCreateInternal, EntityUpdate, EntityUpdateInternal, EntityDelete]\ncrud_entity = CRUDEntity(Entity)\n```\n\nSo, for users:\n\n```python\n# crud_users.py\nfrom app.model.user import User, UserCreateInternal, UserUpdate, UserUpdateInternal, UserDelete\n\nCRUDUser = FastCRUD[User, UserCreateInternal, UserUpdate, UserUpdateInternal, UserDelete]\ncrud_users = CRUDUser(User)\n```\n\nTo understand the methods that `crud_users`, a `FastCRUD` instance provides, head to [FastCRUD's documentation](https://igorbenav.github.io/fastcrud/).\n\n### 5.7 Routes\n\nInside `app/api/v1`, create a new `entities.py` file and create the desired routes\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends\n\nfrom app.models.entity import EntityRead\nfrom app.core.db.database import async_get_db\nfrom app.crud.crud_entity import crud_entity\n\n...\n\nrouter = fastapi.APIRouter(tags=[\"entities\"])\n\n\n@router.get(\"/entities/{id}\", response_model=List[EntityRead])\nasync def read_entities(request: Request, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]):\n    entity = await crud_entities.get(db=db, id=id)\n\n    return entity\n\n\n...\n```\n\nThen in `app/api/v1/__init__.py` add the router such as:\n\n```python\nfrom fastapi import APIRouter\nfrom app.api.v1.entity import router as entity_router\n\n...\n\nrouter = APIRouter(prefix=\"/v1\")  # this should be there already\n...\nrouter.include_router(entity_router)\n```\n\n#### 5.7.1 Paginated Responses\n\nWith the `get_multi` method we get a python `dict` with full suport for pagination:\n\n```javascript\n{\n  \"data\": [\n    {\n      \"id\": 4,\n      \"name\": \"User Userson\",\n      \"username\": \"userson4\",\n      \"email\": \"user.userson4@example.com\",\n      \"profile_image_url\": \"https://profileimageurl.com\"\n    },\n    {\n      \"id\": 5,\n      \"name\": \"User Userson\",\n      \"username\": \"userson5\",\n      \"email\": \"user.userson5@example.com\",\n      \"profile_image_url\": \"https://profileimageurl.com\"\n    }\n  ],\n  \"total_count\": 2,\n  \"has_more\": false,\n  \"page\": 1,\n  \"items_per_page\": 10\n}\n```\n\nAnd in the endpoint, we can import from `fastcrud.paginated` the following functions and Pydantic Schema:\n\n```python\nfrom fastcrud.paginated import (\n    PaginatedListResponse,  # What you'll use as a response_model to validate\n    paginated_response,  # Creates a paginated response based on the parameters\n    compute_offset,  # Calculate the offset for pagination ((page - 1) * items_per_page)\n)\n```\n\nThen let's create the endpoint:\n\n```python\nimport fastapi\n\nfrom app.models.entity import EntityRead\nfrom app.core.db.database import async_get_db\nfrom app.crud.crud_entity import crud_entity\n\n...\n\n\n@router.get(\"/entities\", response_model=PaginatedListResponse[EntityRead])\nasync def read_entities(\n    request: Request, db: Annotated[AsyncSession, Depends(async_get_db)], page: int = 1, items_per_page: int = 10\n):\n    entities_data = await crud_entity.get_multi(\n        db=db,\n        offset=compute_offset(page, items_per_page),\n        limit=items_per_page,\n        schema_to_select=UserRead,\n        is_deleted=False,\n    )\n\n    return paginated_response(crud_data=entities_data, page=page, items_per_page=items_per_page)\n```\n\n#### 5.7.2 HTTP Exceptions\n\nTo add exceptions you may just import from `app/core/exceptions/http_exceptions` and optionally add a detail:\n\n```python\nfrom app.core.exceptions.http_exceptions import NotFoundException\n\n# If you want to specify the detail, just add the message\nif not user:\n    raise NotFoundException(\"User not found\")\n\n# Or you may just use the default message\nif not post:\n    raise NotFoundException()\n```\n\n**The predefined possibilities in http_exceptions are the following:**\n\n- `CustomException`: 500 internal error\n- `BadRequestException`: 400 bad request\n- `NotFoundException`: 404 not found\n- `ForbiddenException`: 403 forbidden\n- `UnauthorizedException`: 401 unauthorized\n- `UnprocessableEntityException`: 422 unprocessable entity\n- `DuplicateValueException`: 422 unprocessable entity\n- `RateLimitException`: 429 too many requests\n\n### 5.8 Caching\n\nThe `cache` decorator allows you to cache the results of FastAPI endpoint functions, enhancing response times and reducing the load on your application by storing and retrieving data in a cache.\n\nCaching the response of an endpoint is really simple, just apply the `cache` decorator to the endpoint function.\n\n> \\[!WARNING\\]\n> Note that you should always pass request as a variable to your endpoint function if you plan to use the cache decorator.\n\n```python\n...\nfrom app.core.utils.cache import cache\n\n\n@app.get(\"/sample/{my_id}\")\n@cache(key_prefix=\"sample_data\", expiration=3600, resource_id_name=\"my_id\")\nasync def sample_endpoint(request: Request, my_id: int):\n    # Endpoint logic here\n    return {\"data\": \"my_data\"}\n```\n\nThe way it works is:\n\n- the data is saved in redis with the following cache key: `sample_data:{my_id}`\n- then the time to expire is set as 3600 seconds (that's the default)\n\nAnother option is not passing the `resource_id_name`, but passing the `resource_id_type` (default int):\n\n```python\n...\nfrom app.core.utils.cache import cache\n\n\n@app.get(\"/sample/{my_id}\")\n@cache(key_prefix=\"sample_data\", resource_id_type=int)\nasync def sample_endpoint(request: Request, my_id: int):\n    # Endpoint logic here\n    return {\"data\": \"my_data\"}\n```\n\nIn this case, what will happen is:\n\n- the `resource_id` will be inferred from the keyword arguments (`my_id` in this case)\n- the data is saved in redis with the following cache key: `sample_data:{my_id}`\n- then the the time to expire is set as 3600 seconds (that's the default)\n\nPassing resource_id_name is usually preferred.\n\n### 5.9 More Advanced Caching\n\nThe behaviour of the `cache` decorator changes based on the request method of your endpoint.\nIt caches the result if you are passing it to a **GET** endpoint, and it invalidates the cache with this key_prefix and id if passed to other endpoints (**PATCH**, **DELETE**).\n\n#### Invalidating Extra Keys\n\nIf you also want to invalidate cache with a different key, you can use the decorator with the `to_invalidate_extra` variable.\n\nIn the following example, I want to invalidate the cache for a certain `user_id`, since I'm deleting it, but I also want to invalidate the cache for the list of users, so it will not be out of sync.\n\n```python\n# The cache here will be saved as \"{username}_posts:{username}\":\n@router.get(\"/{username}/posts\", response_model=List[PostRead])\n@cache(key_prefix=\"{username}_posts\", resource_id_name=\"username\")\nasync def read_posts(request: Request, username: str, db: Annotated[AsyncSession, Depends(async_get_db)]):\n    ...\n\n\n...\n\n# Invalidating cache for the former endpoint by just passing the key_prefix and id as a dictionary:\n@router.delete(\"/{username}/post/{id}\")\n@cache(\n    \"{username}_post_cache\",\n    resource_id_name=\"id\",\n    to_invalidate_extra={\"{username}_posts\": \"{username}\"},  # also invalidate \"{username}_posts:{username}\" cache\n)\nasync def erase_post(\n    request: Request,\n    username: str,\n    id: int,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n):\n    ...\n\n\n# And now I'll also invalidate when I update the user:\n@router.patch(\"/{username}/post/{id}\", response_model=PostRead)\n@cache(\"{username}_post_cache\", resource_id_name=\"id\", to_invalidate_extra={\"{username}_posts\": \"{username}\"})\nasync def patch_post(\n    request: Request,\n    username: str,\n    id: int,\n    values: PostUpdate,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n):\n    ...\n```\n\n> \\[!WARNING\\]\n> Note that adding `to_invalidate_extra` will not work for **GET** requests.\n\n#### Invalidate Extra By Pattern\n\nLet's assume we have an endpoint with a paginated response, such as:\n\n```python\n@router.get(\"/{username}/posts\", response_model=PaginatedListResponse[PostRead])\n@cache(\n    key_prefix=\"{username}_posts:page_{page}:items_per_page:{items_per_page}\",\n    resource_id_name=\"username\",\n    expiration=60,\n)\nasync def read_posts(\n    request: Request,\n    username: str,\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n    page: int = 1,\n    items_per_page: int = 10,\n):\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if not db_user:\n        raise HTTPException(status_code=404, detail=\"User not found\")\n\n    posts_data = await crud_posts.get_multi(\n        db=db,\n        offset=compute_offset(page, items_per_page),\n        limit=items_per_page,\n        schema_to_select=PostRead,\n        created_by_user_id=db_user[\"id\"],\n        is_deleted=False,\n    )\n\n    return paginated_response(crud_data=posts_data, page=page, items_per_page=items_per_page)\n```\n\nJust passing `to_invalidate_extra` will not work to invalidate this cache, since the key will change based on the `page` and `items_per_page` values.\nTo overcome this we may use the `pattern_to_invalidate_extra` parameter:\n\n```python\n@router.patch(\"/{username}/post/{id}\")\n@cache(\"{username}_post_cache\", resource_id_name=\"id\", pattern_to_invalidate_extra=[\"{username}_posts:*\"])\nasync def patch_post(\n    request: Request,\n    username: str,\n    id: int,\n    values: PostUpdate,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n):\n    ...\n```\n\nNow it will invalidate all caches with a key that matches the pattern `\"{username}_posts:*`, which will work for the paginated responses.\n\n> \\[!CAUTION\\]\n> Using `pattern_to_invalidate_extra` can be resource-intensive on large datasets. Use it judiciously and consider the potential impact on Redis performance. Be cautious with patterns that could match a large number of keys, as deleting many keys simultaneously may impact the performance of the Redis server.\n\n#### Client-side Caching\n\nFor `client-side caching`, all you have to do is let the `Settings` class defined in `app/core/config.py` inherit from the `ClientSideCacheSettings` class. You can set the `CLIENT_CACHE_MAX_AGE` value in `.env,` it defaults to 60 (seconds).\n\n### 5.10 ARQ Job Queues\n\nDepending on the problem your API is solving, you might want to implement a job queue. A job queue allows you to run tasks in the background, and is usually aimed at functions that require longer run times and don't directly impact user response in your frontend. As a rule of thumb, if a task takes more than 2 seconds to run, can be executed asynchronously, and its result is not needed for the next step of the user's interaction, then it is a good candidate for the job queue.\n\n> [!TIP]\n> Very common candidates for background functions are calls to and from LLM endpoints (e.g. OpenAI or Openrouter). This is because they span tens of seconds and often need to be further parsed and saved.\n\n#### Background task creation\n\nFor simple background tasks, you can just create a function in the `app/core/worker/functions.py` file. For more complex tasks, we recommend you to create a new file in the `app/core/worker` directory.\n\n```python\nasync def sample_background_task(ctx, name: str) -> str:\n    await asyncio.sleep(5)\n    return f\"Task {name} is complete!\"\n```\n\nThen add the function to the `WorkerSettings` class `functions` variable in `app/core/worker/settings.py` to make it available to the worker. If you created a new file in the `app/core/worker` directory, then simply import this function in the `app/core/worker/settings.py` file:\n\n\n ```python\n from .functions import sample_background_task\n from .your_module import sample_complex_background_task\n\n class WorkerSettings:\n     functions = [sample_background_task, sample_complex_background_task]\n     ...\n ```\n\n#### Add the task to an endpoint\n\nOnce you have created the background task, you can add it to any endpoint of your choice to be enqueued. The best practice is to enqueue the task in a **POST** endpoint, while having a **GET** endpoint to get more information on the task. For more details on how job results are handled, check the [ARQ docs](https://arq-docs.helpmanual.io/#job-results).\n\n```python\n@router.post(\"/task\", response_model=Job, status_code=201)\nasync def create_task(message: str):\n    job = await queue.pool.enqueue_job(\"sample_background_task\", message)\n    return {\"id\": job.job_id}\n\n\n@router.get(\"/task/{task_id}\")\nasync def get_task(task_id: str):\n    job = ArqJob(task_id, queue.pool)\n    return await job.info()\n```\n\nAnd finally run the worker in parallel to your fastapi application.\n\n> [!IMPORTANT]\n> For any change to the `sample_background_task` to be reflected in the worker, you need to restart the worker (e.g. the docker container).\n\nIf you are using `docker compose`, the worker is already running.\nIf you are doing it from scratch, run while in the `root` folder:\n\n```sh\npoetry run arq src.app.core.worker.settings.WorkerSettings\n```\n\n#### Database session with background tasks\n\nWith time your background functions will become 'workflows' increasing in complexity and requirements. Probably, you will need to use a database session to get, create, update, or delete data as part of this workflow.\n\nTo do this, you can add the database session to the `ctx` object in the `startup` and `shutdown` functions in `app/core/worker/functions.py`, like in the example below:\n\n```python\nfrom arq.worker import Worker\nfrom ...core.db.database import async_get_db\n\nasync def startup(ctx: Worker) -> None:\n    ctx[\"db\"] = await anext(async_get_db())\n    logging.info(\"Worker Started\")\n\nasync def shutdown(ctx: Worker) -> None:\n    await ctx[\"db\"].close()\n    logging.info(\"Worker end\")\n```\n\nThis will allow you to have the async database session always available in any background function and automatically close it on worker shutdown. Once you have this database session, you can use it as follows:\n\n```python\nfrom arq.worker import Worker\n\nasync def your_background_function(\n    ctx: Worker,\n    post_id: int,\n    ...\n) -> Any:\n    db = ctx[\"db\"]\n    post = crud_posts.get(db=db, schema_to_select=PostRead, id=post_id)\n    ...\n```\n\n> [!WARNING]\n> When using database sessions, you will want to use Pydantic objects. However, these objects don't mingle well with the seralization required by ARQ tasks and will be retrieved as a dictionary.\n\n### 5.11 Rate Limiting\n\nTo limit how many times a user can make a request in a certain interval of time (very useful to create subscription plans or just to protect your API against DDOS), you may just use the `rate_limiter` dependency:\n\n```python\nfrom fastapi import Depends\n\nfrom app.api.dependencies import rate_limiter\nfrom app.core.utils import queue\nfrom app.models.job import Job\n\n\n@router.post(\"/task\", response_model=Job, status_code=201, dependencies=[Depends(rate_limiter)])\nasync def create_task(message: str):\n    job = await queue.pool.enqueue_job(\"sample_background_task\", message)\n    return {\"id\": job.job_id}\n```\n\nBy default, if no token is passed in the header (that is - the user is not authenticated), the user will be limited by his IP address with the default `limit` (how many times the user can make this request every period) and `period` (time in seconds) defined in `.env`.\n\nEven though this is useful, real power comes from creating `tiers` (categories of users) and standard `rate_limits` (`limits` and `periods` defined for specific `paths` - that is - endpoints) for these tiers.\n\nAll of the `tier` and `rate_limit` models and endpoints are already created in the respective folders (and usable only by superusers). You may use the `create_tier` script to create the first tier (it uses the `.env` variable `TIER_NAME`, which is all you need to create a tier) or just use the api:\n\nHere I'll create a `free` tier:\n\n<p align=\"left\">\n    <img src=\"https://user-images.githubusercontent.com/43156212/282275103-d9c4f511-4cfa-40c6-b882-5b09df9f62b9.png\" alt=\"passing name = free to api request body\" width=\"70%\" height=\"auto\">\n</p>\n\nAnd a `pro` tier:\n\n<p align=\"left\">\n    <img src=\"https://user-images.githubusercontent.com/43156212/282275107-5a6ca593-ccc0-4965-b2db-09ec5ecad91c.png\" alt=\"passing name = pro to api request body\" width=\"70%\" height=\"auto\">\n</p>\n\nThen I'll associate a `rate_limit` for the path `api/v1/tasks/task` for each of them, I'll associate a `rate limit` for the path `api/v1/tasks/task`.\n\n> \\[!WARNING\\]\n> Do not forget to add `api/v1/...` or any other prefix to the beggining of your path. For the structure of the boilerplate, `api/v1/<rest_of_the_path>`\n\n1 request every hour (3600 seconds) for the free tier:\n\n<p align=\"left\">\n    <img src=\"https://user-images.githubusercontent.com/43156212/282275105-95d31e19-b798-4f03-98f0-3e9d1844f7b3.png\" alt=\"passing path=api/v1/tasks/task, limit=1, period=3600, name=api_v1_tasks:1:3600 to free tier rate limit\" width=\"70%\" height=\"auto\">\n</p>\n\n10 requests every hour for the pro tier:\n\n<p align=\"left\">\n    <img src=\"https://user-images.githubusercontent.com/43156212/282275108-deec6f46-9d47-4f01-9899-ca42da0f0363.png\" alt=\"passing path=api/v1/tasks/task, limit=10, period=3600, name=api_v1_tasks:10:3600 to pro tier rate limit\" width=\"70%\" height=\"auto\">\n</p>\n\nNow let's read all the tiers available (`GET api/v1/tiers`):\n\n```javascript\n{\n  \"data\": [\n    {\n      \"name\": \"free\",\n      \"id\": 1,\n      \"created_at\": \"2023-11-11T05:57:25.420360\"\n    },\n    {\n      \"name\": \"pro\",\n      \"id\": 2,\n      \"created_at\": \"2023-11-12T00:40:00.759847\"\n    }\n  ],\n  \"total_count\": 2,\n  \"has_more\": false,\n  \"page\": 1,\n  \"items_per_page\": 10\n}\n```\n\nAnd read the `rate_limits` for the `pro` tier to ensure it's working (`GET api/v1/tier/pro/rate_limits`):\n\n```javascript\n{\n  \"data\": [\n    {\n      \"path\": \"api_v1_tasks_task\",\n      \"limit\": 10,\n      \"period\": 3600,\n      \"id\": 1,\n      \"tier_id\": 2,\n      \"name\": \"api_v1_tasks:10:3600\"\n    }\n  ],\n  \"total_count\": 1,\n  \"has_more\": false,\n  \"page\": 1,\n  \"items_per_page\": 10\n}\n```\n\nNow, whenever an authenticated user makes a `POST` request to the `api/v1/tasks/task`, they'll use the quota that is defined by their tier.\nYou may check this getting the token from the `api/v1/login` endpoint, then passing it in the request header:\n\n```sh\ncurl -X POST 'http://127.0.0.1:8000/api/v1/tasks/task?message=test' \\\n-H 'Authorization: Bearer <your-token-here>'\n```\n\n> \\[!TIP\\]\n> Since the `rate_limiter` dependency uses the `get_optional_user` dependency instead of `get_current_user`, it will not require authentication to be used, but will behave accordingly if the user is authenticated (and token is passed in header). If you want to ensure authentication, also use `get_current_user` if you need.\n\nTo change a user's tier, you may just use the `PATCH api/v1/user/{username}/tier` endpoint.\nNote that for flexibility (since this is a boilerplate), it's not necessary to previously inform a tier_id to create a user, but you probably should set every user to a certain tier (let's say `free`) once they are created.\n\n> \\[!WARNING\\]\n> If a user does not have a `tier` or the tier does not have a defined `rate limit` for the path and the token is still passed to the request, the default `limit` and `period` will be used, this will be saved in `app/logs`.\n\n### 5.12 JWT Authentication\n\n#### 5.12.1 Details\n\nThe JWT in this boilerplate is created in the following way:\n\n1. **JWT Access Tokens:** how you actually access protected resources is passing this token in the request header.\n1. **Refresh Tokens:** you use this type of token to get an `access token`, which you'll use to access protected resources.\n\nThe `access token` is short lived (default 30 minutes) to reduce the damage of a potential leak. The `refresh token`, on the other hand, is long lived (default 7 days), and you use it to renew your `access token` without the need to provide username and password every time it expires.\n\nSince the `refresh token` lasts for a longer time, it's stored as a cookie in a secure way:\n\n```python\n# app/api/v1/login\n\n...\nresponse.set_cookie(\n    key=\"refresh_token\",\n    value=refresh_token,\n    httponly=True,  # Prevent access through JavaScript\n    secure=True,  # Ensure cookie is sent over HTTPS only\n    samesite=\"Lax\",  # Default to Lax for reasonable balance between security and usability\n    max_age=number_of_seconds,  # Set a max age for the cookie\n)\n...\n```\n\nYou may change it to suit your needs. The possible options for `samesite` are:\n\n- `Lax`: Cookies will be sent in top-level navigations (like clicking on a link to go to another site), but not in API requests or images loaded from other sites.\n- `Strict`: Cookies are sent only on top-level navigations from the same site that set the cookie, enhancing privacy but potentially disrupting user sessions.\n- `None`: Cookies will be sent with both same-site and cross-site requests.\n\n#### 5.12.2 Usage\n\nWhat you should do with the client is:\n\n- `Login`: Send credentials to `/api/v1/login`. Store the returned access token in memory for subsequent requests.\n- `Accessing Protected Routes`: Include the access token in the Authorization header.\n- `Token Renewal`: On access token expiry, the front end should automatically call `/api/v1/refresh` for a new token.\n- `Login Again`: If refresh token is expired, credentials should be sent to `/api/v1/login` again, storing the new access token in memory.\n- `Logout`: Call /api/v1/logout to end the session securely.\n\nThis authentication setup in the provides a robust, secure, and user-friendly way to handle user sessions in your API applications.\n\n### 5.13 Running\n\nIf you are using docker compose, just running the following command should ensure everything is working:\n\n```sh\ndocker compose up\n```\n\nIf you are doing it from scratch, ensure your postgres and your redis are running, then\nwhile in the `root` folder, run to start the application with uvicorn server:\n\n```sh\npoetry run uvicorn src.app.main:app --reload\n```\n\nAnd for the worker:\n\n```sh\npoetry run arq src.app.core.worker.settings.WorkerSettings\n```\n### 5.14 Create Application\n\nIf you want to stop tables from being created every time you run the api, you should disable this here:\n\n```python\n# app/main.py\n\nfrom .api import router\nfrom .core.config import settings\nfrom .core.setup import create_application\n\n# create_tables_on_start defaults to True\napp = create_application(router=router, settings=settings, create_tables_on_start=False)\n```\n\nThis `create_application` function is defined in `app/core/setup.py`, and it's a flexible way to configure the behavior of your application.\n\nA few examples:\n\n- Deactivate or password protect /docs\n- Add client-side cache middleware\n- Add Startup and Shutdown event handlers for cache, queue and rate limit\n\n### 5.15 Opting Out of Services\n\nTo opt out of services (like `Redis`, `Queue`, `Rate Limiter`), head to the `Settings` class in `src/app/core/config`:\n\n```python\n# src/app/core/config\nimport os\nfrom enum import Enum\n\nfrom pydantic_settings import BaseSettings\nfrom starlette.config import Config\n\ncurrent_file_dir = os.path.dirname(os.path.realpath(__file__))\nenv_path = os.path.join(current_file_dir, \"..\", \"..\", \".env\")\nconfig = Config(env_path)\n...\n\nclass Settings(\n    AppSettings,\n    PostgresSettings,\n    CryptSettings,\n    FirstUserSettings,\n    TestSettings,\n    RedisCacheSettings,\n    ClientSideCacheSettings,\n    RedisQueueSettings,\n    RedisRateLimiterSettings,\n    DefaultRateLimitSettings,\n    EnvironmentSettings,\n):\n    pass\n\n\nsettings = Settings()\n```\n\nAnd remove the Settings of the services you do not need. For example, without using redis (removed `Cache`, `Queue` and `Rate limit`):\n\n```python\nclass Settings(\n    AppSettings,\n    PostgresSettings,\n    CryptSettings,\n    FirstUserSettings,\n    TestSettings,\n    ClientSideCacheSettings,\n    DefaultRateLimitSettings,\n    EnvironmentSettings,\n):\n    pass\n```\n\nThen comment or remove the services you do not want from `docker-compose.yml`. Here, I removed `redis` and `worker` services:\n\n```yml\nversion: '3.8'\n\nservices:\n  web:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    # -------- replace with comment to run with gunicorn --------\n    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload\n    # command: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n    env_file:\n      - ./src/.env\n    # -------- replace with comment if you are using nginx --------\n    ports:\n      - \"8000:8000\"\n    # expose:\n    #   - \"8000\"\n    depends_on:\n      - db\n      - redis\n    volumes:\n      - ./src/app:/code/app\n      - ./src/.env:/code/.env\n  db:\n    image: postgres:13\n    env_file:\n      - ./src/.env\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    # -------- replace with comment to run migrations with docker --------\n    expose:\n      - \"5432\"\n    # ports:\n    #  - 5432:5432\n\nvolumes:\n  postgres-data:\n  redis-data:\n  #pgadmin-data:\n```\n\n## 6. Running in Production\n\n### 6.1 Uvicorn Workers with Gunicorn\n\nIn production you may want to run using gunicorn to manage uvicorn workers:\n\n```sh\ncommand: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n```\n\nHere it's running with 4 workers, but you should test it depending on how many cores your machine has.\n\nTo do this if you are using docker compose, just replace the comment:\nThis part in `docker-compose.yml`:\n\n```YAML\n# docker-compose.yml\n\n# -------- replace with comment to run with gunicorn --------\ncommand: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload\n# command: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n```\n\nShould be changed to:\n\n```YAML\n# docker-compose.yml\n\n# -------- replace with comment to run with uvicorn --------\n# command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload\ncommand: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n```\n\nAnd the same in `Dockerfile`:\nThis part:\n\n```Dockerfile\n# Dockerfile\n\nCMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\", \"--reload\"]\n# CMD [\"gunicorn\", \"app.main:app\", \"-w\", \"4\", \"-k\", \"uvicorn.workers.UvicornWorker\". \"-b\", \"0.0.0.0:8000\"]\n```\n\nShould be changed to:\n\n```Dockerfile\n# Dockerfile\n\n# CMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\", \"--reload\"]\nCMD [\"gunicorn\", \"app.main:app\", \"-w\", \"4\", \"-k\", \"uvicorn.workers.UvicornWorker\". \"-b\", \"0.0.0.0:8000\"]\n```\n\n> \\[!CAUTION\\]\n> Do not forget to set the `ENVIRONMENT` in `.env` to `production` unless you want the API docs to be public.\n\n### 6.2 Running with NGINX\n\nNGINX is a high-performance web server, known for its stability, rich feature set, simple configuration, and low resource consumption. NGINX acts as a reverse proxy, that is, it receives client requests, forwards them to the FastAPI server (running via Uvicorn or Gunicorn), and then passes the responses back to the clients.\n\nTo run with NGINX, you start by uncommenting the following part in your `docker-compose.yml`:\n\n```python\n# docker-compose.yml\n\n...\n# -------- uncomment to run with nginx --------\n# nginx:\n#   image: nginx:latest\n#   ports:\n#     - \"80:80\"\n#   volumes:\n#     - ./default.conf:/etc/nginx/conf.d/default.conf\n#   depends_on:\n#     - web\n...\n```\n\nWhich should be changed to:\n\n```YAML\n# docker-compose.yml\n\n...\n  #-------- uncomment to run with nginx --------\n  nginx:\n    image: nginx:latest\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./default.conf:/etc/nginx/conf.d/default.conf\n    depends_on:\n      - web\n...\n```\n\nThen comment the following part:\n\n```YAML\n# docker-compose.yml\n\nservices:\n  web:\n    ...\n    # -------- Both of the following should be commented to run with nginx --------\n    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload\n    # command: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n```\n\nWhich becomes:\n\n```YAML\n# docker-compose.yml\n\nservices:\n  web:\n    ...\n    # -------- Both of the following should be commented to run with nginx --------\n    # command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload\n    # command: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n```\n\nThen pick the way you want to run (uvicorn or gunicorn managing uvicorn workers) in `Dockerfile`.\nThe one you want should be uncommented, comment the other one.\n\n```Dockerfile\n# Dockerfile\n\nCMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\", \"--reload\"]\n# CMD [\"gunicorn\", \"app.main:app\", \"-w\", \"4\", \"-k\", \"uvicorn.workers.UvicornWorker\". \"-b\", \"0.0.0.0:8000\"]\n```\n\nAnd finally head to `http://localhost/docs`.\n\n#### 6.2.1 One Server\n\nIf you want to run with one server only, your setup should be ready. Just make sure the only part that is not a comment in `default.conf` is:\n\n```conf\n# default.conf\n\n# ---------------- Running With One Server ----------------\nserver {\n    listen 80;\n\n    location / {\n        proxy_pass http://web:8000;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n    }\n}\n```\n\nSo just type on your browser: `http://localhost/docs`.\n\n#### 6.2.2 Multiple Servers\n\nNGINX can distribute incoming network traffic across multiple servers, improving the efficiency and capacity utilization of your application.\n\nTo run with multiple servers, just comment the `Running With One Server` part in `default.conf` and Uncomment the other one:\n\n```conf\n# default.conf\n\n# ---------------- Running With One Server ----------------\n...\n\n# ---------------- To Run with Multiple Servers, Uncomment below ----------------\nupstream fastapi_app {\n    server fastapi1:8000;  # Replace with actual server names or IP addresses\n    server fastapi2:8000;\n    # Add more servers as needed\n}\n\nserver {\n    listen 80;\n\n    location / {\n        proxy_pass http://fastapi_app;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n    }\n}\n```\n\nAnd finally, on your browser: `http://localhost/docs`.\n\n> \\[!WARNING\\]\n> Note that we are using `fastapi1:8000` and `fastapi2:8000` as examples, you should replace it with the actual name of your service and the port it's running on.\n\n## 7. Testing\n\nFor tests, ensure you have in `.env`:\n\n```\n# ------------- test -------------\nTEST_NAME=\"Tester User\"\nTEST_EMAIL=\"test@tester.com\"\nTEST_USERNAME=\"testeruser\"\nTEST_PASSWORD=\"Str1ng$t\"\n```\n\nWhile in the tests folder, create your test file with the name \"test\\_{entity}.py\", replacing entity with what you're testing\n\n```sh\ntouch test_items.py\n```\n\nFinally create your tests (you may want to copy the structure in test_user.py)\n\nNow, to run:\n\n### 7.1  Docker Compose\n\nFirst you need to uncomment the following part in the `docker-compose.yml` file:\n\n```YAML\n  #-------- uncomment to run tests --------\n  # pytest:\n  #   build:\n  #     context: .\n  #     dockerfile: Dockerfile\n  #   env_file:\n  #     - ./src/.env\n  #   depends_on:\n  #     - db\n  #     - create_superuser\n  #     - redis\n  #   command: python -m pytest ./tests\n  #   volumes:\n  #     - .:/code\n```\n\nYou'll get:\n\n```YAML\n  #-------- uncomment to run tests --------\n  pytest:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    env_file:\n      - ./src/.env\n    depends_on:\n      - db\n      - create_superuser\n      - redis\n    command: python -m pytest ./tests\n    volumes:\n      - .:/code\n```\n\nStart the Docker Compose services:\n\n```sh\ndocker-compose up -d\n```\n\nIt will automatically run the tests, but if you want to run again later:\n\n```sh\ndocker-compose run --rm pytest\n```\n\n### 7.2  From Scratch\n\nWhile in the `root` folder, run:\n\n```sh\npoetry run python -m pytest\n```\n\n## 8. Contributing\n\nRead [contributing](CONTRIBUTING.md).\n\n## 9. References\n\nThis project is a SQLModel version of Fastapi-boilerplate:\n\n- [`FastAPI-boilerplate`](https://github.com/igorbenav/FastAPI-boilerplate)\n\n## 10. License\n\n[`MIT`](LICENSE.md)\n\n## 11. Contact\n\nBenav Labs – [benav.io](https://benav.io)\n[github.com/benavlabs](https://github.com/benavlabs/)\n\n<hr>\n<a href=\"https://benav.io\">\n  <img src=\"https://github.com/benavlabs/fastcrud/raw/main/docs/assets/benav_labs_banner.png\" alt=\"Powered by Benav Labs - benav.io\"/>\n</a>\n"
  },
  {
    "path": "default.conf",
    "content": "# ---------------- Running With One Server ----------------\nserver {\n    listen 80;\n\n    location / {\n        proxy_pass http://web:8000;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n    }\n}\n\n\n# # ---------------- To Run with Multiple Servers, Uncomment below ----------------\n# upstream fastapi_app {\n#     server fastapi1:8000;  # Replace with actual server names or IP addresses\n#     server fastapi2:8000;\n#     # Add more servers as needed\n# }\n\n# server {\n#     listen 80;\n\n#     location / {\n#         proxy_pass http://fastapi_app;\n#         proxy_set_header Host $host;\n#         proxy_set_header X-Real-IP $remote_addr;\n#         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n#         proxy_set_header X-Forwarded-Proto $scheme;\n#     }\n# }\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '3.8'\n\nservices:\n  web:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    # -------- replace with comment to run with gunicorn --------\n    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload\n    # command: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000\n    env_file:\n      - ./src/.env\n    # -------- replace with comment if you are using nginx --------\n    ports:\n      - \"8000:8000\"\n    # expose:\n    #   - \"8000\"\n    depends_on:\n      - db\n      - redis\n    volumes:\n      - ./src/app:/code/app\n      - ./src/.env:/code/.env\n\n  worker:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    command: arq app.core.worker.settings.WorkerSettings\n    env_file:\n      - ./src/.env\n    depends_on:\n      - db\n      - redis\n    volumes:\n      - ./src/app:/code/app\n      - ./src/.env:/code/.env\n\n  db:\n    image: postgres:13\n    env_file:\n      - ./src/.env\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    # -------- replace with comment to run migrations with docker --------\n    expose:\n      - \"5432\"\n    # ports:\n    #  - 5432:5432\n\n  redis:\n    image: redis:alpine\n    volumes:\n      - redis-data:/data\n    expose:\n      - \"6379\"\n\n  #-------- uncomment to run with pgadmin --------\n  # pgadmin:\n  #   container_name: pgadmin4\n  #   image: dpage/pgadmin4:latest\n  #   restart: always\n  #   ports:\n  #     - \"5050:80\"\n  #   volumes:\n  #     - pgadmin-data:/var/lib/pgadmin\n  #   env_file:\n  #     - ./src/.env\n  #   depends_on:\n  #     - db\n\n  #-------- uncomment to run with nginx --------\n  # nginx:\n  #   image: nginx:latest\n  #   ports:\n  #     - \"80:80\"\n  #   volumes:\n  #     - ./default.conf:/etc/nginx/conf.d/default.conf\n  #   depends_on:\n  #     - web\n\n  #-------- uncomment to create first superuser --------\n  # create_superuser:\n  #   build:\n  #     context: .\n  #     dockerfile: Dockerfile\n  #   env_file:\n  #     - ./src/.env\n  #   depends_on:\n  #     - db\n  #     - web\n  #   command: python -m src.scripts.create_first_superuser\n  #   volumes:\n  #     - ./src:/code/src\n\n  #-------- uncomment to run tests --------\n  # pytest:\n  #   build:\n  #     context: .\n  #     dockerfile: Dockerfile\n  #   env_file:\n  #     - ./src/.env\n  #   depends_on:\n  #     - db\n  #     - create_superuser\n  #     - redis\n  #   command: python -m pytest ./tests\n  #   volumes:\n  #     - .:/code\n\n  #-------- uncomment to create first tier --------\n  # create_tier:\n  #   build:\n  #     context: .\n  #     dockerfile: Dockerfile\n  #   env_file:\n  #     - ./src/.env\n  #   depends_on:\n  #     - db\n  #     - web\n  #   command: python -m src.scripts.create_first_tier\n  #   volumes:\n  #     - ./src:/code/src\n\nvolumes:\n  postgres-data:\n  redis-data:\n  #pgadmin-data:\n"
  },
  {
    "path": "mypy.ini",
    "content": "[mypy]\npython_version = 3.11\nwarn_return_any = True\nwarn_unused_configs = True\nignore_missing_imports = True\n\n[mypy-src.app.*]\ndisallow_untyped_defs = True\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.poetry]\nname = \"fastapi-boilerplate\"\nversion = \"0.1.0\"\ndescription = \"A fully Async FastAPI boilerplate using SQLAlchemy and Pydantic 2\"\nauthors = [\"Igor Magalhaes <igor.magalhaes.r@gmail.com>\"]\nlicense = \"MIT\"\nreadme = \"README.md\"\npackages = [{ include = \"src\" }]\n\n[tool.poetry.requires-plugins]\npoetry-plugin-export = \">=1.8\"\n\n[tool.poetry.dependencies]\npython = \"^3.11\"\npython-dotenv = \"^1.0.0\"\npydantic = { extras = [\"email\"], version = \"^2.6.1\" }\nfastapi = \"^0.109.1\"\nuvicorn = \"^0.27.0\"\nuvloop = \"^0.19.0\"\nhttptools = \"^0.6.1\"\nuuid = \"^1.30\"\nalembic = \"^1.13.1\"\nasyncpg = \"^0.29.0\"\nSQLAlchemy-Utils = \"^0.41.1\"\npython-jose = \"^3.3.0\"\nSQLAlchemy = \"^2.0.25\"\npytest = \"^7.4.2\"\npython-multipart = \"^0.0.9\"\ngreenlet = \"^2.0.2\"\nhttpx = \"^0.26.0\"\npydantic-settings = \"^2.0.3\"\nredis = \"^5.0.1\"\narq = \"^0.25.0\"\ngunicorn = \"^22.0.0\"\nbcrypt = \"^4.1.1\"\nfastcrud = \"^0.12.0\"\nsqlmodel = \"^0.0.18\"\n\n\n[build-system]\nrequires = [\"poetry-core\"]\nbuild-backend = \"poetry.core.masonry.api\"\n\n[tool.ruff]\ntarget-version = \"py311\"\nline-length = 120\nfix = true\nselect = [\n    # https://docs.astral.sh/ruff/rules/#pyflakes-f\n    \"F\", # Pyflakes\n    # https://docs.astral.sh/ruff/rules/#pycodestyle-e-w\n    \"E\", # pycodestyle\n    \"W\", # Warning\n    # https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4\n    # https://docs.astral.sh/ruff/rules/#mccabe-c90\n    \"C\", # Complexity (mccabe+) & comprehensions\n    # https://docs.astral.sh/ruff/rules/#pyupgrade-up\n    \"UP\", # pyupgrade\n    # https://docs.astral.sh/ruff/rules/#isort-i\n    \"I\", # isort\n]\nignore = [\n    # https://docs.astral.sh/ruff/rules/#pycodestyle-e-w\n    \"E402\", # module level import not at top of file\n    # https://docs.astral.sh/ruff/rules/#pyupgrade-up\n    \"UP006\", # use-pep585-annotation\n    \"UP007\", # use-pep604-annotation\n    \"E741\",  # Ambiguous variable name\n    # \"UP035\", # deprecated-assertion\n]\n[tool.ruff.per-file-ignores]\n\"__init__.py\" = [\n    \"F401\", # unused import\n    \"F403\", # star imports\n]\n\n[tool.ruff.mccabe]\nmax-complexity = 24\n\n[tool.ruff.pydocstyle]\nconvention = \"numpy\"\n"
  },
  {
    "path": "src/__init__.py",
    "content": ""
  },
  {
    "path": "src/alembic.ini",
    "content": "# A generic, single database configuration.\n\n[alembic]\n# path to migration scripts\nscript_location = migrations\n\n# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s\n# Uncomment the line below if you want the files to be prepended with date and time\n# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file\n# for all available tokens\n# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s\n\n# sys.path path, will be prepended to sys.path if present.\n# defaults to the current working directory.\nprepend_sys_path = .\n\n# timezone to use when rendering the date within the migration file\n# as well as the filename.\n# If specified, requires the python-dateutil library that can be\n# installed by adding `alembic[tz]` to the pip requirements\n# string value is passed to dateutil.tz.gettz()\n# leave blank for localtime\n# timezone =\n\n# max length of characters to apply to the\n# \"slug\" field\n# truncate_slug_length = 40\n\n# set to 'true' to run the environment during\n# the 'revision' command, regardless of autogenerate\n# revision_environment = false\n\n# set to 'true' to allow .pyc and .pyo files without\n# a source .py file to be detected as revisions in the\n# versions/ directory\n# sourceless = false\n\n# version location specification; This defaults\n# to migrations/versions.  When using multiple version\n# directories, initial revisions must be specified with --version-path.\n# The path separator used here should be the separator specified by \"version_path_separator\" below.\n# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions\n\n# version path separator; As mentioned above, this is the character used to split\n# version_locations. The default within new alembic.ini files is \"os\", which uses os.pathsep.\n# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.\n# Valid values for version_path_separator are:\n#\n# version_path_separator = :\n# version_path_separator = ;\n# version_path_separator = space\nversion_path_separator = os  # Use os.pathsep. Default configuration used for new projects.\n\n# set to 'true' to search source files recursively\n# in each \"version_locations\" directory\n# new in Alembic version 1.10\n# recursive_version_locations = false\n\n# the output encoding used when revision files\n# are written from script.py.mako\n# output_encoding = utf-8\n\nsqlalchemy.url = driver://user:pass@localhost/dbname\n\n\n[post_write_hooks]\n# post_write_hooks defines scripts or Python functions that are run\n# on newly generated revision scripts.  See the documentation for further\n# detail and examples\n\n# format using \"black\" - use the console_scripts runner, against the \"black\" entrypoint\n# hooks = black\n# black.type = console_scripts\n# black.entrypoint = black\n# black.options = -l 79 REVISION_SCRIPT_FILENAME\n\n# lint with attempts to fix using \"ruff\" - use the exec runner, execute a binary\n# hooks = ruff\n# ruff.type = exec\n# ruff.executable = %(here)s/.venv/bin/ruff\n# ruff.options = --fix REVISION_SCRIPT_FILENAME\n\n# Logging configuration\n[loggers]\nkeys = root,sqlalchemy,alembic\n\n[handlers]\nkeys = console\n\n[formatters]\nkeys = generic\n\n[logger_root]\nlevel = WARN\nhandlers = console\nqualname =\n\n[logger_sqlalchemy]\nlevel = WARN\nhandlers =\nqualname = sqlalchemy.engine\n\n[logger_alembic]\nlevel = INFO\nhandlers =\nqualname = alembic\n\n[handler_console]\nclass = StreamHandler\nargs = (sys.stderr,)\nlevel = NOTSET\nformatter = generic\n\n[formatter_generic]\nformat = %(levelname)-5.5s [%(name)s] %(message)s\ndatefmt = %H:%M:%S\n"
  },
  {
    "path": "src/app/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/api/__init__.py",
    "content": "from fastapi import APIRouter\n\nfrom ..api.v1 import router as v1_router\n\nrouter = APIRouter(prefix=\"/api\")\nrouter.include_router(v1_router)\n"
  },
  {
    "path": "src/app/api/dependencies.py",
    "content": "from typing import Annotated, Any\n\nfrom fastapi import Depends, HTTPException, Request\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ..core.config import settings\nfrom ..core.db.database import async_get_db\nfrom ..core.exceptions.http_exceptions import ForbiddenException, RateLimitException, UnauthorizedException\nfrom ..core.logger import logging\nfrom ..core.security import oauth2_scheme, verify_token\nfrom ..core.utils.rate_limit import is_rate_limited\nfrom ..crud.crud_rate_limit import crud_rate_limits\nfrom ..crud.crud_tier import crud_tiers\nfrom ..crud.crud_users import crud_users\nfrom ..models.user import User\nfrom ..models.rate_limit import sanitize_path\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_LIMIT = settings.DEFAULT_RATE_LIMIT_LIMIT\nDEFAULT_PERIOD = settings.DEFAULT_RATE_LIMIT_PERIOD\n\n\nasync def get_current_user(\n    token: Annotated[str, Depends(oauth2_scheme)], db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict[str, Any] | None:\n    token_data = await verify_token(token, db)\n    if token_data is None:\n        raise UnauthorizedException(\"User not authenticated.\")\n\n    if \"@\" in token_data.username_or_email:\n        user: dict | None = await crud_users.get(db=db, email=token_data.username_or_email, is_deleted=False)\n    else:\n        user = await crud_users.get(db=db, username=token_data.username_or_email, is_deleted=False)\n\n    if user:\n        return user\n\n    raise UnauthorizedException(\"User not authenticated.\")\n\n\nasync def get_optional_user(request: Request, db: AsyncSession = Depends(async_get_db)) -> dict | None:\n    token = request.headers.get(\"Authorization\")\n    if not token:\n        return None\n\n    try:\n        token_type, _, token_value = token.partition(\" \")\n        if token_type.lower() != \"bearer\" or not token_value:\n            return None\n\n        token_data = await verify_token(token_value, db)\n        if token_data is None:\n            return None\n\n        return await get_current_user(token_value, db=db)\n\n    except HTTPException as http_exc:\n        if http_exc.status_code != 401:\n            logger.error(f\"Unexpected HTTPException in get_optional_user: {http_exc.detail}\")\n        return None\n\n    except Exception as exc:\n        logger.error(f\"Unexpected error in get_optional_user: {exc}\")\n        return None\n\n\nasync def get_current_superuser(current_user: Annotated[dict, Depends(get_current_user)]) -> dict:\n    if not current_user[\"is_superuser\"]:\n        raise ForbiddenException(\"You do not have enough privileges.\")\n\n    return current_user\n\n\nasync def rate_limiter(\n    request: Request, db: Annotated[AsyncSession, Depends(async_get_db)], user: User | None = Depends(get_optional_user)\n) -> None:\n    path = sanitize_path(request.url.path)\n    if user:\n        user_id = user[\"id\"]\n        tier = await crud_tiers.get(db, id=user[\"tier_id\"])\n        if tier:\n            rate_limit = await crud_rate_limits.get(db=db, tier_id=tier[\"id\"], path=path)\n            if rate_limit:\n                limit, period = rate_limit[\"limit\"], rate_limit[\"period\"]\n            else:\n                logger.warning(\n                    f\"User {user_id} with tier '{tier['name']}' has no specific rate limit for path '{path}'. \\\n                        Applying default rate limit.\"\n                )\n                limit, period = DEFAULT_LIMIT, DEFAULT_PERIOD\n        else:\n            logger.warning(f\"User {user_id} has no assigned tier. Applying default rate limit.\")\n            limit, period = DEFAULT_LIMIT, DEFAULT_PERIOD\n    else:\n        user_id = request.client.host\n        limit, period = DEFAULT_LIMIT, DEFAULT_PERIOD\n\n    is_limited = await is_rate_limited(db=db, user_id=user_id, path=path, limit=limit, period=period)\n    if is_limited:\n        raise RateLimitException(\"Rate limit exceeded.\")\n"
  },
  {
    "path": "src/app/api/v1/__init__.py",
    "content": "from fastapi import APIRouter\n\nfrom .login import router as login_router\nfrom .logout import router as logout_router\nfrom .posts import router as posts_router\nfrom .rate_limits import router as rate_limits_router\nfrom .tasks import router as tasks_router\nfrom .tiers import router as tiers_router\nfrom .users import router as users_router\n\nrouter = APIRouter(prefix=\"/v1\")\nrouter.include_router(login_router)\nrouter.include_router(logout_router)\nrouter.include_router(users_router)\nrouter.include_router(posts_router)\nrouter.include_router(tasks_router)\nrouter.include_router(tiers_router)\nrouter.include_router(rate_limits_router)\n"
  },
  {
    "path": "src/app/api/v1/login.py",
    "content": "from datetime import timedelta\nfrom typing import Annotated\n\nfrom fastapi import APIRouter, Depends, Request, Response\nfrom fastapi.security import OAuth2PasswordRequestForm\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...core.config import settings\nfrom ...core.db.database import async_get_db\nfrom ...core.exceptions.http_exceptions import UnauthorizedException\nfrom ...core.schemas import Token\nfrom ...core.security import (\n    ACCESS_TOKEN_EXPIRE_MINUTES,\n    authenticate_user,\n    create_access_token,\n    create_refresh_token,\n    verify_token,\n)\n\nrouter = APIRouter(tags=[\"login\"])\n\n\n@router.post(\"/login\", response_model=Token)\nasync def login_for_access_token(\n    response: Response,\n    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n) -> dict[str, str]:\n    user = await authenticate_user(username_or_email=form_data.username, password=form_data.password, db=db)\n    if not user:\n        raise UnauthorizedException(\"Wrong username, email or password.\")\n\n    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n    access_token = await create_access_token(data={\"sub\": user[\"username\"]}, expires_delta=access_token_expires)\n\n    refresh_token = await create_refresh_token(data={\"sub\": user[\"username\"]})\n    max_age = settings.REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60\n\n    response.set_cookie(\n        key=\"refresh_token\", value=refresh_token, httponly=True, secure=True, samesite=\"Lax\", max_age=max_age\n    )\n\n    return {\"access_token\": access_token, \"token_type\": \"bearer\"}\n\n\n@router.post(\"/refresh\")\nasync def refresh_access_token(request: Request, db: AsyncSession = Depends(async_get_db)) -> dict[str, str]:\n    refresh_token = request.cookies.get(\"refresh_token\")\n    if not refresh_token:\n        raise UnauthorizedException(\"Refresh token missing.\")\n\n    user_data = await verify_token(refresh_token, db)\n    if not user_data:\n        raise UnauthorizedException(\"Invalid refresh token.\")\n\n    new_access_token = await create_access_token(data={\"sub\": user_data.username_or_email})\n    return {\"access_token\": new_access_token, \"token_type\": \"bearer\"}\n"
  },
  {
    "path": "src/app/api/v1/logout.py",
    "content": "from fastapi import APIRouter, Depends, Response\nfrom jose import JWTError\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...core.db.database import async_get_db\nfrom ...core.exceptions.http_exceptions import UnauthorizedException\nfrom ...core.security import blacklist_token, oauth2_scheme\n\nrouter = APIRouter(tags=[\"login\"])\n\n\n@router.post(\"/logout\")\nasync def logout(\n    response: Response, access_token: str = Depends(oauth2_scheme), db: AsyncSession = Depends(async_get_db)\n) -> dict[str, str]:\n    try:\n        await blacklist_token(token=access_token, db=db)\n        response.delete_cookie(key=\"refresh_token\")\n\n        return {\"message\": \"Logged out successfully\"}\n\n    except JWTError:\n        raise UnauthorizedException(\"Invalid token.\")\n"
  },
  {
    "path": "src/app/api/v1/posts.py",
    "content": "from typing import Annotated, Any\n\nfrom fastapi import APIRouter, Depends, Request\nfrom fastcrud.paginated import PaginatedListResponse, compute_offset, paginated_response\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...api.dependencies import get_current_superuser, get_current_user\nfrom ...core.db.database import async_get_db\nfrom ...core.exceptions.http_exceptions import ForbiddenException, NotFoundException\nfrom ...core.utils.cache import cache\nfrom ...crud.crud_posts import crud_posts\nfrom ...crud.crud_users import crud_users\nfrom ...models.post import PostCreate, PostCreateInternal, PostRead, PostUpdate\nfrom ...models.user import UserRead\n\nrouter = APIRouter(tags=[\"posts\"])\n\n\n@router.post(\"/{username}/post\", response_model=PostRead, status_code=201)\nasync def write_post(\n    request: Request,\n    username: str,\n    post: PostCreate,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n) -> PostRead:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    if current_user[\"id\"] != db_user[\"id\"]:\n        raise ForbiddenException()\n\n    post_internal_dict = post.model_dump()\n    post_internal_dict[\"created_by_user_id\"] = db_user[\"id\"]\n\n    post_internal = PostCreateInternal(**post_internal_dict)\n    created_post: PostRead = await crud_posts.create(db=db, object=post_internal)\n    return created_post\n\n\n@router.get(\"/{username}/posts\", response_model=PaginatedListResponse[PostRead])\n@cache(\n    key_prefix=\"{username}_posts:page_{page}:items_per_page:{items_per_page}\",\n    resource_id_name=\"username\",\n    expiration=60,\n)\nasync def read_posts(\n    request: Request,\n    username: str,\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n    page: int = 1,\n    items_per_page: int = 10,\n) -> dict:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if not db_user:\n        raise NotFoundException(\"User not found\")\n\n    posts_data = await crud_posts.get_multi(\n        db=db,\n        offset=compute_offset(page, items_per_page),\n        limit=items_per_page,\n        schema_to_select=PostRead,\n        created_by_user_id=db_user[\"id\"],\n        is_deleted=False,\n    )\n\n    response: dict[str, Any] = paginated_response(crud_data=posts_data, page=page, items_per_page=items_per_page)\n    return response\n\n\n@router.get(\"/{username}/post/{id}\", response_model=PostRead)\n@cache(key_prefix=\"{username}_post_cache\", resource_id_name=\"id\")\nasync def read_post(\n    request: Request, username: str, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    db_post: PostRead | None = await crud_posts.get(\n        db=db, schema_to_select=PostRead, id=id, created_by_user_id=db_user[\"id\"], is_deleted=False\n    )\n    if db_post is None:\n        raise NotFoundException(\"Post not found\")\n\n    return db_post\n\n\n@router.patch(\"/{username}/post/{id}\")\n@cache(\"{username}_post_cache\", resource_id_name=\"id\", pattern_to_invalidate_extra=[\"{username}_posts:*\"])\nasync def patch_post(\n    request: Request,\n    username: str,\n    id: int,\n    values: PostUpdate,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n) -> dict[str, str]:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    if current_user[\"id\"] != db_user[\"id\"]:\n        raise ForbiddenException()\n\n    db_post = await crud_posts.get(db=db, schema_to_select=PostRead, id=id, is_deleted=False)\n    if db_post is None:\n        raise NotFoundException(\"Post not found\")\n\n    await crud_posts.update(db=db, object=values, id=id)\n    return {\"message\": \"Post updated\"}\n\n\n@router.delete(\"/{username}/post/{id}\")\n@cache(\"{username}_post_cache\", resource_id_name=\"id\", to_invalidate_extra={\"{username}_posts\": \"{username}\"})\nasync def erase_post(\n    request: Request,\n    username: str,\n    id: int,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n) -> dict[str, str]:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    if current_user[\"id\"] != db_user[\"id\"]:\n        raise ForbiddenException()\n\n    db_post = await crud_posts.get(db=db, schema_to_select=PostRead, id=id, is_deleted=False)\n    if db_post is None:\n        raise NotFoundException(\"Post not found\")\n\n    await crud_posts.delete(db=db, id=id)\n\n    return {\"message\": \"Post deleted\"}\n\n\n@router.delete(\"/{username}/db_post/{id}\", dependencies=[Depends(get_current_superuser)])\n@cache(\"{username}_post_cache\", resource_id_name=\"id\", to_invalidate_extra={\"{username}_posts\": \"{username}\"})\nasync def erase_db_post(\n    request: Request, username: str, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict[str, str]:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username, is_deleted=False)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    db_post = await crud_posts.get(db=db, schema_to_select=PostRead, id=id, is_deleted=False)\n    if db_post is None:\n        raise NotFoundException(\"Post not found\")\n\n    await crud_posts.db_delete(db=db, id=id)\n    return {\"message\": \"Post deleted from the database\"}\n"
  },
  {
    "path": "src/app/api/v1/rate_limits.py",
    "content": "from typing import Annotated, Any\n\nfrom fastapi import APIRouter, Depends, Request\nfrom fastcrud.paginated import PaginatedListResponse, compute_offset, paginated_response\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...api.dependencies import get_current_superuser\nfrom ...core.db.database import async_get_db\nfrom ...core.exceptions.http_exceptions import DuplicateValueException, NotFoundException, RateLimitException\nfrom ...crud.crud_rate_limit import crud_rate_limits\nfrom ...crud.crud_tier import crud_tiers\nfrom ...models.rate_limit import RateLimitCreate, RateLimitCreateInternal, RateLimitRead, RateLimitUpdate\n\nrouter = APIRouter(tags=[\"rate_limits\"])\n\n\n@router.post(\"/tier/{tier_name}/rate_limit\", dependencies=[Depends(get_current_superuser)], status_code=201)\nasync def write_rate_limit(\n    request: Request, tier_name: str, rate_limit: RateLimitCreate, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> RateLimitRead:\n    db_tier = await crud_tiers.get(db=db, name=tier_name)\n    if not db_tier:\n        raise NotFoundException(\"Tier not found\")\n\n    rate_limit_internal_dict = rate_limit.model_dump()\n    rate_limit_internal_dict[\"tier_id\"] = db_tier[\"id\"]\n\n    db_rate_limit = await crud_rate_limits.exists(db=db, name=rate_limit_internal_dict[\"name\"])\n    if db_rate_limit:\n        raise DuplicateValueException(\"Rate Limit Name not available\")\n\n    rate_limit_internal = RateLimitCreateInternal(**rate_limit_internal_dict)\n    created_rate_limit: RateLimitRead = await crud_rate_limits.create(db=db, object=rate_limit_internal)\n    return created_rate_limit\n\n\n@router.get(\"/tier/{tier_name}/rate_limits\", response_model=PaginatedListResponse[RateLimitRead])\nasync def read_rate_limits(\n    request: Request,\n    tier_name: str,\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n    page: int = 1,\n    items_per_page: int = 10,\n) -> dict:\n    db_tier = await crud_tiers.get(db=db, name=tier_name)\n    if not db_tier:\n        raise NotFoundException(\"Tier not found\")\n\n    rate_limits_data = await crud_rate_limits.get_multi(\n        db=db,\n        offset=compute_offset(page, items_per_page),\n        limit=items_per_page,\n        schema_to_select=RateLimitRead,\n        tier_id=db_tier[\"id\"],\n    )\n\n    response: dict[str, Any] = paginated_response(crud_data=rate_limits_data, page=page, items_per_page=items_per_page)\n    return response\n\n\n@router.get(\"/tier/{tier_name}/rate_limit/{id}\", response_model=RateLimitRead)\nasync def read_rate_limit(\n    request: Request, tier_name: str, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict:\n    db_tier = await crud_tiers.get(db=db, name=tier_name)\n    if not db_tier:\n        raise NotFoundException(\"Tier not found\")\n\n    db_rate_limit: dict | None = await crud_rate_limits.get(\n        db=db, schema_to_select=RateLimitRead, tier_id=db_tier[\"id\"], id=id\n    )\n    if db_rate_limit is None:\n        raise NotFoundException(\"Rate Limit not found\")\n\n    return db_rate_limit\n\n\n@router.patch(\"/tier/{tier_name}/rate_limit/{id}\", dependencies=[Depends(get_current_superuser)])\nasync def patch_rate_limit(\n    request: Request,\n    tier_name: str,\n    id: int,\n    values: RateLimitUpdate,\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n) -> dict[str, str]:\n    db_tier = await crud_tiers.get(db=db, name=tier_name)\n    if db_tier is None:\n        raise NotFoundException(\"Tier not found\")\n\n    db_rate_limit = await crud_rate_limits.get(db=db, schema_to_select=RateLimitRead, tier_id=db_tier[\"id\"], id=id)\n    if db_rate_limit is None:\n        raise NotFoundException(\"Rate Limit not found\")\n\n    db_rate_limit_path = await crud_rate_limits.exists(db=db, tier_id=db_tier[\"id\"], path=values.path)\n    if db_rate_limit_path:\n        raise DuplicateValueException(\"There is already a rate limit for this path\")\n\n    await crud_rate_limits.exists(db=db)\n    if db_rate_limit_path:\n        raise DuplicateValueException(\"There is already a rate limit with this name\")\n\n    await crud_rate_limits.update(db=db, object=values, id=db_rate_limit[\"id\"])\n    return {\"message\": \"Rate Limit updated\"}\n\n\n@router.delete(\"/tier/{tier_name}/rate_limit/{id}\", dependencies=[Depends(get_current_superuser)])\nasync def erase_rate_limit(\n    request: Request, tier_name: str, id: int, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict[str, str]:\n    db_tier = await crud_tiers.get(db=db, name=tier_name)\n    if not db_tier:\n        raise NotFoundException(\"Tier not found\")\n\n    db_rate_limit = await crud_rate_limits.get(db=db, schema_to_select=RateLimitRead, tier_id=db_tier[\"id\"], id=id)\n    if db_rate_limit is None:\n        raise NotFoundException(\"Rate Limit not found\")\n\n    await crud_rate_limits.delete(db=db, id=db_rate_limit[\"id\"])\n    return {\"message\": \"Rate Limit deleted\"}\n"
  },
  {
    "path": "src/app/api/v1/tasks.py",
    "content": "from typing import Any\n\nfrom arq.jobs import Job as ArqJob\nfrom fastapi import APIRouter, Depends\n\nfrom ...api.dependencies import rate_limiter\nfrom ...core.utils import queue\nfrom ...models.job import Job\n\nrouter = APIRouter(prefix=\"/tasks\", tags=[\"tasks\"])\n\n\n@router.post(\"/task\", response_model=Job, status_code=201, dependencies=[Depends(rate_limiter)])\nasync def create_task(message: str) -> dict[str, str]:\n    \"\"\"Create a new background task.\n\n    Parameters\n    ----------\n    message: str\n        The message or data to be processed by the task.\n\n    Returns\n    -------\n    dict[str, str]\n        A dictionary containing the ID of the created task.\n    \"\"\"\n    job = await queue.pool.enqueue_job(\"sample_background_task\", message)  # type: ignore\n    return {\"id\": job.job_id}\n\n\n@router.get(\"/task/{task_id}\")\nasync def get_task(task_id: str) -> dict[str, Any] | None:\n    \"\"\"Get information about a specific background task.\n\n    Parameters\n    ----------\n    task_id: str\n        The ID of the task.\n\n    Returns\n    -------\n    Optional[dict[str, Any]]\n        A dictionary containing information about the task if found, or None otherwise.\n    \"\"\"\n    job = ArqJob(task_id, queue.pool)\n    job_info: dict = await job.info()\n    return vars(job_info)\n"
  },
  {
    "path": "src/app/api/v1/tiers.py",
    "content": "from typing import Annotated, Any\n\nfrom fastapi import APIRouter, Depends, Request\nfrom fastcrud.paginated import PaginatedListResponse, compute_offset, paginated_response\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...api.dependencies import get_current_superuser\nfrom ...core.db.database import async_get_db\nfrom ...core.exceptions.http_exceptions import DuplicateValueException, NotFoundException\nfrom ...crud.crud_tier import crud_tiers\nfrom ...models.tier import TierCreate, TierCreateInternal, TierRead, TierUpdate\n\nrouter = APIRouter(tags=[\"tiers\"])\n\n\n@router.post(\"/tier\", dependencies=[Depends(get_current_superuser)], status_code=201)\nasync def write_tier(\n    request: Request, tier: TierCreate, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> TierRead:\n    tier_internal_dict = tier.model_dump()\n    db_tier = await crud_tiers.exists(db=db, name=tier_internal_dict[\"name\"])\n    if db_tier:\n        raise DuplicateValueException(\"Tier Name not available\")\n\n    tier_internal = TierCreateInternal(**tier_internal_dict)\n    created_tier: TierRead = await crud_tiers.create(db=db, object=tier_internal)\n    return created_tier\n\n\n@router.get(\"/tiers\", response_model=PaginatedListResponse[TierRead])\nasync def read_tiers(\n    request: Request, db: Annotated[AsyncSession, Depends(async_get_db)], page: int = 1, items_per_page: int = 10\n) -> dict:\n    tiers_data = await crud_tiers.get_multi(\n        db=db, offset=compute_offset(page, items_per_page), limit=items_per_page, schema_to_select=TierRead\n    )\n\n    response: dict[str, Any] = paginated_response(crud_data=tiers_data, page=page, items_per_page=items_per_page)\n    return response\n\n\n@router.get(\"/tier/{name}\", response_model=TierRead)\nasync def read_tier(request: Request, name: str, db: Annotated[AsyncSession, Depends(async_get_db)]) -> dict:\n    db_tier: TierRead | None = await crud_tiers.get(db=db, schema_to_select=TierRead, name=name)\n    if db_tier is None:\n        raise NotFoundException(\"Tier not found\")\n\n    return db_tier\n\n\n@router.patch(\"/tier/{name}\", dependencies=[Depends(get_current_superuser)])\nasync def patch_tier(\n    request: Request, values: TierUpdate, name: str, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict[str, str]:\n    db_tier = await crud_tiers.get(db=db, schema_to_select=TierRead, name=name)\n    if db_tier is None:\n        raise NotFoundException(\"Tier not found\")\n\n    await crud_tiers.update(db=db, object=values, name=name)\n    return {\"message\": \"Tier updated\"}\n\n\n@router.delete(\"/tier/{name}\", dependencies=[Depends(get_current_superuser)])\nasync def erase_tier(request: Request, name: str, db: Annotated[AsyncSession, Depends(async_get_db)]) -> dict[str, str]:\n    db_tier = await crud_tiers.get(db=db, schema_to_select=TierRead, name=name)\n    if db_tier is None:\n        raise NotFoundException(\"Tier not found\")\n\n    await crud_tiers.delete(db=db, name=name)\n    return {\"message\": \"Tier deleted\"}\n"
  },
  {
    "path": "src/app/api/v1/users.py",
    "content": "from typing import Annotated, Any\n\nfrom fastapi import APIRouter, Depends, Request\nfrom fastcrud.paginated import PaginatedListResponse, compute_offset, paginated_response\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...api.dependencies import get_current_superuser, get_current_user\nfrom ...core.db.database import async_get_db\nfrom ...core.exceptions.http_exceptions import DuplicateValueException, ForbiddenException, NotFoundException\nfrom ...core.security import blacklist_token, get_password_hash, oauth2_scheme\nfrom ...crud.crud_rate_limit import crud_rate_limits\nfrom ...crud.crud_tier import crud_tiers\nfrom ...crud.crud_users import crud_users\nfrom ...models.tier import Tier, TierRead\nfrom ...models.user import UserCreate, UserCreateInternal, UserRead, UserTierUpdate, UserUpdate\n\nrouter = APIRouter(tags=[\"users\"])\n\n\n@router.post(\"/user\", response_model=UserRead, status_code=201)\nasync def write_user(\n    request: Request, user: UserCreate, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> UserRead:\n    email_row = await crud_users.exists(db=db, email=user.email)\n    if email_row:\n        raise DuplicateValueException(\"Email is already registered\")\n\n    username_row = await crud_users.exists(db=db, username=user.username)\n    if username_row:\n        raise DuplicateValueException(\"Username not available\")\n\n    user_internal_dict = user.model_dump()\n    user_internal_dict[\"hashed_password\"] = get_password_hash(password=user_internal_dict[\"password\"])\n    del user_internal_dict[\"password\"]\n\n    user_internal = UserCreateInternal(**user_internal_dict)\n    created_user: UserRead = await crud_users.create(db=db, object=user_internal)\n    return created_user\n\n\n@router.get(\"/users\", response_model=PaginatedListResponse[UserRead])\nasync def read_users(\n    request: Request, db: Annotated[AsyncSession, Depends(async_get_db)], page: int = 1, items_per_page: int = 10\n) -> dict:\n    users_data = await crud_users.get_multi(\n        db=db,\n        offset=compute_offset(page, items_per_page),\n        limit=items_per_page,\n        schema_to_select=UserRead,\n        is_deleted=False,\n    )\n\n    response: dict[str, Any] = paginated_response(crud_data=users_data, page=page, items_per_page=items_per_page)\n    return response\n\n\n@router.get(\"/user/me/\", response_model=UserRead)\nasync def read_users_me(request: Request, current_user: Annotated[UserRead, Depends(get_current_user)]) -> UserRead:\n    return current_user\n\n\n@router.get(\"/user/{username}\", response_model=UserRead)\nasync def read_user(request: Request, username: str, db: Annotated[AsyncSession, Depends(async_get_db)]) -> dict:\n    db_user: UserRead | None = await crud_users.get(\n        db=db, schema_to_select=UserRead, username=username, is_deleted=False\n    )\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    return db_user\n\n\n@router.patch(\"/user/{username}\")\nasync def patch_user(\n    request: Request,\n    values: UserUpdate,\n    username: str,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n) -> dict[str, str]:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    if db_user[\"username\"] != current_user[\"username\"]:\n        raise ForbiddenException()\n\n    if values.username != db_user[\"username\"]:\n        existing_username = await crud_users.exists(db=db, username=values.username)\n        if existing_username:\n            raise DuplicateValueException(\"Username not available\")\n\n    if values.email != db_user[\"email\"]:\n        existing_email = await crud_users.exists(db=db, email=values.email)\n        if existing_email:\n            raise DuplicateValueException(\"Email is already registered\")\n\n    await crud_users.update(db=db, object=values, username=username)\n    return {\"message\": \"User updated\"}\n\n\n@router.delete(\"/user/{username}\")\nasync def erase_user(\n    request: Request,\n    username: str,\n    current_user: Annotated[UserRead, Depends(get_current_user)],\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n    token: str = Depends(oauth2_scheme),\n) -> dict[str, str]:\n    db_user = await crud_users.get(db=db, schema_to_select=UserRead, username=username)\n    if not db_user:\n        raise NotFoundException(\"User not found\")\n\n    if username != current_user[\"username\"]:\n        raise ForbiddenException()\n\n    await crud_users.delete(db=db, username=username)\n    await blacklist_token(token=token, db=db)\n    return {\"message\": \"User deleted\"}\n\n\n@router.delete(\"/db_user/{username}\", dependencies=[Depends(get_current_superuser)])\nasync def erase_db_user(\n    request: Request,\n    username: str,\n    db: Annotated[AsyncSession, Depends(async_get_db)],\n    token: str = Depends(oauth2_scheme),\n) -> dict[str, str]:\n    db_user = await crud_users.exists(db=db, username=username)\n    if not db_user:\n        raise NotFoundException(\"User not found\")\n\n    await crud_users.db_delete(db=db, username=username)\n    await blacklist_token(token=token, db=db)\n    return {\"message\": \"User deleted from the database\"}\n\n\n@router.get(\"/user/{username}/rate_limits\", dependencies=[Depends(get_current_superuser)])\nasync def read_user_rate_limits(\n    request: Request, username: str, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict[str, Any]:\n    db_user: dict | None = await crud_users.get(db=db, username=username, schema_to_select=UserRead)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    if db_user[\"tier_id\"] is None:\n        db_user[\"tier_rate_limits\"] = []\n        return db_user\n\n    db_tier = await crud_tiers.get(db=db, id=db_user[\"tier_id\"])\n    if db_tier is None:\n        raise NotFoundException(\"Tier not found\")\n\n    db_rate_limits = await crud_rate_limits.get_multi(db=db, tier_id=db_tier[\"id\"])\n\n    db_user[\"tier_rate_limits\"] = db_rate_limits[\"data\"]\n\n    return db_user\n\n\n@router.get(\"/user/{username}/tier\")\nasync def read_user_tier(\n    request: Request, username: str, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict | None:\n    db_user = await crud_users.get(db=db, username=username, schema_to_select=UserRead)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    db_tier = await crud_tiers.exists(db=db, id=db_user[\"tier_id\"])\n    if not db_tier:\n        raise NotFoundException(\"Tier not found\")\n\n    joined: dict = await crud_users.get_joined(\n        db=db,\n        join_model=Tier,\n        join_prefix=\"tier_\",\n        schema_to_select=UserRead,\n        join_schema_to_select=TierRead,\n        username=username,\n    )\n\n    return joined\n\n\n@router.patch(\"/user/{username}/tier\", dependencies=[Depends(get_current_superuser)])\nasync def patch_user_tier(\n    request: Request, username: str, values: UserTierUpdate, db: Annotated[AsyncSession, Depends(async_get_db)]\n) -> dict[str, str]:\n    db_user = await crud_users.get(db=db, username=username, schema_to_select=UserRead)\n    if db_user is None:\n        raise NotFoundException(\"User not found\")\n\n    db_tier = await crud_tiers.get(db=db, id=values.tier_id)\n    if db_tier is None:\n        raise NotFoundException(\"Tier not found\")\n\n    await crud_users.update(db=db, object=values, username=username)\n    return {\"message\": f\"User {db_user['name']} Tier updated\"}\n"
  },
  {
    "path": "src/app/core/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/core/config.py",
    "content": "import os\nfrom enum import Enum\n\nfrom pydantic_settings import BaseSettings\nfrom starlette.config import Config\n\ncurrent_file_dir = os.path.dirname(os.path.realpath(__file__))\nenv_path = os.path.join(current_file_dir, \"..\", \"..\", \".env\")\nconfig = Config(env_path)\n\n\nclass AppSettings(BaseSettings):\n    APP_NAME: str = config(\"APP_NAME\", default=\"FastAPI app\")\n    APP_DESCRIPTION: str | None = config(\"APP_DESCRIPTION\", default=None)\n    APP_VERSION: str | None = config(\"APP_VERSION\", default=None)\n    LICENSE_NAME: str | None = config(\"LICENSE\", default=None)\n    CONTACT_NAME: str | None = config(\"CONTACT_NAME\", default=None)\n    CONTACT_EMAIL: str | None = config(\"CONTACT_EMAIL\", default=None)\n\n\nclass CryptSettings(BaseSettings):\n    SECRET_KEY: str = config(\"SECRET_KEY\")\n    ALGORITHM: str = config(\"ALGORITHM\", default=\"HS256\")\n    ACCESS_TOKEN_EXPIRE_MINUTES: int = config(\"ACCESS_TOKEN_EXPIRE_MINUTES\", default=30)\n    REFRESH_TOKEN_EXPIRE_DAYS: int = config(\"REFRESH_TOKEN_EXPIRE_DAYS\", default=7)\n\n\nclass DatabaseSettings(BaseSettings):\n    pass\n\n\nclass SQLiteSettings(DatabaseSettings):\n    SQLITE_URI: str = config(\"SQLITE_URI\", default=\"./sql_app.db\")\n    SQLITE_SYNC_PREFIX: str = config(\"SQLITE_SYNC_PREFIX\", default=\"sqlite:///\")\n    SQLITE_ASYNC_PREFIX: str = config(\"SQLITE_ASYNC_PREFIX\", default=\"sqlite+aiosqlite:///\")\n\n\nclass PostgresSettings(DatabaseSettings):\n    POSTGRES_USER: str = config(\"POSTGRES_USER\", default=\"postgres\")\n    POSTGRES_PASSWORD: str = config(\"POSTGRES_PASSWORD\", default=\"postgres\")\n    POSTGRES_SERVER: str = config(\"POSTGRES_SERVER\", default=\"localhost\")\n    POSTGRES_PORT: int = config(\"POSTGRES_PORT\", default=5432)\n    POSTGRES_DB: str = config(\"POSTGRES_DB\", default=\"postgres\")\n    POSTGRES_SYNC_PREFIX: str = config(\"POSTGRES_SYNC_PREFIX\", default=\"postgresql://\")\n    POSTGRES_ASYNC_PREFIX: str = config(\"POSTGRES_ASYNC_PREFIX\", default=\"postgresql+asyncpg://\")\n    POSTGRES_URI: str = f\"{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_SERVER}:{POSTGRES_PORT}/{POSTGRES_DB}\"\n    POSTGRES_URL: str | None = config(\"POSTGRES_URL\", default=None)\n\n\nclass FirstUserSettings(BaseSettings):\n    ADMIN_NAME: str = config(\"ADMIN_NAME\", default=\"admin\")\n    ADMIN_EMAIL: str = config(\"ADMIN_EMAIL\", default=\"admin@admin.com\")\n    ADMIN_USERNAME: str = config(\"ADMIN_USERNAME\", default=\"admin\")\n    ADMIN_PASSWORD: str = config(\"ADMIN_PASSWORD\", default=\"!Ch4ng3Th1sP4ssW0rd!\")\n\n\nclass TestSettings(BaseSettings):\n    TEST_NAME: str = config(\"TEST_NAME\", default=\"Tester User\")\n    TEST_EMAIL: str = config(\"TEST_EMAIL\", default=\"test@tester.com\")\n    TEST_USERNAME: str = config(\"TEST_USERNAME\", default=\"testeruser\")\n    TEST_PASSWORD: str = config(\"TEST_PASSWORD\", default=\"Str1ng$t\")\n\n\nclass RedisCacheSettings(BaseSettings):\n    REDIS_CACHE_HOST: str = config(\"REDIS_CACHE_HOST\", default=\"localhost\")\n    REDIS_CACHE_PORT: int = config(\"REDIS_CACHE_PORT\", default=6379)\n    REDIS_CACHE_URL: str = f\"redis://{REDIS_CACHE_HOST}:{REDIS_CACHE_PORT}\"\n\n\nclass ClientSideCacheSettings(BaseSettings):\n    CLIENT_CACHE_MAX_AGE: int = config(\"CLIENT_CACHE_MAX_AGE\", default=60)\n\n\nclass RedisQueueSettings(BaseSettings):\n    REDIS_QUEUE_HOST: str = config(\"REDIS_QUEUE_HOST\", default=\"localhost\")\n    REDIS_QUEUE_PORT: int = config(\"REDIS_QUEUE_PORT\", default=6379)\n\n\nclass RedisRateLimiterSettings(BaseSettings):\n    REDIS_RATE_LIMIT_HOST: str = config(\"REDIS_RATE_LIMIT_HOST\", default=\"localhost\")\n    REDIS_RATE_LIMIT_PORT: int = config(\"REDIS_RATE_LIMIT_PORT\", default=6379)\n    REDIS_RATE_LIMIT_URL: str = f\"redis://{REDIS_RATE_LIMIT_HOST}:{REDIS_RATE_LIMIT_PORT}\"\n\n\nclass DefaultRateLimitSettings(BaseSettings):\n    DEFAULT_RATE_LIMIT_LIMIT: int = config(\"DEFAULT_RATE_LIMIT_LIMIT\", default=10)\n    DEFAULT_RATE_LIMIT_PERIOD: int = config(\"DEFAULT_RATE_LIMIT_PERIOD\", default=3600)\n\n\nclass EnvironmentOption(Enum):\n    LOCAL = \"local\"\n    STAGING = \"staging\"\n    PRODUCTION = \"production\"\n\n\nclass DBOption(Enum):\n    POSTGRES = \"postgres\"\n    SQLITE = \"sqlite\"\n\n\nclass EnvironmentSettings(BaseSettings):\n    ENVIRONMENT: EnvironmentOption = config(\"ENVIRONMENT\", default=\"local\")\n    DB_ENGINE: DBOption = config(\"DB_ENGINE\", default=\"sqlite\")\n\n\ndb_type = PostgresSettings\nif config(\"DB_ENGINE\", default=\"sqlite\") == \"sqlite\":\n    db_type = SQLiteSettings\n\n\nclass Settings(\n    AppSettings,\n    db_type,\n    CryptSettings,\n    FirstUserSettings,\n    TestSettings,\n    RedisCacheSettings,\n    ClientSideCacheSettings,\n    RedisQueueSettings,\n    RedisRateLimiterSettings,\n    DefaultRateLimitSettings,\n    EnvironmentSettings,\n):\n    pass\n\n\nsettings = Settings()\n"
  },
  {
    "path": "src/app/core/db/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/core/db/crud_token_blacklist.py",
    "content": "from fastcrud import FastCRUD\n\nfrom ..db.token_blacklist import TokenBlacklist\nfrom ..schemas import TokenBlacklistCreate, TokenBlacklistUpdate\n\nCRUDTokenBlacklist = FastCRUD[TokenBlacklist, TokenBlacklistCreate, TokenBlacklistUpdate, TokenBlacklistUpdate, None]\ncrud_token_blacklist = CRUDTokenBlacklist(TokenBlacklist)\n"
  },
  {
    "path": "src/app/core/db/database.py",
    "content": "from sqlalchemy.ext.asyncio import create_async_engine\nfrom sqlalchemy.ext.asyncio.session import AsyncSession\nfrom sqlalchemy.orm import sessionmaker\n\nfrom ..config import settings, DBOption\n\nif settings.DB_ENGINE == DBOption.SQLITE:\n    DATABASE_URI = settings.SQLITE_URI\n    DATABASE_PREFIX = settings.SQLITE_ASYNC_PREFIX\n    DATABASE_URL = f\"{DATABASE_PREFIX}{DATABASE_URI}\"\nif settings.DB_ENGINE == DBOption.POSTGRES:\n    DATABASE_URI = settings.POSTGRES_URI\n    DATABASE_PREFIX = settings.POSTGRES_ASYNC_PREFIX\n    DATABASE_URL = f\"{DATABASE_PREFIX}{DATABASE_URI}\"\n\nasync_engine = create_async_engine(DATABASE_URL, echo=False, future=True)\n\nlocal_session = sessionmaker(bind=async_engine, class_=AsyncSession, expire_on_commit=False)\n\n\nasync def async_get_db() -> AsyncSession:\n    async_session = local_session\n    async with async_session() as db:\n        yield db\n"
  },
  {
    "path": "src/app/core/db/models.py",
    "content": "import uuid as uuid_pkg\nfrom datetime import UTC, datetime\n\nfrom sqlalchemy import Boolean, Column, DateTime, text\nfrom sqlalchemy.dialects.postgresql import UUID\n\n\nclass UUIDMixin:\n    uuid: uuid_pkg.UUID = Column(\n        UUID, primary_key=True, default=uuid_pkg.uuid4, server_default=text(\"gen_random_uuid()\")\n    )\n\n\nclass TimestampMixin:\n    created_at: datetime = Column(DateTime, default=datetime.now(UTC), server_default=text(\"current_timestamp(0)\"))\n    updated_at: datetime = Column(\n        DateTime, nullable=True, onupdate=datetime.now(UTC), server_default=text(\"current_timestamp(0)\")\n    )\n\n\nclass SoftDeleteMixin:\n    deleted_at: datetime = Column(DateTime, nullable=True)\n    is_deleted: bool = Column(Boolean, default=False)\n"
  },
  {
    "path": "src/app/core/db/token_blacklist.py",
    "content": "from datetime import datetime\nfrom sqlmodel import SQLModel, Field\n\nclass TokenBlacklist(SQLModel, table=True):\n    id: int = Field(default=None, primary_key=True, nullable=False)\n    token: str = Field(index=True, nullable=False, unique=True)\n    expires_at: datetime = Field(nullable=False)\n"
  },
  {
    "path": "src/app/core/exceptions/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/core/exceptions/cache_exceptions.py",
    "content": "class CacheIdentificationInferenceError(Exception):\n    def __init__(self, message: str = \"Could not infer id for resource being cached.\") -> None:\n        self.message = message\n        super().__init__(self.message)\n\n\nclass InvalidRequestError(Exception):\n    def __init__(self, message: str = \"Type of request not supported.\") -> None:\n        self.message = message\n        super().__init__(self.message)\n\n\nclass MissingClientError(Exception):\n    def __init__(self, message: str = \"Client is None.\") -> None:\n        self.message = message\n        super().__init__(self.message)\n"
  },
  {
    "path": "src/app/core/exceptions/http_exceptions.py",
    "content": "# ruff: noqa\nfrom fastcrud.exceptions.http_exceptions import (\n    CustomException,\n    BadRequestException,\n    NotFoundException,\n    ForbiddenException,\n    UnauthorizedException,\n    UnprocessableEntityException,\n    DuplicateValueException,\n    RateLimitException,\n)\n"
  },
  {
    "path": "src/app/core/logger.py",
    "content": "import logging\nimport os\nfrom logging.handlers import RotatingFileHandler\n\nLOG_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"logs\")\nif not os.path.exists(LOG_DIR):\n    os.makedirs(LOG_DIR)\n\nLOG_FILE_PATH = os.path.join(LOG_DIR, \"app.log\")\n\nLOGGING_LEVEL = logging.INFO\nLOGGING_FORMAT = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n\nlogging.basicConfig(level=LOGGING_LEVEL, format=LOGGING_FORMAT)\n\nfile_handler = RotatingFileHandler(LOG_FILE_PATH, maxBytes=10485760, backupCount=5)\nfile_handler.setLevel(LOGGING_LEVEL)\nfile_handler.setFormatter(logging.Formatter(LOGGING_FORMAT))\n\nlogging.getLogger(\"\").addHandler(file_handler)\n"
  },
  {
    "path": "src/app/core/schemas.py",
    "content": "import uuid as uuid_pkg\nfrom datetime import UTC, datetime\nfrom typing import Any\n\nfrom pydantic import BaseModel, Field, field_serializer\n\n\nclass HealthCheck(BaseModel):\n    name: str\n    version: str\n    description: str\n\n\n# -------------- mixins --------------\nclass UUIDSchema(BaseModel):\n    uuid: uuid_pkg.UUID = Field(default_factory=uuid_pkg.uuid4)\n\n\nclass TimestampSchema(BaseModel):\n    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC).replace(tzinfo=None))\n    updated_at: datetime = Field(default=None)\n\n    @field_serializer(\"created_at\")\n    def serialize_dt(self, created_at: datetime | None, _info: Any) -> str | None:\n        if created_at is not None:\n            return created_at.isoformat()\n\n        return None\n\n    @field_serializer(\"updated_at\")\n    def serialize_updated_at(self, updated_at: datetime | None, _info: Any) -> str | None:\n        if updated_at is not None:\n            return updated_at.isoformat()\n\n        return None\n\n\nclass PersistentDeletion(BaseModel):\n    deleted_at: datetime | None = Field(default=None)\n    is_deleted: bool = False\n\n    @field_serializer(\"deleted_at\")\n    def serialize_dates(self, deleted_at: datetime | None, _info: Any) -> str | None:\n        if deleted_at is not None:\n            return deleted_at.isoformat()\n\n        return None\n\n\n# -------------- token --------------\nclass Token(BaseModel):\n    access_token: str\n    token_type: str\n\n\nclass TokenData(BaseModel):\n    username_or_email: str\n\n\nclass TokenBlacklistBase(BaseModel):\n    token: str\n    expires_at: datetime\n\n\nclass TokenBlacklistCreate(TokenBlacklistBase):\n    pass\n\n\nclass TokenBlacklistUpdate(TokenBlacklistBase):\n    pass\n"
  },
  {
    "path": "src/app/core/security.py",
    "content": "from datetime import UTC, datetime, timedelta\nfrom typing import Any, Literal\n\nimport bcrypt\nfrom fastapi.security import OAuth2PasswordBearer\nfrom jose import JWTError, jwt\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ..crud.crud_users import crud_users\nfrom .config import settings\nfrom .db.crud_token_blacklist import crud_token_blacklist\nfrom .schemas import TokenBlacklistCreate, TokenData\n\nSECRET_KEY = settings.SECRET_KEY\nALGORITHM = settings.ALGORITHM\nACCESS_TOKEN_EXPIRE_MINUTES = settings.ACCESS_TOKEN_EXPIRE_MINUTES\nREFRESH_TOKEN_EXPIRE_DAYS = settings.REFRESH_TOKEN_EXPIRE_DAYS\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"/api/v1/login\")\n\n\nasync def verify_password(plain_password: str, hashed_password: str) -> bool:\n    correct_password: bool = bcrypt.checkpw(plain_password.encode(), hashed_password.encode())\n    return correct_password\n\n\ndef get_password_hash(password: str) -> str:\n    hashed_password: str = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()\n    return hashed_password\n\n\nasync def authenticate_user(username_or_email: str, password: str, db: AsyncSession) -> dict[str, Any] | Literal[False]:\n    if \"@\" in username_or_email:\n        db_user: dict | None = await crud_users.get(db=db, email=username_or_email, is_deleted=False)\n    else:\n        db_user = await crud_users.get(db=db, username=username_or_email, is_deleted=False)\n\n    if not db_user:\n        return False\n\n    elif not await verify_password(password, db_user[\"hashed_password\"]):\n        return False\n\n    return db_user\n\n\nasync def create_access_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:\n    to_encode = data.copy()\n    if expires_delta:\n        expire = datetime.now(UTC).replace(tzinfo=None) + expires_delta\n    else:\n        expire = datetime.now(UTC).replace(tzinfo=None) + timedelta(minutes=15)\n    to_encode.update({\"exp\": expire})\n    encoded_jwt: str = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n    return encoded_jwt\n\n\nasync def create_refresh_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:\n    to_encode = data.copy()\n    if expires_delta:\n        expire = datetime.now(UTC).replace(tzinfo=None) + expires_delta\n    else:\n        expire = datetime.now(UTC).replace(tzinfo=None) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)\n    to_encode.update({\"exp\": expire})\n    encoded_jwt: str = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n    return encoded_jwt\n\n\nasync def verify_token(token: str, db: AsyncSession) -> TokenData | None:\n    \"\"\"Verify a JWT token and return TokenData if valid.\n\n    Parameters\n    ----------\n    token: str\n        The JWT token to be verified.\n    db: AsyncSession\n        Database session for performing database operations.\n\n    Returns\n    -------\n    TokenData | None\n        TokenData instance if the token is valid, None otherwise.\n    \"\"\"\n    is_blacklisted = await crud_token_blacklist.exists(db, token=token)\n    if is_blacklisted:\n        return None\n\n    try:\n        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n        username_or_email: str = payload.get(\"sub\")\n        if username_or_email is None:\n            return None\n        return TokenData(username_or_email=username_or_email)\n\n    except JWTError:\n        return None\n\n\nasync def blacklist_token(token: str, db: AsyncSession) -> None:\n    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n    expires_at = datetime.fromtimestamp(payload.get(\"exp\"))\n    await crud_token_blacklist.create(db, object=TokenBlacklistCreate(**{\"token\": token, \"expires_at\": expires_at}))\n"
  },
  {
    "path": "src/app/core/setup.py",
    "content": "from collections.abc import AsyncGenerator, Callable\nfrom contextlib import _AsyncGeneratorContextManager, asynccontextmanager\nfrom typing import Any\n\nimport anyio\nimport fastapi\nimport redis.asyncio as redis\nfrom arq import create_pool\nfrom arq.connections import RedisSettings\nfrom fastapi import APIRouter, Depends, FastAPI\nfrom fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html\nfrom fastapi.openapi.utils import get_openapi\nfrom sqlmodel import SQLModel\n\nfrom ..api.dependencies import get_current_superuser\nfrom ..middleware.client_cache_middleware import ClientCacheMiddleware\nfrom .config import (\n    AppSettings,\n    ClientSideCacheSettings,\n    DatabaseSettings,\n    EnvironmentOption,\n    EnvironmentSettings,\n    RedisCacheSettings,\n    RedisQueueSettings,\n    RedisRateLimiterSettings,\n    settings,\n)\nfrom .db.database import async_engine as engine\nfrom .utils import cache, queue, rate_limit\nfrom ..models import *\n\n# -------------- database --------------\nasync def create_tables() -> None:\n    async with engine.begin() as conn:\n        await conn.run_sync(SQLModel.metadata.create_all)\n\n\n# -------------- cache --------------\nasync def create_redis_cache_pool() -> None:\n    cache.pool = redis.ConnectionPool.from_url(settings.REDIS_CACHE_URL)\n    cache.client = redis.Redis.from_pool(cache.pool)  # type: ignore\n\n\nasync def close_redis_cache_pool() -> None:\n    await cache.client.aclose()  # type: ignore\n\n\n# -------------- queue --------------\nasync def create_redis_queue_pool() -> None:\n    queue.pool = await create_pool(RedisSettings(host=settings.REDIS_QUEUE_HOST, port=settings.REDIS_QUEUE_PORT))\n\n\nasync def close_redis_queue_pool() -> None:\n    await queue.pool.aclose()  # type: ignore\n\n\n# -------------- rate limit --------------\nasync def create_redis_rate_limit_pool() -> None:\n    rate_limit.pool = redis.ConnectionPool.from_url(settings.REDIS_RATE_LIMIT_URL)\n    rate_limit.client = redis.Redis.from_pool(rate_limit.pool)  # type: ignore\n\n\nasync def close_redis_rate_limit_pool() -> None:\n    await rate_limit.client.aclose()  # type: ignore\n\n\n# -------------- application --------------\nasync def set_threadpool_tokens(number_of_tokens: int = 100) -> None:\n    limiter = anyio.to_thread.current_default_thread_limiter()\n    limiter.total_tokens = number_of_tokens\n\n\ndef lifespan_factory(\n    settings: (\n        DatabaseSettings\n        | RedisCacheSettings\n        | AppSettings\n        | ClientSideCacheSettings\n        | RedisQueueSettings\n        | RedisRateLimiterSettings\n        | EnvironmentSettings\n    ),\n    create_tables_on_start: bool = True,\n) -> Callable[[FastAPI], _AsyncGeneratorContextManager[Any]]:\n    \"\"\"Factory to create a lifespan async context manager for a FastAPI app.\"\"\"\n\n    @asynccontextmanager\n    async def lifespan(app: FastAPI) -> AsyncGenerator:\n        await set_threadpool_tokens()\n\n        if isinstance(settings, DatabaseSettings) and create_tables_on_start:\n            await create_tables()\n\n        if settings.ENVIRONMENT != EnvironmentOption.LOCAL:\n            if isinstance(settings, RedisCacheSettings):\n                await create_redis_cache_pool()\n\n            if isinstance(settings, RedisQueueSettings):\n                await create_redis_queue_pool()\n\n            if isinstance(settings, RedisRateLimiterSettings):\n                await create_redis_rate_limit_pool()\n\n        yield\n\n        if isinstance(settings, RedisCacheSettings):\n            await close_redis_cache_pool()\n\n        if isinstance(settings, RedisQueueSettings):\n            await close_redis_queue_pool()\n\n        if isinstance(settings, RedisRateLimiterSettings):\n            await close_redis_rate_limit_pool()\n\n    return lifespan\n\n\n# -------------- application --------------\ndef create_application(\n    router: APIRouter,\n    settings: (\n        DatabaseSettings\n        | RedisCacheSettings\n        | AppSettings\n        | ClientSideCacheSettings\n        | RedisQueueSettings\n        | RedisRateLimiterSettings\n        | EnvironmentSettings\n    ),\n    create_tables_on_start: bool = True,\n    **kwargs: Any,\n) -> FastAPI:\n    \"\"\"Creates and configures a FastAPI application based on the provided settings.\n\n    This function initializes a FastAPI application and configures it with various settings\n    and handlers based on the type of the `settings` object provided.\n\n    Parameters\n    ----------\n    router : APIRouter\n        The APIRouter object containing the routes to be included in the FastAPI application.\n\n    settings\n        An instance representing the settings for configuring the FastAPI application.\n        It determines the configuration applied:\n\n        - AppSettings: Configures basic app metadata like name, description, contact, and license info.\n        - DatabaseSettings: Adds event handlers for initializing database tables during startup.\n        - RedisCacheSettings: Sets up event handlers for creating and closing a Redis cache pool.\n        - ClientSideCacheSettings: Integrates middleware for client-side caching.\n        - RedisQueueSettings: Sets up event handlers for creating and closing a Redis queue pool.\n        - RedisRateLimiterSettings: Sets up event handlers for creating and closing a Redis rate limiter pool.\n        - EnvironmentSettings: Conditionally sets documentation URLs and integrates custom routes for API documentation\n          based on the environment type.\n\n    create_tables_on_start : bool\n        A flag to indicate whether to create database tables on application startup.\n        Defaults to True.\n\n    **kwargs\n        Additional keyword arguments passed directly to the FastAPI constructor.\n\n    Returns\n    -------\n    FastAPI\n        A fully configured FastAPI application instance.\n\n    The function configures the FastAPI application with different features and behaviors\n    based on the provided settings. It includes setting up database connections, Redis pools\n    for caching, queue, and rate limiting, client-side caching, and customizing the API documentation\n    based on the environment settings.\n    \"\"\"\n    # --- before creating application ---\n    if isinstance(settings, AppSettings):\n        to_update = {\n            \"title\": settings.APP_NAME,\n            \"description\": settings.APP_DESCRIPTION,\n            \"contact\": {\"name\": settings.CONTACT_NAME, \"email\": settings.CONTACT_EMAIL},\n            \"license_info\": {\"name\": settings.LICENSE_NAME},\n        }\n        kwargs.update(to_update)\n\n    if isinstance(settings, EnvironmentSettings):\n        kwargs.update({\"docs_url\": None, \"redoc_url\": None, \"openapi_url\": None})\n\n    lifespan = lifespan_factory(settings, create_tables_on_start=create_tables_on_start)\n\n    application = FastAPI(lifespan=lifespan, **kwargs)\n    application.include_router(router)\n\n    if isinstance(settings, ClientSideCacheSettings):\n        application.add_middleware(ClientCacheMiddleware, max_age=settings.CLIENT_CACHE_MAX_AGE)\n\n    if isinstance(settings, EnvironmentSettings):\n        if settings.ENVIRONMENT != EnvironmentOption.PRODUCTION:\n            docs_router = APIRouter()\n            if settings.ENVIRONMENT != EnvironmentOption.LOCAL:\n                docs_router = APIRouter(dependencies=[Depends(get_current_superuser)])\n\n            @docs_router.get(\"/docs\", include_in_schema=False)\n            async def get_swagger_documentation() -> fastapi.responses.HTMLResponse:\n                return get_swagger_ui_html(openapi_url=\"/openapi.json\", title=\"docs\")\n\n            @docs_router.get(\"/redoc\", include_in_schema=False)\n            async def get_redoc_documentation() -> fastapi.responses.HTMLResponse:\n                return get_redoc_html(openapi_url=\"/openapi.json\", title=\"docs\")\n\n            @docs_router.get(\"/openapi.json\", include_in_schema=False)\n            async def openapi() -> dict[str, Any]:\n                out: dict = get_openapi(title=application.title, version=application.version, routes=application.routes)\n                return out\n\n            application.include_router(docs_router)\n\n        return application\n"
  },
  {
    "path": "src/app/core/utils/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/core/utils/cache.py",
    "content": "import functools\nimport json\nimport re\nfrom collections.abc import Callable\nfrom typing import Any\n\nfrom fastapi import Request, Response\nfrom fastapi.encoders import jsonable_encoder\nfrom redis.asyncio import ConnectionPool, Redis\n\nfrom ..exceptions.cache_exceptions import CacheIdentificationInferenceError, InvalidRequestError, MissingClientError\n\npool: ConnectionPool | None = None\nclient: Redis | None = None\n\n\ndef _infer_resource_id(kwargs: dict[str, Any], resource_id_type: type | tuple[type, ...]) -> int | str:\n    \"\"\"Infer the resource ID from a dictionary of keyword arguments.\n\n    Parameters\n    ----------\n    kwargs: Dict[str, Any]\n        A dictionary of keyword arguments.\n    resource_id_type: Union[type, Tuple[type, ...]]\n        The expected type of the resource ID, which can be integer (int) or a string (str).\n\n    Returns\n    -------\n    Union[None, int, str]\n        The inferred resource ID. If it cannot be inferred or does not match the expected type, it returns None.\n\n    Note\n    ----\n        - When `resource_id_type` is `int`, the function looks for an argument with the key 'id'.\n        - When `resource_id_type` is `str`, it attempts to infer the resource ID as a string.\n    \"\"\"\n    resource_id: int | str | None = None\n    for arg_name, arg_value in kwargs.items():\n        if isinstance(arg_value, resource_id_type):\n            if (resource_id_type is int) and (\"id\" in arg_name):\n                resource_id = arg_value\n\n            elif (resource_id_type is int) and (\"id\" not in arg_name):\n                pass\n\n            elif resource_id_type is str:\n                resource_id = arg_value\n\n    if resource_id is None:\n        raise CacheIdentificationInferenceError\n\n    return resource_id\n\n\ndef _extract_data_inside_brackets(input_string: str) -> list[str]:\n    \"\"\"Extract data inside curly brackets from a given string using regular expressions.\n\n    Parameters\n    ----------\n    input_string: str\n        The input string in which to find data enclosed within curly brackets.\n\n    Returns\n    -------\n    List[str]\n        A list of strings containing the data found inside the curly brackets within the input string.\n\n    Example\n    -------\n    >>> _extract_data_inside_brackets(\"The {quick} brown {fox} jumps over the {lazy} dog.\")\n    ['quick', 'fox', 'lazy']\n    \"\"\"\n    data_inside_brackets = re.findall(r\"{(.*?)}\", input_string)\n    return data_inside_brackets\n\n\ndef _construct_data_dict(data_inside_brackets: list[str], kwargs: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Construct a dictionary based on data inside brackets and keyword arguments.\n\n    Parameters\n    ----------\n    data_inside_brackets: List[str]\n        A list of keys inside brackets.\n    kwargs: Dict[str, Any]\n        A dictionary of keyword arguments.\n\n    Returns\n    -------\n    Dict[str, Any]: A dictionary with keys from data_inside_brackets and corresponding values from kwargs.\n    \"\"\"\n    data_dict = {}\n    for key in data_inside_brackets:\n        data_dict[key] = kwargs[key]\n    return data_dict\n\n\ndef _format_prefix(prefix: str, kwargs: dict[str, Any]) -> str:\n    \"\"\"Format a prefix using keyword arguments.\n\n    Parameters\n    ----------\n    prefix: str\n        The prefix template to be formatted.\n    kwargs: Dict[str, Any]\n        A dictionary of keyword arguments.\n\n    Returns\n    -------\n    str: The formatted prefix.\n    \"\"\"\n    data_inside_brackets = _extract_data_inside_brackets(prefix)\n    data_dict = _construct_data_dict(data_inside_brackets, kwargs)\n    formatted_prefix = prefix.format(**data_dict)\n    return formatted_prefix\n\n\ndef _format_extra_data(to_invalidate_extra: dict[str, str], kwargs: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Format extra data based on provided templates and keyword arguments.\n\n    This function takes a dictionary of templates and their associated values and a dictionary of keyword arguments.\n    It formats the templates with the corresponding values from the keyword arguments and returns a dictionary\n    where keys are the formatted templates and values are the associated keyword argument values.\n\n    Parameters\n    ----------\n    to_invalidate_extra: Dict[str, str]\n        A dictionary where keys are templates and values are the associated values.\n    kwargs: Dict[str, Any]\n        A dictionary of keyword arguments.\n\n    Returns\n    -------\n        Dict[str, Any]: A dictionary where keys are formatted templates and values\n        are associated keyword argument values.\n    \"\"\"\n    formatted_extra = {}\n    for prefix, id_template in to_invalidate_extra.items():\n        formatted_prefix = _format_prefix(prefix, kwargs)\n        id = _extract_data_inside_brackets(id_template)[0]\n        formatted_extra[formatted_prefix] = kwargs[id]\n\n    return formatted_extra\n\n\nasync def _delete_keys_by_pattern(pattern: str) -> None:\n    \"\"\"Delete keys from Redis that match a given pattern using the SCAN command.\n\n    This function iteratively scans the Redis key space for keys that match a specific pattern\n    and deletes them. It uses the SCAN command to efficiently find keys, which is more\n    performance-friendly compared to the KEYS command, especially for large datasets.\n\n    The function scans the key space in an iterative manner using a cursor-based approach.\n    It retrieves a batch of keys matching the pattern on each iteration and deletes them\n    until no matching keys are left.\n\n    Parameters\n    ----------\n    pattern: str\n        The pattern to match keys against. The pattern can include wildcards,\n        such as '*' for matching any character sequence. Example: 'user:*'\n\n    Notes\n    -----\n    - The SCAN command is used with a count of 100 to retrieve keys in batches.\n      This count can be adjusted based on the size of your dataset and Redis performance.\n\n    - The function uses the delete command to remove keys in bulk. If the dataset\n      is extremely large, consider implementing additional logic to handle bulk deletion\n      more efficiently.\n\n    - Be cautious with patterns that could match a large number of keys, as deleting\n      many keys simultaneously may impact the performance of the Redis server.\n    \"\"\"\n    if client is None:\n        raise MissingClientError\n\n    cursor = -1\n    while cursor != 0:\n        cursor, keys = await client.scan(cursor, match=pattern, count=100)\n        if keys:\n            await client.delete(*keys)\n\n\ndef cache(\n    key_prefix: str,\n    resource_id_name: Any = None,\n    expiration: int = 3600,\n    resource_id_type: type | tuple[type, ...] = int,\n    to_invalidate_extra: dict[str, Any] | None = None,\n    pattern_to_invalidate_extra: list[str] | None = None,\n) -> Callable:\n    \"\"\"Cache decorator for FastAPI endpoints.\n\n    This decorator enables caching the results of FastAPI endpoint functions to improve response times\n    and reduce the load on the application by storing and retrieving data in a cache.\n\n    Parameters\n    ----------\n    key_prefix: str\n        A unique prefix to identify the cache key.\n    resource_id_name: Any, optional\n        The name of the resource ID argument in the decorated function. If provided, it is used directly;\n        otherwise, the resource ID is inferred from the function's arguments.\n    expiration: int, optional\n        The expiration time for the cached data in seconds. Defaults to 3600 seconds (1 hour).\n    resource_id_type: Union[type, Tuple[type, ...]], default int\n        The expected type of the resource ID.\n        This can be a single type (e.g., int) or a tuple of types (e.g., (int, str)).\n        Defaults to int. This is used only if resource_id_name is not provided.\n    to_invalidate_extra: Dict[str, Any] | None, optional\n        A dictionary where keys are cache key prefixes and values are templates for cache key suffixes.\n        These keys are invalidated when the decorated function is called with a method other than GET.\n    pattern_to_invalidate_extra: List[str] | None, optional\n        A list of string patterns for cache keys that should be invalidated when the decorated function is called.\n        This allows for bulk invalidation of cache keys based on a matching pattern.\n\n    Returns\n    -------\n    Callable\n        A decorator function that can be applied to FastAPI endpoint functions.\n\n    Example usage\n    -------------\n\n    ```python\n    from fastapi import FastAPI, Request\n    from my_module import cache  # Replace with your actual module and imports\n\n    app = FastAPI()\n\n    # Define a sample endpoint with caching\n    @app.get(\"/sample/{resource_id}\")\n    @cache(key_prefix=\"sample_data\", expiration=3600, resource_id_type=int)\n    async def sample_endpoint(request: Request, resource_id: int):\n        # Your endpoint logic here\n        return {\"data\": \"your_data\"}\n    ```\n\n    This decorator caches the response data of the endpoint function using a unique cache key.\n    The cached data is retrieved for GET requests, and the cache is invalidated for other types of requests.\n\n    Advanced Example Usage\n    -------------\n    ```python\n    from fastapi import FastAPI, Request\n    from my_module import cache\n\n    app = FastAPI()\n\n\n    @app.get(\"/users/{user_id}/items\")\n    @cache(key_prefix=\"user_items\", resource_id_name=\"user_id\", expiration=1200)\n    async def read_user_items(request: Request, user_id: int):\n        # Endpoint logic to fetch user's items\n        return {\"items\": \"user specific items\"}\n\n\n    @app.put(\"/items/{item_id}\")\n    @cache(\n        key_prefix=\"item_data\",\n        resource_id_name=\"item_id\",\n        to_invalidate_extra={\"user_items\": \"{user_id}\"},\n        pattern_to_invalidate_extra=[\"user_*_items:*\"],\n    )\n    async def update_item(request: Request, item_id: int, data: dict, user_id: int):\n        # Update logic for an item\n        # Invalidate both the specific item cache and all user-specific item lists\n        return {\"status\": \"updated\"}\n    ```\n\n    In this example:\n    - When reading user items, the response is cached under a key formed with 'user_items' prefix and 'user_id'.\n    - When updating an item, the cache for this specific item (under 'item_data:item_id') and all caches with keys\n      starting with 'user_{user_id}_items:' are invalidated. The `to_invalidate_extra` parameter specifically targets\n      the cache for user-specific item lists, while `pattern_to_invalidate_extra` allows bulk invalidation of all keys\n      matching the pattern 'user_*_items:*', covering all users.\n\n    Note\n    ----\n    - resource_id_type is used only if resource_id is not passed.\n    - `to_invalidate_extra` and `pattern_to_invalidate_extra` are used for cache invalidation on methods other than GET.\n    - Using `pattern_to_invalidate_extra` can be resource-intensive on large datasets. Use it judiciously and\n      consider the potential impact on Redis performance.\n    \"\"\"\n\n    def wrapper(func: Callable) -> Callable:\n        @functools.wraps(func)\n        async def inner(request: Request, *args: Any, **kwargs: Any) -> Response:\n            if client is None:\n                raise MissingClientError\n\n            if resource_id_name:\n                resource_id = kwargs[resource_id_name]\n            else:\n                resource_id = _infer_resource_id(kwargs=kwargs, resource_id_type=resource_id_type)\n\n            formatted_key_prefix = _format_prefix(key_prefix, kwargs)\n            cache_key = f\"{formatted_key_prefix}:{resource_id}\"\n            if request.method == \"GET\":\n                if to_invalidate_extra is not None or pattern_to_invalidate_extra is not None:\n                    raise InvalidRequestError\n\n                cached_data = await client.get(cache_key)\n                if cached_data:\n                    return json.loads(cached_data.decode())\n\n            result = await func(request, *args, **kwargs)\n\n            if request.method == \"GET\":\n                serializable_data = jsonable_encoder(result)\n                serialized_data = json.dumps(serializable_data)\n\n                await client.set(cache_key, serialized_data)\n                await client.expire(cache_key, expiration)\n\n                serialized_data = json.loads(serialized_data)\n\n            else:\n                await client.delete(cache_key)\n                if to_invalidate_extra is not None:\n                    formatted_extra = _format_extra_data(to_invalidate_extra, kwargs)\n                    for prefix, id in formatted_extra.items():\n                        extra_cache_key = f\"{prefix}:{id}\"\n                        await client.delete(extra_cache_key)\n\n                if pattern_to_invalidate_extra is not None:\n                    for pattern in pattern_to_invalidate_extra:\n                        formatted_pattern = _format_prefix(pattern, kwargs)\n                        await _delete_keys_by_pattern(formatted_pattern + \"*\")\n\n            return result\n\n        return inner\n\n    return wrapper\n"
  },
  {
    "path": "src/app/core/utils/queue.py",
    "content": "from arq.connections import ArqRedis\n\npool: ArqRedis | None = None\n"
  },
  {
    "path": "src/app/core/utils/rate_limit.py",
    "content": "from datetime import UTC, datetime\n\nfrom redis.asyncio import ConnectionPool, Redis\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom ...core.logger import logging\nfrom ...models.rate_limit import sanitize_path\n\nlogger = logging.getLogger(__name__)\n\npool: ConnectionPool | None = None\nclient: Redis | None = None\n\n\nasync def is_rate_limited(db: AsyncSession, user_id: int, path: str, limit: int, period: int) -> bool:\n    if client is None:\n        logger.error(\"Redis client is not initialized.\")\n        raise Exception(\"Redis client is not initialized.\")\n\n    current_timestamp = int(datetime.now(UTC).timestamp())\n    window_start = current_timestamp - (current_timestamp % period)\n\n    sanitized_path = sanitize_path(path)\n    key = f\"ratelimit:{user_id}:{sanitized_path}:{window_start}\"\n\n    try:\n        current_count = await client.incr(key)\n        if current_count == 1:\n            await client.expire(key, period)\n\n        if current_count > limit:\n            return True\n\n    except Exception as e:\n        logger.exception(f\"Error checking rate limit for user {user_id} on path {path}: {e}\")\n        raise e\n\n    return False\n"
  },
  {
    "path": "src/app/core/worker/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/core/worker/functions.py",
    "content": "import asyncio\nimport logging\n\nimport uvloop\nfrom arq.worker import Worker\n\nasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n\n\n# -------- background tasks --------\nasync def sample_background_task(ctx: Worker, name: str) -> str:\n    await asyncio.sleep(5)\n    return f\"Task {name} is complete!\"\n\n\n# -------- base functions --------\nasync def startup(ctx: Worker) -> None:\n    logging.info(\"Worker Started\")\n\n\nasync def shutdown(ctx: Worker) -> None:\n    logging.info(\"Worker end\")\n"
  },
  {
    "path": "src/app/core/worker/settings.py",
    "content": "from arq.connections import RedisSettings\n\nfrom ...core.config import settings\nfrom .functions import sample_background_task, shutdown, startup\n\nREDIS_QUEUE_HOST = settings.REDIS_QUEUE_HOST\nREDIS_QUEUE_PORT = settings.REDIS_QUEUE_PORT\n\n\nclass WorkerSettings:\n    functions = [sample_background_task]\n    redis_settings = RedisSettings(host=REDIS_QUEUE_HOST, port=REDIS_QUEUE_PORT)\n    on_startup = startup\n    on_shutdown = shutdown\n    handle_signals = False\n"
  },
  {
    "path": "src/app/crud/__init__.py",
    "content": ""
  },
  {
    "path": "src/app/crud/crud_posts.py",
    "content": "from fastcrud import FastCRUD\n\nfrom ..models.post import Post, PostCreateInternal, PostDelete, PostUpdate, PostUpdateInternal\n\nCRUDPost = FastCRUD[Post, PostCreateInternal, PostUpdate, PostUpdateInternal, PostDelete]\ncrud_posts = CRUDPost(Post)\n"
  },
  {
    "path": "src/app/crud/crud_rate_limit.py",
    "content": "from fastcrud import FastCRUD\n\nfrom ..models.rate_limit import RateLimit, RateLimitCreateInternal, RateLimitDelete, RateLimitUpdate, RateLimitUpdateInternal\n\nCRUDRateLimit = FastCRUD[RateLimit, RateLimitCreateInternal, RateLimitUpdate, RateLimitUpdateInternal, RateLimitDelete]\ncrud_rate_limits = CRUDRateLimit(RateLimit)\n"
  },
  {
    "path": "src/app/crud/crud_tier.py",
    "content": "from fastcrud import FastCRUD\n\nfrom ..models.tier import Tier, TierCreateInternal, TierDelete, TierUpdate, TierUpdateInternal\n\nCRUDTier = FastCRUD[Tier, TierCreateInternal, TierUpdate, TierUpdateInternal, TierDelete]\ncrud_tiers = CRUDTier(Tier)\n"
  },
  {
    "path": "src/app/crud/crud_users.py",
    "content": "from fastcrud import FastCRUD\n\nfrom ..models.user import User, UserCreateInternal, UserDelete, UserUpdate, UserUpdateInternal\n\nCRUDUser = FastCRUD[User, UserCreateInternal, UserUpdate, UserUpdateInternal, UserDelete]\ncrud_users = CRUDUser(User)\n"
  },
  {
    "path": "src/app/main.py",
    "content": "from .api import router\nfrom .core.config import settings\nfrom .core.setup import create_application\n\napp = create_application(router=router, settings=settings)\n"
  },
  {
    "path": "src/app/middleware/client_cache_middleware.py",
    "content": "from fastapi import FastAPI, Request, Response\nfrom starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint\n\n\nclass ClientCacheMiddleware(BaseHTTPMiddleware):\n    \"\"\"Middleware to set the `Cache-Control` header for client-side caching on all responses.\n\n    Parameters\n    ----------\n    app: FastAPI\n        The FastAPI application instance.\n    max_age: int, optional\n        Duration (in seconds) for which the response should be cached. Defaults to 60 seconds.\n\n    Attributes\n    ----------\n    max_age: int\n        Duration (in seconds) for which the response should be cached.\n\n    Methods\n    -------\n    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:\n        Process the request and set the `Cache-Control` header in the response.\n\n    Note\n    ----\n        - The `Cache-Control` header instructs clients (e.g., browsers)\n        to cache the response for the specified duration.\n    \"\"\"\n\n    def __init__(self, app: FastAPI, max_age: int = 60) -> None:\n        super().__init__(app)\n        self.max_age = max_age\n\n    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:\n        \"\"\"Process the request and set the `Cache-Control` header in the response.\n\n        Parameters\n        ----------\n        request: Request\n            The incoming request.\n        call_next: RequestResponseEndpoint\n            The next middleware or route handler in the processing chain.\n\n        Returns\n        -------\n        Response\n            The response object with the `Cache-Control` header set.\n\n        Note\n        ----\n            - This method is automatically called by Starlette for processing the request-response cycle.\n        \"\"\"\n        response: Response = await call_next(request)\n        response.headers[\"Cache-Control\"] = f\"public, max-age={self.max_age}\"\n        return response\n"
  },
  {
    "path": "src/app/models/__init__.py",
    "content": "from .post import Post\nfrom .rate_limit import RateLimit\nfrom .tier import Tier\nfrom .user import User\n"
  },
  {
    "path": "src/app/models/job.py",
    "content": "from sqlmodel import SQLModel\n\n\nclass Job(SQLModel):\n    id: str\n"
  },
  {
    "path": "src/app/models/post.py",
    "content": "from datetime import datetime\nfrom typing import Optional\nfrom sqlmodel import SQLModel, Field, Relationship\nfrom uuid import uuid4\n\n\nclass PostBase(SQLModel):\n    title: str = Field(..., min_length=2, max_length=30, schema_extra={\"example\": \"This is my post\"})\n    text: str = Field(..., min_length=1, max_length=63206, schema_extra={\"example\": \"This is the content of my post.\"})\n\n\nclass Post(PostBase, table=True):\n    id: Optional[int] = Field(default=None, primary_key=True)\n    created_by_user_id: int = Field(foreign_key=\"user.id\")\n    media_url: Optional[str] = Field(default=None, regex=r\"^(https?|ftp)://[^\\s/$.?#].[^\\s]*$\", schema_extra={\"example\": \"https://www.postimageurl.com\"})\n    created_at: datetime = Field(default_factory=lambda: datetime.now(datetime.timezone.utc))\n    updated_at: Optional[datetime] = None\n    deleted_at: Optional[datetime] = None\n    is_deleted: bool = Field(default=False)\n\n\nclass PostRead(PostBase):\n    id: int\n    created_by_user_id: int\n    media_url: Optional[str]\n    created_at: datetime\n\n\nclass PostCreate(PostBase):\n    media_url: Optional[str] = Field(default=None, regex=r\"^(https?|ftp)://[^\\s/$.?#].[^\\s]*$\", schema_extra={\"example\": \"https://www.postimageurl.com\"})\n\n\nclass PostCreateInternal(PostCreate):\n    created_by_user_id: int\n\n\nclass PostUpdate(SQLModel):\n    title: Optional[str] = Field(default=None, min_length=2, max_length=30)\n    text: Optional[str] = Field(default=None, min_length=1, max_length=63206)\n    media_url: Optional[str] = Field(default=None, regex=r\"^(https?|ftp)://[^\\s/$.?#].[^\\s]*$\")\n\n\nclass PostUpdateInternal(PostUpdate):\n    updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow)\n\n\nclass PostDelete(SQLModel):\n    is_deleted: bool\n    deleted_at: datetime\n"
  },
  {
    "path": "src/app/models/rate_limit.py",
    "content": "from datetime import datetime\nfrom typing import Optional\nfrom sqlmodel import SQLModel, Field\n\n\ndef sanitize_path(path: str) -> str:\n    return path.strip(\"/\").replace(\"/\", \"_\")\n\n\nclass RateLimitBase(SQLModel):\n    path: str = Field(..., schema_extra={\"example\": \"users\"})\n    limit: int = Field(..., schema_extra={\"example\": 5})\n    period: int = Field(..., schema_extra={\"example\": 60})\n\n    @classmethod\n    def validate_path(cls, v: str) -> str:\n        return sanitize_path(v)\n\n\nclass RateLimit(RateLimitBase, table=True):\n    id: Optional[int] = Field(default=None, primary_key=True)\n    tier_id: int = Field(foreign_key=\"tier.id\")\n    name: Optional[str] = Field(default=None, schema_extra={\"example\": \"users:5:60\"})\n    created_at: datetime = Field(default_factory=lambda: datetime.now(datetime.timezone.utc))\n    updated_at: Optional[datetime] = None\n\n\nclass RateLimitRead(RateLimitBase):\n    id: int\n    tier_id: int\n    name: str\n\n\nclass RateLimitCreate(RateLimitBase):\n    name: Optional[str] = Field(default=None, schema_extra={\"example\": \"api_v1_users:5:60\"})\n\n\nclass RateLimitCreateInternal(RateLimitCreate):\n    tier_id: int\n\n\nclass RateLimitUpdate(SQLModel):\n    path: Optional[str] = Field(default=None)\n    limit: Optional[int] = None\n    period: Optional[int] = None\n    name: Optional[str] = None\n\n    @classmethod\n    def validate_path(cls, v: Optional[str]) -> Optional[str]:\n        return sanitize_path(v) if v is not None else None\n\n\nclass RateLimitUpdateInternal(RateLimitUpdate):\n    updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow)\n\n\nclass RateLimitDelete(SQLModel):\n    pass\n"
  },
  {
    "path": "src/app/models/tier.py",
    "content": "from datetime import datetime\nfrom typing import Optional\nfrom sqlmodel import SQLModel, Field\n\n\nclass TierBase(SQLModel):\n    name: str = Field(..., schema_extra={\"example\": \"free\"})\n\n\nclass Tier(TierBase, table=True):\n    id: Optional[int] = Field(default=None, primary_key=True)\n    created_at: datetime = Field(default_factory=lambda: datetime.now(datetime.timezone.utc))\n    updated_at: Optional[datetime] = None\n\n\nclass TierRead(TierBase):\n    id: int\n    created_at: datetime\n\n\nclass TierCreate(TierBase):\n    pass\n\n\nclass TierCreateInternal(TierCreate):\n    pass\n\n\nclass TierUpdate(SQLModel):\n    name: Optional[str] = None\n\n\nclass TierUpdateInternal(TierUpdate):\n    updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow)\n\n\nclass TierDelete(SQLModel):\n    pass\n"
  },
  {
    "path": "src/app/models/user.py",
    "content": "from datetime import datetime\nfrom typing import Optional\nimport uuid as uuid_pkg\n\nfrom sqlmodel import SQLModel, Field\nfrom pydantic import validator\n\n\nclass UserBase(SQLModel):\n    name: str = Field(..., min_length=2, max_length=30, schema_extra={\"example\": \"User Userson\"})\n    username: str = Field(..., min_length=2, max_length=20, regex=\"^[a-z0-9]+$\", schema_extra={\"example\": \"userson\"})\n    email: str = Field(..., schema_extra={\"example\": \"user.userson@example.com\"})\n\n\nclass User(UserBase, table=True):\n    id: Optional[int] = Field(default=None, primary_key=True)\n    profile_image_url: str = Field(\"https://www.profileimageurl.com\")\n    hashed_password: str\n    is_superuser: bool = Field(default=False)\n    tier_id: Optional[int] = Field(default=None, foreign_key=\"tier.id\")\n    created_at: datetime = Field(default_factory=lambda: datetime.now(datetime.timezone.utc))\n    uuid: uuid_pkg.UUID = Field(default_factory=uuid_pkg.uuid4, primary_key=True)\n    updated_at: Optional[datetime] = None\n    deleted_at: Optional[datetime] = None\n    is_deleted: bool = Field(default=False)\n\n\nclass UserRead(SQLModel):\n    id: int\n    name: str\n    username: str\n    email: str\n    profile_image_url: str\n    tier_id: Optional[int]\n\n\nclass UserCreate(UserBase):\n    password: str = Field(..., regex=\"^.{8,}|[0-9]+|[A-Z]+|[a-z]+|[^a-zA-Z0-9]+$\", schema_extra={\"example\": \"Str1ngst!\"})\n\n    @validator('password')\n    def validate_password(cls, value):\n        if len(value) < 8:\n            raise ValueError(\"Password must be at least 8 characters\")\n        return value\n\n\nclass UserCreateInternal(UserBase):\n    hashed_password: str\n\n\nclass UserUpdate(SQLModel):\n    name: Optional[str] = Field(None, min_length=2, max_length=30)\n    username: Optional[str] = Field(None, min_length=2, max_length=20, regex=\"^[a-z0-9]+$\")\n    email: Optional[str] = None\n    profile_image_url: Optional[str] = None\n\n\nclass UserUpdateInternal(UserUpdate):\n    updated_at: Optional[datetime] = Field(default_factory=datetime.utcnow)\n\n\nclass UserTierUpdate(SQLModel):\n    tier_id: int\n\n\nclass UserDelete(SQLModel):\n    is_deleted: bool\n    deleted_at: datetime\n\n\nclass UserRestoreDeleted(SQLModel):\n    is_deleted: bool\n"
  },
  {
    "path": "src/migrations/README",
    "content": "Generic single-database configuration.\n"
  },
  {
    "path": "src/migrations/env.py",
    "content": "import asyncio\nfrom logging.config import fileConfig\n\nfrom alembic import context\nfrom app.core.config import settings\nfrom app.core.db.database import SQLModel\nfrom sqlalchemy import pool\nfrom sqlalchemy.engine import Connection\nfrom sqlalchemy.ext.asyncio import async_engine_from_config\n\n# this is the Alembic Config object, which provides\n# access to the values within the .ini file in use.\nconfig = context.config\n\nconfig.set_main_option(\n    \"sqlalchemy.url\",\n    f\"{settings.POSTGRES_ASYNC_PREFIX}{settings.POSTGRES_USER}:{settings.POSTGRES_PASSWORD}@localhost/{settings.POSTGRES_DB}\",\n)\n\n# Interpret the config file for Python logging.\n# This line sets up loggers basically.\nif config.config_file_name is not None:\n    fileConfig(config.config_file_name)\n\n# add your model's MetaData object here\n# for 'autogenerate' support\n# from myapp import mymodel\n# target_metadata = mymodel.Base.metadata\ntarget_metadata = SQLModel.metadata\n\n# other values from the config, defined by the needs of env.py,\n# can be acquired:\n# my_important_option = config.get_main_option(\"my_important_option\")\n# ... etc.\n\n\ndef run_migrations_offline() -> None:\n    \"\"\"Run migrations in 'offline' mode.\n\n    This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well.  By\n    skipping the Engine creation we don't even need a DBAPI to be available.\n\n    Calls to context.execute() here emit the given string to the script output.\n    \"\"\"\n    url = config.get_main_option(\"sqlalchemy.url\")\n    context.configure(\n        url=url,\n        target_metadata=target_metadata,\n        literal_binds=True,\n        dialect_opts={\"paramstyle\": \"named\"},\n    )\n\n    with context.begin_transaction():\n        context.run_migrations()\n\n\ndef do_run_migrations(connection: Connection) -> None:\n    context.configure(connection=connection, target_metadata=target_metadata)\n\n    with context.begin_transaction():\n        context.run_migrations()\n\n\nasync def run_async_migrations() -> None:\n    \"\"\"In this scenario we need to create an Engine and associate a connection with the context.\"\"\"\n\n    connectable = async_engine_from_config(\n        config.get_section(config.config_ini_section, {}),\n        prefix=\"sqlalchemy.\",\n        poolclass=pool.NullPool,\n    )\n\n    async with connectable.connect() as connection:\n        await connection.run_sync(do_run_migrations)\n\n    await connectable.dispose()\n\n\ndef run_migrations_online() -> None:\n    \"\"\"Run migrations in 'online' mode.\"\"\"\n\n    asyncio.run(run_async_migrations())\n\n\nif context.is_offline_mode():\n    run_migrations_offline()\nelse:\n    run_migrations_online()\n"
  },
  {
    "path": "src/migrations/script.py.mako",
    "content": "\"\"\"${message}\n\nRevision ID: ${up_revision}\nRevises: ${down_revision | comma,n}\nCreate Date: ${create_date}\n\n\"\"\"\nfrom typing import Sequence, Union\n\nfrom alembic import op\nimport sqlalchemy as sa\n${imports if imports else \"\"}\n\n# revision identifiers, used by Alembic.\nrevision: str = ${repr(up_revision)}\ndown_revision: Union[str, None] = ${repr(down_revision)}\nbranch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}\ndepends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}\n\n\ndef upgrade() -> None:\n    ${upgrades if upgrades else \"pass\"}\n\n\ndef downgrade() -> None:\n    ${downgrades if downgrades else \"pass\"}\n"
  },
  {
    "path": "src/migrations/versions/README.MD",
    "content": ""
  },
  {
    "path": "src/scripts/__init__.py",
    "content": ""
  },
  {
    "path": "src/scripts/create_first_superuser.py",
    "content": "import asyncio\nimport logging\nimport uuid\nfrom datetime import UTC, datetime\n\nfrom sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, MetaData, String, Table, insert, select\nfrom sqlalchemy.dialects.postgresql import UUID\n\nfrom ..app.core.config import settings\nfrom ..app.core.db.database import AsyncSession, async_engine, local_session\nfrom ..app.core.security import get_password_hash\nfrom ..app.models.user import User\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nasync def create_first_user(session: AsyncSession) -> None:\n    try:\n        name = settings.ADMIN_NAME\n        email = settings.ADMIN_EMAIL\n        username = settings.ADMIN_USERNAME\n        hashed_password = get_password_hash(settings.ADMIN_PASSWORD)\n\n        query = select(User).filter_by(email=email)\n        result = await session.execute(query)\n        user = result.scalar_one_or_none()\n\n        if user is None:\n            metadata = MetaData()\n            user_table = Table(\n                \"user\",\n                metadata,\n                Column(\"id\", Integer, primary_key=True, autoincrement=True, nullable=False),\n                Column(\"name\", String(30), nullable=False),\n                Column(\"username\", String(20), nullable=False, unique=True, index=True),\n                Column(\"email\", String(50), nullable=False, unique=True, index=True),\n                Column(\"hashed_password\", String, nullable=False),\n                Column(\"profile_image_url\", String, default=\"https://profileimageurl.com\"),\n                Column(\"uuid\", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True),\n                Column(\"created_at\", DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False),\n                Column(\"updated_at\", DateTime),\n                Column(\"deleted_at\", DateTime),\n                Column(\"is_deleted\", Boolean, default=False, index=True),\n                Column(\"is_superuser\", Boolean, default=False),\n                Column(\"tier_id\", Integer, ForeignKey(\"tier.id\"), index=True),\n            )\n\n            data = {\n                \"name\": name,\n                \"email\": email,\n                \"username\": username,\n                \"hashed_password\": hashed_password,\n                \"is_superuser\": True,\n            }\n\n            stmt = insert(user_table).values(data)\n            async with async_engine.connect() as conn:\n                await conn.execute(stmt)\n                await conn.commit()\n\n            logger.info(f\"Admin user {username} created successfully.\")\n\n        else:\n            logger.info(f\"Admin user {username} already exists.\")\n\n    except Exception as e:\n        logger.error(f\"Error creating admin user: {e}\")\n\n\nasync def main():\n    async with local_session() as session:\n        await create_first_user(session)\n\n\nif __name__ == \"__main__\":\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n"
  },
  {
    "path": "src/scripts/create_first_tier.py",
    "content": "import asyncio\nimport logging\n\nfrom sqlalchemy import select\n\nfrom ..app.core.config import config\nfrom ..app.core.db.database import AsyncSession, local_session\nfrom ..app.models.tier import Tier\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nasync def create_first_tier(session: AsyncSession) -> None:\n    try:\n        tier_name = config(\"TIER_NAME\", default=\"free\")\n\n        query = select(Tier).where(Tier.name == tier_name)\n        result = await session.execute(query)\n        tier = result.scalar_one_or_none()\n\n        if tier is None:\n            session.add(Tier(name=tier_name))\n            await session.commit()\n            logger.info(f\"Tier '{tier_name}' created successfully.\")\n\n        else:\n            logger.info(f\"Tier '{tier_name}' already exists.\")\n\n    except Exception as e:\n        logger.error(f\"Error creating tier: {e}\")\n\n\nasync def main():\n    async with local_session() as session:\n        await create_first_tier(session)\n\n\nif __name__ == \"__main__\":\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/conftest.py",
    "content": "import pytest\nfrom fastapi.testclient import TestClient\n\nfrom src.app.main import app\n\n\n@pytest.fixture(scope=\"session\")\ndef client():\n    with TestClient(app) as _client:\n        yield _client\n"
  },
  {
    "path": "tests/helper.py",
    "content": "from fastapi.testclient import TestClient\n\n\ndef _get_token(username: str, password: str, client: TestClient):\n    return client.post(\n        \"/api/v1/login\",\n        data={\"username\": username, \"password\": password},\n        headers={\"content-type\": \"application/x-www-form-urlencoded\"},\n    )\n"
  },
  {
    "path": "tests/test_user.py",
    "content": "from fastapi.testclient import TestClient\n\nfrom src.app.core.config import settings\nfrom src.app.main import app\n\nfrom .helper import _get_token\n\ntest_name = settings.TEST_NAME\ntest_username = settings.TEST_USERNAME\ntest_email = settings.TEST_EMAIL\ntest_password = settings.TEST_PASSWORD\n\nadmin_username = settings.ADMIN_USERNAME\nadmin_password = settings.ADMIN_PASSWORD\n\nclient = TestClient(app)\n\n\ndef test_post_user(client: TestClient) -> None:\n    response = client.post(\n        \"/api/v1/user\",\n        json={\"name\": test_name, \"username\": test_username, \"email\": test_email, \"password\": test_password},\n    )\n    assert response.status_code == 201\n\n\ndef test_get_user(client: TestClient) -> None:\n    response = client.get(f\"/api/v1/user/{test_username}\")\n    assert response.status_code == 200\n\n\ndef test_get_multiple_users(client: TestClient) -> None:\n    response = client.get(\"/api/v1/users\")\n    assert response.status_code == 200\n\n\ndef test_update_user(client: TestClient) -> None:\n    token = _get_token(username=test_username, password=test_password, client=client)\n\n    response = client.patch(\n        f\"/api/v1/user/{test_username}\",\n        json={\"name\": f\"Updated {test_name}\"},\n        headers={\"Authorization\": f'Bearer {token.json()[\"access_token\"]}'},\n    )\n    assert response.status_code == 200\n\n\ndef test_delete_user(client: TestClient) -> None:\n    token = _get_token(username=test_username, password=test_password, client=client)\n\n    response = client.delete(\n        f\"/api/v1/user/{test_username}\", headers={\"Authorization\": f'Bearer {token.json()[\"access_token\"]}'}\n    )\n    assert response.status_code == 200\n\n\ndef test_delete_db_user(client: TestClient) -> None:\n    token = _get_token(username=admin_username, password=admin_password, client=client)\n\n    response = client.delete(\n        f\"/api/v1/db_user/{test_username}\", headers={\"Authorization\": f'Bearer {token.json()[\"access_token\"]}'}\n    )\n    assert response.status_code == 200\n"
  }
]