# Conflicts: # backend/router/v1/index/index.py # backend/services/calc/index_calc.py # backend/services/index_service.py # backend/tests/conftest.py # backend/tests/test_index_api.py # backend/tests/test_index_calc.py # backend/tests/test_sky_api.py # backend/worker_main.py
90 lines
4.2 KiB
Python
90 lines
4.2 KiB
Python
import httpx
|
|
from sqlalchemy import text
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.kma_time import now_kst
|
|
from crud.air_crud import AirCRUD
|
|
from crud.feed_crud import FeedCRUD
|
|
from crud.region_crud import RegionCRUD
|
|
from crud.season_crud import SeasonCRUD
|
|
from crud.weather_crud import WeatherCRUD
|
|
from services.external.airkorea import fetch_stations, parse_stations
|
|
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
|
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
|
from services.feed_service import build_feed_day, clear_feed_cache
|
|
from services.weekend_rank import WeekendRank
|
|
|
|
_CLEANUP_SQL = [
|
|
"DELETE FROM public.weather_hourly WHERE forecast_at < now() - interval '7 days'",
|
|
"DELETE FROM public.weather_daily WHERE forecast_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
|
"DELETE FROM public.sun_time WHERE sun_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
|
"DELETE FROM public.index_score WHERE score_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
|
"DELETE FROM public.sky_score WHERE score_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 7",
|
|
"DELETE FROM public.cloud_hourly WHERE forecast_at < now() - interval '2 days'",
|
|
"DELETE FROM public.event WHERE end_date < (now() AT TIME ZONE 'Asia/Seoul')::date - 30",
|
|
"DELETE FROM public.openmeteo_hourly WHERE forecast_at < now() - interval '7 days'",
|
|
]
|
|
_OPENMETEO_DAYS = 4
|
|
|
|
|
|
async def cleanup_old_rows() -> ErrorType:
|
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s, q=q: s.execute(text(q)) for q in _CLEANUP_SQL])
|
|
LOG.info(f"[scheduler] cleanup_old_rows: {err.name}")
|
|
return err
|
|
|
|
|
|
async def refresh_air_stations() -> ErrorType:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=30) as client:
|
|
rows = parse_stations(await fetch_stations(client))
|
|
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
|
|
LOG.error(f"[scheduler] refresh_air_stations: {e}")
|
|
return ErrorType.EXTERNAL_API_ERROR
|
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: AirCRUD().replace_stations(s, rows)])
|
|
LOG.info(f"[scheduler] refresh_air_stations {len(rows)}: {err.name}")
|
|
return err
|
|
|
|
|
|
async def refresh_weekend_rank(only_if_missing: bool = False) -> ErrorType:
|
|
"""주말 전국 순위·당일치기용 나들이 점수를 미리 계산해 Redis 에 둔다. only_if_missing 이면 캐시가 있을 때 건너뛴다."""
|
|
rank = WeekendRank()
|
|
err, _ = await (rank.scores() if only_if_missing else rank.refresh())
|
|
LOG.info(f"[scheduler] refresh_weekend_rank: {err.name}")
|
|
return err
|
|
|
|
|
|
async def refresh_openmeteo_weather() -> ErrorType:
|
|
"""전국 구 중심 좌표의 자외선·가시거리·돌풍·기압·일조·일사·지면온도를 3시간 구간으로 묶어 저장한다."""
|
|
err, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err
|
|
by_point: dict[tuple[float, float], list[str]] = {}
|
|
for r in regions:
|
|
by_point.setdefault((round(float(r.lat), 2), round(float(r.lon), 2)), []).append(r.code)
|
|
points = sorted(by_point)
|
|
try:
|
|
async with httpx.AsyncClient(timeout=30) as client:
|
|
data = await fetch_weather(client, points, days=_OPENMETEO_DAYS)
|
|
except OpenMeteoRequestFailed as e:
|
|
LOG.error(f"[scheduler] refresh_openmeteo_weather: {e}")
|
|
return ErrorType.EXTERNAL_API_ERROR
|
|
fetched_at = now_kst()
|
|
rows = [
|
|
{"region_code": code, "fetched_at": fetched_at, **slot}
|
|
for point, d in zip(points, data)
|
|
for slot in parse_weather(d)
|
|
for code in by_point[point]
|
|
]
|
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
|
|
LOG.info(f"[scheduler] refresh_openmeteo_weather {len(points)} points rows {len(rows)}: {err.name}")
|
|
return err
|
|
|
|
|
|
async def build_today_feed() -> ErrorType:
|
|
"""그날 전국 공통 피드 칸을 넣고, 구별 피드 캐시를 비운다."""
|
|
err = await build_feed_day(now_kst().date(), FeedCRUD(), SeasonCRUD())
|
|
await clear_feed_cache()
|
|
return err
|