feat(lps): IP 선제 로테이션 — 요청 예산·포트 쿨다운·ip_session 관측

쿠팡 크롤 IP 를 '막힐 때까지' 쓰던 방식을 '막히기 전에 교체'로 전환한다.

- 요청 예산(LPS_IP_REQUEST_BUDGET, 기본 3): IP당 요청 수가 예산에 닿으면
  차단 전에 선제 회전. 실측상 5회 부근 차단 이력이 있어 보수적으로 3회.
  선제 교체된 포트는 평판이 깨끗해 로테이션 복귀 시 재사용된다.
- 포트 쿨다운(LPS_PORT_COOLDOWN_SEC, 기본 max(sticky,30분)): 차단 감지·
  전송오류 포트는 격리하고 _port() 가 건너뛴다. 전 포트 쿨다운이면 만료
  임박 포트 사용(가용성 우선). 포트 수는 config 범위에서 동적 산출.
- 차단 재시도 소진 시에도 회전 예약 — 불탄 포트로 다음 검색을 하지 않음.
- ip_session 테이블 신설: 세션마다 요청 수·성공/차단·종료 사유(budget/
  block/proxy_error/window/idle/shutdown)를 기록. bot_detection 과 달리
  무사 종료도 남아 예산 상한 튜닝의 원천 데이터가 된다(쿼리 database.md).
  models.py·migrations·init.sql(lps_db 섹션) 동행 갱신, dev DB 적용 완료.
- 테스트 17건 추가(쿨다운·예산 판정·세션 기록·CRUD), 전체 126 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Fable 5 committed 2026-07-13 16:35:44 +09:00
1 parent f97e407f7c
commit 3c5286aeec
14 files changed
+409 -18

No files matched your search

+59 -9
View File
@@ -33,6 +33,10 @@ _BLOCKED_RESOURCES = {"image", "media", "font", "stylesheet"}
_CHROME_CHANNEL = os.environ.get("LPS_CHROME_CHANNEL", "chrome")
_CHROME_EXECUTABLE = os.environ.get("LPS_CHROME_EXECUTABLE") or None
# IP(포트 세션)당 요청 예산 — 도달하면 차단당하기 **전에** 선제 회전해 IP 평판을 보존한다.
# 실측상 5회 부근에서 차단된 이력이 있어 보수적으로 3회. 0 이면 비활성(시간창 회전만).
_IP_REQUEST_BUDGET = int(os.environ.get("LPS_IP_REQUEST_BUDGET", "3"))
def detect_block(html: str, product_count: int, markers: tuple, min_len: int) -> str | None:
"""0건 응답의 차단 여부 판정(순수 함수). 반환: 차단 마커(차단) 또는 None(정상 빈결과).
@@ -73,7 +77,8 @@ class BrowserSearchAdapter(SearchAdapter):
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):
proxy=None, block_resources: bool | None = None, on_detect=None, max_block_retries: int = 1,
ip_request_budget: int | None = None, on_session_end=None):
self._headless = headless
self._user_data_dir = user_data_dir or f"/tmp/lps_{self.source}_profile"
self._rl = rate_limiter or RateLimiter()
@@ -82,6 +87,8 @@ class BrowserSearchAdapter(SearchAdapter):
self._block_active = self._block_resources # 요청별 실제 차단 여부(_blocking_now 로 갱신)
self._on_detect = on_detect # async def(event: dict) — 감지 영속화(선택)
self._max_block_retries = max_block_retries
self._ip_budget = _IP_REQUEST_BUDGET if ip_request_budget is None else ip_request_budget
self._on_session_end = on_session_end # async def(event: dict) — IP 세션 종료 기록(선택, 상한 튜닝 데이터)
self._pw = None
self._ctx = None
self._launched_at = 0.0
@@ -91,6 +98,9 @@ class BrowserSearchAdapter(SearchAdapter):
self._lock = asyncio.Lock()
self._ok = 0
self._blocked = 0
self._sess_ok = 0 # 현재 IP 세션의 성공/차단(세션 종료 기록용, 재기동 시 리셋)
self._sess_blocked = 0
self._end_reason = None # 이번 세션이 끝나는 이유(budget/block/proxy_error/window/idle/shutdown)
self._last_used = 0.0 # 마지막 검색 시각(monotonic) — 유휴 브라우저 정리 판단용
self._cdp = None # CDP 세션(실제 네트워크 바이트 계측용). 미지원 시 None → DOM 크기 폴백
self._net_bytes = 0 # 현재 검색의 실제 전송 바이트(encodedDataLength 누적)
@@ -143,6 +153,8 @@ class BrowserSearchAdapter(SearchAdapter):
if self._ctx is not None:
if self._recycle_due():
LOG.d(f"[{self.source}] 브라우저 재기동(IP 회전)")
if self._end_reason is None: # force 가 아닌 시간창 만료 재기동
self._end_reason = "window"
await self._close_ctx()
else:
return
@@ -163,16 +175,35 @@ class BrowserSearchAdapter(SearchAdapter):
await self._ctx.route("**/*", self._route)
self._launched_at = time.monotonic()
self._ip_requests = 0
self._sess_ok = self._sess_blocked = 0
self._end_reason = None
self._force_recycle = False
async def _close_ctx(self):
self._cdp = None # 컨텍스트와 함께 CDP 세션도 죽음 → 다음 검색 때 재부착
if self._ctx is not None:
await self._record_session_end()
try:
await self._ctx.close()
finally:
self._ctx = None
async def _record_session_end(self):
"""IP 세션 종료 1건 기록 — '이 IP 로 몇 번 요청하고 어떻게 끝났나'. 예산(상한) 튜닝의 원천 데이터.
요청이 없던 세션(유휴 정리 등)은 노이즈라 기록하지 않는다. 기록 실패가 검색을 막지 않는다."""
if self._on_session_end is None or self._ip_requests == 0:
self._end_reason = None
return
event = {"source": self.source, "proxy_port": self._current_port,
"requests": self._ip_requests, "ok_count": self._sess_ok, "blocked_count": self._sess_blocked,
"elapsed_sec": int(time.monotonic() - self._launched_at),
"end_reason": self._end_reason or "window"}
self._end_reason = None
try:
await self._on_session_end(event)
except Exception as ex:
LOG.e_no_callstack(f"[{self.source}] IP 세션 기록 실패(무시): {ex}")
def _add_net(self, event):
"""CDP Network.loadingFinished 콜백 — 실제 전송 바이트(encodedDataLength) 누적."""
try:
@@ -196,12 +227,18 @@ class BrowserSearchAdapter(SearchAdapter):
"""이 어댑터가 프록시(DECODO)를 경유하는지 — 대역폭 비용 귀속용."""
return bool(self._proxy and self._proxy.enabled)
def _rotate_ip(self, reason: str):
"""즉시 다음 IP(포트)로 회전 예약 + 다음 _ensure_browser 에서 브라우저 재기동."""
def _budget_reached(self) -> bool:
"""현재 IP 로 요청 예산을 소진했는지(선제 회전 트리거). 프록시 미사용·예산 0(비활성)이면 False."""
return self.uses_proxy and self._ip_budget > 0 and self._ip_requests >= self._ip_budget
def _rotate_ip(self, reason: str, kind: str = "rotate", warn: bool = True):
"""즉시 다음 IP(포트)로 회전 예약 + 다음 _ensure_browser 에서 브라우저 재기동.
kind 는 세션 종료 사유로 기록된다(budget=선제/block=차단/proxy_error=포트사망)."""
if self._proxy and self._proxy.enabled:
self._proxy.rotate()
self._force_recycle = True
LOG.w(f"[{self.source}] IP 회전 — {reason}")
self._end_reason = kind
(LOG.w if warn else LOG.i)(f"[{self.source}] IP 회전 — {reason}")
# ---- 검색(프록시 전송오류·봇 감지 → IP 회전 인라인 재시도) --------
async def search(self, query: str, limit: int = 40) -> list[NormalizedProduct]:
@@ -210,6 +247,10 @@ class BrowserSearchAdapter(SearchAdapter):
proxy_retries, block_retries = self.max_proxy_retries, self._max_block_retries
while True:
await self._rl.wait()
# 예산 도달 → 차단당하기 전에 선제 회전. 이 포트는 불탄 게 아니라 쿨다운 없이
# 로테이션 복귀 시 재사용된다(IP 평판 보존이 목적).
if self._budget_reached():
self._rotate_ip(f"요청예산 {self._ip_budget}회 도달 — 선제 회전", kind="budget", warn=False)
await self._ensure_browser()
self._ip_requests += 1
page = self._ctx.pages[0] if self._ctx.pages else await self._ctx.new_page()
@@ -225,7 +266,8 @@ class BrowserSearchAdapter(SearchAdapter):
# 프록시 전송 실패(포트/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}")
self._proxy.mark_burned(self._current_port) # 죽은 포트 — 쿨다운 뒤 복귀(sticky 만료로 새 IP)
self._rotate_ip(f"프록시 전송오류({type(ex).__name__}) 재시도 {self.max_proxy_retries - proxy_retries}/{self.max_proxy_retries}", kind="proxy_error")
continue
raise AdapterError(f"{self.source} 검색 실패: {ex}", source=self.source) from ex
@@ -234,6 +276,7 @@ class BrowserSearchAdapter(SearchAdapter):
products = self._parse(html)
if products:
self._ok += 1
self._sess_ok += 1
LOG.d(f"[{self.source}] query={query!r} → {len(products)}건 (limit {limit}, ip_req#{self._ip_requests})")
return products[:limit]
@@ -241,13 +284,18 @@ class BrowserSearchAdapter(SearchAdapter):
blocked = marker is not None
self._blocked += 1
if blocked:
self._sess_blocked += 1
await self._report_detection(query, marker, len(html))
if self.uses_proxy:
self._proxy.mark_burned(self._current_port) # 불탄 포트 — 쿨다운 격리(로테이션이 건너뜀)
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}")
self._rotate_ip(f"봇 감지 재시도 {self._max_block_retries - block_retries}/{self._max_block_retries}", kind="block")
continue
if blocked: # 재시도 소진/비활성 — 불탄 포트로 다음 검색을 하지 않도록 회전만 예약하고 포기
self._rotate_ip("봇 감지 — 다음 검색은 새 IP", kind="block")
raise AdapterError(f"{self.source} 결과 없음/차단 (query={query!r}, blocked={blocked})", source=self.source, blocked=blocked)
async def _report_detection(self, query: str, marker: str, html_len: int):
@@ -279,12 +327,14 @@ class BrowserSearchAdapter(SearchAdapter):
async with self._lock:
if self._ctx is not None and time.monotonic() - self._last_used >= idle_sec:
LOG.d(f"[{self.source}] 유휴 {idle_sec:.0f}s 초과 → 브라우저 정리(다음 검색 때 재기동)")
if self._end_reason is None:
self._end_reason = "idle"
await self._close_ctx()
async def close(self):
if self._ctx is not None:
await self._ctx.close()
self._ctx = None
if self._end_reason is None:
self._end_reason = "shutdown"
await self._close_ctx()
if self._pw is not None:
await self._pw.stop()
self._pw = None