feat(lps): 알림 확장 — AlertManager 쿨다운·회복, DB풀 포화·소스별 장기실패 룰
기존 ops-monitor 는 임계 초과가 지속되면 30초마다 같은 웹훅을 반복 발송했고 (쿨다운 없음), 해소 여부도 알 수 없었다. 감시 항목도 큐 지표 4종뿐이었다. - common/alerts.py AlertManager 신설: 룰 키별 상태 관리 — 발화 1회 + 쿨다운(LPS_ALERT_COOLDOWN_MIN, 기본 30분)마다 리마인드, 해소 시 회복 알림 1회. sender/clock 주입으로 네트워크·대기 없이 단위 테스트. - 워커 ops-monitor 를 AlertManager 로 이관(기존 4룰 유지) + 신규 2룰: db_pool(풀 포화율 ≥ LPS_ALERT_POOL_PCT 90%) · source_fail:<src>(최근 30분 시도 ≥ LPS_ALERT_SOURCE_FAIL_30M(5) & 성공 0 — 쿼터 소진·셀렉터 드리프트·전면 차단 신호). - DBSessionManager.pool_status(): 전 엔진 합산 checked_out/capacity/pct. - SearchAdapter 에 시간 윈도우 성공/실패 카운터(recent_stats) — 누적 카운터로는 '최근 30분 성공 0건'을 볼 수 없어 추가. 쿠팡(브라우저)· 네이버(API) 성공/실패 지점에 배선. - API 자체 풀 모니터: lifespan 백그라운드 태스크(run_pool_monitor) — 대량 폴링으로 풀을 고갈시키는 주범이 API 자신일 수 있다. /v1/lps/ops 에 pool_checked_out/pool_capacity/pool_pct 노출(스모크 확인). - 테스트 9건 추가(발화·쿨다운·회복·룰 독립·윈도우 카운터·풀 현황), 전체 135 passed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3c5286aeec
commit
8b9e81777c
11 files changed
+297
-46
No files matched your search
@@ -8,6 +8,7 @@ import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import ErrorType, JobStatus, JobType
|
||||
from crud.job_crud import JobQueue
|
||||
from crud.price_history import PriceHistory
|
||||
@@ -74,9 +75,11 @@ class LpsService:
|
||||
return res
|
||||
|
||||
async def ops(self) -> dict:
|
||||
"""운영 스냅샷(모니터링·알림용, 플랫 JSON): 큐 카운트·지연·최근 DEAD·최근 차단 수."""
|
||||
"""운영 스냅샷(모니터링·알림용, 플랫 JSON): 큐 카운트·지연·최근 DEAD·최근 차단 수 + DB 풀 사용률."""
|
||||
snap = await self.queue.ops()
|
||||
snap["blocks_1h"] = await self.bot_log.recent_count(60)
|
||||
pool = DB_SESSION_MNG.pool_status() # API 프로세스 자신의 풀(워커 풀은 워커 ops-monitor 가 감시)
|
||||
snap["pool_checked_out"], snap["pool_capacity"], snap["pool_pct"] = pool["checked_out"], pool["capacity"], pool["pct"]
|
||||
return snap
|
||||
|
||||
async def price_history(self, product_code: str, limit: int = 100) -> Res_PriceHistory:
|
||||
|
||||
@@ -269,6 +269,7 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
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
|
||||
self._note_result(False)
|
||||
raise AdapterError(f"{self.source} 검색 실패: {ex}", source=self.source) from ex
|
||||
|
||||
# 실제 프록시 전송 바이트(CDP encodedDataLength) — 미지원 시 DOM 크기 폴백
|
||||
@@ -277,6 +278,7 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
if products:
|
||||
self._ok += 1
|
||||
self._sess_ok += 1
|
||||
self._note_result(True)
|
||||
LOG.d(f"[{self.source}] query={query!r} → {len(products)}건 (limit {limit}, ip_req#{self._ip_requests})")
|
||||
return products[:limit]
|
||||
|
||||
@@ -296,6 +298,7 @@ class BrowserSearchAdapter(SearchAdapter):
|
||||
|
||||
if blocked: # 재시도 소진/비활성 — 불탄 포트로 다음 검색을 하지 않도록 회전만 예약하고 포기
|
||||
self._rotate_ip("봇 감지 — 다음 검색은 새 IP", kind="block")
|
||||
self._note_result(False)
|
||||
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):
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
새 소스는 SearchAdapter 를 구현하기만 하면 코어 변경 없이 붙는다(트레드밀 격리).
|
||||
"""
|
||||
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -59,3 +61,24 @@ class SearchAdapter(ABC):
|
||||
async def health(self) -> AdapterHealth:
|
||||
"""기본 건강도. 어댑터가 관측 지표를 축적하면 override."""
|
||||
return AdapterHealth(source=self.source, ok=True)
|
||||
|
||||
# ---- 시간 윈도우 성공/실패 카운터(장기 실패 알림용) ------------------
|
||||
# 기존 _ok/_blocked 는 기동 후 누적이라 '최근 30분 성공 0건' 같은 장기 실패를 못 본다.
|
||||
# 어댑터의 search 성공/실패 지점에서 _note_result 를 부르면 ops-monitor 가 recent_stats 로 읽는다.
|
||||
# (lazy init — 서브클래스가 super().__init__ 을 부르지 않아도 동작)
|
||||
|
||||
def _note_result(self, ok: bool):
|
||||
ev = getattr(self, "_win_events", None)
|
||||
if ev is None:
|
||||
ev = self._win_events = deque(maxlen=512)
|
||||
ev.append((time.monotonic(), ok))
|
||||
|
||||
def recent_stats(self, window_sec: float = 1800.0) -> tuple[int, int]:
|
||||
"""최근 window_sec 내 (시도 수, 성공 수)."""
|
||||
now = time.monotonic()
|
||||
tries = ok = 0
|
||||
for t, s in getattr(self, "_win_events", ()):
|
||||
if now - t <= window_sec:
|
||||
tries += 1
|
||||
ok += s
|
||||
return tries, ok
|
||||
@@ -50,24 +50,29 @@ class NaverAdapter(SearchAdapter):
|
||||
|
||||
self.last_bytes = 0
|
||||
collected: list[dict] = []
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
start = 1
|
||||
while len(collected) < limit and start <= _MAX_START:
|
||||
display = min(_MAX_DISPLAY, limit - len(collected))
|
||||
data = await self._request(client, {
|
||||
"query": query, "display": display, "start": start,
|
||||
"sort": "sim", "exclude": "used:rental:cbshop",
|
||||
})
|
||||
items = data.get("items", [])
|
||||
if not items:
|
||||
break
|
||||
collected.extend(items)
|
||||
start += display
|
||||
if len(items) < display:
|
||||
break
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
start = 1
|
||||
while len(collected) < limit and start <= _MAX_START:
|
||||
display = min(_MAX_DISPLAY, limit - len(collected))
|
||||
data = await self._request(client, {
|
||||
"query": query, "display": display, "start": start,
|
||||
"sort": "sim", "exclude": "used:rental:cbshop",
|
||||
})
|
||||
items = data.get("items", [])
|
||||
if not items:
|
||||
break
|
||||
collected.extend(items)
|
||||
start += display
|
||||
if len(items) < display:
|
||||
break
|
||||
except Exception:
|
||||
self._note_result(False) # 장기 실패 알림용 윈도우 카운터(쿼터 소진·네트워크 포함)
|
||||
raise
|
||||
|
||||
products = transform_items(collected, self.source)
|
||||
self._ok += 1
|
||||
self._note_result(True)
|
||||
LOG.d(f"[naver] query={query!r} → {len(products)}건 (limit {limit})")
|
||||
return products[:limit]
|
||||
|
||||
|
||||
Reference in new issue
Block a user