Files
site/apps/api/app/modules/zootech/lab/db_guard.py
T
2026-07-17 12:57:18 +03:00

29 lines
800 B
Python

from __future__ import annotations
import time
from functools import wraps
from typing import Any, Callable, TypeVar
from sqlalchemy.exc import OperationalError
F = TypeVar("F", bound=Callable[..., Any])
def retry_locked(fn: F, *, attempts: int = 3, delay: float = 0.15) -> F:
@wraps(fn)
def wrapper(*args: Any, **kwargs: Any) -> Any:
last_exc: Exception | None = None
for i in range(attempts):
try:
return fn(*args, **kwargs)
except OperationalError as exc:
if "locked" not in str(exc).lower():
raise
last_exc = exc
time.sleep(delay * (i + 1))
if last_exc:
raise last_exc
return None
return wrapper # type: ignore[return-value]