Files
king cf7c44ce49 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>
2026-10-13 05:53:07 +09:00

92 lines
3.5 KiB
Python

"""쿠팡 발주서 — 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))