[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

@@ -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