fix(performance): coupang 504 timeouts shrink the query window instead of failing
A 31-day FINAL_DELIVERY ordersheet query times out at Coupang's gateway (504 "Request timed out"). On 502/503/504 or a client timeout the window is halved (31 -> 15 -> 7 -> 3 -> 1 day) and retried; the shrunk size is kept for the same status's next windows. Rocket Growth orders do the same. A 1-day window that still times out is retried twice (3s, 6s) then fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -63,8 +63,13 @@ MAX_PAGES = 400 # 한 조회 2만 건 — 무한 반복 방지
|
||||
CALL_INTERVAL_SEC = 0.25 # 발주서 목록 호출 간격
|
||||
RG_CALL_INTERVAL_SEC = 1.25 # 로켓그로스 분당 50회 제한
|
||||
RETRY_429 = 3
|
||||
RETRY_TIMEOUT_1DAY = 2 # 하루 구간도 시간 초과면 잠깐 쉬고 다시 부르는 횟수
|
||||
PROBE_MAX_DAYS = 31
|
||||
KST_OFFSET = timedelta(hours=9)
|
||||
|
||||
|
||||
class GatewayTimeout(ApiError):
|
||||
"""쿠팡 서버가 시간 안에 답하지 못함(502·503·504·응답 시간 초과) — 조회 기간을 줄이면 대개 풀린다."""
|
||||
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
|
||||
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
|
||||
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
|
||||
@@ -280,6 +285,8 @@ class CoupangAdapter(MarketplaceAdapter):
|
||||
"Content-Type": "application/json;charset=UTF-8"}
|
||||
try:
|
||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise GatewayTimeout(f"쿠팡 {what} 응답 시간 초과: {type(exc).__name__}") from None
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||
finally:
|
||||
@@ -304,6 +311,8 @@ class CoupangAdapter(MarketplaceAdapter):
|
||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||
if res.status_code == 429:
|
||||
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||
if res.status_code in (502, 503, 504):
|
||||
raise GatewayTimeout(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||
if res.status_code >= 400:
|
||||
raise ApiError(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||
code = body.get("code")
|
||||
@@ -326,17 +335,37 @@ class CoupangAdapter(MarketplaceAdapter):
|
||||
return out
|
||||
|
||||
def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가."""
|
||||
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가.
|
||||
|
||||
건수가 많은 상태(배송완료 등)는 31일을 한 번에 부르면 쿠팡 서버가 504(시간 초과)를 낸다 — 그러면 그 구간을
|
||||
반으로 줄여 다시 부르고(하루까지), 줄인 크기는 같은 상태의 다음 구간에도 그대로 쓴다(매번 31일로 실패하지 않게)."""
|
||||
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
size_by_status = {st: ORDER_SPAN_DAYS for st in STATUSES}
|
||||
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
|
||||
for st in STATUSES:
|
||||
try:
|
||||
rows = self._pages(ctx, path, {"createdAtFrom": f"{a.isoformat()}+09:00",
|
||||
"createdAtTo": f"{b.isoformat()}+09:00",
|
||||
"status": st, "maxPerPage": PAGE_SIZE})
|
||||
except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게
|
||||
raise ApiError(f"{exc.message} [주문일 {a.isoformat()}~{b.isoformat()}, 상태 {st}]") from None
|
||||
rows: list[dict[str, Any]] = []
|
||||
d, tries = a, 0
|
||||
while d <= b:
|
||||
e = min(b, d + timedelta(days=size_by_status[st] - 1))
|
||||
try:
|
||||
part = self._pages(ctx, path, {"createdAtFrom": f"{d.isoformat()}+09:00",
|
||||
"createdAtTo": f"{e.isoformat()}+09:00",
|
||||
"status": st, "maxPerPage": PAGE_SIZE})
|
||||
except GatewayTimeout as exc:
|
||||
if size_by_status[st] > 1:
|
||||
size_by_status[st] = max(1, size_by_status[st] // 2)
|
||||
continue
|
||||
tries += 1
|
||||
if tries <= RETRY_TIMEOUT_1DAY:
|
||||
time.sleep(3.0 * tries)
|
||||
continue
|
||||
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루도 시간 초과, 상태 {st}] "
|
||||
"— 잠시 뒤 다시 시도하세요.") from None
|
||||
except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게
|
||||
raise ApiError(f"{exc.message} [주문일 {d.isoformat()}~{e.isoformat()}, 상태 {st}]") from None
|
||||
rows.extend(part)
|
||||
d, tries = e + timedelta(days=1), 0
|
||||
out.extend(rows)
|
||||
ctx.progress.step(items=len(rows))
|
||||
return out
|
||||
@@ -345,11 +374,27 @@ class CoupangAdapter(MarketplaceAdapter):
|
||||
path = RG_ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||
out: list[dict[str, Any]] = []
|
||||
for a, b in spans(start, end, RG_SPAN_DAYS):
|
||||
try:
|
||||
rows = self._pages(ctx, path, {"paidDateFrom": a.strftime("%Y%m%d"), "paidDateTo": b.strftime("%Y%m%d")},
|
||||
rg=True)
|
||||
except ApiError as exc:
|
||||
raise ApiError(f"{exc.message} [로켓그로스 결제일 {a.isoformat()}~{b.isoformat()}]") from None
|
||||
rows: list[dict[str, Any]] = []
|
||||
d, size, tries = a, RG_SPAN_DAYS, 0
|
||||
while d <= b: # 시간 초과면 판매자배송과 같이 구간을 반으로(하루까지)
|
||||
e = min(b, d + timedelta(days=size - 1))
|
||||
try:
|
||||
part = self._pages(ctx, path, {"paidDateFrom": d.strftime("%Y%m%d"),
|
||||
"paidDateTo": e.strftime("%Y%m%d")}, rg=True)
|
||||
except GatewayTimeout as exc:
|
||||
if size > 1:
|
||||
size = max(1, size // 2)
|
||||
continue
|
||||
tries += 1
|
||||
if tries <= RETRY_TIMEOUT_1DAY:
|
||||
time.sleep(3.0 * tries)
|
||||
continue
|
||||
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루도 시간 초과] "
|
||||
"— 잠시 뒤 다시 시도하세요.") from None
|
||||
except ApiError as exc:
|
||||
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()}~{e.isoformat()}]") from None
|
||||
rows.extend(part)
|
||||
d, tries = e + timedelta(days=1), 0
|
||||
out.extend(rows)
|
||||
ctx.progress.step(items=len(rows))
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""쿠팡 발주서 — 504(시간 초과)면 조회 구간을 반으로 줄여 다시 부른다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.performance.adapters import coupang as cp
|
||||
from app.modules.performance.adapters.base import AdapterContext, ApiError
|
||||
|
||||
|
||||
class Creds:
|
||||
def get(self, key):
|
||||
return {"vendor_id": "A001", "access_key": "ak", "secret_key": "sk"}[key]
|
||||
|
||||
def has(self, key):
|
||||
return True
|
||||
|
||||
|
||||
def _ctx():
|
||||
return AdapterContext(code="coupang", credentials=Creds())
|
||||
|
||||
|
||||
def _days(params):
|
||||
a = date.fromisoformat(params["createdAtFrom"][:10])
|
||||
b = date.fromisoformat(params["createdAtTo"][:10])
|
||||
return a, b
|
||||
|
||||
|
||||
def test_seller_window_halves_on_timeout_and_remembers(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||
a, b = _days(params)
|
||||
calls.append((params["status"], a, b))
|
||||
if params["status"] == "FINAL_DELIVERY" and (b - a).days + 1 > 7:
|
||||
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||
return [{"orderId": f"{params['status']}-{a}-{b}"}]
|
||||
|
||||
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||
ad = cp.CoupangAdapter()
|
||||
start, end = date(2026, 1, 1), date(2026, 3, 31) # 주문일 2025-12-31 ~ 3-31 = 91일 → 31일 구간 3개
|
||||
ad._seller_orders(_ctx(), start, end)
|
||||
|
||||
fd = [(a, b) for st, a, b in calls if st == "FINAL_DELIVERY"]
|
||||
ok = [(a, b) for a, b in fd if (b - a).days + 1 <= 7]
|
||||
# 성공한 구간이 빈틈·겹침 없이 전체 주문일을 덮는다
|
||||
d = start - timedelta(days=1)
|
||||
for a, b in ok:
|
||||
assert a == d
|
||||
d = b + timedelta(days=1)
|
||||
assert d == end + timedelta(days=1)
|
||||
# 31 → 15 → 7 로 줄인 뒤엔 다음 31일 구간도 처음부터 7일로(실패는 첫 구간의 두 번뿐)
|
||||
assert len(fd) - len(ok) == 2
|
||||
# 다른 상태는 31일 그대로
|
||||
assert sum(1 for st, a, b in calls if st == "ACCEPT") == 3
|
||||
|
||||
|
||||
def test_one_day_timeout_retries_then_fails(monkeypatch):
|
||||
sleeps = []
|
||||
monkeypatch.setattr(cp.time, "sleep", lambda s: sleeps.append(s))
|
||||
|
||||
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||
if params["status"] == "FINAL_DELIVERY":
|
||||
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||
with pytest.raises(ApiError) as ei:
|
||||
cp.CoupangAdapter()._seller_orders(_ctx(), date(2026, 1, 5), date(2026, 1, 5))
|
||||
assert "하루도 시간 초과" in ei.value.message and "FINAL_DELIVERY" in ei.value.message
|
||||
assert sleeps == [3.0, 6.0]
|
||||
|
||||
|
||||
def test_rg_window_halves_on_timeout(monkeypatch):
|
||||
got = []
|
||||
|
||||
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||
a = date(int(params["paidDateFrom"][:4]), int(params["paidDateFrom"][4:6]), int(params["paidDateFrom"][6:]))
|
||||
b = date(int(params["paidDateTo"][:4]), int(params["paidDateTo"][4:6]), int(params["paidDateTo"][6:]))
|
||||
if (b - a).days + 1 > 10:
|
||||
raise cp.GatewayTimeout("쿠팡 로켓그로스 주문 API 오류(504)")
|
||||
got.append((a, b))
|
||||
return [{"orderId": str(a)}]
|
||||
|
||||
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||
cp.CoupangAdapter()._rg_orders(_ctx(), date(2026, 1, 1), date(2026, 1, 30))
|
||||
assert got[0][0] == date(2026, 1, 1) and got[-1][1] == date(2026, 1, 30)
|
||||
assert all((b - a).days + 1 <= 10 for a, b in got)
|
||||
assert all(got[i + 1][0] == got[i][1] + timedelta(days=1) for i in range(len(got) - 1))
|
||||
@@ -184,6 +184,10 @@
|
||||
- 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`.
|
||||
|
||||
### 쿠팡 (`adapters/coupang.py`, 구현됨 — 규칙 대조 전)
|
||||
- **시간 초과 대응**(2026-10-13): 31일치 배송완료(FINAL_DELIVERY) 발주서처럼 건수가 많으면 쿠팡 게이트웨이가
|
||||
504 "Request timed out" 을 낸다. 502·503·504·응답 시간 초과(`GatewayTimeout`)면 그 구간을 반으로(31→15→7→3→1일) 줄여 다시 부르고,
|
||||
줄인 크기는 같은 상태의 다음 구간에도 쓴다(로켓그로스도 같은 방식). 하루 구간도 계속 시간 초과면 3·6초 쉬고 2번 더 부른 뒤 실패.
|
||||
오류 문구 끝에 실패한 구간·상태 `[주문일 …~…, 상태 …]` 를 붙인다.
|
||||
|
||||
- 맞출 화면(2026-10-12 사용자 지정): WING → 비즈니스 인사이트 → **판매분석**, 판매자배송 + 로켓그로스, 날짜 선택 → **매출(원)**.
|
||||
판매분석 자체를 주는 Open API 는 없다(developers.coupang.com API 목록 확인) → 주문 API 두 개를 **결제일(한국 시간)** 로 합친다.
|
||||
|
||||
Reference in New Issue
Block a user