|
1 | 1 | import datetime |
2 | | -import logging |
3 | | -from asyncio.log import logger |
4 | | -from collections.abc import AsyncIterator |
5 | | -from contextlib import asynccontextmanager |
6 | | -from typing import Final, TypeAlias |
| 2 | +import functools |
| 3 | +from collections.abc import Callable, Coroutine |
| 4 | +from typing import Any, Final, ParamSpec, TypeAlias, TypeVar |
7 | 5 |
|
8 | 6 | import redis |
9 | 7 | import redis.exceptions |
10 | 8 | from models_library.projects import ProjectID |
11 | 9 | from models_library.projects_access import Owner |
12 | 10 | from models_library.projects_state import ProjectLocked, ProjectStatus |
13 | | -from redis.asyncio.lock import Lock |
14 | | -from servicelib.redis._client import RedisClientSDK |
15 | 11 |
|
16 | | -from .background_task import periodic_task |
17 | | -from .logging_utils import log_context |
18 | | - |
19 | | -_logger = logging.getLogger(__name__) |
| 12 | +from .redis import RedisClientSDK, exclusive |
20 | 13 |
|
21 | 14 | PROJECT_REDIS_LOCK_KEY: str = "project_lock:{}" |
22 | 15 | PROJECT_LOCK_TIMEOUT: Final[datetime.timedelta] = datetime.timedelta(seconds=10) |
23 | | -ProjectLock = Lock |
24 | 16 |
|
25 | 17 | ProjectLockError: TypeAlias = redis.exceptions.LockError |
26 | 18 |
|
27 | 19 |
|
28 | | -async def _auto_extend_project_lock(project_lock: Lock) -> None: |
29 | | - # NOTE: the background task already catches anything that might raise here |
30 | | - await project_lock.reacquire() |
| 20 | +P = ParamSpec("P") |
| 21 | +R = TypeVar("R") |
31 | 22 |
|
32 | 23 |
|
33 | | -@asynccontextmanager |
34 | | -async def lock_project( |
35 | | - redis_client: RedisClientSDK, |
| 24 | +def with_locked_project( |
| 25 | + redis_client: RedisClientSDK | Callable[..., RedisClientSDK], |
36 | 26 | *, |
37 | 27 | project_uuid: str | ProjectID, |
38 | 28 | status: ProjectStatus, |
39 | 29 | owner: Owner | None = None, |
40 | | -) -> AsyncIterator[None]: |
41 | | - """Context manager to lock and unlock a project by user_id |
42 | | -
|
43 | | - Raises: |
44 | | - ProjectLockError: if project is already locked |
45 | | - """ |
46 | | - |
47 | | - redis_lock = redis_client.create_lock( |
48 | | - PROJECT_REDIS_LOCK_KEY.format(project_uuid), |
49 | | - ttl=PROJECT_LOCK_TIMEOUT, |
50 | | - ) |
51 | | - |
52 | | - try: |
53 | | - if not await redis_lock.acquire( |
54 | | - blocking=False, |
55 | | - token=ProjectLocked( |
| 30 | +) -> Callable[ |
| 31 | + [Callable[P, Coroutine[Any, Any, R]]], Callable[P, Coroutine[Any, Any, R]] |
| 32 | +]: |
| 33 | + def _decorator( |
| 34 | + func: Callable[P, Coroutine[Any, Any, R]], |
| 35 | + ) -> Callable[P, Coroutine[Any, Any, R]]: |
| 36 | + @exclusive( |
| 37 | + redis_client, |
| 38 | + lock_key=PROJECT_REDIS_LOCK_KEY.format(project_uuid), |
| 39 | + lock_value=ProjectLocked( |
56 | 40 | value=True, |
57 | 41 | owner=owner, |
58 | 42 | status=status, |
59 | 43 | ).model_dump_json(), |
60 | | - ): |
61 | | - msg = f"Lock for project {project_uuid!r} owner {owner!r} could not be acquired" |
62 | | - raise ProjectLockError(msg) |
| 44 | + ) |
| 45 | + @functools.wraps(func) |
| 46 | + async def _wrapper(*args: P.args, **kwargs: P.kwargs) -> R: |
| 47 | + return await func(*args, **kwargs) |
63 | 48 |
|
64 | | - with log_context( |
65 | | - _logger, |
66 | | - logging.DEBUG, |
67 | | - msg=f"with lock for {owner=}:{project_uuid=}:{status=}", |
68 | | - ): |
69 | | - async with periodic_task( |
70 | | - _auto_extend_project_lock, |
71 | | - interval=0.6 * PROJECT_LOCK_TIMEOUT, |
72 | | - task_name=f"{PROJECT_REDIS_LOCK_KEY.format(project_uuid)}_lock_auto_extend", |
73 | | - project_lock=redis_lock, |
74 | | - ): |
75 | | - yield |
| 49 | + return _wrapper |
76 | 50 |
|
77 | | - finally: |
78 | | - # let's ensure we release that stuff |
79 | | - try: |
80 | | - if await redis_lock.owned(): |
81 | | - await redis_lock.release() |
82 | | - except (redis.exceptions.LockError, redis.exceptions.LockNotOwnedError) as exc: |
83 | | - logger.warning( |
84 | | - "releasing %s unexpectedly raised an exception: %s", |
85 | | - f"{redis_lock=!r}", |
86 | | - f"{exc}", |
87 | | - ) |
| 51 | + return _decorator |
0 commit comments