import uuid from contextlib import asynccontextmanager from typing import AsyncIterator from redis.exceptions import RedisError from common.cache.redis_client import REDIS from common.logger import LOG _RELEASE = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" @asynccontextmanager async def redis_lock(key: str, ttl_sec: int = 10) -> AsyncIterator[bool]: """잡았으면 True. 다른 요청이 잡고 있으면 False (기다리지 않음).""" token = uuid.uuid4().hex try: acquired = bool(await REDIS.conn.set(key, token, nx=True, ex=ttl_sec)) except RedisError as e: LOG.error(f"[lock] {key} acquire failed: {e}") acquired = True try: yield acquired finally: if acquired: try: await REDIS.conn.eval(_RELEASE, 1, key, token) except RedisError as e: LOG.error(f"[lock] {key} release failed: {e}")