[feat] solution/backend,postgres-init: AI 크롤러 요청 기록과 통계 API — 사이트관리 통계의 수집·조회 쪽

크롤러는 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·날씨 문구 등 이번 변경과 무관한 기존 실패로 수정 전후 목록이 같다.
This commit is contained in:
skkim committed 2026-10-08 11:31:49 +09:00
1 parent c0f361b831
commit 603189d3a1
16 files changed
+945 -3

No files matched your search

+11
View File
@@ -267,6 +267,17 @@ Gemini 가 쓰고, 곡은 Suno 가 붙인다.
화면의 반려 카드가 이 사유 코드로 문구를 고른다 — 전부 "렌더 실패" 로 뭉개면 사장님이
손댈 곳을 모른다.
### `site_crawler_hits` — 봇 요청 기록 (2026-10-07)
nginx 가 `/s/…`·`/robots.txt`·`/sitemap.xml` 요청을 mirror 로 `/internal/track/hit` 에 넘기고,
백엔드가 UA 로 봇만 골라 **1건 = 1행**으로 쌓는다(`services/track_service.py`). 집계 표는 없다 —
사이트관리 통계가 조회 때 `GROUP BY` 한다. 기한 없이 보관한다.
- `purpose`: `training` · `search` · `user-fetch` · `search-engine` · `other`(목록 밖 봇). 목록은
`services/crawler_detect.py` — AEORanking 과 같게 둔다.
- `site_id`: 슬러그를 `site_payload.publish_slug()` 로 만든 표에서 찾는다. robots·sitemap·없는 슬러그는 NULL.
- `ip`: 목록 봇만. 사람 요청은 저장하지 않는다.
### `jobs` — 작업 큐 (PostgreSQL 을 큐로)
COPY 단계는 `jobs.progress`(JSONB)의 `steps`·`attempt`에 기록한다.
+20
View File
@@ -357,6 +357,21 @@ CREATE TABLE IF NOT EXISTS public.alert_outbox (
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS public.site_crawler_hits (
hit_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
site_id uuid NULL, -- robots·sitemap·없는 슬러그는 NULL
path TEXT NOT NULL,
kind VARCHAR(10) NOT NULL, -- page · robots · sitemap
bot VARCHAR(40) NULL, -- 목록 밖(other)이면 NULL
vendor VARCHAR(40) NULL,
purpose VARCHAR(20) NOT NULL, -- training · search · user-fetch · search-engine · other
user_agent TEXT NOT NULL,
ip VARCHAR(45) NULL, -- 목록 봇만(migrations/0024)
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS public.place_posts (
post_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
place_id uuid NOT NULL,
@@ -584,6 +599,11 @@ CREATE INDEX IF NOT EXISTS ix_alert_outbox_pending ON public.alert_outbox (statu
CREATE INDEX IF NOT EXISTS ix_alert_outbox_dedupe ON public.alert_outbox (dedupe_key, created_at DESC)
WHERE dedupe_key IS NOT NULL;
-- site_crawler_hits — 사이트별 기간 조회 · 전체 기간 조회 · 봇별 조회(migrations/0024).
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_site ON public.site_crawler_hits (site_id, created_at);
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_created ON public.site_crawler_hits (created_at);
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_bot ON public.site_crawler_hits (bot, created_at);
-- ============================================================
-- 마이그레이션 기준선(baseline)
-- ============================================================
@@ -0,0 +1,32 @@
-- 0024 · site_crawler_hits — 봇 요청 기록(사이트 트래픽 통계 1단계)
--
-- ★ 크롤러는 JS 를 실행하지 않아 브라우저 트래커로는 안 잡힌다. nginx 가 /s/·robots.txt·
-- sitemap.xml 요청을 mirror 로 백엔드에 넘기고(nginx/site.conf `_track_hit`), 백엔드가 UA 로
-- 봇만 골라 여기에 1건 = 1행으로 쌓는다. 집계 표는 두지 않는다 — 조회 때 GROUP BY 한다.
CREATE TABLE IF NOT EXISTS public.site_crawler_hits (
hit_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
site_id uuid NULL,
path TEXT NOT NULL,
kind VARCHAR(10) NOT NULL,
bot VARCHAR(40) NULL,
vendor VARCHAR(40) NULL,
purpose VARCHAR(20) NOT NULL,
user_agent TEXT NOT NULL,
ip VARCHAR(45) NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
COMMENT ON COLUMN public.site_crawler_hits.site_id IS
'robots·sitemap 과 없는 슬러그는 NULL';
COMMENT ON COLUMN public.site_crawler_hits.kind IS 'page · robots · sitemap';
COMMENT ON COLUMN public.site_crawler_hits.purpose IS
'training · search · user-fetch · search-engine · other(목록 밖 봇)';
COMMENT ON COLUMN public.site_crawler_hits.ip IS
'목록 봇만 저장 — other 에는 봇을 흉내 낸 사람이 섞일 수 있다';
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_site ON public.site_crawler_hits (site_id, created_at);
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_created ON public.site_crawler_hits (created_at);
CREATE INDEX IF NOT EXISTS ix_site_crawler_hits_bot ON public.site_crawler_hits (bot, created_at);
@@ -447,6 +447,29 @@ class alert_outbox(MainTableMixin, MAIN_BASE):
resolved_at = Column(DateTime(timezone=True), nullable=True)
class site_crawler_hits(MainTableMixin, MAIN_BASE):
"""봇 요청 1건 = 1행 — nginx mirror 가 /internal/track/hit 로 넘긴 것. 기한 없이 보관한다(Umami 와 같다)."""
__tablename__ = "site_crawler_hits"
__table_args__ = (
Index("ix_site_crawler_hits_site", "site_id", "created_at"),
Index("ix_site_crawler_hits_created", "created_at"),
Index("ix_site_crawler_hits_bot", "bot", "created_at"),
)
hit_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
# robots·sitemap 은 오리진 공용이라, 없는 슬러그는 사이트를 못 찾아서 NULL 이다.
site_id = Column(UUID(as_uuid=True), nullable=True)
path = Column(Text, nullable=False)
kind = Column(String(10), nullable=False) # page · robots · sitemap
bot = Column(String(40), nullable=True) # 목록 밖(other)이면 NULL
vendor = Column(String(40), nullable=True)
purpose = Column(String(20), nullable=False) # training · search · user-fetch · search-engine · other
user_agent = Column(Text, nullable=False)
# 목록 봇만 남긴다 — other 에는 봇 UA 를 흉내 낸 사람이 섞일 수 있다.
ip = Column(String(45), nullable=True)
class site_sections(MainTableMixin, MAIN_BASE):
"""섹션 하나의 콘텐츠."""
+122
View File
@@ -0,0 +1,122 @@
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, {}
+3
View File
@@ -26,6 +26,7 @@ import router.v1.site.post
import router.v1.site.review
import router.v1.local.local
import router.v1.ops.ops
import router.v1.track.track
import router.v1.social.social
import router.v1.social.oauth
import router.v1.agent.kakao
@@ -127,6 +128,8 @@ app.include_router(router.v1.site.review.router)
app.include_router(router.v1.local.local.router)
app.include_router(router.v1.local.local.weather_router)
app.include_router(router.v1.ops.ops.router)
# nginx mirror 전용 수집점(/internal — 외부 비노출).
app.include_router(router.v1.track.track.router)
app.include_router(router.v1.social.social.router)
app.include_router(router.v1.social.oauth.router)
+27 -1
View File
@@ -1,9 +1,13 @@
import uuid
from datetime import date
from fastapi import APIRouter, Depends, Query
from common.models.gmodel import PageParams
from router.v1.validator.dependencies import RemoveNoneResponse, RequireDeveloper
from services.crawler_stats_service import CrawlerStatsService
from services.ops_service import OpsService
from .protocol import Res_OpsSites, Res_OpsUsers
from .protocol import Res_CrawlerStats, Res_OpsSites, Res_OpsUsers
# 내부 운영(개발자) 전용 조회 — 회사 스코프를 걷어낸 전 계정 사이트·유저 목록.
router = APIRouter(prefix="/v1/ops", tags=["Ops"])
@@ -28,3 +32,25 @@ async def list_users(
_user=Depends(RequireDeveloper),
):
return RemoveNoneResponse(await service.list_users(pg, search))
@router.get(path="/stats/crawlers", response_model=Res_CrawlerStats, summary="전체 크롤러 통계(개발자 전용)")
async def crawler_stats(
service: CrawlerStatsService = Depends(),
date_from: date | None = Query(None, alias="from", description="KST 날짜, 기본 to-6일"),
date_to: date | None = Query(None, alias="to", description="KST 날짜, 기본 오늘"),
_user=Depends(RequireDeveloper),
):
return RemoveNoneResponse(await service.overall(date_from, date_to))
@router.get(path="/sites/{place_id}/stats/crawlers", response_model=Res_CrawlerStats,
summary="사이트별 크롤러 통계(개발자 전용)")
async def site_crawler_stats(
place_id: uuid.UUID,
service: CrawlerStatsService = Depends(),
date_from: date | None = Query(None, alias="from", description="KST 날짜, 기본 to-6일"),
date_to: date | None = Query(None, alias="to", description="KST 날짜, 기본 오늘"),
_user=Depends(RequireDeveloper),
):
return RemoveNoneResponse(await service.for_place(place_id, date_from, date_to))
+78 -2
View File
@@ -1,9 +1,11 @@
import uuid
from datetime import datetime
from datetime import date, datetime
from typing import Optional
from pydantic import Field
from common.enums import AuthProvider, PlaceCategory, PlaceStatus, SiteStatus, UserRole, UserStatus
from common.models.gmodel import Res_PageProtocol, WebPacketProtocol
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
class OpsSiteData(WebPacketProtocol):
@@ -49,3 +51,77 @@ class OpsUserData(WebPacketProtocol):
class Res_OpsUsers(Res_PageProtocol):
users: list[OpsUserData] = []
class CrawlerSummary(WebPacketProtocol):
total: int = 0
ai: int = 0 # training + search + user-fetch
bots: int = 0 # 서로 다른 목록 봇 수
last_at: Optional[datetime] = None
class CrawlerDaily(WebPacketProtocol):
day: date # KST
purpose: str
hits: int
class CrawlerBotRow(WebPacketProtocol):
bot: Optional[str] = None
vendor: Optional[str] = None
purpose: str
hits: int
last_at: datetime
class CrawlerSiteRow(WebPacketProtocol):
site_id: uuid.UUID
place_id: uuid.UUID
name: str
hits: int
ai_hits: int
last_at: datetime
class CrawlerRootRow(WebPacketProtocol):
kind: str # robots · sitemap
bot: Optional[str] = None
purpose: str
hits: int
last_at: datetime
class CrawlerUaRow(WebPacketProtocol):
user_agent: str
hits: int
last_at: datetime
class CrawlerPathRow(WebPacketProtocol):
path: str
hits: int
last_at: datetime
class CrawlerHitRow(WebPacketProtocol):
created_at: datetime
kind: str
bot: Optional[str] = None
vendor: Optional[str] = None
purpose: str
path: str
class Res_CrawlerStats(Res_WebPacketProtocol):
"""전체(sites·root_files·others)와 사이트별(pages·recent)이 같은 모델을 쓴다 — 해당 없는 칸은 비어 있다."""
date_from: Optional[date] = None
date_to: Optional[date] = None
summary: CrawlerSummary = Field(default_factory=CrawlerSummary)
daily: list[CrawlerDaily] = []
bots: list[CrawlerBotRow] = []
sites: list[CrawlerSiteRow] = []
root_files: list[CrawlerRootRow] = []
others: list[CrawlerUaRow] = []
pages: list[CrawlerPathRow] = []
recent: list[CrawlerHitRow] = []
Whitespace-only changes.
+30
View File
@@ -0,0 +1,30 @@
from fastapi import APIRouter, BackgroundTasks, Depends, Request, Response
from common.logger import LOG
from services.track_service import TrackService
# nginx mirror 전용. /v1 밖에 두는 이유: nginx 는 /v1/ 만 백엔드로 넘기므로 밖에서 이 경로를 부를 길이 없다.
# include_in_schema=False — orval 이 이 경로로 클라이언트를 만들지 않게.
router = APIRouter(prefix="/internal/track", include_in_schema=False)
async def _record(service: TrackService, uri: str, user_agent: str | None, xff: str | None) -> None:
try:
await service.record_hit(uri=uri, user_agent=user_agent, xff=xff)
except Exception as ex: # noqa: BLE001 — 기록 실패가 크롤링 응답을 늦추거나 깨면 안 된다
LOG.w(f"[track] 크롤러 기록 실패: {type(ex).__name__}: {ex}")
# mirror 는 원래 요청의 메서드를 그대로 쓴다 — 봇의 HEAD 요청도 받는다.
# ★ 저장은 응답을 보낸 **뒤** 백그라운드로 돈다. nginx 는 mirror 하위 요청이 끝나기 전까지 같은 연결의
# 다음 요청을 읽지 않으므로, DB 를 기다렸다 204 를 주면 DB 가 느릴 때 그 연결의 다른 요청까지 늦어진다.
@router.api_route("/hit", methods=["GET", "HEAD"], status_code=204)
async def record_hit(request: Request, background: BackgroundTasks, service: TrackService = Depends()):
background.add_task(
_record,
service,
request.headers.get("x-original-uri", ""),
request.headers.get("user-agent"),
request.headers.get("x-forwarded-for"),
)
return Response(status_code=204)
@@ -0,0 +1,62 @@
"""자칭 크롤러 판별 — UA 만 본다.
UA 는 위조할 수 있다. 여기서 세는 것은 "자칭 크롤러"이고 IP 대역으로 진위를 확인하지 않는다.
목록은 AEORanking(킹서버 AEORankingPlatform/frontend/src/lib/analytics/ai-crawlers.ts)과 같게 둔다 —
두 서비스의 통계를 나란히 놓고 볼 때 분류가 갈리면 비교가 안 된다.
"""
import re
from dataclasses import dataclass
# training: 모델 학습 수집 · search: AI 답변 엔진 색인 · user-fetch: 사용자가 물어서 그 자리에서 여는 요청
# search-engine: 전통 검색 크롤러(AI 답변에도 쓰인다) · other: 목록 밖이지만 스스로 봇이라 밝힌 것
AI_PURPOSES = ("training", "search", "user-fetch")
@dataclass(frozen=True)
class CrawlerMatch:
bot: str | None
vendor: str | None
purpose: str
_KNOWN: tuple[tuple[str, str, str, re.Pattern], ...] = tuple(
(bot, vendor, purpose, re.compile(pattern, re.IGNORECASE))
for bot, vendor, purpose, pattern in (
("GPTBot", "OpenAI", "training", r"\bGPTBot\b"),
("OAI-SearchBot", "OpenAI", "search", r"\bOAI-SearchBot\b"),
("ChatGPT-User", "OpenAI", "user-fetch", r"\bChatGPT-User\b"),
("ClaudeBot", "Anthropic", "training", r"\bClaudeBot\b"),
("Claude-SearchBot", "Anthropic", "search", r"\bClaude-SearchBot\b"),
("Claude-User", "Anthropic", "user-fetch", r"\bClaude-User\b"),
("PerplexityBot", "Perplexity", "search", r"\bPerplexityBot\b"),
("Perplexity-User", "Perplexity", "user-fetch", r"\bPerplexity-User\b"),
("meta-externalagent", "Meta", "training", r"\bmeta-externalagent\b"),
("meta-externalfetcher", "Meta", "user-fetch", r"\bmeta-externalfetcher\b"),
("MistralAI-User", "Mistral", "user-fetch", r"\bMistralAI-User\b"),
("DuckAssistBot", "DuckDuckGo", "search", r"\bDuckAssistBot\b"),
("Amazonbot", "Amazon", "search", r"\bAmazonbot\b"),
("Bytespider", "ByteDance", "training", r"\bBytespider\b"),
("CCBot", "Common Crawl", "training", r"\bCCBot\b"),
("Googlebot", "Google", "search-engine", r"\bGooglebot\b"),
("bingbot", "Microsoft", "search-engine", r"\bbingbot\b"),
("Applebot", "Apple", "search-engine", r"\bApplebot\b"),
("Yeti", "Naver", "search-engine", r"\bYeti/"),
)
)
# 목록에 없는 새 봇을 놓치지 않으려고 둔다 — 쌓인 UA 를 보고 목록에 올린다.
# HeadlessChrome 은 일부러 안 넣는다: 우리 목업 검증 스크립트가 그 UA 로 돈다.
_GENERIC = re.compile(r"bot|crawl|spider|slurp|externalhit|fetch", re.IGNORECASE)
_OTHER = CrawlerMatch(None, None, "other")
def classify(user_agent: str | None) -> CrawlerMatch | None:
if not user_agent:
return None
for bot, vendor, purpose, pattern in _KNOWN:
if pattern.search(user_agent):
return CrawlerMatch(bot, vendor, purpose)
if _GENERIC.search(user_agent):
return _OTHER
return None
@@ -0,0 +1,93 @@
"""사이트관리 크롤러 통계 — 기간을 KST 날짜로 해석하고 CRUD 집계를 응답 모델로 옮긴다."""
from datetime import date, datetime, time, timedelta, timezone
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import site_crawler_hits, sites
from common.enums import DBWRType, ErrorType
from crud.crawler_hit_crud import CrawlerHitCRUD, ICrawlerHitCRUD
from crud.site_crud import ISiteCRUD, SiteCRUD
from router.v1.ops.protocol import (
CrawlerBotRow, CrawlerDaily, CrawlerHitRow, CrawlerPathRow, CrawlerRootRow, CrawlerSiteRow,
CrawlerSummary, CrawlerUaRow, Res_CrawlerStats,
)
# 한국은 서머타임이 없다 — zoneinfo(Windows 에선 tzdata 패키지가 따로 필요)를 쓰지 않고 고정 오프셋으로 둔다.
KST = timezone(timedelta(hours=9))
DEFAULT_DAYS = 7
MAX_DAYS = 366
def resolve_range(date_from: date | None, date_to: date | None, today: date | None = None) -> tuple[date, date] | None:
"""빈 값은 '오늘(KST)까지 7일'. 뒤집혔거나 366일을 넘으면 None — 원본 GROUP BY 라 무한정 넓히지 않는다."""
to = date_to or today or datetime.now(KST).date()
frm = date_from or (to - timedelta(days=DEFAULT_DAYS - 1))
if frm > to or (to - frm).days >= MAX_DAYS:
return None
return frm, to
def _bounds(frm: date, to: date) -> tuple[datetime, datetime]:
return datetime.combine(frm, time.min, tzinfo=KST), datetime.combine(to + timedelta(days=1), time.min, tzinfo=KST)
class CrawlerStatsService:
def __init__(self, crud: ICrawlerHitCRUD = Depends(CrawlerHitCRUD), site_crud: ISiteCRUD = Depends(SiteCRUD)):
self.crud = crud
self.site_crud = site_crud
async def overall(self, date_from: date | None, date_to: date | None) -> Res_CrawlerStats:
return await self._build(date_from, date_to, site_id=None, overall=True)
async def for_place(self, place_id, date_from: date | None, date_to: date | None) -> Res_CrawlerStats:
err_type, site = await DB_SESSION_MNG.execute_lambda(
sites.DBType(), DBWRType.DB_READ.value, lambda s: self.site_crud.get_site_by_place(s, place_id)
)
if err_type != ErrorType.SUCCESS:
res = Res_CrawlerStats()
res.result.SetResult(err_type)
return res
if site is None:
# 사이트를 아직 안 만든 사업장 — 크롤링될 주소가 없으니 빈 통계가 맞는 답이다.
rng = resolve_range(date_from, date_to)
return Res_CrawlerStats(date_from=rng[0], date_to=rng[1]) if rng else self._invalid()
return await self._build(date_from, date_to, site_id=site.site_id, overall=False)
@staticmethod
def _invalid() -> Res_CrawlerStats:
res = Res_CrawlerStats()
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
return res
async def _build(self, date_from, date_to, site_id, overall: bool) -> Res_CrawlerStats:
rng = resolve_range(date_from, date_to)
if rng is None:
return self._invalid()
frm, to = rng
start, end = _bounds(frm, to)
err_type, data = await DB_SESSION_MNG.execute_lambda(
site_crawler_hits.DBType(), DBWRType.DB_READ.value,
lambda s: self.crud.stats(s, start, end, site_id, overall),
)
res = Res_CrawlerStats(date_from=frm, date_to=to)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
summary = data["summary"][0]
res.summary = CrawlerSummary(total=summary.hits, ai=summary.ai_hits, bots=summary.bots, last_at=summary.last_at)
res.daily = [CrawlerDaily(day=r.day, purpose=r.purpose, hits=r.hits) for r in data["daily"]]
res.bots = [CrawlerBotRow(bot=r.bot, vendor=r.vendor, purpose=r.purpose, hits=r.hits, last_at=r.last_at)
for r in data["bots"]]
if overall:
res.sites = [CrawlerSiteRow(site_id=r.site_id, place_id=r.place_id, name=r.name, hits=r.hits,
ai_hits=r.ai_hits, last_at=r.last_at) for r in data["sites"]]
res.root_files = [CrawlerRootRow(kind=r.kind, bot=r.bot, purpose=r.purpose, hits=r.hits, last_at=r.last_at)
for r in data["root_files"]]
res.others = [CrawlerUaRow(user_agent=r.user_agent, hits=r.hits, last_at=r.last_at) for r in data["others"]]
else:
res.pages = [CrawlerPathRow(path=r.path, hits=r.hits, last_at=r.last_at) for r in data["pages"]]
res.recent = [CrawlerHitRow(created_at=r.created_at, kind=r.kind, bot=r.bot, vendor=r.vendor,
purpose=r.purpose, path=r.path) for r in data["recent"]]
return res
+110
View File
@@ -0,0 +1,110 @@
"""nginx mirror 가 넘긴 요청 중 봇 요청을 기록한다(사이트 트래픽 통계 1단계)."""
import re
import time
import unicodedata
from urllib.parse import unquote, urlsplit
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import site_crawler_hits
from common.enums import DBWRType, ErrorType
from common.logger import LOG
from crud.crawler_hit_crud import CrawlerHitCRUD, ICrawlerHitCRUD
from services.crawler_detect import classify
from services.site_payload import publish_slug
# 발행·이름 변경이 반영되는 데 이 정도 늦어도 통계에는 문제가 없다.
_SLUG_TTL_SEC = 60.0
# 없는 슬러그(오타·내린 사이트)를 두드리는 봇이 매번 표를 다시 읽게 하지 않는다.
_SLUG_RETRY_SEC = 5.0
# nginx 가 1차로 끊지만(site.conf `$track_skip`), 설정이 어긋나도 사진 요청이 "페이지" 로 쌓이지 않게 한 번 더 본다.
_FILE_EXT = re.compile(r"\.[A-Za-z0-9]+$")
def hit_kind(uri: str) -> str | None:
path = urlsplit(uri or "").path
if path == "/robots.txt":
return "robots"
if path == "/sitemap.xml":
return "sitemap"
if path.startswith("/s/") and len(path) > 3 and not _FILE_EXT.search(path):
return "page"
return None
def slug_of(uri: str) -> str | None:
segment = urlsplit(uri or "").path[3:].split("/", 1)[0]
if not segment:
return None
# 발행 슬러그는 NFC 다(site_payload.slugify). 브라우저·봇이 NFD 로 보내도 같은 사이트로 묶는다.
return unicodedata.normalize("NFC", unquote(segment))
def client_ip(xff: str | None) -> str | None:
# 앞단 Apache 를 거치므로 nginx 의 $remote_addr 는 늘 Apache 다 — 첫 XFF 값이 실제 요청자다.
first = (xff or "").split(",")[0].strip()
return first[:45] or None
class TrackService:
# 요청마다 새 인스턴스(Depends)라 캐시는 클래스에 둔다.
_slug_map: dict = {}
_slug_loaded_at: float = float("-inf")
def __init__(self, crud: ICrawlerHitCRUD = Depends(CrawlerHitCRUD)):
self.crud = crud
@classmethod
def reset_cache(cls) -> None:
cls._slug_map = {}
cls._slug_loaded_at = float("-inf")
async def record_hit(self, uri: str, user_agent: str | None, xff: str | None) -> None:
kind = hit_kind(uri)
if kind is None:
return
match = classify(user_agent)
if match is None:
return
site_id = await self._site_id(slug_of(uri)) if kind == "page" else None
hit = site_crawler_hits(
site_id=site_id,
path=unquote(uri),
kind=kind,
bot=match.bot,
vendor=match.vendor,
purpose=match.purpose,
user_agent=user_agent or "",
ip=client_ip(xff) if match.bot else None,
)
err = await DB_SESSION_MNG.execute_lambda_run(
[site_crawler_hits.DBType()], [lambda s: self.crud.add_hit(s, hit)]
)
if err != ErrorType.SUCCESS:
LOG.w(f"[track] 크롤러 기록 저장 실패: {err.name} {match.bot or 'other'} {kind}")
async def _site_id(self, slug: str | None):
if not slug:
return None
cls = TrackService
age = time.monotonic() - cls._slug_loaded_at
if age > _SLUG_TTL_SEC or (slug not in cls._slug_map and age > _SLUG_RETRY_SEC):
await self._reload_slugs()
return cls._slug_map.get(slug)
async def _reload_slugs(self) -> None:
cls = TrackService
# 실패해도 시각은 옮긴다 — DB 가 죽은 동안 요청마다 다시 읽으러 가지 않게.
cls._slug_loaded_at = time.monotonic()
err, rows = await DB_SESSION_MNG.execute_lambda(
site_crawler_hits.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.list_site_slugs(s)
)
if err != ErrorType.SUCCESS:
LOG.w(f"[track] 슬러그 표를 못 읽어 이전 표를 쓴다: {err.name}")
return
# 발행 주소와 같은 함수로 만든다 — domain 이 빈 사이트는 <이름>-<place_id 앞 8자> 로 발행된다.
cls._slug_map = {
publish_slug({"place_id": str(r.place_id), "name": r.name}, {"domain": r.domain}): r.site_id
for r in rows
}
@@ -0,0 +1,52 @@
import pytest
from services.crawler_detect import CrawlerMatch, classify
KNOWN = [
("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36; compatible; OAI-SearchBot/1.3; +https://openai.com/searchbot",
CrawlerMatch("OAI-SearchBot", "OpenAI", "search")),
("Mozilla/5.0 (compatible; Yeti/1.1; +https://naver.me/spd)", CrawlerMatch("Yeti", "Naver", "search-engine")),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko; compatible; Yeti/1.1; +https://naver.me/spd) Chrome/131.0.0.0 Safari/537.36",
CrawlerMatch("Yeti", "Naver", "search-engine")),
("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 (compatible; meta-externalagent/1.1 (+https://developers.facebook.com/docs/sharing/webmasters/crawler))",
CrawlerMatch("meta-externalagent", "Meta", "training")),
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/116.0.1938.76 Safari/537.36",
CrawlerMatch("bingbot", "Microsoft", "search-engine")),
("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", CrawlerMatch("Googlebot", "Google", "search-engine")),
("Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
CrawlerMatch("Googlebot", "Google", "search-engine")),
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)", CrawlerMatch("GPTBot", "OpenAI", "training")),
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ChatGPT-User/1.0; +https://openai.com/bot)", CrawlerMatch("ChatGPT-User", "OpenAI", "user-fetch")),
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)", CrawlerMatch("PerplexityBot", "Perplexity", "search")),
("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)", CrawlerMatch("ClaudeBot", "Anthropic", "training")),
]
OTHER = [
"facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
"AIO2O-Bot/1.0 (+https://aio2o.com/bot)",
]
HUMAN_OR_TOOL = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Mozilla/5.0 (Linux; Android 16; SM-F731N Build/BP4A.251005.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/140.0.0.0 Mobile Safari/537.36 BizWebView KAKAOTALK/26.1.0 (PFINAPP)",
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1 NAVER(inapp; search; 2100; 12.10.5; 16)",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/131.0.0.0 Safari/537.36",
"curl/8.5.0",
"",
None,
]
@pytest.mark.parametrize("ua,expected", KNOWN)
def test_목록_봇은_이름_회사_용도를_붙인다(ua, expected):
assert classify(ua) == expected
@pytest.mark.parametrize("ua", OTHER)
def test_목록_밖_봇은_기타로_남긴다(ua):
assert classify(ua) == CrawlerMatch(None, None, "other")
@pytest.mark.parametrize("ua", HUMAN_OR_TOOL)
def test_사람과_도구는_버린다(ua):
assert classify(ua) is None
@@ -0,0 +1,111 @@
import uuid
from datetime import date, datetime
from sqlalchemy import text
from common.enums import UserRole
from services.crawler_stats_service import resolve_range
async def _site(client, auth_headers, db_engine, name):
owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}")
pid = (await client.post("/v1/place", headers=owner, json={"name": name, "category": 2})).json()["place"]["place_id"]
async with db_engine.begin() as conn:
await conn.execute(text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"),
{"p": pid})
sid = (await conn.execute(text("SELECT site_id::text FROM sites WHERE place_id = :p AND deleted = false"),
{"p": pid})).scalar_one()
return pid, sid
async def _hit(db_engine, at, *, site_id=None, kind="page", bot="OAI-SearchBot", vendor="OpenAI",
purpose="search", path="/s/x", ua="ua"):
async with db_engine.begin() as conn:
await conn.execute(text(
"INSERT INTO site_crawler_hits (hit_id, site_id, path, kind, bot, vendor, purpose, user_agent, created_at) "
"VALUES (gen_random_uuid(), :site_id, :path, :kind, :bot, :vendor, :purpose, :ua, :at)"
), {"site_id": site_id, "path": path, "kind": kind, "bot": bot, "vendor": vendor,
"purpose": purpose, "ua": ua, "at": datetime.fromisoformat(at)})
def test_기간_기본값은_오늘까지_7일():
assert resolve_range(None, None, today=date(2026, 10, 7)) == (date(2026, 10, 1), date(2026, 10, 7))
def test_뒤집힌_기간과_366일_넘는_기간은_거부한다():
assert resolve_range(date(2026, 10, 7), date(2026, 10, 1)) is None
assert resolve_range(date(2025, 1, 1), date(2026, 10, 7)) is None
async def test_일별_집계는_KST_날짜로_자른다(client, auth_headers, db_engine):
dev = await auth_headers("dev1", role=UserRole.DEVELOPER.value)
await _hit(db_engine, "2026-10-06T14:59:00+00:00") # KST 10-06 23:59
await _hit(db_engine, "2026-10-06T15:30:00+00:00") # KST 10-07 00:30
body = (await client.get("/v1/ops/stats/crawlers", headers=dev,
params={"from": "2026-10-07", "to": "2026-10-07"})).json()
assert body["result"]["success"] is True
assert body["summary"]["total"] == 1
assert body["daily"] == [{"day": "2026-10-07", "purpose": "search", "hits": 1}]
async def test_전체_통계는_봇_사이트_공용파일_기타를_모은다(client, auth_headers, db_engine):
dev = await auth_headers("dev2", role=UserRole.DEVELOPER.value)
pid, sid = await _site(client, auth_headers, db_engine, "통계카페")
at = "2026-10-07T03:00:00+00:00"
await _hit(db_engine, at, site_id=sid)
await _hit(db_engine, at, site_id=sid, bot="Googlebot", vendor="Google", purpose="search-engine")
await _hit(db_engine, at, kind="robots", path="/robots.txt")
await _hit(db_engine, at, bot=None, vendor=None, purpose="other", ua="AIO2O-Bot/1.0")
body = (await client.get("/v1/ops/stats/crawlers", headers=dev,
params={"from": "2026-10-07", "to": "2026-10-07"})).json()
assert body["summary"]["total"] == 4
assert body["summary"]["ai"] == 2 # search 2건(사이트 1 + robots 1). search-engine·other 는 AI 아님
assert body["summary"]["bots"] == 2 # OAI-SearchBot, Googlebot
assert {(b["bot"], b["hits"]) for b in body["bots"]} == {("OAI-SearchBot", 2), ("Googlebot", 1)}
[site] = body["sites"]
assert (site["place_id"], site["name"], site["hits"], site["ai_hits"]) == (pid, "통계카페", 2, 1)
assert [(r["kind"], r["bot"], r["hits"]) for r in body["root_files"]] == [("robots", "OAI-SearchBot", 1)]
assert [(o["user_agent"], o["hits"]) for o in body["others"]] == [("AIO2O-Bot/1.0", 1)]
assert "pages" not in body or body["pages"] == []
async def test_사이트별_통계는_그_사이트_것만_본다(client, auth_headers, db_engine):
dev = await auth_headers("dev3", role=UserRole.DEVELOPER.value)
pid, sid = await _site(client, auth_headers, db_engine, "내가게")
_, other_sid = await _site(client, auth_headers, db_engine, "남의가게")
await _hit(db_engine, "2026-10-07T01:00:00+00:00", site_id=sid, path="/s/mine")
await _hit(db_engine, "2026-10-07T02:00:00+00:00", site_id=sid, path="/s/mine/blog/1")
await _hit(db_engine, "2026-10-07T02:00:00+00:00", site_id=other_sid, path="/s/other")
body = (await client.get(f"/v1/ops/sites/{pid}/stats/crawlers", headers=dev,
params={"from": "2026-10-07", "to": "2026-10-07"})).json()
assert body["summary"]["total"] == 2
assert sorted(p["path"] for p in body["pages"]) == ["/s/mine", "/s/mine/blog/1"]
assert [r["path"] for r in body["recent"]] == ["/s/mine/blog/1", "/s/mine"] # 최신순
async def test_사이트가_없는_사업장은_빈_통계(client, auth_headers):
dev = await auth_headers("dev4", role=UserRole.DEVELOPER.value)
owner = await auth_headers("owner4")
pid = (await client.post("/v1/place", headers=owner, json={"name": "새가게", "category": 2})).json()["place"]["place_id"]
body = (await client.get(f"/v1/ops/sites/{pid}/stats/crawlers", headers=dev)).json()
assert body["result"]["success"] is True
assert body["summary"]["total"] == 0
async def test_뒤집힌_기간은_실패_결과(client, auth_headers):
dev = await auth_headers("dev5", role=UserRole.DEVELOPER.value)
body = (await client.get("/v1/ops/stats/crawlers", headers=dev,
params={"from": "2026-10-07", "to": "2026-10-01"})).json()
assert body["result"]["success"] is False
async def test_개발자가_아니면_403(client, auth_headers):
owner = await auth_headers("owner5", role=UserRole.OWNER.value)
assert (await client.get("/v1/ops/stats/crawlers", headers=owner)).status_code == 403
assert (await client.get(f"/v1/ops/sites/{uuid.uuid4()}/stats/crawlers", headers=owner)).status_code == 403
+171
View File
@@ -0,0 +1,171 @@
import asyncio
import uuid
from urllib.parse import quote
import pytest
from sqlalchemy import text
from services.track_service import TrackService
OAI = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.3; +https://openai.com/searchbot"
CHROME = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
FB = "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)"
@pytest.fixture(autouse=True)
def _fresh_slug_cache():
# 슬러그 표는 프로세스 캐시다 — 테스트마다 DB 를 비우므로 캐시도 비운다.
TrackService.reset_cache()
yield
TrackService.reset_cache()
async def _place(client, auth_headers, name):
owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}")
r = await client.post("/v1/place", headers=owner, json={"name": name, "category": 2})
return r.json()["place"]["place_id"]
async def _site(db_engine, place_id, domain):
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"),
{"p": place_id},
)
await conn.execute(text("UPDATE sites SET domain = :d WHERE place_id = :p AND deleted = false"),
{"d": domain, "p": place_id})
row = (await conn.execute(text("SELECT site_id FROM sites WHERE place_id = :p AND deleted = false"),
{"p": place_id})).first()
return str(row[0])
async def _hits(db_engine):
async with db_engine.begin() as conn:
rows = (await conn.execute(text(
"SELECT site_id::text, path, kind, bot, vendor, purpose, user_agent, ip FROM site_crawler_hits ORDER BY created_at"
))).mappings().all()
return [dict(r) for r in rows]
async def _send(client, uri, ua, xff="203.0.113.7"):
return await client.get("/internal/track/hit",
headers={"X-Original-URI": uri, "User-Agent": ua, "X-Forwarded-For": xff})
async def test_봇_요청을_사이트에_묶어_저장한다(client, auth_headers, db_engine):
pid = await _place(client, auth_headers, "머뭄")
site_id = await _site(db_engine, pid, "mermum")
r = await _send(client, "/s/mermum", OAI, "203.0.113.7, 10.0.0.1")
assert r.status_code == 204
[hit] = await _hits(db_engine)
assert hit["site_id"] == site_id
assert (hit["kind"], hit["bot"], hit["vendor"], hit["purpose"]) == ("page", "OAI-SearchBot", "OpenAI", "search")
assert hit["path"] == "/s/mermum"
assert hit["ip"] == "203.0.113.7"
async def test_사람_요청은_저장하지_않는다(client, db_engine):
r = await _send(client, "/s/mermum", CHROME)
assert r.status_code == 204
assert await _hits(db_engine) == []
async def test_한글_슬러그와_하위경로를_같은_사이트로_묶는다(client, auth_headers, db_engine):
pid = await _place(client, auth_headers, "스테이머뭄")
site_id = await _site(db_engine, pid, "스테이머뭄")
await _send(client, "/s/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/", OAI)
await _send(client, "/s/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/blog/1?utm_source=x", OAI)
hits = await _hits(db_engine)
assert [h["site_id"] for h in hits] == [site_id, site_id]
assert hits[1]["path"] == "/s/스테이머뭄/blog/1?utm_source=x"
async def test_domain_없는_사이트는_이름_슬러그로_찾는다(client, auth_headers, db_engine):
pid = await _place(client, auth_headers, "검색 카페")
site_id = await _site(db_engine, pid, None)
# 헤더는 ASCII 만 실린다(httpx 도 nginx 의 $request_uri 도) — 한글 슬러그는 퍼센트 인코딩으로 온다.
await _send(client, "/s/" + quote(f"검색-카페-{pid[:8]}"), OAI)
[hit] = await _hits(db_engine)
assert hit["site_id"] == site_id
async def test_없는_슬러그는_사이트_없이_남긴다(client, db_engine):
await _send(client, "/s/no-such-site", OAI)
[hit] = await _hits(db_engine)
assert hit["site_id"] is None
assert hit["kind"] == "page"
async def test_robots_sitemap_은_kind_로_가른다(client, db_engine):
await _send(client, "/robots.txt", OAI)
await _send(client, "/sitemap.xml", OAI)
assert [(h["kind"], h["site_id"]) for h in await _hits(db_engine)] == [("robots", None), ("sitemap", None)]
async def test_확장자_붙은_요청과_범위_밖_경로는_버린다(client, db_engine):
await _send(client, "/s/mermum/img/abc.jpg", OAI)
await _send(client, "/s/mermum/assets/x.js?v=1", OAI)
await _send(client, "/builder", OAI)
await _send(client, "/s", OAI)
assert await _hits(db_engine) == []
async def test_기타_봇은_UA는_남기고_IP는_남기지_않는다(client, db_engine):
await _send(client, "/s/mermum", FB)
[hit] = await _hits(db_engine)
assert (hit["bot"], hit["purpose"], hit["ip"]) == (None, "other", None)
assert hit["user_agent"] == FB
async def test_DB_오류여도_204(client, monkeypatch):
async def boom(*args, **kwargs):
raise RuntimeError("db down")
monkeypatch.setattr(TrackService, "record_hit", boom)
r = await _send(client, "/s/mermum", OAI)
assert r.status_code == 204
async def test_응답은_기록이_끝나기_전에_나간다(monkeypatch):
# nginx 는 mirror 하위 요청이 끝나기 전까지 같은 연결의 다음 요청을 읽지 않는다 —
# 저장(DB)을 기다렸다 204 를 주면 DB 가 느릴 때 그 연결의 다른 요청까지 같이 늦어진다.
from router.router import app
done = asyncio.Event()
response_sent_before_done = []
async def slow_record_hit(self, uri, user_agent, xff):
await asyncio.sleep(0.2)
done.set()
monkeypatch.setattr(TrackService, "record_hit", slow_record_hit)
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message):
if message["type"] == "http.response.body" and not message.get("more_body"):
response_sent_before_done.append(not done.is_set())
scope = {
"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
"path": "/internal/track/hit", "raw_path": b"/internal/track/hit", "query_string": b"",
"headers": [(b"x-original-uri", b"/robots.txt"), (b"user-agent", b"OAI-SearchBot/1.3")],
"client": ("127.0.0.1", 1), "server": ("test", 80),
}
await app(scope, receive, send)
assert response_sent_before_done == [True]
assert done.is_set() # 응답 뒤에도 기록은 끝까지 돈다
async def test_HEAD_요청도_받는다(client, db_engine):
r = await client.head("/internal/track/hit", headers={"X-Original-URI": "/robots.txt", "User-Agent": OAI})
assert r.status_code == 204
assert len(await _hits(db_engine)) == 1