-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.py
More file actions
72 lines (56 loc) · 2.28 KB
/
decorators.py
File metadata and controls
72 lines (56 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import functools
import logging
import typing
import asyncpg
import tenacity
from sqlalchemy.exc import DBAPIError
from modern_pg import settings
P = typing.ParamSpec("P")
T = typing.TypeVar("T")
logger = logging.getLogger(__name__)
def _connection_retry_handler(exception: BaseException) -> bool:
if (
isinstance(exception, DBAPIError)
and hasattr(exception, "orig")
and isinstance(exception.orig.__cause__, asyncpg.PostgresConnectionError) # type: ignore[union-attr]
):
logger.debug("postgres_reconnect, backoff triggered")
return True
logger.debug("postgres_reconnect, giving up on backoff")
return False
def postgres_reconnect(func: typing.Callable[P, typing.Awaitable[T]]) -> typing.Callable[P, typing.Awaitable[T]]:
@tenacity.retry(
stop=tenacity.stop_after_attempt(settings.DB_UTILS_CONNECTION_TRIES),
wait=tenacity.wait_exponential_jitter(),
retry=tenacity.retry_if_exception(_connection_retry_handler),
reraise=True,
before=tenacity.before_log(logger, logging.DEBUG),
)
@functools.wraps(func)
async def wrapped_method(*args: P.args, **kwargs: P.kwargs) -> T:
return await func(*args, **kwargs)
return wrapped_method
def _transaction_retry_handler(exception: BaseException) -> bool:
if (
isinstance(exception, DBAPIError)
and hasattr(exception, "orig")
and isinstance(exception.orig.__cause__, asyncpg.SerializationError) # type: ignore[union-attr]
):
logger.debug("transaction_retry, backoff triggered")
return True
logger.debug("transaction_retry, giving up on backoff")
return False
def transaction_retry(
func: typing.Callable[P, typing.Coroutine[typing.Any, typing.Any, T]],
) -> typing.Callable[P, typing.Coroutine[typing.Any, typing.Any, T]]:
@tenacity.retry(
stop=tenacity.stop_after_attempt(settings.DB_UTILS_TRANSACTIONS_TRIES),
wait=tenacity.wait_exponential_jitter(),
retry=tenacity.retry_if_exception(_transaction_retry_handler),
reraise=True,
before=tenacity.before_log(logger, logging.DEBUG),
)
@functools.wraps(func)
async def wrapped_method(*args: P.args, **kwargs: P.kwargs) -> T:
return await func(*args, **kwargs)
return wrapped_method