fix: 비 오는데 바깥 각이 1위 — 초단기예보가 비라고 한 시각은 각 점수 계산에 비로 넣고, 초단기예보가 새로 나올 때마다 다시 계산

This commit is contained in:
minaChoi committed 2026-10-13 09:19:57 +09:00
1 parent db233d8ffc
commit 8a677a766d
3 files changed
+80 -17

No files matched your search

+19 -4
View File
@@ -9,7 +9,7 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
from common.utils.kma_time import KST, kst_midnight, now_kst
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, now_kst
from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD
@@ -21,6 +21,7 @@ from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, e
from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot
from services.now_service import RainHour, ultra_hours
from services.warning_service import WarningService
from services.weather_service import WeatherService
@@ -175,6 +176,18 @@ def windows_for(
return out
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 is RainType.NONE or r.rain_type != RainType.NONE.value:
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": max(float(r.rain_mm), h.rain_mm)})
return out
EARLY = "early" # 0~5시: 전날 밤 구간
@@ -346,9 +359,9 @@ class IndexService:
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
_, _, _, warnings = await asyncio.gather(
_, _, _, warnings, ultra = await asyncio.gather(
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
self.warning_service.for_region(region, now),
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True),
)
today = now.date()
start = kst_midnight(today)
@@ -367,7 +380,7 @@ class IndexService:
)
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
air = await self.air_service.nearest(region)
by_at = {r.forecast_at: r for r in rows}
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
base_ctx = dict(
pm25=air.pm25 if air else None,
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
@@ -381,6 +394,8 @@ class IndexService:
inputs_at = max(issued, air.measured_at) if air else issued
if by_om:
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
if ultra is not None:
inputs_at = max(inputs_at, latest_ultra_base(now) + ULTRA_DELAY)
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
+31 -12
View File
@@ -142,17 +142,35 @@ class NowService:
)
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
key = f"ultra:{region.code}"
base = latest_ultra_base(now)
try:
cached = await REDIS.conn.get(key)
if cached:
data = orjson.loads(cached)
if data["base"] == base.isoformat():
return [RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"]) for h in data["hours"]]
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"]) 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:
return None
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"]) for p in parsed]
@@ -160,6 +178,7 @@ class NowService:
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm} for h in hours]}
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
return hours
except _FETCH_ERRORS as e:
LOG.error(f"[now] ultra {region.code}: {e}")
return None
return None
except _FETCH_ERRORS as e:
LOG.error(f"[now] ultra {region.code}: {e}")
return None