Files
o2o-site-AEO/solution/backend/tests/test_track_hit.py
T
skkim 603189d3a1 [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·날씨 문구 등 이번 변경과 무관한 기존 실패로 수정 전후 목록이 같다.
2026-10-08 11:31:49 +09:00

172 lines
6.8 KiB
Python

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