fix: 오늘 날씨 0~6시가 비면 전날 23시 발표를 다시 받아 채움
This commit is contained in:
1 parent
4ebf1cd894
commit
73294622ad
3 files changed
+58
-6
No files matched your search
@@ -52,6 +52,9 @@ class WeatherCRUD:
|
|||||||
async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]:
|
async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]:
|
||||||
return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code))
|
return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code))
|
||||||
|
|
||||||
|
async def has_hourly_at(self, s: AsyncSession, region_code: str, at: datetime) -> bool:
|
||||||
|
return await s.get(WeatherHourly, (region_code, at)) is not None
|
||||||
|
|
||||||
async def hourly_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[WeatherHourly]:
|
async def hourly_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[WeatherHourly]:
|
||||||
stmt = (
|
stmt = (
|
||||||
select(WeatherHourly)
|
select(WeatherHourly)
|
||||||
|
|||||||
@@ -170,19 +170,33 @@ class WeatherService:
|
|||||||
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
||||||
latest = latest_vilage_base(now)
|
latest = latest_vilage_base(now)
|
||||||
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
||||||
if err is not ErrorType.SUCCESS or (issued is not None and issued >= latest):
|
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
|
return
|
||||||
if issued is None or not background:
|
if issued is None or not background:
|
||||||
await self._refresh(region, now, latest, wait=issued is None)
|
await self._refresh(region, now, latest, wait=issued is None, from_midnight=from_midnight)
|
||||||
return
|
return
|
||||||
task = asyncio.create_task(self._refresh(region, now, latest, wait=False))
|
task = asyncio.create_task(self._refresh(region, now, latest, wait=False, from_midnight=from_midnight))
|
||||||
_background.add(task)
|
_background.add(task)
|
||||||
task.add_done_callback(_background.discard)
|
task.add_done_callback(_background.discard)
|
||||||
|
|
||||||
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool) -> None:
|
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:
|
async with redis_lock(f"lock:vilage:{region.code}") as acquired:
|
||||||
if acquired:
|
if acquired:
|
||||||
bases = [day_start_base(now.date()), latest] if wait else [latest]
|
bases = [day_start_base(now.date()), latest] if from_midnight else [latest]
|
||||||
await self._fetch_and_store(region, sorted(set(bases)))
|
await self._fetch_and_store(region, sorted(set(bases)))
|
||||||
return
|
return
|
||||||
if wait:
|
if wait:
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import asyncio
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -5,8 +6,10 @@ from httpx import ASGITransport, AsyncClient
|
|||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
import services.weather_service as weather_service
|
import services.weather_service as weather_service
|
||||||
|
from common.cache.redis_client import REDIS
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.utils.kma_time import kst_midnight, now_kst
|
from common.utils.kma_time import kst_midnight, latest_vilage_base, now_kst
|
||||||
|
from services.external.kma import day_start_base
|
||||||
from router.router import app
|
from router.router import app
|
||||||
|
|
||||||
REGION = "1144000000"
|
REGION = "1144000000"
|
||||||
@@ -32,6 +35,7 @@ async def clean_region():
|
|||||||
lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")),
|
lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")),
|
||||||
lambda s: s.execute(text(f"DELETE FROM sun_time WHERE region_code='{REGION}'")),
|
lambda s: s.execute(text(f"DELETE FROM sun_time WHERE region_code='{REGION}'")),
|
||||||
])
|
])
|
||||||
|
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
||||||
await wipe()
|
await wipe()
|
||||||
yield
|
yield
|
||||||
await wipe()
|
await wipe()
|
||||||
@@ -106,3 +110,34 @@ def test_slot_view_shows_sunset_only_when_clear():
|
|||||||
assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을")
|
assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을")
|
||||||
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
||||||
assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")
|
assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_today_refetches_midnight_when_first_fetch_missed_it(monkeypatch, clean_region):
|
||||||
|
"""전날 23시 발표 받기가 실패해 0시~ 칸이 비면, 다음 요청 때 그 발표를 다시 받아 채운다."""
|
||||||
|
midnight_base = day_start_base(now_kst().date())
|
||||||
|
if latest_vilage_base(now_kst()) == midnight_base:
|
||||||
|
pytest.skip("최신 발표가 전날 23시면 두 발표가 같다")
|
||||||
|
calls = []
|
||||||
|
fail_midnight = True
|
||||||
|
|
||||||
|
async def fake_fetch(client, nx, ny, base):
|
||||||
|
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||||
|
|
||||||
|
calls.append(base)
|
||||||
|
if base == midnight_base and fail_midnight:
|
||||||
|
raise DataGoKrRequestFailed("timeout")
|
||||||
|
return [it for it in _fake_items(base) if base == midnight_base or it["fcstDate"] + it["fcstTime"] > base.strftime("%Y%m%d%H%M")]
|
||||||
|
|
||||||
|
monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch)
|
||||||
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||||
|
first = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||||
|
assert first["slots"][0].get("temp_c") is None
|
||||||
|
fail_midnight = False
|
||||||
|
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
||||||
|
await client.get("/v1/weather/today", params={"region": REGION})
|
||||||
|
await asyncio.gather(*weather_service._background)
|
||||||
|
body = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||||
|
|
||||||
|
assert calls.count(midnight_base) == 2
|
||||||
|
assert body["slots"][0]["temp_c"] == 18
|
||||||
Reference in new issue
Block a user