fix: 초단기예보가 닿는 시간은 비·비 없음 모두 초단기예보를 따르게 (단기예보에 남은 비로 '지금' 칸·우산각이 비로 나오던 것)

This commit is contained in:
minaChoi committed 2026-10-13 13:22:42 +09:00
1 parent e28a2e297e
commit 012d8a4821
9 files changed
+86 -96

No files matched your search

+1 -14
View File
@@ -21,9 +21,8 @@ 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
from services.weather_service import WeatherService, ultra_hours, with_ultra_rain
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
DAYS = 3
@@ -176,18 +175,6 @@ 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시: 전날 밤 구간
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
+2 -60
View File
@@ -3,39 +3,23 @@ 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.kma_time import KST, kst_midnight, 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
from services.weather_service import RainHour, WeatherService, ultra_hours
_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
@@ -146,45 +130,3 @@ class NowService:
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
+67 -4
View File
@@ -5,6 +5,7 @@ from datetime import date, datetime, timedelta
from typing import Optional
import httpx
import orjson
from fastapi import Depends
from redis.exceptions import RedisError
@@ -14,14 +15,14 @@ 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, kst_midnight, latest_vilage_base, now_kst
from common.utils.kma_time import KST, kst_midnight, 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_vilage, latest_mid_base, parse_mid, parse_vilage
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
SLOT_HOURS = range(0, 24, 3)
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
@@ -31,6 +32,14 @@ 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 Slot:
at: datetime
@@ -49,6 +58,18 @@ class TodayWeather:
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 _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
rows = []
for at, v in hourly.items():
@@ -138,7 +159,7 @@ class WeatherService:
return ErrorType.NOT_FOUND, None
now = now_kst()
await self.ensure_vilage(region, now)
_, ultra = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True))
day = day or now.date()
sun = await self._ensure_sun(region, day)
start = kst_midnight(day)
@@ -154,7 +175,7 @@ class WeatherService:
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 = {r.forecast_at: r for r in rows}
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
slots = []
for h in SLOT_HOURS:
at = start + timedelta(hours=h)
@@ -262,3 +283,45 @@ class WeatherService:
}
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