from contextlib import asynccontextmanager

from aioredis import Redis
from aioredis_lock import LockTimeoutError, RedisLock

__all__ = ["LockManager"]


class LockManager:
    __slots__ = ("_redis",)

    _redis: Redis

    def __init__(self, redis: Redis):
        self._redis = redis

    @asynccontextmanager
    async def try_lock_creation_entry(self, session_id: str) -> bool:
        lock = RedisLock(
            self._redis,
            key=f"session_{session_id}",
            timeout=600,  # TODO: parametrize?
            wait_timeout=0,  # No retries needed
        )

        try:
            async with lock:
                yield True
        except LockTimeoutError:
            yield False
