191 lines
8.1 KiB
Python
191 lines
8.1 KiB
Python
import asyncio
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
|
|
import httpx
|
|
import orjson
|
|
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 AirQuality, Region, WeatherHourly
|
|
from common.enums import AirGrade, ErrorType, RainType, Sky
|
|
from common.logger import LOG
|
|
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, now_kst
|
|
from common.utils.text import hour_label
|
|
from crud.region_crud import RegionCRUD
|
|
from crud.weather_crud import WeatherCRUD
|
|
from services.air_service import GRADE_LABEL, AirService
|
|
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
|
from services.external.kma import fetch_ultra, parse_ultra
|
|
from services.warning_service import WarningItem, WarningService
|
|
from services.weather_service import WeatherService
|
|
|
|
_FETCH_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
|
_COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
|
|
|
|
|
@dataclass
|
|
class RainHour:
|
|
at: datetime
|
|
rain_type: RainType
|
|
rain_mm: float
|
|
lightning: bool = False
|
|
|
|
|
|
@dataclass
|
|
class CommuteRow:
|
|
label: str
|
|
at: datetime
|
|
icon: str
|
|
temp_c: Optional[float]
|
|
text: str
|
|
|
|
|
|
@dataclass
|
|
class NowWeather:
|
|
region: Region
|
|
will_rain_2h: bool
|
|
rain_2h_text: str
|
|
rain_hours: list[RainHour]
|
|
tomorrow_text: str
|
|
tomorrow_rain_from: Optional[datetime]
|
|
commute: list[CommuteRow]
|
|
air: Optional[AirQuality]
|
|
air_text: Optional[str]
|
|
warnings: Optional[list[WarningItem]] = field(default=None)
|
|
thunder_2h: bool = False
|
|
|
|
|
|
def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]:
|
|
if rain is RainType.SNOW:
|
|
return "snow", "눈"
|
|
if rain is not RainType.NONE:
|
|
return "rain", "약한 비" if rain_mm < 1 else "비"
|
|
return {Sky.CLEAR: ("sun", "맑음"), Sky.PARTLY: ("sun_cloud", "구름 많음"), Sky.CLOUDY: ("cloud", "흐림")}[sky]
|
|
|
|
|
|
def _rain_2h_text(hours: list[RainHour]) -> tuple[bool, str]:
|
|
rainy = [h for h in hours if h.rain_type is not RainType.NONE]
|
|
if not rainy:
|
|
return False, "앞으로 2시간, 우산 없어도 돼요"
|
|
return True, f"{hour_label(rainy[0].at.astimezone(KST).hour)}쯤 비가 와요. 우산 챙기세요"
|
|
|
|
|
|
def _tomorrow(rows: list[WeatherHourly]) -> tuple[Optional[datetime], str, list[CommuteRow]]:
|
|
rainy = [r for r in rows if r.rain_type != RainType.NONE.value]
|
|
if rainy:
|
|
first = rainy[0]
|
|
how = "부슬부슬" if float(first.rain_mm) < 1 else "비가"
|
|
text = f"내일은 {hour_label(first.forecast_at.astimezone(KST).hour)}쯤부터 {how} 와요"
|
|
else:
|
|
text = "내일은 비 소식이 없어요"
|
|
by_hour = {r.forecast_at.astimezone(KST).hour: r for r in rows}
|
|
commute = []
|
|
for label, h in _COMMUTE:
|
|
r = by_hour.get(h)
|
|
if r is None:
|
|
continue
|
|
icon, word = _weather_word(RainType(r.rain_type), Sky(r.sky), float(r.rain_mm))
|
|
commute.append(CommuteRow(label=label, at=r.forecast_at, icon=icon, temp_c=float(r.temp_c), text=f"{word} {round(float(r.temp_c))}°"))
|
|
return (rainy[0].forecast_at if rainy else None), text, commute
|
|
|
|
|
|
class NowService:
|
|
def __init__(
|
|
self,
|
|
regions: RegionCRUD = Depends(RegionCRUD),
|
|
weather: WeatherCRUD = Depends(WeatherCRUD),
|
|
weather_service: WeatherService = Depends(WeatherService),
|
|
air_service: AirService = Depends(AirService),
|
|
warning_service: WarningService = Depends(WarningService),
|
|
) -> None:
|
|
self.regions, self.weather = regions, weather
|
|
self.weather_service, self.air_service, self.warning_service = weather_service, air_service, warning_service
|
|
|
|
async def now(self, region_code: str) -> tuple[ErrorType, Optional[NowWeather]]:
|
|
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
if region is None:
|
|
return ErrorType.NOT_FOUND, None
|
|
|
|
now = now_kst()
|
|
ultra, _, _, warnings = await asyncio.gather(
|
|
self._ultra(region, now), self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now),
|
|
self.warning_service.for_region(region, now),
|
|
)
|
|
tomorrow_start = kst_midnight(now.date() + timedelta(days=1))
|
|
err, next_rows = await DB_SESSION_MNG.execute_lambda(
|
|
lambda s: self.weather.hourly_between(s, region.code, now - timedelta(hours=1), tomorrow_start + timedelta(days=1))
|
|
)
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
|
|
hours = ultra if ultra is not None else [
|
|
RainHour(at=r.forecast_at, rain_type=RainType(r.rain_type), rain_mm=float(r.rain_mm)) for r in next_rows
|
|
]
|
|
hours = [h for h in hours if now < h.at <= now + timedelta(hours=2)]
|
|
if not hours and not next_rows:
|
|
return ErrorType.EXTERNAL_API_ERROR, None
|
|
will_rain, rain_text = _rain_2h_text(hours)
|
|
rain_from, tomorrow_text, commute = _tomorrow([r for r in next_rows if r.forecast_at >= tomorrow_start])
|
|
air = await self.air_service.nearest(region)
|
|
air_text = None
|
|
if air is not None and air.grade is not None:
|
|
label = GRADE_LABEL[AirGrade(air.grade)]
|
|
air_text = f"초미세먼지 {air.pm25} {label}" if air.pm25 is not None else label
|
|
return ErrorType.SUCCESS, NowWeather(
|
|
region=region, will_rain_2h=will_rain, rain_2h_text=rain_text, rain_hours=hours,
|
|
tomorrow_text=tomorrow_text, tomorrow_rain_from=rain_from, commute=commute, air=air, air_text=air_text, warnings=warnings,
|
|
thunder_2h=any(h.lightning for h in hours),
|
|
)
|
|
|
|
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
|
|
return await ultra_hours(region, now)
|
|
|
|
|
|
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
|
|
|
|
|
|
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
|
|
cached = await REDIS.conn.get(key)
|
|
if not cached:
|
|
return None
|
|
data = orjson.loads(cached)
|
|
if data["base"] != base.isoformat():
|
|
return None
|
|
return [
|
|
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
|
|
for h in data["hours"]
|
|
]
|
|
|
|
|
|
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
|
|
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
|
|
key = f"ultra:{region.code}"
|
|
base = latest_ultra_base(now)
|
|
try:
|
|
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
|
|
if attempt:
|
|
await asyncio.sleep(_ULTRA_WAIT_SEC)
|
|
if (hours := await _cached_ultra(key, base)) is not None:
|
|
return hours
|
|
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
|
if not acquired:
|
|
continue
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
|
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
|
|
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
|
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
|
|
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
|
return hours
|
|
return None
|
|
except _FETCH_ERRORS as e:
|
|
LOG.error(f"[now] ultra {region.code}: {e}")
|
|
return None
|