발행 사이트를 연 사람의 페이지뷰를 쿠키·식별자 없이 모은다. 방문자 구분은
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·날씨 문구의 기존 실패).
92 lines
4.2 KiB
Python
92 lines
4.2 KiB
Python
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_page_views, sites
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
|
|
|
|
class IVisitCRUD(ABC):
|
|
@abstractmethod
|
|
async def add_view(self, cdb: AsyncSession, view: site_page_views) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, realtime_since: datetime, site_id,
|
|
overall: bool) -> Tuple[ErrorType, dict]:
|
|
"""기간 [start, end) 집계 + realtime_since 이후 고유 방문자. 키: realtime·summary·daily·referrers·devices + (overall) sites | (사이트) pages·utm."""
|
|
pass
|
|
|
|
|
|
class VisitCRUD(IVisitCRUD):
|
|
async def add_view(self, cdb: AsyncSession, view: site_page_views) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, view)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, realtime_since: datetime, site_id,
|
|
overall: bool) -> Tuple[ErrorType, dict]:
|
|
try:
|
|
v = site_page_views
|
|
scope = v.deleted == False # noqa: E712
|
|
if site_id is not None:
|
|
scope = and_(scope, v.site_id == site_id)
|
|
where = and_(scope, v.created_at >= start, v.created_at < end)
|
|
views = func.count().label("views")
|
|
visitors = func.count(distinct(v.visitor_hash)).label("visitors")
|
|
# GROUP BY 는 라벨로 — 같은 식 두 번이면 'Asia/Seoul' 바인드가 갈라져 Postgres 가 거부한다(크롤러 통계와 같은 이유).
|
|
day = func.date(func.timezone("Asia/Seoul", v.created_at)).label("day")
|
|
queries = {
|
|
# 실시간은 기간 선택과 무관하다 — "지금 몇 명" 을 묻는 숫자다.
|
|
"realtime": select(func.count(distinct(v.visitor_hash)).label("n")).where(scope, v.created_at >= realtime_since),
|
|
"summary": select(views, visitors, func.max(v.created_at).label("last_at")).where(where),
|
|
"daily": select(day, views, visitors).where(where).group_by("day").order_by("day"),
|
|
"referrers": (
|
|
select(v.referrer_domain, views)
|
|
.where(where, v.referrer_domain.isnot(None))
|
|
.group_by(v.referrer_domain)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
),
|
|
"devices": select(v.device, views).where(where).group_by(v.device).order_by(func.count().desc()),
|
|
}
|
|
if overall:
|
|
queries["sites"] = (
|
|
select(v.site_id, places.place_id, places.name, views, visitors)
|
|
.join(sites, sites.site_id == v.site_id)
|
|
.join(places, places.place_id == sites.place_id)
|
|
.where(where)
|
|
.group_by(v.site_id, places.place_id, places.name)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
else:
|
|
queries["pages"] = (
|
|
select(v.path, views, visitors).where(where).group_by(v.path).order_by(func.count().desc()).limit(20)
|
|
)
|
|
queries["utm"] = (
|
|
select(v.utm_source, views)
|
|
.where(where, v.utm_source.isnot(None))
|
|
.group_by(v.utm_source)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
|
|
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, {}
|