발행 사이트를 연 사람의 페이지뷰를 쿠키·식별자 없이 모은다. 방문자 구분은
sha256(JWT_ACCESS_SECRET|IP|UA|KST 월) 해시로만 하고 IP 원문은 저장하지 않는다(Umami 와 같은 방식).
- POST /v1/track/view(공개): 응답을 먼저 주고 BackgroundTasks 로 저장 — sendBeacon 은 응답을 읽지 않는다.
본문은 2KB 를 넘으면 다 읽기 전에 끊는다(nginx 상한 20MB 를 매번 메모리에 올리지 않게)
- 봇(crawler_detect)과 HeadlessChrome(우리 목업 검증 스크립트)은 세지 않는다
- IP 는 X-Forwarded-For 뒤에서 두 번째(Apache → nginx) — 첫 값은 손님이 위조해 한도·중복 제거를 피할 수 있다
- 같은 해시+경로 10초 1회, IP 당 분당 120건. common.utils.rate_limit 은 키를 안 지워 공개 엔드포인트에선
메모리가 끝없이 늘어 상한 있는 표를 따로 둔다
- 경로는 발행 경로 + 탭(#/stay) — 하위 페이지가 해시 탭이라 빼면 "많이 본 페이지" 가 한 줄로 뭉친다. 끝 슬래시는 걷는다
- GET /v1/ops/stats/visits · /v1/ops/sites/{place_id}/stats/visits(RequireDeveloper): 실시간(최근 5분 고유
방문자), 일별(KST)·사이트 순위·인기 페이지·유입·utm·기기. 기간 해석은 크롤러 통계와 같은 함수를 쓴다
- TrackService._site_id → site_id_for(공개) — 방문도 같은 슬러그 표를 쓴다
- 0025 마이그레이션과 init.sql 함께 수정
방문 테스트 25건 추가(방문·크롤러 관련 56 passed). 전체 1106 passed · 50 failed — 실패 목록이
1단계 기준과 같다(LLM 키 미설정·cp949·스케줄러·SNS·날씨 문구의 기존 실패).
138 lines
6.0 KiB
Python
138 lines
6.0 KiB
Python
"""발행 사이트 비콘(/v1/track/view) → 사람 페이지뷰 1건 저장(사이트 트래픽 통계 2단계)."""
|
|
import json
|
|
import os
|
|
import time
|
|
from datetime import datetime, timezone
|
|
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_page_views
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from crud.crawler_hit_crud import CrawlerHitCRUD, ICrawlerHitCRUD
|
|
from crud.visit_crud import IVisitCRUD, VisitCRUD
|
|
from services.track_service import TrackService, slug_of
|
|
from services.visit_detect import device_of, is_human, referrer_domain, visitor_hash
|
|
|
|
# 비콘 본문은 경로·리퍼러·utm 셋뿐이다 — 이보다 크면 정상 요청이 아니다(라우터가 읽기 전에 끊는다).
|
|
MAX_BEACON_BODY = 2048
|
|
# 공개 엔드포인트라 표를 채우는 남용을 막는다(사람은 분당 이만큼 페이지를 넘기지 않는다).
|
|
_IP_LIMIT_PER_MIN = 120
|
|
# 새로고침 연타·뒤로가기 왕복을 한 번으로 본다.
|
|
_DEDUPE_SEC = 10.0
|
|
# 아래 두 메모리 표의 상한 — 넘치면 만료분을 걷고, 그래도 넘치면 오래된 절반을 버린다.
|
|
_TABLE_MAX_KEYS = 20_000
|
|
# 운영 경로는 Apache → nginx → 백엔드다. 두 프록시가 X-Forwarded-For 끝에 하나씩 덧붙이므로
|
|
# 뒤에서 두 번째가 실제 손님이다. 첫 값은 손님이 마음대로 넣을 수 있다 — 그걸 쓰면 요청마다 새 방문자가 된다.
|
|
_PROXY_HOPS = 2
|
|
_TAB_MAX = 100
|
|
|
|
|
|
def real_client_ip(xff: str | None, client_host: str | None) -> str:
|
|
parts = [p.strip() for p in (xff or "").split(",") if p.strip()]
|
|
if len(parts) >= _PROXY_HOPS:
|
|
return parts[-_PROXY_HOPS][:45]
|
|
# 프록시가 하나뿐인 환경(로컬 nginx·개발 서버) — 붙은 값이 곧 손님이다.
|
|
return (parts[0] if parts else (client_host or ""))[:45]
|
|
|
|
|
|
def page_path(raw: str) -> str | None:
|
|
"""발행 경로 + 탭(#/…). 끝 슬래시는 같은 페이지라 걷는다. 발행 경로가 아니면 None."""
|
|
try:
|
|
parts = urlsplit(raw)
|
|
except ValueError:
|
|
return None
|
|
base = unquote(parts.path).rstrip("/")
|
|
if not base.startswith("/s/") or len(base) <= 3:
|
|
return None
|
|
# 발행 사이트의 하위 페이지는 해시 탭(#/stay)이다. #/ 는 홈, 그 밖의 해시는 문서 안 앵커다.
|
|
tab = f"#{parts.fragment}" if parts.fragment.startswith("/") and parts.fragment != "/" else ""
|
|
return base + tab[:_TAB_MAX]
|
|
|
|
|
|
def _shrink(table: dict, alive) -> dict:
|
|
kept = {k: v for k, v in table.items() if alive(v)}
|
|
if len(kept) > _TABLE_MAX_KEYS:
|
|
# 만료분을 걷어도 넘친다 = 짧은 시간에 서로 다른 키가 쏟아졌다. 삽입 순서상 오래된 절반을 버린다.
|
|
kept = dict(list(kept.items())[-(_TABLE_MAX_KEYS // 2):])
|
|
return kept
|
|
|
|
|
|
class VisitService:
|
|
# 요청마다 새 인스턴스(Depends)라 상태는 클래스에 둔다. common.utils.rate_limit 은 키를 지우지 않아
|
|
# 공개 엔드포인트의 IP·방문자 키로 쓰면 메모리가 끝없이 는다 — 그래서 상한이 있는 작은 표를 따로 둔다.
|
|
_recent: dict[str, float] = {}
|
|
_ip_hits: dict[str, tuple[float, int]] = {}
|
|
|
|
def __init__(self, crud: IVisitCRUD = Depends(VisitCRUD), hit_crud: ICrawlerHitCRUD = Depends(CrawlerHitCRUD)):
|
|
self.crud = crud
|
|
self.slugs = TrackService(hit_crud)
|
|
|
|
@classmethod
|
|
def reset_dedupe(cls) -> None:
|
|
cls._recent = {}
|
|
cls._ip_hits = {}
|
|
|
|
@classmethod
|
|
def _seen_recently(cls, key: str) -> bool:
|
|
now = time.monotonic()
|
|
if len(cls._recent) > _TABLE_MAX_KEYS:
|
|
cls._recent = _shrink(cls._recent, lambda t: now - t < _DEDUPE_SEC)
|
|
last = cls._recent.get(key)
|
|
if last is not None and now - last < _DEDUPE_SEC:
|
|
return True
|
|
cls._recent[key] = now
|
|
return False
|
|
|
|
@classmethod
|
|
def _ip_allowed(cls, ip: str) -> bool:
|
|
now = time.monotonic()
|
|
if len(cls._ip_hits) > _TABLE_MAX_KEYS:
|
|
cls._ip_hits = _shrink(cls._ip_hits, lambda v: now - v[0] < 60.0)
|
|
start, count = cls._ip_hits.get(ip, (now, 0))
|
|
if now - start >= 60.0:
|
|
start, count = now, 0
|
|
if count >= _IP_LIMIT_PER_MIN:
|
|
return False
|
|
cls._ip_hits[ip] = (start, count + 1)
|
|
return True
|
|
|
|
async def record_view(self, body: bytes, user_agent: str | None, xff: str | None, client_host: str | None) -> None:
|
|
if not is_human(user_agent) or len(body) > MAX_BEACON_BODY:
|
|
return
|
|
try:
|
|
data = json.loads(body.decode("utf-8"))
|
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
return
|
|
if not isinstance(data, dict):
|
|
return
|
|
path = page_path(str(data.get("path") or ""))
|
|
if path is None:
|
|
return
|
|
ip = real_client_ip(xff, client_host)
|
|
if not self._ip_allowed(ip):
|
|
return
|
|
site_id = await self.slugs.site_id_for(slug_of(path.split("#", 1)[0]))
|
|
if site_id is None:
|
|
return
|
|
# 비밀값은 후기 IP 해시(review_service._ip_hash)와 같은 것을 쓴다 — 새 비밀을 하나 더 관리하지 않는다.
|
|
hashed = visitor_hash(os.environ.get("JWT_ACCESS_SECRET", ""), ip, user_agent or "", datetime.now(timezone.utc))
|
|
if self._seen_recently(f"{hashed}|{path}"):
|
|
return
|
|
utm = str(data.get("utm_source") or "").strip()[:100] or None
|
|
view = site_page_views(
|
|
site_id=site_id,
|
|
path=path[:2000],
|
|
visitor_hash=hashed,
|
|
referrer_domain=referrer_domain(str(data.get("referrer") or "")),
|
|
utm_source=utm,
|
|
device=device_of(user_agent or ""),
|
|
)
|
|
err = await DB_SESSION_MNG.execute_lambda_run(
|
|
[site_page_views.DBType()], [lambda s: self.crud.add_view(s, view)]
|
|
)
|
|
if err != ErrorType.SUCCESS:
|
|
LOG.w(f"[visit] 방문 기록 저장 실패: {err.name}")
|