From 1fa0695c840007b1805022e2ec1c8e7233655570 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 13:58:06 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=EC=B6=9C=EC=8B=9C=20=EC=A0=84=20QA=20?= =?UTF-8?q?=EB=B2=84=EA=B7=B8=203=EA=B1=B4=20=E2=80=94=20=EC=A3=BC?= =?UTF-8?q?=EB=A7=90=20=ED=94=8C=EB=9E=9C=20500,=20=EA=B4=91=EC=A3=BC?= =?UTF-8?q?=C2=B7=EC=A0=84=EB=82=A8=20=ED=96=89=EC=82=AC=200=EA=B1=B4,=20?= =?UTF-8?q?=EB=AF=B8=EC=84=B8=EB=A8=BC=EC=A7=80=20=EA=B0=B1=EC=8B=A0=20?= =?UTF-8?q?=EB=A9=88=EC=B6=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 주말 플랜: '14시~' 같은 시간 라벨에서 정렬이 멈춰 피드 전체가 500 (광산구·울릉군) - 광주·전남: 구 코드는 12인데 행사는 29·46으로 저장돼 27개 구에서 행사를 못 찾음 - 미세먼지: 에어코리아 전국 조회가 15~20초 걸려 8초 한도에 매번 걸림 → 45초 --- backend/services/external/airkorea.py | 6 ++++-- backend/services/external/data_go_kr.py | 9 +++++---- backend/services/week_service.py | 17 +++++++++++++---- backend/services/weekend_plan.py | 3 ++- backend/tests/test_api_guard.py | 16 +++++++++++++++- backend/tests/test_week.py | 16 ++++++++++++++++ backend/tests/test_weekend_plan.py | 5 +++++ 7 files changed, 60 insertions(+), 12 deletions(-) diff --git a/backend/services/external/airkorea.py b/backend/services/external/airkorea.py index b8b6eab..5e612fd 100644 --- a/backend/services/external/airkorea.py +++ b/backend/services/external/airkorea.py @@ -8,6 +8,8 @@ from services.external.data_go_kr import get_all_items REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty" STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList" +# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다. +BUDGET_SEC = 45.0 def _int(v) -> Optional[int]: @@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime: async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]: - return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}) + return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}, budget_sec=BUDGET_SEC) async def fetch_stations(client: httpx.AsyncClient) -> list[dict]: - return await get_all_items(client, STATION_URL, {"returnType": "json"}) + return await get_all_items(client, STATION_URL, {"returnType": "json"}, budget_sec=BUDGET_SEC) def parse_realtime(items: list[dict]) -> list[dict]: diff --git a/backend/services/external/data_go_kr.py b/backend/services/external/data_go_kr.py index b4d9b73..4a214f5 100644 --- a/backend/services/external/data_go_kr.py +++ b/backend/services/external/data_go_kr.py @@ -1,4 +1,5 @@ import asyncio +from typing import Optional import httpx @@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError): pass -async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict: +async def get_body(client: httpx.AsyncClient, url: str, params: dict, budget_sec: Optional[float] = None) -> dict: """data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다.""" if not settings.data_go_kr_service_key: raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty") op = url.rsplit("/", 1)[-1] - return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed) + return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed, budget_sec) async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict: @@ -44,11 +45,11 @@ async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last or 'unexpected body'}") -async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000) -> list[dict]: +async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000, budget_sec: Optional[float] = None) -> list[dict]: items: list[dict] = [] page = 1 while True: - body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}) + body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}, budget_sec) raw = body.get("items") or [] chunk = raw.get("item", []) if isinstance(raw, dict) else raw chunk = [chunk] if isinstance(chunk, dict) else chunk diff --git a/backend/services/week_service.py b/backend/services/week_service.py index 5fdd275..ef5d888 100644 --- a/backend/services/week_service.py +++ b/backend/services/week_service.py @@ -43,6 +43,8 @@ MAX_EVENT_DAYS = 60 EVENT_RADIUS_KM = 30 # 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다. _SIDO_REACH_KM = EVENT_RADIUS_KM + 20 +# 구 코드는 광주·전남을 한 시도(12)로 묶지만, 행사는 TourAPI·문화정보 시도 코드(광주 29 · 전남 46)로 받는다. +_EVENT_SIDOS = {"12": ("29", "46")} PLACE_RADIUS_KM = EVENT_RADIUS_KM PLACE_LIMIT = 10 # 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다. @@ -129,11 +131,18 @@ def mix_kinds(items: list[EventItem]) -> list[EventItem]: return mixed +def event_sidos(region_code: str) -> tuple[str, ...]: + """구가 속한 시도의 행사 시도 코드들.""" + sido = region_code[:2] + return _EVENT_SIDOS.get(sido, (sido,)) + + def nearby_sidos(region: Region, regions: list[Region]) -> list[str]: - """반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에.""" + """반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에.""" lat, lon = float(region.lat), float(region.lon) - near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM} - return [region.code[:2]] + sorted(near - {region.code[:2]}) + own = event_sidos(region.code) + near = {s for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM for s in event_sidos(r.code)} + return list(own) + sorted(near - set(own)) def event_distance(region: Region, e: Event) -> Optional[float]: @@ -148,7 +157,7 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool: return distance_km <= EVENT_RADIUS_KM if e.region_code is not None: return e.region_code == region.code - return e.sido_code == region.code[:2] + return e.sido_code in event_sidos(region.code) def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]: diff --git a/backend/services/weekend_plan.py b/backend/services/weekend_plan.py index f3a5835..0797782 100644 --- a/backend/services/weekend_plan.py +++ b/backend/services/weekend_plan.py @@ -1,3 +1,4 @@ +import re from dataclasses import dataclass from datetime import date, datetime from typing import Optional @@ -158,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]: def key(s: Step) -> float: t = s.time if t[0].isdigit(): - h = int(t.split("~")[0].split(":")[0]) + h = int(re.match(r"\d+", t).group()) return 5.5 if h >= 17 else 1.5 if h < 12 else 3 if t.startswith("~"): return 0 diff --git a/backend/tests/test_api_guard.py b/backend/tests/test_api_guard.py index ba1aafc..3a40fd9 100644 --- a/backend/tests/test_api_guard.py +++ b/backend/tests/test_api_guard.py @@ -5,7 +5,8 @@ import httpx import pytest from config.settings import settings -from services.external import data_go_kr, guard, open_meteo +from services.external import airkorea, data_go_kr, guard, open_meteo +from services.external.airkorea import fetch_realtime from services.external.data_go_kr import DataGoKrRequestFailed, get_body from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds @@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch): with pytest.raises(OpenMeteoRequestFailed): await fetch_clouds(client, [(37.5, 127.0)]) assert len(calls) == 1 + + +@pytest.mark.anyio +async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch): + """전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다.""" + monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0) + + async def slow(req: httpx.Request) -> httpx.Response: + await asyncio.sleep(0.5) + return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}}) + + async with _client(slow) as client: + assert await fetch_realtime(client) == [{"stationName": "x"}] diff --git a/backend/tests/test_week.py b/backend/tests/test_week.py index 480ea54..2beb396 100644 --- a/backend/tests/test_week.py +++ b/backend/tests/test_week.py @@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch): assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"} +@pytest.mark.anyio +async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch): + """구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다.""" + today = now_kst().date() + span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")} + by_sido = { + "29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}], + "46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}], + } + monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, []))) + await _collect("29", "46") + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json() + assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"} + + @pytest.mark.anyio async def test_places_put_indoor_first_on_rainy_day(fakes): rainy_day = (now_kst().date() + timedelta(days=2)).isoformat() diff --git a/backend/tests/test_weekend_plan.py b/backend/tests/test_weekend_plan.py index 682b0d9..24d5adb 100644 --- a/backend/tests/test_weekend_plan.py +++ b/backend/tests/test_weekend_plan.py @@ -55,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it(): assert card.line.startswith("비 오는 토요일") +def test_morning_rain_then_outdoor_after_it_ends(): + card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None) + assert [s.time for s in card.steps] == ["9~14시", "14시~"] + + def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events(): near = _event("가까운 축제", SAT, SUN, 3.0) ends_sat = _event("토요일 끝", SAT, SAT, 50.0)