from dataclasses import dataclass from datetime import datetime, timedelta from typing import Optional import httpx from fastapi import Depends from redis.exceptions import RedisError from common.cache.lock import redis_lock from common.cache.redis_client import REDIS from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import Region, WeatherWarning from common.enums import ErrorType, WarningLevel, WarningType from common.logger import LOG from crud.air_crud import WarningCRUD from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.kma import active_warnings, fetch_warning_events _LOOKBACK = timedelta(days=7) _NAME = { WarningType.WIND: "강풍", WarningType.RAIN: "호우", WarningType.COLD: "한파", WarningType.DRY: "건조", WarningType.STORM_SURGE: "폭풍해일", WarningType.HIGH_SEAS: "풍랑", WarningType.TYPHOON: "태풍", WarningType.SNOW: "대설", WarningType.YELLOW_DUST: "황사", WarningType.HEAT: "폭염", WarningType.TROPICAL_NIGHT: "열대야", } _LEVEL = {WarningLevel.ADVISORY: "주의보", WarningLevel.WARNING: "경보", WarningLevel.SEVERE: "중대경보"} @dataclass class WarningItem: warning_type: WarningType level: WarningLevel text: str def _zone_prefix(code: str) -> str: return code.rstrip("0") or code def warning_applies(region_zone: str, warning_zone: str) -> bool: """구역 코드는 뒤 0을 뺀 앞부분이 상위 구역이다. 어느 한쪽이 다른 쪽을 포함하면 해당한다.""" a, b = _zone_prefix(region_zone), _zone_prefix(warning_zone) return a.startswith(b) or b.startswith(a) def _item(w: WeatherWarning) -> WarningItem: t, lv = WarningType(w.warning_type), WarningLevel(w.level) return WarningItem(warning_type=t, level=lv, text=f"{_NAME[t]}{_LEVEL[lv]}") class WarningService: def __init__(self, crud: WarningCRUD = Depends(WarningCRUD)) -> None: self.crud = crud async def for_region(self, region: Region, now: datetime) -> Optional[list[WarningItem]]: """그 구에 내려진 특보. 한 번도 받지 못했으면 None ('없음'과 구분).""" if not await self._ensure(now): return None err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.all(s)) if err is not ErrorType.SUCCESS: return None return [_item(w) for w in rows if warning_applies(region.warning_zone_code, w.warning_zone_code)] async def _ensure(self, now: datetime) -> bool: hour_key = f"warning:fetched:{now:%Y%m%d%H}" try: if await REDIS.conn.exists(hour_key): return True async with redis_lock("lock:warning") as acquired: if acquired: async with httpx.AsyncClient(timeout=20) as client: rows = active_warnings(await fetch_warning_events(client, now - _LOOKBACK, now)) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.replace_all(s, rows)]) if err is ErrorType.SUCCESS: await REDIS.conn.set(hour_key, "1", ex=3600) await REDIS.conn.set("warning:ever", "1") return True return bool(await REDIS.conn.exists("warning:ever")) except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e: LOG.error(f"[warning] {e}") try: return bool(await REDIS.conn.exists("warning:ever")) except RedisError: return False