|
1 | 1 | import abc |
| 2 | +import logging |
2 | 3 | from abc import abstractmethod |
3 | | -from typing import Any, Callable, Optional, Type |
| 4 | +from typing import Callable, Optional |
4 | 5 |
|
| 6 | +from asyncpg.exceptions import SerializationError |
5 | 7 | from sqlalchemy.ext.asyncio import ( |
6 | 8 | AsyncSession, |
7 | 9 | AsyncSessionTransaction, |
8 | 10 | async_scoped_session, |
9 | 11 | ) |
| 12 | +from tenacity import ( |
| 13 | + RetryError, |
| 14 | + before_sleep_log, |
| 15 | + retry, |
| 16 | + retry_if_exception_type, |
| 17 | + stop_after_attempt, |
| 18 | + wait_exponential, |
| 19 | +) |
10 | 20 |
|
11 | 21 | from internal.infrastructures.relational_db import CommentRepo, PostRepo, UserRepo |
12 | 22 | from internal.infrastructures.relational_db.abstraction import ( |
13 | 23 | AbstractCommentRepo, |
14 | 24 | AbstractPostRepo, |
15 | 25 | AbstractUserRepo, |
16 | 26 | ) |
| 27 | +from utils.logger_utils import get_shared_logger |
17 | 28 |
|
18 | 29 |
|
19 | 30 | class AbstractUnitOfWork(abc.ABC): |
@@ -59,30 +70,68 @@ def __init__( |
59 | 70 | self._comment_repo_factory = comment_repo_factory |
60 | 71 | self._user_repo_factory = user_repo_factory |
61 | 72 |
|
62 | | - async def __aenter__(self): |
| 73 | + @retry( |
| 74 | + stop=stop_after_attempt(3), |
| 75 | + wait=wait_exponential(multiplier=0.5, min=0.5, max=5), |
| 76 | + retry=retry_if_exception_type(SerializationError), |
| 77 | + before_sleep=before_sleep_log(get_shared_logger(), logging.WARNING), |
| 78 | + ) |
| 79 | + async def _init_session(self): |
| 80 | + """Initialize session with retry logic for serialization errors.""" |
63 | 81 | self._session = self._scoped_session_factory() |
64 | 82 | self._transaction = await self._session.begin() |
65 | 83 |
|
66 | | - # register repo |
| 84 | + # register repos |
67 | 85 | self.post_repo = self._post_repo_factory(self._session) |
68 | 86 | self.comment_repo = self._comment_repo_factory(self._session) |
69 | 87 | self.user_repo = self._user_repo_factory(self._session) |
70 | 88 | return self |
71 | 89 |
|
72 | | - async def __aexit__( |
73 | | - self, |
74 | | - exc_type: Optional[Type[BaseException]], |
75 | | - exc: Optional[BaseException], |
76 | | - tb: Any, |
77 | | - ): |
| 90 | + async def __aenter__(self): |
| 91 | + try: |
| 92 | + return await self._init_session() |
| 93 | + except SerializationError as e: |
| 94 | + # Ensure resources are cleaned up if all retries fail |
| 95 | + if self._session: |
| 96 | + await self._session.close() |
| 97 | + await self._scoped_session_factory.remove() |
| 98 | + raise |
| 99 | + |
| 100 | + @retry( |
| 101 | + stop=stop_after_attempt(3), |
| 102 | + wait=wait_exponential(multiplier=0.5, min=0.5, max=5), |
| 103 | + retry=retry_if_exception_type(SerializationError), |
| 104 | + before_sleep=before_sleep_log(get_shared_logger(), logging.WARNING), |
| 105 | + ) |
| 106 | + async def _commit_transaction(self): |
| 107 | + """Commit transaction with retry logic for serialization errors.""" |
| 108 | + try: |
| 109 | + await self._transaction.commit() |
| 110 | + except SerializationError: |
| 111 | + # Rollback the failed transaction and start a new one for retry |
| 112 | + await self._transaction.rollback() |
| 113 | + self._transaction = await self._session.begin() |
| 114 | + # Re-raise to trigger retry |
| 115 | + raise |
| 116 | + |
| 117 | + async def __aexit__(self, exc_type, exc, tb): |
| 118 | + logger = get_shared_logger() |
| 119 | + |
78 | 120 | try: |
79 | 121 | if exc_type is None: |
80 | | - await self._transaction.commit() |
| 122 | + try: |
| 123 | + # Try to commit with retries |
| 124 | + await self._commit_transaction() |
| 125 | + except RetryError as e: |
| 126 | + # All retries exhausted |
| 127 | + logger.error(f"Max retries exceeded for commit: {e}") |
| 128 | + await self._transaction.rollback() |
| 129 | + raise SerializationError( |
| 130 | + "Failed to commit transaction after multiple retries" |
| 131 | + ) from e |
81 | 132 | else: |
| 133 | + # If there was an exception in the context, just rollback |
82 | 134 | await self._transaction.rollback() |
83 | | - except Exception: |
84 | | - await self._transaction.rollback() |
85 | | - raise |
86 | 135 | finally: |
87 | 136 | await self._session.close() |
88 | 137 | await self._scoped_session_factory.remove() |
0 commit comments