import asyncio from typing import Awaitable, Callable, Optional, TypeVar from redis.exceptions import RedisError from common.cache.redis_client import REDIS from common.logger import LOG T = TypeVar("T") BUDGET_SEC = 8.0 # 재시도까지 합쳐 한 번 호출에 기다리는 최대 시간 DOWN_SEC = 120 # 응답이 없던 API 는 이 시간 동안 부르지 않고 바로 실패로 돌린다 class Unreachable(Exception): """재시도해도 응답을 못 받음 (연결 실패·HTTP 오류). API 가 준 오류 코드와 달리 '잠시 쉬기' 대상이다.""" async def _is_down(name: str) -> bool: try: return bool(await REDIS.conn.exists(f"apidown:{name}")) except RedisError as e: LOG.error(f"[api] {name} down check: {e}") return False async def _mark_down(name: str, reason: str) -> None: LOG.error(f"[api] {name} 응답 없음, {DOWN_SEC}초 동안 부르지 않음: {reason}") try: await REDIS.conn.set(f"apidown:{name}", reason[:200], ex=DOWN_SEC) except RedisError as e: LOG.error(f"[api] {name} mark down: {e}") async def guarded(name: str, call: Callable[[], Awaitable[T]], fail: type[Exception], budget_sec: Optional[float] = None) -> T: """외부 API 호출을 budget_sec 안에 끝내고, 응답이 없던 API 는 DOWN_SEC 동안 기다리지 않고 바로 fail 을 던진다.""" if await _is_down(name): raise fail(f"{name} skipped: no answer within the last {DOWN_SEC}s") budget_sec = budget_sec or BUDGET_SEC try: async with asyncio.timeout(budget_sec): return await call() except (TimeoutError, Unreachable) as e: reason = str(e) or f"no answer within {budget_sec:.0f}s" await _mark_down(name, reason) raise fail(f"{name} {reason}") from None