Files

77 lines
3.2 KiB
Python

import json
from dataclasses import dataclass
from datetime import date, datetime
from pathlib import Path
from typing import Optional
import httpx
from redis.exceptions import RedisError
from common.cache.redis_client import REDIS
from common.logger import LOG
from common.utils.kma_time import KST
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_snow, parse_snow
# 지점별 평년 첫눈 날짜 (기상청 계절관측지침, 1991~2020). 출처·기준은 파일 안에 적혀 있다
SPOTS: list[dict] = json.loads((Path(__file__).parent / "first_snow.json").read_text(encoding="utf-8"))["spots"]
_DAYS = 7
# 하루 눈 오는 양이 이만큼(cm)은 돼야 '눈 예보'로 친다 (0 에 가까운 값은 뺀다)
_MIN_CM = 0.1
# 눈 예보는 3시간에 한 번만 받는다. 첫 사용자가 볼 때 받아 Redis 에 둔다
_KEY = "firstsnow:forecast"
_TTL_SEC = 3 * 3600
@dataclass
class SnowSpot:
name: str
region: str
lat: float
lon: float
normal: str
top: bool
snow_date: Optional[date] = None
snow_cm: Optional[float] = None
def first_snow_day(days: list[tuple[date, float]], today: date) -> Optional[tuple[date, float]]:
"""오늘부터 눈 예보가 있는 첫 날과 그날 양. 없으면 None."""
return next(((d, cm) for d, cm in sorted(days) if d >= today and cm >= _MIN_CM), None)
class FirstSnowService:
async def spots(self, now: datetime) -> tuple[bool, list[SnowSpot]]:
"""(눈 예보를 받았는지, 지점 목록). 예보를 못 받아도 평년 날짜는 돌려준다."""
forecast = await self._forecast()
today = now.astimezone(KST).date()
out = []
for s in SPOTS:
hit = first_snow_day(forecast[s["name"]], today) if forecast and s["name"] in forecast else None
out.append(SnowSpot(
name=s["name"], region=s["region"], lat=s["lat"], lon=s["lon"], normal=s["normal"], top=bool(s.get("top")),
snow_date=hit[0] if hit else None, snow_cm=round(hit[1], 1) if hit else None,
))
return forecast is not None, out
async def _forecast(self) -> Optional[dict[str, list[tuple[date, float]]]]:
"""지점 이름 → 날짜별 눈 오는 양. Redis 에 있으면 그것을, 없으면 Open-Meteo 에서 받아 둔다. 못 받으면 None."""
try:
cached = await REDIS.conn.get(_KEY)
if cached:
return {name: [(date.fromisoformat(d), cm) for d, cm in days] for name, days in json.loads(cached).items()}
except RedisError as e:
LOG.error(f"[first_snow] cache read: {e}")
try:
async with httpx.AsyncClient(timeout=10) as client:
data = await fetch_snow(client, [(s["lat"], s["lon"]) for s in SPOTS], _DAYS)
except OpenMeteoRequestFailed as e:
LOG.error(f"[first_snow] {e}")
return None
forecast = {s["name"]: parse_snow(d) for s, d in zip(SPOTS, data)}
try:
await REDIS.conn.set(_KEY, json.dumps({name: [[d.isoformat(), cm] for d, cm in days] for name, days in forecast.items()}), ex=_TTL_SEC)
except RedisError as e:
LOG.error(f"[first_snow] cache write: {e}")
return forecast