| 1 |
""" |
| 2 |
MIT License |
| 3 |
|
| 4 |
Copyright (c) 2023 giuppep |
| 5 |
|
| 6 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 |
of this software and associated documentation files (the "Software"), to deal |
| 8 |
in the Software without restriction, including without limitation the rights |
| 9 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 |
copies of the Software, and to permit persons to whom the Software is |
| 11 |
furnished to do so, subject to the following conditions: |
| 12 |
|
| 13 |
The above copyright notice and this permission notice shall be included in all |
| 14 |
copies or substantial portions of the Software. |
| 15 |
|
| 16 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 |
SOFTWARE. |
| 23 |
""" |
| 24 |
|
| 25 |
import time |
| 26 |
from functools import wraps |
| 27 |
from typing import Any, Callable |
| 28 |
|
| 29 |
from flask import current_app |
| 30 |
|
| 31 |
|
| 32 |
def total_seconds(timedelta): |
| 33 |
return int(timedelta.total_seconds()) |
| 34 |
|
| 35 |
|
| 36 |
def retry_query( |
| 37 |
*, max_attempts: int = 3, delay: float = 0.3, backoff: int = 2 |
| 38 |
) -> Callable[..., Any]: |
| 39 |
"""Decorator to retry a query when an OperationalError is raised. |
| 40 |
|
| 41 |
Args: |
| 42 |
max_attempts: Maximum number of attempts. Defaults to 3. |
| 43 |
delay: Delay between attempts in seconds. Defaults to 0.3. |
| 44 |
backoff: Backoff factor. Defaults to 2. |
| 45 |
""" |
| 46 |
|
| 47 |
def decorator(func: Callable[..., Any]) -> Callable[..., Any]: |
| 48 |
@wraps(func) |
| 49 |
def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 50 |
for attempt in range(max_attempts): |
| 51 |
try: |
| 52 |
return func(*args, **kwargs) |
| 53 |
# TODO: use proper exception type |
| 54 |
except Exception as e: |
| 55 |
if attempt == max_attempts - 1: |
| 56 |
raise e |
| 57 |
|
| 58 |
sleep_time = delay * backoff**attempt |
| 59 |
current_app.logger.exception( |
| 60 |
f"Exception when querying database ({e})." |
| 61 |
f"Retrying ({attempt + 1}/{max_attempts}) in {sleep_time:.2f}s." |
| 62 |
) |
| 63 |
time.sleep(sleep_time) |
| 64 |
|
| 65 |
return wrapper |
| 66 |
|
| 67 |
return decorator |