feat(lps): 관리자 FE 용 API 6종 — 잡 목록/재큐·상품 목록·IP세션/차단/비용 통계
React 관리자 페이지(협의: 모니터링+필수 액션)의 데이터 소스.
- GET /v1/lps/jobs: 최신순 목록+총건수, status/q(상품코드·명) 필터.
결과에 outcome·최저가·검색원가·오류를 평탄화해 목록에서 바로 보이게.
- POST /v1/lps/jobs/{id}/requeue: DEAD 재큐(attempts 리셋+pg_notify 워커
깨움). 활성 중복(dedupe)이면 DB_ALREADY_SAME_KEY 로 거절.
- GET /v1/lps/products: 상품별 최신 스냅샷+누적 검색 수(최근 검색순).
- GET /v1/lps/stats/ip-sessions: 종료사유 분포·요청수 히스토그램·차단
세션 최소 요청수(예산 튜닝 기준선)·최근 세션 50.
- GET /v1/lps/stats/bot: 시간대별 차단 + 최근 감지 목록.
- GET /v1/lps/stats/cost: 시간별 원가(AI/프록시 분해)+평균 소요.
- AdminService/admin_protocol/admin 라우터 신설, guard 일괄 적용.
설정 변경 UI 는 두지 않음 — toml 단일 소스 원칙.
- 테스트 9건 추가, 전체 154 passed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8fb54be830
commit
61b438d8d0
9 files changed
+596
No files matched your search
@@ -236,6 +236,82 @@ class JobQueue:
|
||||
finally:
|
||||
await DB_SESSION_MNG.end_session(self.DB, DBWRType.DB_READ.value)
|
||||
|
||||
# ---- 관리자(FE) 조회/액션 -------------------------------------------
|
||||
async def list_jobs(self, status: int | None = None, q: str | None = None,
|
||||
limit: int = 50, offset: int = 0) -> tuple[list[dict], int]:
|
||||
"""잡 목록(최신순) + 전체 건수. status(코드)·q(product_code/상품명 부분일치) 필터."""
|
||||
where = ["TRUE"]
|
||||
params: dict = {"limit": limit, "offset": offset}
|
||||
if status is not None:
|
||||
where.append("status = :st")
|
||||
params["st"] = status
|
||||
if q:
|
||||
where.append("(payload->>'product_code' ILIKE :q OR payload->>'product_name' ILIKE :q)")
|
||||
params["q"] = f"%{q}%"
|
||||
cond = " AND ".join(where)
|
||||
sql = text(f"""
|
||||
SELECT job_id, job_type, status, priority, attempts, max_attempts,
|
||||
payload->>'product_code' AS product_code, payload->>'product_name' AS product_name,
|
||||
result->>'outcome' AS outcome,
|
||||
(result#>>'{{lowest,price}}')::int AS final_lowest,
|
||||
(result#>>'{{metrics,cost,total_usd}}')::float AS cost_usd,
|
||||
last_error, created_at, run_started_at, updated_at
|
||||
FROM job WHERE {cond}
|
||||
ORDER BY created_at DESC LIMIT :limit OFFSET :offset
|
||||
""")
|
||||
cnt = text(f"SELECT count(*) FROM job WHERE {cond}")
|
||||
s = await DB_SESSION_MNG.start_session(self.DB, DBWRType.DB_READ.value)
|
||||
try:
|
||||
rows = [dict(r) for r in (await s.execute(sql, params)).mappings().all()]
|
||||
total = int((await s.execute(cnt, params)).scalar() or 0)
|
||||
for d in rows:
|
||||
d["job_id"] = str(d["job_id"])
|
||||
return rows, total
|
||||
finally:
|
||||
await DB_SESSION_MNG.end_session(self.DB, DBWRType.DB_READ.value)
|
||||
|
||||
async def requeue(self, job_id: str) -> str | None:
|
||||
"""DEAD 잡 재큐(관리자 액션): attempts 리셋 + PENDING 전이 + 워커 깨움.
|
||||
DEAD 가 아니거나 없으면 None. 같은 dedupe_key 의 활성 잡이 있으면 부분 유니크
|
||||
위반(IntegrityError) — 호출부가 '활성 중복'으로 안내한다."""
|
||||
sql = text("""
|
||||
UPDATE job SET status = 1, attempts = 0, run_after = now(),
|
||||
lease_until = NULL, worker_id = NULL, run_started_at = NULL,
|
||||
last_error = NULL, updated_at = now()
|
||||
WHERE job_id = CAST(:jid AS uuid) AND status = 4
|
||||
RETURNING job_id
|
||||
""")
|
||||
|
||||
async def run(s):
|
||||
row = (await s.execute(sql, {"jid": job_id})).first()
|
||||
if row:
|
||||
await s.execute(text("SELECT pg_notify(:ch, '')"), {"ch": JOB_NOTIFY_CHANNEL})
|
||||
return str(row[0]) if row else None
|
||||
|
||||
return await self._tx(run)
|
||||
|
||||
async def cost_buckets(self, hours: int = 48) -> list[dict]:
|
||||
"""시간별 검색원가 집계(완료 잡의 metrics 합산) — 비용 차트용."""
|
||||
sql = text("""
|
||||
SELECT date_trunc('hour', updated_at) AS bucket,
|
||||
count(*) AS jobs,
|
||||
COALESCE(sum((result#>>'{metrics,cost,ai_usd}')::float), 0) AS ai_usd,
|
||||
COALESCE(sum((result#>>'{metrics,cost,proxy_usd}')::float), 0) AS proxy_usd,
|
||||
COALESCE(sum((result#>>'{metrics,cost,total_usd}')::float), 0) AS total_usd,
|
||||
COALESCE(avg((result#>>'{metrics,duration_ms}')::float), 0) AS avg_ms
|
||||
FROM job
|
||||
WHERE status = 3 AND updated_at > now() - make_interval(hours => :h)
|
||||
GROUP BY 1 ORDER BY 1
|
||||
""")
|
||||
s = await DB_SESSION_MNG.start_session(self.DB, DBWRType.DB_READ.value)
|
||||
try:
|
||||
return [{"bucket": r["bucket"].isoformat(), "jobs": int(r["jobs"]),
|
||||
"ai_usd": round(float(r["ai_usd"]), 4), "proxy_usd": round(float(r["proxy_usd"]), 4),
|
||||
"total_usd": round(float(r["total_usd"]), 4), "avg_ms": int(r["avg_ms"])}
|
||||
for r in (await s.execute(sql, {"h": hours})).mappings().all()]
|
||||
finally:
|
||||
await DB_SESSION_MNG.end_session(self.DB, DBWRType.DB_READ.value)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
"""DB 도달성 확인(readiness). 실패 시 예외."""
|
||||
s = await DB_SESSION_MNG.start_session(self.DB, DBWRType.DB_READ.value)
|
||||
|
||||
Reference in new issue
Block a user