feat(lps): 프록시 전송오류 IP회전 + 시작 프리플라이트 + DECODO/컴포넌트별 비용
프록시(DECODO) 포트/IP 사망(407/ERR_TUNNEL/ERR_HTTP_RESPONSE_CODE_FAILURE)이
봇차단과 구분 없이 예외로 튕겨 같은 죽은 포트로 재시도만 하다 DEAD 되던 문제를 고친다.
- browser_base: is_proxy_error(순수함수) + search 루프에서 프록시 전송오류 시 IP 회전 재시도
(max_proxy_retries=2). 봇감지 회전과 통합. uses_proxy 프로퍼티.
- 쿠팡 어댑터를 BrowserSearchAdapter 로 통합 — 중복 machinery 제거, 회전 로직 한 곳에서 공유
(detect_block 순수함수는 유지, 테스트 호환).
- proxy.healthcheck(): 시작 프리플라이트 — 살아있는 포트 선점 + egress IP 로그(빠른 실패·가시성).
worker_main 기동 시 호출.
- 비용: DecodoConfig.cost_per_gb 추가. metrics 에 proxy_bytes(네이버 직접 제외) + 컴포넌트별
cost{ai_usd, proxy_usd, total_usd}. FE 원가 타일에 AI/DECODO 분해·프록시 바이트.
- 테스트: is_proxy_error 8종 + 비용 분해 1종.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c478e80fd
commit
c955a8f367
10 files changed
+162
-177
No files matched your search
@@ -38,6 +38,20 @@ def detect_block(html: str, product_count: int, markers: tuple, min_len: int) ->
|
||||
return marker
|
||||
|
||||
|
||||
# 프록시 전송 실패 마커 — 사이트 차단이 아니라 DECODO 포트/IP 사망·세션만료. 봇 감지와 별개로 IP 회전 트리거.
|
||||
_PROXY_ERR_MARKERS = (
|
||||
"ERR_TUNNEL_CONNECTION_FAILED", "ERR_PROXY_CONNECTION_FAILED", "ERR_HTTP_RESPONSE_CODE_FAILURE",
|
||||
"ERR_NO_SUPPORTED_PROXIES", "ERR_SOCKS_CONNECTION_FAILED", "ERR_CONNECTION_CLOSED",
|
||||
"Proxy Authentication", "status code 407", "407 ",
|
||||
)
|
||||
|
||||
|
||||
def is_proxy_error(msg: str) -> bool:
|
||||
"""예외 메시지가 프록시 전송 실패(포트/IP 사망·407)인지(순수 함수, 단위 테스트 가능).
|
||||
True 면 사이트 차단이 아니라 프록시 문제 → 다른 IP 로 회전하면 회복 가능."""
|
||||
return any(m in (msg or "") for m in _PROXY_ERR_MARKERS)
|
||||
|
||||
|
||||
class BrowserSearchAdapter(SearchAdapter):
|
||||
"""patchright(스텔스 Chrome) 기반 검색 어댑터 베이스. persistent context 로 브라우저를 재사용한다."""
|
||||
|
||||
@@ -48,6 +62,7 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
ready_timeout_ms: int = 20000
|
||||
block_resources_default: bool = True # 쿠팡=True(대역폭↓). 오픈마켓은 리소스차단이 렌더/챌린지를 깨 False.
|
||||
scroll_steps: int = 0 # >0 이면 렌더 대기 전 스크롤(지연 로딩 트리거, 예: 11번가)
|
||||
max_proxy_retries: int = 2 # 프록시 전송오류(포트 사망) 시 IP 회전 재시도 횟수
|
||||
|
||||
def __init__(self, headless: bool = False, user_data_dir: str | None = None, rate_limiter: RateLimiter | None = None,
|
||||
proxy=None, block_resources: bool | None = None, on_detect=None, max_block_retries: int = 1):
|
||||
@@ -134,10 +149,23 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
finally:
|
||||
self._ctx = None
|
||||
|
||||
# ---- 검색(차단 감지 + IP 회전 인라인 재시도) ----------------------
|
||||
@property
|
||||
def uses_proxy(self) -> bool:
|
||||
"""이 어댑터가 프록시(DECODO)를 경유하는지 — 대역폭 비용 귀속용."""
|
||||
return bool(self._proxy and self._proxy.enabled)
|
||||
|
||||
def _rotate_ip(self, reason: str):
|
||||
"""즉시 다음 IP(포트)로 회전 예약 + 다음 _ensure_browser 에서 브라우저 재기동."""
|
||||
if self._proxy and self._proxy.enabled:
|
||||
self._proxy.rotate()
|
||||
self._force_recycle = True
|
||||
LOG.w(f"[{self.source}] IP 회전 — {reason}")
|
||||
|
||||
# ---- 검색(프록시 전송오류·봇 감지 → IP 회전 인라인 재시도) --------
|
||||
async def search(self, query: str, limit: int = 40) -> list[NormalizedProduct]:
|
||||
async with self._lock: # 인스턴스 내 검색 직렬화(브라우저 컨텍스트 공유)
|
||||
for attempt in range(self._max_block_retries + 1):
|
||||
proxy_retries, block_retries = self.max_proxy_retries, self._max_block_retries
|
||||
while True:
|
||||
await self._rl.wait()
|
||||
await self._ensure_browser()
|
||||
self._ip_requests += 1
|
||||
@@ -148,6 +176,11 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
await self._wait_ready(page)
|
||||
html = await page.content()
|
||||
except Exception as ex:
|
||||
# 프록시 전송 실패(포트/IP 사망·407)면 사이트 문제가 아니므로 IP 회전 후 재시도
|
||||
if self.uses_proxy and is_proxy_error(str(ex)) and proxy_retries > 0:
|
||||
proxy_retries -= 1
|
||||
self._rotate_ip(f"프록시 전송오류({type(ex).__name__}) 재시도 {self.max_proxy_retries - proxy_retries}/{self.max_proxy_retries}")
|
||||
continue
|
||||
raise AdapterError(f"{self.source} 검색 실패: {ex}", source=self.source) from ex
|
||||
|
||||
self.last_bytes = len(html.encode("utf-8"))
|
||||
@@ -163,11 +196,9 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
if blocked:
|
||||
await self._report_detection(query, marker, len(html))
|
||||
|
||||
can_retry = blocked and self._proxy and self._proxy.enabled and attempt < self._max_block_retries
|
||||
if can_retry:
|
||||
self._proxy.rotate()
|
||||
self._force_recycle = True
|
||||
LOG.w(f"[{self.source}] 봇 감지 → IP 회전 후 재시도 ({attempt + 1}/{self._max_block_retries})")
|
||||
if blocked and self.uses_proxy and block_retries > 0:
|
||||
block_retries -= 1
|
||||
self._rotate_ip(f"봇 감지 재시도 {self._max_block_retries - block_retries}/{self._max_block_retries}")
|
||||
continue
|
||||
|
||||
raise AdapterError(f"{self.source} 결과 없음/차단 (query={query!r}, blocked={blocked})", source=self.source, blocked=blocked)
|
||||
|
||||
Reference in new issue
Block a user