크롤러는 JS 를 실행하지 않아 브라우저 트래커로는 안 잡힌다. nginx mirror 가 /s/·robots.txt·
sitemap.xml 요청의 사본을 /internal/track/hit 로 넘기고, 백엔드가 UA 로 봇만 골라
site_crawler_hits 에 1건 = 1행으로 쌓는다(Umami 와 같은 원본 이벤트 방식, 기한 없이 보관).
- crawler_detect: AEORanking 과 같은 19개 봇을 training/search/user-fetch/search-engine 으로 분류,
목록 밖이지만 스스로 봇이라 밝힌 UA 는 other. HeadlessChrome 은 우리 목업 검증 스크립트라 뺀다
- track_service: 슬러그→site_id 는 발행 때와 같은 publish_slug() 로 만든다 — domain 이 빈
사이트는 <이름>-<place_id 앞 8자> 로 발행되므로 domain 칼럼만 보면 못 찾는다. 퍼센트 인코딩·NFC 정규화
- /internal/track/hit: /v1 밖이라 nginx 가 밖으로 노출하지 않는다. 저장은 응답을 보낸 뒤 백그라운드 —
nginx 는 mirror 가 끝나기 전까지 같은 연결의 다음 요청을 읽지 않아서, DB 를 기다렸다 204 를 주면
DB 가 느릴 때 그 연결의 다른 요청까지 늦어진다
- GET /v1/ops/stats/crawlers · /v1/ops/sites/{place_id}/stats/crawlers (RequireDeveloper):
일별(KST)×용도 추이, 봇별, 사이트 순위, robots·sitemap, 기타 UA, 많이 읽힌 페이지, 최근 50건
- 0024 마이그레이션과 init.sql 을 함께 수정(둘 중 하나만 고치면 새 DB 와 서버 DB 가 갈라진다)
크롤러 테스트 31건 추가(전체 43건 통과). 전체 스위트 1081 passed · 50 failed 는 LLM 키 미설정·
cp949·스케줄러·SNS·날씨 문구 등 이번 변경과 무관한 기존 실패로 수정 전후 목록이 같다.
123 lines
5.4 KiB
Python
123 lines
5.4 KiB
Python
from abc import ABC, abstractmethod
|
|
from datetime import datetime
|
|
from typing import Tuple
|
|
|
|
from sqlalchemy import and_, distinct, func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import places, site_crawler_hits, sites
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from services.crawler_detect import AI_PURPOSES
|
|
|
|
|
|
class ICrawlerHitCRUD(ABC):
|
|
@abstractmethod
|
|
async def add_hit(self, cdb: AsyncSession, hit: site_crawler_hits) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_site_slugs(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
|
|
"""(ErrorType, [Row(place_id, name, site_id, domain)]) — 슬러그 → site_id 표 재료."""
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, site_id, overall: bool) -> Tuple[ErrorType, dict]:
|
|
"""기간 [start, end) 집계. 키: summary·daily·bots + (overall) sites·root_files·others | (사이트) pages·recent."""
|
|
pass
|
|
|
|
|
|
class CrawlerHitCRUD(ICrawlerHitCRUD):
|
|
async def add_hit(self, cdb: AsyncSession, hit: site_crawler_hits) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, hit)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def list_site_slugs(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
|
|
try:
|
|
query = (
|
|
select(places.place_id, places.name, sites.site_id, sites.domain)
|
|
.join(sites, and_(sites.place_id == places.place_id, sites.deleted == False)) # noqa: E712
|
|
.where(places.deleted == False) # noqa: E712
|
|
)
|
|
return await DB_SESSION_MNG.execute(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, []
|
|
|
|
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, site_id, overall: bool) -> Tuple[ErrorType, dict]:
|
|
try:
|
|
h = site_crawler_hits
|
|
where = and_(h.deleted == False, h.created_at >= start, h.created_at < end) # noqa: E712
|
|
if site_id is not None:
|
|
where = and_(where, h.site_id == site_id)
|
|
hits = func.count().label("hits")
|
|
ai_hits = func.count().filter(h.purpose.in_(AI_PURPOSES)).label("ai_hits")
|
|
last_at = func.max(h.created_at).label("last_at")
|
|
# GROUP BY 는 라벨("day")로 건다 — 같은 식을 두 번 쓰면 'Asia/Seoul' 이 다른 바인드 파라미터가 돼
|
|
# Postgres 가 "must appear in the GROUP BY clause" 로 거부한다.
|
|
day = func.date(func.timezone("Asia/Seoul", h.created_at)).label("day")
|
|
|
|
queries = {
|
|
"summary": select(hits, ai_hits, func.count(distinct(h.bot)).label("bots"), last_at).where(where),
|
|
"daily": select(day, h.purpose, hits).where(where).group_by("day", h.purpose).order_by("day", h.purpose),
|
|
"bots": (
|
|
select(h.bot, h.vendor, h.purpose, hits, last_at)
|
|
.where(where, h.bot.isnot(None))
|
|
.group_by(h.bot, h.vendor, h.purpose)
|
|
.order_by(func.count().desc())
|
|
.limit(50)
|
|
),
|
|
}
|
|
if overall:
|
|
queries["sites"] = (
|
|
select(h.site_id, places.place_id, places.name, hits, ai_hits, last_at)
|
|
.join(sites, sites.site_id == h.site_id)
|
|
.join(places, places.place_id == sites.place_id)
|
|
.where(where)
|
|
.group_by(h.site_id, places.place_id, places.name)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
queries["root_files"] = (
|
|
select(h.kind, h.bot, h.purpose, hits, last_at)
|
|
.where(where, h.kind.in_(("robots", "sitemap")))
|
|
.group_by(h.kind, h.bot, h.purpose)
|
|
.order_by(h.kind, func.count().desc())
|
|
)
|
|
queries["others"] = (
|
|
select(h.user_agent, hits, last_at)
|
|
.where(where, h.purpose == "other")
|
|
.group_by(h.user_agent)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
else:
|
|
queries["pages"] = (
|
|
select(h.path, hits, last_at)
|
|
.where(where, h.kind == "page")
|
|
.group_by(h.path)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
queries["recent"] = (
|
|
select(h.created_at, h.kind, h.bot, h.vendor, h.purpose, h.path)
|
|
.where(where)
|
|
.order_by(h.created_at.desc())
|
|
.limit(50)
|
|
)
|
|
|
|
out: dict = {}
|
|
for key, query in queries.items():
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
out[key] = list(rows)
|
|
return ErrorType.SUCCESS, out
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|