- 지금 구간 한 줄(히어로·각): 실황으로 관측한 시각은 예보 확률 대신 본 대로 씀. 비가 오면 '비 오는 중'(눈·진눈깨비도), 비가 없으면 확률 없이 바람·하늘. 비가 관측됐는데 예보 확률이 낮아 '바람 조금'으로 나오던 것도 같이 고쳐짐. 예보 시각(다른 구간·내일)은 그대로 확률 - 2시간 비 안내: 실황이 지금 비를 관측했으면 앞으로의 예보보다 먼저 '지금 비가 와요. 우산 챙기세요' - 매시 00~10분은 그 시각 실황이 아직 없어 예보 문구가 나옴
400 lines
19 KiB
Python
400 lines
19 KiB
Python
import asyncio
|
|
from collections import Counter
|
|
from dataclasses import dataclass
|
|
from datetime import date, 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 Region, SunTime, WeatherHourly
|
|
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
|
|
from common.logger import LOG
|
|
from common.utils.kma_time import KST, NCST_DELAY, kst_midnight, latest_ncst_base, latest_ultra_base, latest_vilage_base, now_kst
|
|
from crud.region_crud import RegionCRUD
|
|
from crud.sky_crud import SkyCRUD
|
|
from crud.weather_crud import WeatherCRUD
|
|
from services.calc.sun import sun_times
|
|
from services.calc.weather_calc import discomfort_index, feels_like_c
|
|
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
|
from services.external.kma import (
|
|
day_start_base, fetch_mid, fetch_ncst, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ncst, parse_ultra, parse_vilage,
|
|
)
|
|
|
|
SLOT_HOURS = range(0, 24, 3)
|
|
_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
|
|
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
|
_MIN_DAY_HOURS = 8
|
|
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
|
_background: set[asyncio.Task] = set()
|
|
|
|
|
|
@dataclass
|
|
class RainHour:
|
|
at: datetime
|
|
rain_type: RainType
|
|
rain_mm: float
|
|
lightning: bool = False
|
|
|
|
|
|
@dataclass
|
|
class Observed:
|
|
"""초단기실황: 정시(at)에 관측한 지금 날씨."""
|
|
at: datetime
|
|
rain_type: RainType
|
|
rain_mm: float
|
|
temp_c: float
|
|
humidity: int
|
|
wind_ms: float
|
|
|
|
|
|
@dataclass
|
|
class Slot:
|
|
at: datetime
|
|
row: Optional[WeatherHourly]
|
|
icon: str
|
|
tone: SlotTone
|
|
note: str
|
|
|
|
|
|
@dataclass
|
|
class TodayWeather:
|
|
region: Region
|
|
day: date
|
|
issued_at: Optional[datetime]
|
|
headline: str
|
|
slots: list[Slot]
|
|
|
|
|
|
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
|
|
"""초단기예보가 닿는 시각은 비·비 없음 모두 초단기예보로 바꾼 사본. 단기예보는 3시간마다라 그 사이 바뀐 비를 놓친다."""
|
|
out = dict(by_at)
|
|
for h in ultra or []:
|
|
r = out.get(h.at)
|
|
if r is None or (h.rain_type.value, h.rain_mm) == (r.rain_type, float(r.rain_mm)):
|
|
continue
|
|
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
|
|
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": h.rain_mm})
|
|
return out
|
|
|
|
|
|
def with_observed(by_at: dict[datetime, WeatherHourly], obs: Optional[Observed]) -> dict[datetime, WeatherHourly]:
|
|
"""실황이 닿는 정시 한 시각은 비·기온·습도·바람을 관측값으로 바꾼 사본. 체감온도·불쾌지수는 관측값으로 다시 계산한다."""
|
|
r = by_at.get(obs.at) if obs else None
|
|
if r is None:
|
|
return by_at
|
|
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
|
|
row = WeatherHourly(**{
|
|
**cols, "rain_type": obs.rain_type.value, "rain_mm": obs.rain_mm, "temp_c": obs.temp_c, "humidity": obs.humidity, "wind_ms": obs.wind_ms,
|
|
"feels_c": feels_like_c(obs.temp_c, obs.humidity, obs.wind_ms, obs.at.month), "discomfort_index": discomfort_index(obs.temp_c, obs.humidity),
|
|
})
|
|
row.observed = True # DB 칸이 아니라 이 사본에만 붙는 표시: 한 줄 문구가 확률 대신 관측한 대로 쓴다
|
|
return {**by_at, obs.at: row}
|
|
|
|
|
|
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
|
|
rows = []
|
|
for at, v in hourly.items():
|
|
rows.append({
|
|
"region_code": region_code, "forecast_at": at, "temp_c": v["temp_c"],
|
|
"feels_c": feels_like_c(v["temp_c"], v["humidity"], v["wind_ms"], at.month),
|
|
"discomfort_index": discomfort_index(v["temp_c"], v["humidity"]),
|
|
"sky": v["sky"].value, "rain_type": v["rain_type"].value, "rain_prob": v["rain_prob"],
|
|
"rain_mm": v["rain_mm"], "humidity": v["humidity"], "wind_ms": v["wind_ms"], "issued_at": issued,
|
|
})
|
|
return rows
|
|
|
|
|
|
def _daily_rows(region_code: str, hourly: dict[datetime, dict], daily: dict[date, dict], issued: datetime) -> list[dict]:
|
|
by_day: dict[date, list[tuple[datetime, dict]]] = {}
|
|
for at, v in hourly.items():
|
|
by_day.setdefault(at.date(), []).append((at, v))
|
|
rows = []
|
|
for d, hours in by_day.items():
|
|
vs = [v for _, v in hours]
|
|
if len(vs) < _MIN_DAY_HOURS and d not in daily:
|
|
continue
|
|
temps = [v["temp_c"] for v in vs]
|
|
rains = [v["rain_type"] for v in vs if v["rain_type"] is not RainType.NONE]
|
|
rows.append({
|
|
"region_code": region_code, "forecast_date": d,
|
|
"temp_min_c": daily.get(d, {}).get("temp_min_c", min(temps)),
|
|
"temp_max_c": daily.get(d, {}).get("temp_max_c", max(temps)),
|
|
"sky": Counter(v["sky"] for v in vs).most_common(1)[0][0].value,
|
|
"rain_type": (rains[0] if rains else RainType.NONE).value,
|
|
"rain_prob": max(v["rain_prob"] for v in vs),
|
|
"rain_prob_am": max((v["rain_prob"] for t, v in hours if t.hour < 12), default=None),
|
|
"rain_prob_pm": max((v["rain_prob"] for t, v in hours if t.hour >= 12), default=None), "issued_at": issued,
|
|
})
|
|
return rows
|
|
|
|
|
|
def _slot_view(at: datetime, row: Optional[WeatherHourly], sun: SunTime) -> tuple[str, SlotTone, str]:
|
|
if row is None:
|
|
return "none", SlotTone.DAY, ""
|
|
is_sunset = at <= sun.sunset_at < at + timedelta(hours=3)
|
|
is_night = not (sun.sunrise_at <= at + timedelta(hours=1, minutes=30) < sun.dusk_end_at)
|
|
rain, sky, temp = RainType(row.rain_type), Sky(row.sky), float(row.temp_c)
|
|
tone = SlotTone.SUNSET if is_sunset else SlotTone.NIGHT if is_night else SlotTone.DAY
|
|
if rain is not RainType.NONE:
|
|
icon = "snow" if rain is RainType.SNOW else "rain"
|
|
note = {RainType.SNOW: "눈", RainType.SHOWER: "소나기", RainType.SLEET: "비·눈"}.get(rain, f"비 {row.rain_prob}%")
|
|
return icon, tone, note
|
|
if sky is Sky.CLOUDY:
|
|
return "cloud", tone, "흐림"
|
|
if sky is Sky.PARTLY:
|
|
return ("cloud" if is_night else "sun_cloud"), tone, "구름 많음"
|
|
if is_sunset:
|
|
return "sunset", tone, "노을"
|
|
if temp <= 10:
|
|
return ("moon" if is_night else "sun"), tone, "쌀쌀"
|
|
if temp >= 28:
|
|
return ("moon" if is_night else "sun"), tone, "더워요"
|
|
return ("moon", tone, "맑음") if is_night else ("sun", tone, "햇볕")
|
|
|
|
|
|
def _headline(slots: list[Slot]) -> str:
|
|
rows = [s for s in slots if s.row is not None]
|
|
if not rows:
|
|
return ""
|
|
rainy = [s for s in rows if s.row.rain_type != RainType.NONE.value]
|
|
if rainy:
|
|
return f"{rainy[0].at.astimezone(KST).hour}시쯤부터 비, 우산 챙기세요"
|
|
hot = max(rows, key=lambda s: s.row.temp_c)
|
|
return f"낮 최고 {round(float(hot.row.temp_c))}°, 저녁 {round(float(rows[-1].row.temp_c))}°"
|
|
|
|
|
|
class WeatherService:
|
|
def __init__(
|
|
self, regions: RegionCRUD = Depends(RegionCRUD), crud: WeatherCRUD = Depends(WeatherCRUD), sky: SkyCRUD = Depends(SkyCRUD)
|
|
) -> None:
|
|
self.regions = regions
|
|
self.crud = crud
|
|
self.sky = sky
|
|
|
|
async def today(self, region_code: str, day: Optional[date] = None) -> tuple[ErrorType, Optional[TodayWeather]]:
|
|
"""day 하루의 3시간 칸. 기본은 오늘."""
|
|
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, observed = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True), observed_now(region, now, wait=True))
|
|
day = day or now.date()
|
|
sun = await self._ensure_sun(region, day)
|
|
start = kst_midnight(day)
|
|
err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
lambda s: self.crud.hourly_between(s, region.code, start, start + timedelta(days=1))
|
|
)
|
|
if err is not ErrorType.SUCCESS or sun is None:
|
|
return ErrorType.DB_ERROR, None
|
|
if not rows:
|
|
return ErrorType.EXTERNAL_API_ERROR, None
|
|
|
|
err, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], day))
|
|
sunset_score = next(
|
|
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None
|
|
)
|
|
by_at = with_observed(with_ultra_rain({r.forecast_at: r for r in rows}, ultra), observed)
|
|
slots = []
|
|
hour_now = now.replace(minute=0, second=0, microsecond=0)
|
|
for h in SLOT_HOURS:
|
|
at = start + timedelta(hours=h)
|
|
# 지금이 든 칸은 칸 첫 시각 대신 지금 시각 예보 (이미 지난 시각의 비가 '지금'으로 보이지 않게)
|
|
row = by_at.get(hour_now) if at <= now < at + timedelta(hours=3) and hour_now in by_at else by_at.get(at)
|
|
icon, tone, note = _slot_view(at, row, sun)
|
|
if note == "노을" and sunset_score is not None:
|
|
note = f"노을 {sunset_score}"
|
|
slots.append(Slot(at=at, row=row, icon=icon, tone=tone, note=note))
|
|
issued = max((r.issued_at for r in rows), default=None)
|
|
return ErrorType.SUCCESS, TodayWeather(region=region, day=day, issued_at=issued, headline=_headline(slots), slots=slots)
|
|
|
|
async def ensure_vilage(self, region: Region, now: datetime, background: bool = True) -> None:
|
|
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
|
latest = latest_vilage_base(now)
|
|
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
|
if err is not ErrorType.SUCCESS:
|
|
return
|
|
from_midnight = issued is None or await self._midnight_missing(region, now)
|
|
if issued is not None and issued >= latest and not from_midnight:
|
|
return
|
|
if issued is None or not background:
|
|
await self._refresh(region, now, latest, wait=issued is None, from_midnight=from_midnight)
|
|
return
|
|
task = asyncio.create_task(self._refresh(region, now, latest, wait=False, from_midnight=from_midnight))
|
|
_background.add(task)
|
|
task.add_done_callback(_background.discard)
|
|
|
|
async def _midnight_missing(self, region: Region, now: datetime) -> bool:
|
|
"""오늘 0시 칸이 비었는지. 전날 23시 발표 받기가 실패했을 때 다시 받되, 10분에 한 번만 시도한다."""
|
|
err, has = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_hourly_at(s, region.code, kst_midnight(now.date())))
|
|
if err is not ErrorType.SUCCESS or has:
|
|
return False
|
|
try:
|
|
return bool(await REDIS.conn.set(f"vilage0:{region.code}:{now:%Y%m%d}", "1", ex=600, nx=True))
|
|
except RedisError as e:
|
|
LOG.error(f"[weather] {region.code} midnight retry: {e}")
|
|
return False
|
|
|
|
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool, from_midnight: bool) -> None:
|
|
async with redis_lock(f"lock:vilage:{region.code}") as acquired:
|
|
if acquired:
|
|
bases = [day_start_base(now.date()), latest] if from_midnight else [latest]
|
|
await self._fetch_and_store(region, sorted(set(bases)))
|
|
return
|
|
if wait:
|
|
for _ in range(_WAIT_STEPS):
|
|
await asyncio.sleep(_WAIT_SEC)
|
|
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
|
if err is ErrorType.SUCCESS and issued is not None:
|
|
return
|
|
|
|
async def _fetch_and_store(self, region: Region, bases: list[datetime]) -> None:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
for base in bases:
|
|
try:
|
|
items = await fetch_vilage(client, region.nx, region.ny, base)
|
|
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
|
LOG.error(f"[weather] {region.code} {e}")
|
|
continue
|
|
hourly, daily = parse_vilage(items)
|
|
hourly_rows = _hourly_rows(region.code, hourly, base)
|
|
daily_rows = _daily_rows(region.code, hourly, daily, base)
|
|
err = await DB_SESSION_MNG.execute_lambda_run([
|
|
lambda s: self.crud.upsert_hourly(s, hourly_rows),
|
|
lambda s: self.crud.upsert_daily(s, daily_rows),
|
|
])
|
|
LOG.info(f"[weather] {region.code} base {base:%m-%d %H}시 hourly {len(hourly_rows)} daily {len(daily_rows)}: {err.name}")
|
|
|
|
async def ensure_mid(self, region: Region, now: datetime) -> None:
|
|
base = latest_mid_base(now)
|
|
key = f"mid:{region.code}:{base:%Y%m%d%H}"
|
|
try:
|
|
if await REDIS.conn.exists(key):
|
|
return
|
|
async with redis_lock(f"lock:mid:{region.code}") as acquired:
|
|
if not acquired:
|
|
return
|
|
async with httpx.AsyncClient(timeout=20) as client:
|
|
land, ta = await fetch_mid(client, region.mid_land_code, region.mid_temp_code, base)
|
|
days = parse_mid(land, ta, base)
|
|
rows = [
|
|
{"region_code": region.code, "forecast_date": d, **{**v, "sky": v["sky"].value, "rain_type": v["rain_type"].value}, "issued_at": base}
|
|
for d, v in days.items()
|
|
if d < now.date() + timedelta(days=MID_DAYS)
|
|
]
|
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_daily(s, rows)])
|
|
if err is ErrorType.SUCCESS:
|
|
await REDIS.conn.set(key, "1", ex=13 * 3600)
|
|
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
|
LOG.error(f"[weather] mid {region.code}: {e}")
|
|
|
|
async def sun(self, region: Region, d: date) -> Optional[SunTime]:
|
|
return await self._ensure_sun(region, d)
|
|
|
|
async def _ensure_sun(self, region: Region, d: date) -> Optional[SunTime]:
|
|
err, sun = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get_sun(s, region.code, d))
|
|
if err is not ErrorType.SUCCESS:
|
|
return None
|
|
if sun is not None:
|
|
return sun
|
|
t = sun_times(d, float(region.lat), float(region.lon))
|
|
row = {
|
|
"region_code": region.code, "sun_date": d, "sunrise_at": t.sunrise_at, "sunset_at": t.sunset_at,
|
|
"dusk_end_at": t.dusk_end_at, "sunset_azimuth": t.sunset_azimuth,
|
|
}
|
|
await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)])
|
|
return SunTime(**row)
|
|
|
|
|
|
_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 (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
|
LOG.error(f"[now] ultra {region.code}: {e}")
|
|
return None
|
|
|
|
|
|
async def _cached_ncst(key: str, base: datetime) -> Optional[Observed]:
|
|
cached = await REDIS.conn.get(key)
|
|
if not cached:
|
|
return None
|
|
data = orjson.loads(cached)
|
|
if data["base"] != base.isoformat():
|
|
return None
|
|
return Observed(
|
|
at=base, rain_type=RainType(data["rain_type"]), rain_mm=data["rain_mm"], temp_c=data["temp_c"], humidity=data["humidity"], wind_ms=data["wind_ms"],
|
|
)
|
|
|
|
|
|
async def observed_now(region: Region, now: datetime, wait: bool = False) -> Optional[Observed]:
|
|
"""초단기실황(지금 관측). 정시마다 한 번 받아 그 시간 동안 쓴다. 실패하거나 값이 비면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다린다."""
|
|
key = f"ncst:{region.code}"
|
|
base = latest_ncst_base(now)
|
|
try:
|
|
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
|
|
if attempt:
|
|
await asyncio.sleep(_ULTRA_WAIT_SEC)
|
|
if (obs := await _cached_ncst(key, base)) is not None:
|
|
return obs
|
|
async with redis_lock(f"lock:ncst:{region.code}") as acquired:
|
|
if not acquired:
|
|
continue
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
parsed = parse_ncst(await fetch_ncst(client, region.nx, region.ny, base))
|
|
if parsed is None:
|
|
return None
|
|
obs = Observed(at=base, **parsed)
|
|
payload = {
|
|
"base": base.isoformat(), "rain_type": obs.rain_type.value, "rain_mm": obs.rain_mm, "temp_c": obs.temp_c,
|
|
"humidity": obs.humidity, "wind_ms": obs.wind_ms,
|
|
}
|
|
ttl = int((base + timedelta(hours=1) + NCST_DELAY - now).total_seconds())
|
|
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
|
return obs
|
|
return None
|
|
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
|
LOG.error(f"[now] ncst {region.code}: {e}")
|
|
return None
|