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_crawler_hits, sites from common.enums import ErrorType from common.logger import LOG from services.crawler_detect import AI_PURPOSES class ICrawlerHitCRUD(ABC): @abstractmethod async def add_hit(self, cdb: AsyncSession, hit: site_crawler_hits) -> ErrorType: pass @abstractmethod async def list_site_slugs(self, cdb: AsyncSession) -> Tuple[ErrorType, list]: """(ErrorType, [Row(place_id, name, site_id, domain)]) — 슬러그 → site_id 표 재료.""" pass @abstractmethod async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, site_id, overall: bool) -> Tuple[ErrorType, dict]: """기간 [start, end) 집계. 키: summary·daily·bots + (overall) sites·root_files·others | (사이트) pages·recent.""" pass class CrawlerHitCRUD(ICrawlerHitCRUD): async def add_hit(self, cdb: AsyncSession, hit: site_crawler_hits) -> ErrorType: try: return await DB_SESSION_MNG.insert(cdb, hit) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED async def list_site_slugs(self, cdb: AsyncSession) -> Tuple[ErrorType, list]: try: query = ( select(places.place_id, places.name, sites.site_id, sites.domain) .join(sites, and_(sites.place_id == places.place_id, sites.deleted == False)) # noqa: E712 .where(places.deleted == False) # noqa: E712 ) return await DB_SESSION_MNG.execute(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, [] async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, site_id, overall: bool) -> Tuple[ErrorType, dict]: try: h = site_crawler_hits where = and_(h.deleted == False, h.created_at >= start, h.created_at < end) # noqa: E712 if site_id is not None: where = and_(where, h.site_id == site_id) hits = func.count().label("hits") ai_hits = func.count().filter(h.purpose.in_(AI_PURPOSES)).label("ai_hits") last_at = func.max(h.created_at).label("last_at") # GROUP BY 는 라벨("day")로 건다 — 같은 식을 두 번 쓰면 'Asia/Seoul' 이 다른 바인드 파라미터가 돼 # Postgres 가 "must appear in the GROUP BY clause" 로 거부한다. day = func.date(func.timezone("Asia/Seoul", h.created_at)).label("day") queries = { "summary": select(hits, ai_hits, func.count(distinct(h.bot)).label("bots"), last_at).where(where), "daily": select(day, h.purpose, hits).where(where).group_by("day", h.purpose).order_by("day", h.purpose), "bots": ( select(h.bot, h.vendor, h.purpose, hits, last_at) .where(where, h.bot.isnot(None)) .group_by(h.bot, h.vendor, h.purpose) .order_by(func.count().desc()) .limit(50) ), } if overall: queries["sites"] = ( select(h.site_id, places.place_id, places.name, hits, ai_hits, last_at) .join(sites, sites.site_id == h.site_id) .join(places, places.place_id == sites.place_id) .where(where) .group_by(h.site_id, places.place_id, places.name) .order_by(func.count().desc()) .limit(20) ) queries["root_files"] = ( select(h.kind, h.bot, h.purpose, hits, last_at) .where(where, h.kind.in_(("robots", "sitemap"))) .group_by(h.kind, h.bot, h.purpose) .order_by(h.kind, func.count().desc()) ) queries["others"] = ( select(h.user_agent, hits, last_at) .where(where, h.purpose == "other") .group_by(h.user_agent) .order_by(func.count().desc()) .limit(20) ) else: queries["pages"] = ( select(h.path, hits, last_at) .where(where, h.kind == "page") .group_by(h.path) .order_by(func.count().desc()) .limit(20) ) queries["recent"] = ( select(h.created_at, h.kind, h.bot, h.vendor, h.purpose, h.path) .where(where) .order_by(h.created_at.desc()) .limit(50) ) 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, {}