feat: backoffice 사이트 트래픽 통계(방문·봇 크롤링) 추가
This commit is contained in:
1 parent
3854aef320
commit
01dd8e7522
33 files changed
+2253
-57
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,249 @@
|
||||
"""nginx 접근 로그 → site_requests 수집.
|
||||
|
||||
웹 프로세스 lifespan 에서 도는 루프(run_forever)가 주기마다 ingest_once 를 부른다. 수동 실행은
|
||||
POST /internal/traffic/ingest. gunicorn 워커가 여럿이면 루프도 여럿이지만, 커서 행(site_log_cursor id=1)을
|
||||
SELECT … FOR UPDATE SKIP LOCKED 로 잡은 하나만 그 회차를 읽고 나머지는 건너뛴다.
|
||||
|
||||
로그 형식은 docs/deploy/traffic-nginx.md 의 `log_format ado2_traffic` (escape=json, 한 줄 = JSON 하나).
|
||||
로테이션: 파일 inode 가 바뀌면 이전 파일(`<경로>.1`)의 남은 줄을 먼저 읽고 새 파일 처음으로 넘어간다.
|
||||
copytruncate 로 크기가 줄었으면 처음부터 다시 읽는다(그 사이 줄은 잃는다).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import BackgroundSessionLocal
|
||||
from app.traffic.detect.crawler_detect import classify
|
||||
from app.traffic.detect.paths import request_of
|
||||
from app.traffic.detect.visit_detect import referrer_host, visitor_hash
|
||||
from app.traffic.models import SiteLogCursor, SiteRequest
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.timezone import now as kst_now
|
||||
from config import TIMEZONE, internal_settings, traffic_settings
|
||||
|
||||
logger = get_logger("traffic")
|
||||
|
||||
CURSOR_ID = 1
|
||||
_MAX_UA = 512
|
||||
|
||||
|
||||
@dataclass
|
||||
class Chunk:
|
||||
"""한 회차에 읽은 완전한 줄들과, 다음 회차가 이어 읽을 위치."""
|
||||
|
||||
lines: list[bytes] = field(default_factory=list)
|
||||
inode: int = 0
|
||||
offset: int = 0
|
||||
rotated: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class IngestResult:
|
||||
lines_read: int = 0
|
||||
inserted: int = 0
|
||||
#: 정적 자원·API 등 통계 대상이 아니라 버린 줄
|
||||
skipped: int = 0
|
||||
#: JSON 이 깨졌거나 필드가 틀린 줄
|
||||
bad: int = 0
|
||||
rotated: bool = False
|
||||
#: 다른 프로세스가 이 회차를 잡고 있어 건너뜀
|
||||
locked: bool = False
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _read_lines(path: str, offset: int, max_lines: int) -> tuple[list[bytes], int]:
|
||||
"""offset 부터 개행으로 끝나는 줄만 max_lines 까지 읽는다. 쓰다 만 마지막 줄은 다음 회차로 남긴다."""
|
||||
lines: list[bytes] = []
|
||||
with open(path, "rb") as f:
|
||||
f.seek(offset)
|
||||
while len(lines) < max_lines:
|
||||
line = f.readline()
|
||||
if not line.endswith(b"\n"):
|
||||
break
|
||||
offset += len(line)
|
||||
lines.append(line)
|
||||
return lines, offset
|
||||
|
||||
|
||||
def read_new_lines(path: str, inode: int, offset: int, max_lines: int) -> Chunk:
|
||||
st = os.stat(path)
|
||||
if st.st_ino == inode and st.st_size >= offset:
|
||||
lines, new_offset = _read_lines(path, offset, max_lines)
|
||||
return Chunk(lines, inode, new_offset)
|
||||
|
||||
first_run = inode == 0 and offset == 0
|
||||
if not first_run and st.st_ino != inode:
|
||||
# logrotate 가 이름을 바꿨다 — 이전 파일에 남은 줄부터 마저 읽는다
|
||||
old = f"{path}.1"
|
||||
try:
|
||||
old_st = os.stat(old)
|
||||
except FileNotFoundError:
|
||||
old_st = None
|
||||
if old_st is not None and old_st.st_ino == inode and old_st.st_size > offset:
|
||||
lines, new_offset = _read_lines(old, offset, max_lines)
|
||||
if lines:
|
||||
return Chunk(lines, inode, new_offset)
|
||||
|
||||
lines, new_offset = _read_lines(path, 0, max_lines)
|
||||
return Chunk(lines, st.st_ino, new_offset, rotated=not first_run)
|
||||
|
||||
|
||||
def _kst_naive(value: str) -> datetime:
|
||||
t = datetime.fromisoformat(value)
|
||||
if t.tzinfo is not None:
|
||||
t = t.astimezone(TIMEZONE)
|
||||
return t.replace(tzinfo=None)
|
||||
|
||||
|
||||
def build_request(entry: dict, secret: str) -> SiteRequest | None:
|
||||
"""로그 한 줄(JSON) → 저장할 행. 통계 대상이 아니면 None. 필드가 틀리면 KeyError/ValueError/TypeError."""
|
||||
uri = entry["uri"]
|
||||
if not isinstance(uri, str):
|
||||
raise TypeError("uri")
|
||||
info = request_of(uri)
|
||||
if info is None:
|
||||
return None
|
||||
|
||||
created_at = _kst_naive(entry["time"])
|
||||
ip = str(entry.get("ip") or "")
|
||||
ua = str(entry.get("ua") or "")[:_MAX_UA]
|
||||
ref = entry.get("ref")
|
||||
bot = classify(ua)
|
||||
return SiteRequest(
|
||||
created_at=created_at,
|
||||
method=str(entry.get("method") or "")[:8],
|
||||
path=info.path,
|
||||
status=int(entry["status"]),
|
||||
bytes_sent=int(entry.get("bytes") or 0),
|
||||
request_time_ms=round(float(entry.get("rt") or 0) * 1000),
|
||||
kind=info.kind,
|
||||
content_type=info.content_type,
|
||||
content_id=info.content_id,
|
||||
ip_hash=visitor_hash(secret, ip, ua, created_at),
|
||||
# IP 는 목록에 있는 봇만 남긴다 — 사람·기타 봇은 해시만
|
||||
ip=ip[:45] if bot is not None and bot.bot is not None else None,
|
||||
is_bot=bot is not None,
|
||||
bot_name=bot.bot if bot else None,
|
||||
bot_company=bot.company if bot else None,
|
||||
bot_purpose=bot.purpose if bot else None,
|
||||
user_agent=ua,
|
||||
referrer_host=referrer_host(ref if isinstance(ref, str) and ref != "-" else None),
|
||||
)
|
||||
|
||||
|
||||
def process_lines(lines: list[bytes], secret: str) -> tuple[list[SiteRequest], int, int]:
|
||||
"""→ (저장할 행, 버린 줄 수, 깨진 줄 수)."""
|
||||
rows: list[SiteRequest] = []
|
||||
skipped = bad = 0
|
||||
for raw in lines:
|
||||
try:
|
||||
entry = json.loads(raw.decode("utf-8", errors="replace"))
|
||||
if not isinstance(entry, dict):
|
||||
raise TypeError("line is not an object")
|
||||
row = build_request(entry, secret)
|
||||
except (KeyError, ValueError, TypeError):
|
||||
bad += 1
|
||||
continue
|
||||
if row is None:
|
||||
skipped += 1
|
||||
else:
|
||||
rows.append(row)
|
||||
if bad:
|
||||
logger.warning(f"[traffic] 접근 로그 깨진 줄 {bad}건 건너뜀")
|
||||
return rows, skipped, bad
|
||||
|
||||
|
||||
def lock_cursor_stmt():
|
||||
"""다른 프로세스가 잡은 행은 기다리지 않고 건너뛴다(MySQL 8 SKIP LOCKED)."""
|
||||
return select(SiteLogCursor).where(SiteLogCursor.id == CURSOR_ID).with_for_update(skip_locked=True)
|
||||
|
||||
|
||||
async def _lock_cursor(session: AsyncSession) -> SiteLogCursor | None:
|
||||
"""커서 행을 잠근다. 다른 프로세스가 잡고 있으면 None. 행이 없으면 만든다(DEBUG 자동 생성 대비)."""
|
||||
cursor = (await session.execute(lock_cursor_stmt())).scalar_one_or_none()
|
||||
if cursor is not None:
|
||||
return cursor
|
||||
|
||||
count = await session.scalar(select(func.count()).select_from(SiteLogCursor).where(SiteLogCursor.id == CURSOR_ID))
|
||||
if count:
|
||||
await session.rollback()
|
||||
return None
|
||||
cursor = SiteLogCursor(id=CURSOR_ID, inode=0, file_offset=0)
|
||||
session.add(cursor)
|
||||
try:
|
||||
await session.flush()
|
||||
except IntegrityError:
|
||||
# 다른 프로세스가 같은 순간에 만들었다 — 이번 회차는 그쪽이 읽는다
|
||||
await session.rollback()
|
||||
return None
|
||||
return cursor
|
||||
|
||||
|
||||
async def _insert_rows(session: AsyncSession, rows: list[SiteRequest]) -> None:
|
||||
session.add_all(rows)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def ingest_once(session: AsyncSession, path: str, max_lines: int, secret: str) -> IngestResult:
|
||||
cursor = await _lock_cursor(session)
|
||||
if cursor is None:
|
||||
return IngestResult(locked=True)
|
||||
|
||||
chunk = await asyncio.to_thread(read_new_lines, path, cursor.inode, cursor.file_offset, max_lines)
|
||||
rows, skipped, bad = process_lines(chunk.lines, secret)
|
||||
if rows:
|
||||
await _insert_rows(session, rows)
|
||||
cursor.inode = chunk.inode
|
||||
cursor.file_offset = chunk.offset
|
||||
cursor.updated_at = kst_now().replace(tzinfo=None)
|
||||
await session.commit()
|
||||
return IngestResult(
|
||||
lines_read=len(chunk.lines), inserted=len(rows), skipped=skipped, bad=bad, rotated=chunk.rotated
|
||||
)
|
||||
|
||||
|
||||
async def ingest_configured(session: AsyncSession) -> IngestResult:
|
||||
"""설정값으로 한 회차 수집."""
|
||||
return await ingest_once(
|
||||
session,
|
||||
traffic_settings.TRAFFIC_ACCESS_LOG_PATH,
|
||||
traffic_settings.TRAFFIC_INGEST_MAX_LINES,
|
||||
internal_settings.INTERNAL_SECRET_KEY,
|
||||
)
|
||||
|
||||
|
||||
async def run_forever(stop: asyncio.Event) -> None:
|
||||
"""lifespan 에서 띄우는 수집 루프. 상한까지 읽은 회차 뒤에는 쉬지 않고 이어 읽는다."""
|
||||
interval = traffic_settings.TRAFFIC_INGEST_INTERVAL_SECONDS
|
||||
max_lines = traffic_settings.TRAFFIC_INGEST_MAX_LINES
|
||||
logger.info(f"[traffic] 접근 로그 수집 시작 - path: {traffic_settings.TRAFFIC_ACCESS_LOG_PATH}, 주기: {interval}s")
|
||||
while not stop.is_set():
|
||||
backlog = False
|
||||
try:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
result = await ingest_configured(session)
|
||||
backlog = result.lines_read >= max_lines
|
||||
if result.lines_read:
|
||||
logger.info(f"[traffic] 접근 로그 수집 - {result.as_dict()}")
|
||||
except FileNotFoundError:
|
||||
logger.warning(f"[traffic] 접근 로그 파일 없음 - path: {traffic_settings.TRAFFIC_ACCESS_LOG_PATH}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[traffic] 접근 로그 수집 실패 - error: {e}")
|
||||
if backlog:
|
||||
await asyncio.sleep(0)
|
||||
continue
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), timeout=interval)
|
||||
except TimeoutError:
|
||||
# 주기가 끝났다는 뜻일 뿐이다(오류 아님) — 다음 회차로
|
||||
continue
|
||||
logger.info("[traffic] 접근 로그 수집 중단")
|
||||
@@ -0,0 +1,302 @@
|
||||
"""트래픽 통계 집계 — 원본을 기간으로 잘라 GROUP BY 한다(집계 테이블 없음).
|
||||
|
||||
기간은 KST 날짜(오늘 포함 N일)이고 created_at 이 KST naive 라 그대로 비교한다.
|
||||
쿼리 만들기(build_*)와 결과 다듬기(shape_*)를 나눠 둔다 — 화면은 *_stats() 만 부른다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import Select, and_, case, distinct, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.traffic.detect.crawler_detect import AI_PURPOSES
|
||||
from app.traffic.models import SitePageView, SiteRequest
|
||||
from app.utils.timezone import now as kst_now
|
||||
|
||||
ALLOWED_DAYS = (7, 30, 90)
|
||||
DEFAULT_DAYS = 7
|
||||
TOP_N = 20
|
||||
RECENT_N = 50
|
||||
|
||||
#: 화면 표시 순서와 이름
|
||||
PURPOSE_LABELS: dict[str, str] = {
|
||||
"search": "AI 검색 색인",
|
||||
"user-fetch": "AI 실시간 조회",
|
||||
"training": "AI 학습",
|
||||
"search-engine": "검색엔진",
|
||||
"preview": "링크 미리보기",
|
||||
"other": "기타",
|
||||
}
|
||||
PAGE_KIND_LABELS: dict[str, str] = {
|
||||
"landing": "첫 화면(/)",
|
||||
"video": "영상 상세",
|
||||
"ssul": "썰박스 상세",
|
||||
"p2v_f1": "무빙 포스터 상세",
|
||||
"p2v_playreel": "롱컷 상세",
|
||||
"static": "FAQ·약관",
|
||||
"other": "기타 경로",
|
||||
}
|
||||
DEVICE_LABELS: dict[str, str] = {"mobile": "모바일", "desktop": "PC", "tablet": "태블릿"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Period:
|
||||
days: int
|
||||
#: 첫날(포함)
|
||||
start: date
|
||||
#: 오늘(포함)
|
||||
end: date
|
||||
|
||||
@property
|
||||
def start_dt(self) -> datetime:
|
||||
return datetime.combine(self.start, time.min)
|
||||
|
||||
@property
|
||||
def end_dt(self) -> datetime:
|
||||
"""마지막 날 다음 날 0시(미포함)."""
|
||||
return datetime.combine(self.end + timedelta(days=1), time.min)
|
||||
|
||||
def dates(self) -> list[date]:
|
||||
return [self.start + timedelta(days=i) for i in range(self.days)]
|
||||
|
||||
|
||||
def resolve_period(days: Any, today: date | None = None) -> Period:
|
||||
"""?days= 값 → 기간. 허용 값(7·30·90)이 아니면 7일."""
|
||||
try:
|
||||
n = int(days)
|
||||
except (TypeError, ValueError):
|
||||
n = DEFAULT_DAYS
|
||||
if n not in ALLOWED_DAYS:
|
||||
n = DEFAULT_DAYS
|
||||
end = today or kst_now().date()
|
||||
return Period(n, end - timedelta(days=n - 1), end)
|
||||
|
||||
|
||||
def _as_date(value: Any) -> date:
|
||||
# MySQL DATE() 는 date, SQLite date() 는 문자열을 돌려준다
|
||||
return value if isinstance(value, date) and not isinstance(value, datetime) else date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def _in_period(col, period: Period):
|
||||
return and_(col >= period.start_dt, col < period.end_dt)
|
||||
|
||||
|
||||
def fill_daily(rows: list[tuple], period: Period, fields: tuple[str, ...]) -> list[dict]:
|
||||
"""[(날짜, 값...)] → 기간의 모든 날짜를 채운 [{date, field: 값}]. 기록 없는 날은 0."""
|
||||
by_day = {_as_date(r[0]): r[1:] for r in rows}
|
||||
out = []
|
||||
for d in period.dates():
|
||||
values = by_day.get(d, (0,) * len(fields))
|
||||
out.append({"date": d, **{f: int(v or 0) for f, v in zip(fields, values)}})
|
||||
return out
|
||||
|
||||
|
||||
def pivot_daily(rows: list[tuple], period: Period, keys: tuple[str, ...]) -> list[dict]:
|
||||
"""[(날짜, 키, 값)] → [{date, 키1: 값, 키2: 값, …, total}]. 목록 밖 키는 버리지 않고 마지막 키에 더한다."""
|
||||
table = {d: dict.fromkeys(keys, 0) for d in period.dates()}
|
||||
for day, key, value in rows:
|
||||
d = _as_date(day)
|
||||
if d not in table:
|
||||
continue
|
||||
k = key if key in table[d] else keys[-1]
|
||||
table[d][k] += int(value or 0)
|
||||
return [{"date": d, **v, "total": sum(v.values())} for d, v in table.items()]
|
||||
|
||||
|
||||
def _rows(result) -> list[tuple]:
|
||||
return [tuple(r) for r in result]
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 방문 (site_page_views)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def build_visit_statements(period: Period) -> dict[str, Select]:
|
||||
v = SitePageView
|
||||
within = _in_period(v.created_at, period)
|
||||
today_start = datetime.combine(period.end, time.min)
|
||||
day = func.date(v.created_at)
|
||||
views = func.count(v.id)
|
||||
visitors = func.count(distinct(v.visitor_hash))
|
||||
r = SiteRequest
|
||||
return {
|
||||
"today": select(func.count(distinct(v.visitor_hash))).where(
|
||||
v.created_at >= today_start, v.created_at < period.end_dt
|
||||
),
|
||||
"summary": select(
|
||||
views,
|
||||
visitors,
|
||||
func.max(v.created_at),
|
||||
func.sum(case((v.referrer_host.is_(None), 1), else_=0)),
|
||||
func.count(distinct(case((v.referrer_host.is_(None), v.visitor_hash)))),
|
||||
).where(within),
|
||||
"daily": select(day, visitors, views).where(within).group_by(day).order_by(day),
|
||||
"page_kinds": select(v.page_kind, views, visitors).where(within).group_by(v.page_kind).order_by(views.desc()),
|
||||
"contents": select(v.content_type, v.content_id, views, visitors)
|
||||
.where(within, v.content_id.is_not(None))
|
||||
.group_by(v.content_type, v.content_id)
|
||||
.order_by(views.desc())
|
||||
.limit(TOP_N),
|
||||
"pages": select(v.path, views, visitors).where(within).group_by(v.path).order_by(views.desc()).limit(TOP_N),
|
||||
"referrers": select(v.referrer_host, views, visitors)
|
||||
.where(within, v.referrer_host.is_not(None))
|
||||
.group_by(v.referrer_host)
|
||||
.order_by(views.desc())
|
||||
.limit(TOP_N),
|
||||
"ai_engines": select(v.ai_engine, v.ai_signal, views)
|
||||
.where(within, v.ai_engine.is_not(None))
|
||||
.group_by(v.ai_engine, v.ai_signal)
|
||||
.order_by(views.desc()),
|
||||
"utm": select(v.utm_source, views, visitors)
|
||||
.where(within, v.utm_source.is_not(None))
|
||||
.group_by(v.utm_source)
|
||||
.order_by(views.desc())
|
||||
.limit(TOP_N),
|
||||
"devices": select(v.device, views, visitors).where(within).group_by(v.device).order_by(views.desc()),
|
||||
# 참고: 접근 로그에서 본 사람(봇 아님)의 첫 화면 요청 — JS 를 막은 손님·사람인 척하는 봇까지 들어간다
|
||||
"log_landing": select(func.count(r.id), func.count(distinct(r.ip_hash))).where(
|
||||
_in_period(r.created_at, period), r.is_bot.is_(False), r.kind == "page", r.path == "/"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def shape_visit_stats(rows: dict[str, list[tuple]], period: Period) -> dict:
|
||||
pageviews, visitors, last_seen, direct, direct_visitors = (
|
||||
rows["summary"][0] if rows["summary"] else (0, 0, None, 0, 0)
|
||||
)
|
||||
log_requests, log_ips = rows["log_landing"][0] if rows["log_landing"] else (0, 0)
|
||||
ai: dict[str, dict] = {}
|
||||
for engine, signal, n in rows["ai_engines"]:
|
||||
item = ai.setdefault(engine, {"engine": engine, "views": 0, "referrer": 0, "utm": 0})
|
||||
item["views"] += int(n)
|
||||
item[signal] = item.get(signal, 0) + int(n)
|
||||
return {
|
||||
"period": period,
|
||||
"today_visitors": int(rows["today"][0][0] or 0) if rows["today"] else 0,
|
||||
"summary": {
|
||||
"pageviews": int(pageviews or 0),
|
||||
"visitors": int(visitors or 0),
|
||||
"last_seen": last_seen,
|
||||
"direct_views": int(direct or 0),
|
||||
"direct_visitors": int(direct_visitors or 0),
|
||||
},
|
||||
"daily": fill_daily(rows["daily"], period, ("visitors", "pageviews")),
|
||||
"page_kinds": [
|
||||
{"kind": k, "label": PAGE_KIND_LABELS.get(k, k), "views": int(n), "visitors": int(u)}
|
||||
for k, n, u in rows["page_kinds"]
|
||||
],
|
||||
"contents": [
|
||||
{"content_type": t, "content_id": i, "views": int(n), "visitors": int(u)} for t, i, n, u in rows["contents"]
|
||||
],
|
||||
"pages": [{"path": p, "views": int(n), "visitors": int(u)} for p, n, u in rows["pages"]],
|
||||
"referrers": [{"host": h, "views": int(n), "visitors": int(u)} for h, n, u in rows["referrers"]],
|
||||
"ai_engines": sorted(ai.values(), key=lambda x: -x["views"]),
|
||||
"utm": [{"source": s, "views": int(n), "visitors": int(u)} for s, n, u in rows["utm"]],
|
||||
"devices": [
|
||||
{"device": d, "label": DEVICE_LABELS.get(d, d), "views": int(n), "visitors": int(u)}
|
||||
for d, n, u in rows["devices"]
|
||||
],
|
||||
"log_landing": {"requests": int(log_requests or 0), "ip_hashes": int(log_ips or 0)},
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 봇 크롤링 (site_requests, is_bot)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def build_crawler_statements(period: Period) -> dict[str, Select]:
|
||||
r = SiteRequest
|
||||
within = and_(_in_period(r.created_at, period), r.is_bot.is_(True))
|
||||
day = func.date(r.created_at)
|
||||
hits = func.count(r.id)
|
||||
return {
|
||||
"summary": select(
|
||||
hits,
|
||||
func.sum(case((r.bot_purpose.in_(AI_PURPOSES), 1), else_=0)),
|
||||
func.count(distinct(r.bot_name)),
|
||||
func.sum(case((r.bot_name.is_(None), 1), else_=0)),
|
||||
func.max(r.created_at),
|
||||
).where(within),
|
||||
"daily": select(day, r.bot_purpose, hits).where(within).group_by(day, r.bot_purpose).order_by(day),
|
||||
"bots": select(r.bot_name, r.bot_company, r.bot_purpose, hits, func.max(r.created_at))
|
||||
.where(within, r.bot_name.is_not(None))
|
||||
.group_by(r.bot_name, r.bot_company, r.bot_purpose)
|
||||
.order_by(hits.desc(), r.bot_name),
|
||||
"paths": select(r.path, r.kind, hits).where(within).group_by(r.path, r.kind).order_by(hits.desc()).limit(TOP_N),
|
||||
# GROUP BY 에는 바인드 파라미터 없는 식만 쓴다(ONLY_FULL_GROUP_BY 가 SELECT 쪽과 다른 식으로 볼 수 있다)
|
||||
"root_files": select(r.kind, r.bot_name, hits)
|
||||
.where(within, r.kind.in_(("robots", "sitemap", "llms")))
|
||||
.group_by(r.kind, r.bot_name)
|
||||
.order_by(r.kind, hits.desc()),
|
||||
"others": select(r.user_agent, hits, func.max(r.created_at))
|
||||
.where(within, r.bot_purpose == "other")
|
||||
.group_by(r.user_agent)
|
||||
.order_by(hits.desc())
|
||||
.limit(TOP_N),
|
||||
"recent": select(r.created_at, r.bot_name, r.bot_purpose, r.path, r.status, r.ip)
|
||||
.where(within)
|
||||
.order_by(r.created_at.desc(), r.id.desc())
|
||||
.limit(RECENT_N),
|
||||
}
|
||||
|
||||
|
||||
def shape_crawler_stats(rows: dict[str, list[tuple]], period: Period) -> dict:
|
||||
total, ai_total, named_kinds, other_hits, last = rows["summary"][0] if rows["summary"] else (0, 0, 0, 0, None)
|
||||
return {
|
||||
"period": period,
|
||||
"purpose_labels": PURPOSE_LABELS,
|
||||
"summary": {
|
||||
"total": int(total or 0),
|
||||
"ai_total": int(ai_total or 0),
|
||||
# 목록 밖(기타) 봇은 한 종류로 센다
|
||||
"bot_kinds": int(named_kinds or 0) + (1 if other_hits else 0),
|
||||
"last_seen": last,
|
||||
},
|
||||
"daily": pivot_daily(rows["daily"], period, tuple(PURPOSE_LABELS)),
|
||||
"bots": [
|
||||
{
|
||||
"bot": b,
|
||||
"company": c,
|
||||
"purpose": p,
|
||||
"purpose_label": PURPOSE_LABELS.get(p, p),
|
||||
"hits": int(n),
|
||||
"last_seen": t,
|
||||
}
|
||||
for b, c, p, n, t in rows["bots"]
|
||||
],
|
||||
"paths": [{"path": p, "kind": k, "hits": int(n)} for p, k, n in rows["paths"]],
|
||||
"root_files": [{"kind": k, "bot": b or "기타", "hits": int(n)} for k, b, n in rows["root_files"]],
|
||||
"others": [{"user_agent": ua, "hits": int(n), "last_seen": t} for ua, n, t in rows["others"]],
|
||||
"recent": [
|
||||
{
|
||||
"at": t,
|
||||
"bot": b or "기타",
|
||||
"purpose_label": PURPOSE_LABELS.get(p, p),
|
||||
"path": path,
|
||||
"status": s,
|
||||
"ip": ip,
|
||||
}
|
||||
for t, b, p, path, s, ip in rows["recent"]
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 화면에서 부르는 것
|
||||
# =============================================================================
|
||||
|
||||
|
||||
async def _run(session: AsyncSession, statements: dict[str, Select]) -> dict[str, list[tuple]]:
|
||||
return {name: _rows(await session.execute(stmt)) for name, stmt in statements.items()}
|
||||
|
||||
|
||||
async def visit_stats(session: AsyncSession, period: Period) -> dict:
|
||||
return shape_visit_stats(await _run(session, build_visit_statements(period)), period)
|
||||
|
||||
|
||||
async def crawler_stats(session: AsyncSession, period: Period) -> dict:
|
||||
return shape_crawler_stats(await _run(session, build_crawler_statements(period)), period)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""사람 방문 비콘 기록.
|
||||
|
||||
거르는 순서: 봇·도구 UA → 통계에서 빼는 경로 → IP 당 분당 120건 → 같은 방문자+경로 10초 안 중복.
|
||||
중복·과다 판정은 프로세스 메모리 표라 gunicorn 워커가 여럿이면 워커마다 따로다(중복 제거가 느슨해진다).
|
||||
저장은 응답을 돌려준 뒤 백그라운드에서 하고, 실패해도 사이트 응답에 영향이 없다.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from app.database.session import BackgroundSessionLocal
|
||||
from app.traffic.detect.ai_referral import classify_ai_referral
|
||||
from app.traffic.detect.paths import normalize_path, page_of
|
||||
from app.traffic.detect.visit_detect import device_of, is_visitor, referrer_host, visitor_hash
|
||||
from app.traffic.models import SitePageView
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.timezone import now as kst_now
|
||||
from config import internal_settings
|
||||
|
||||
logger = get_logger("traffic")
|
||||
|
||||
MAX_BODY_BYTES = 2048
|
||||
_MAX_UA = 512
|
||||
_MAX_UTM = 100
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BeaconPayload:
|
||||
path: str
|
||||
referrer: str | None
|
||||
utm_source: str | None
|
||||
|
||||
|
||||
def parse_beacon(body: bytes) -> BeaconPayload | None:
|
||||
"""sendBeacon 본문(text/plain JSON) → 값. 형식이 틀리면 None."""
|
||||
try:
|
||||
data = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, dict) or not isinstance(data.get("path"), str):
|
||||
return None
|
||||
|
||||
def _opt(key: str) -> str | None:
|
||||
value = data.get(key)
|
||||
return (value.strip() or None) if isinstance(value, str) else None
|
||||
|
||||
return BeaconPayload(path=data["path"], referrer=_opt("referrer"), utm_source=_opt("utm_source"))
|
||||
|
||||
|
||||
def build_view(
|
||||
payload: BeaconPayload, ip: str, user_agent: str | None, now: datetime, secret: str
|
||||
) -> SitePageView | None:
|
||||
"""비콘 1건 → 저장할 행. 사람이 아니거나 통계에서 빼는 경로면 None."""
|
||||
if not is_visitor(user_agent):
|
||||
return None
|
||||
path = normalize_path(payload.path)
|
||||
page = page_of(path)
|
||||
if page is None:
|
||||
return None
|
||||
|
||||
ua = (user_agent or "")[:_MAX_UA]
|
||||
host = referrer_host(payload.referrer)
|
||||
utm = payload.utm_source[:_MAX_UTM] if payload.utm_source else None
|
||||
ai = classify_ai_referral(host, utm)
|
||||
return SitePageView(
|
||||
created_at=now.replace(tzinfo=None),
|
||||
path=path,
|
||||
page_kind=page.page_kind,
|
||||
content_type=page.content_type,
|
||||
content_id=page.content_id,
|
||||
visitor_hash=visitor_hash(secret, ip, ua, now),
|
||||
device=device_of(ua),
|
||||
referrer_host=host,
|
||||
utm_source=utm,
|
||||
ai_engine=ai.engine if ai else None,
|
||||
ai_signal=ai.signal if ai else None,
|
||||
)
|
||||
|
||||
|
||||
class VisitGate:
|
||||
"""IP 당 분당 상한 + 같은 방문자·경로 짧은 중복을 거르는 메모리 표."""
|
||||
|
||||
def __init__(self, per_ip_per_minute: int = 120, dedup_seconds: float = 10.0, max_keys: int = 20_000) -> None:
|
||||
self.per_ip_per_minute = per_ip_per_minute
|
||||
self.dedup_seconds = dedup_seconds
|
||||
self.max_keys = max_keys
|
||||
self._ip_windows: dict[str, tuple[float, int]] = {}
|
||||
self._recent: dict[tuple[str, str], float] = {}
|
||||
|
||||
def allow(self, ip: str, visitor: str, path: str, now: float) -> bool:
|
||||
start, count = self._ip_windows.get(ip, (now, 0))
|
||||
if now - start >= 60:
|
||||
start, count = now, 0
|
||||
if count >= self.per_ip_per_minute:
|
||||
return False
|
||||
self._ip_windows[ip] = (start, count + 1)
|
||||
|
||||
key = (visitor, path)
|
||||
last = self._recent.get(key)
|
||||
if last is not None and now - last < self.dedup_seconds:
|
||||
return False
|
||||
self._recent[key] = now
|
||||
|
||||
self._prune(now)
|
||||
return True
|
||||
|
||||
def _prune(self, now: float) -> None:
|
||||
# 상한을 넘으면 만료된 키부터 지우고, 그래도 넘으면 비운다 — 메모리를 지키는 쪽이 우선이다
|
||||
if len(self._ip_windows) > self.max_keys:
|
||||
self._ip_windows = {k: v for k, v in self._ip_windows.items() if now - v[0] < 60}
|
||||
if len(self._ip_windows) > self.max_keys:
|
||||
self._ip_windows.clear()
|
||||
if len(self._recent) > self.max_keys:
|
||||
self._recent = {k: t for k, t in self._recent.items() if now - t < self.dedup_seconds}
|
||||
if len(self._recent) > self.max_keys:
|
||||
self._recent.clear()
|
||||
|
||||
|
||||
_gate = VisitGate()
|
||||
|
||||
|
||||
async def _save(row: SitePageView) -> None:
|
||||
async with BackgroundSessionLocal() as session:
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def record_view(body: bytes, ip: str, user_agent: str | None) -> None:
|
||||
"""비콘 1건을 걸러서 저장한다. BackgroundTasks 에서 부른다."""
|
||||
payload = parse_beacon(body)
|
||||
if payload is None:
|
||||
return
|
||||
row = build_view(payload, ip, user_agent, kst_now(), internal_settings.INTERNAL_SECRET_KEY)
|
||||
if row is None or not _gate.allow(ip, row.visitor_hash, row.path, time.monotonic()):
|
||||
return
|
||||
try:
|
||||
await _save(row)
|
||||
except Exception as e:
|
||||
# 통계 저장 실패가 사이트를 깨뜨리면 안 된다 — 남기고 넘어간다
|
||||
logger.warning(f"[traffic] 방문 저장 실패 - path: {row.path}, error: {e}")
|
||||
Reference in new issue
Block a user