Skip to content

Commit

Permalink
Add retry logic with tenacity
Browse files Browse the repository at this point in the history
  • Loading branch information
ahdamin committed Oct 8, 2024
1 parent 4149b3b commit 9348379
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
9 changes: 9 additions & 0 deletions genotype_api/database/base_handler.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from dataclasses import dataclass
from typing import Type

from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import DeclarativeBase, Query
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed

from genotype_api.config import settings
from genotype_api.database.models import Analysis, Sample


Expand All @@ -15,6 +18,12 @@ class BaseHandler:
def __init__(self, session: AsyncSession):
self.session = session

@retry(
stop=stop_after_attempt(settings.max_retries),
wait=wait_fixed(settings.retry_delay),
retry=retry_if_exception_type(OperationalError),
reraise=True,
)
def _get_query(self, table: Type[DeclarativeBase]) -> Query:
"""Return a query for the given table."""
return select(table)
Expand Down
9 changes: 9 additions & 0 deletions genotype_api/database/store.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""Module for the store handler."""

from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed

from genotype_api.config import settings
from genotype_api.database.crud.create import CreateHandler
from genotype_api.database.crud.delete import DeleteHandler
from genotype_api.database.crud.read import ReadHandler
Expand All @@ -24,6 +27,12 @@ def __init__(self, session: AsyncSession):
UpdateHandler.__init__(self, session)

@classmethod
@retry(
stop=stop_after_attempt(settings.max_retries),
wait=wait_fixed(settings.retry_delay),
retry=retry_if_exception_type(OperationalError),
reraise=True,
)
async def create(cls) -> "Store":
"""Asynchronously create and return a Store instance with a session."""
async with get_session() as session: # Correctly use async context manager
Expand Down
17 changes: 16 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ uvicorn = "^0.29.0"
uvloop = "^0.19.0"
aiomysql = "^0.2.0"
pytest-asyncio = "^0.24.0"
tenacity = "^9.0.0"

[tool.poetry.group.dev.dependencies]
bump2version = "^1.0.1"
Expand Down

0 comments on commit 9348379

Please sign in to comment.