blacklist_users.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import threading
  2. import time
  3. from datetime import datetime
  4. from typing import Any
  5. from urllib.parse import urlparse
  6. from loguru import logger
  7. from sqlalchemy import func, inspect, literal, select
  8. from sqlalchemy.exc import SQLAlchemyError
  9. from sqlalchemy.orm import Session
  10. from database.database import get_dynamic_models, get_engine
  11. from database.models.models import BlacklistDomain
  12. # ---------------------------------------------------------------------------
  13. # Module-level TTL cache
  14. # Stores the fully aggregated result so paginated requests don't recompute.
  15. # ---------------------------------------------------------------------------
  16. _CACHE_TTL = 300 # seconds (5 minutes)
  17. _cache_lock = threading.Lock()
  18. _cache_data: dict | None = None
  19. _cache_time: float = 0.0
  20. def invalidate_blacklist_cache() -> None:
  21. """Force the next request to recompute aggregations (call after blacklist edits)."""
  22. global _cache_data, _cache_time
  23. with _cache_lock:
  24. _cache_data = None
  25. _cache_time = 0.0
  26. _BLACKLIST_DOMAIN_THRESHOLD = 50 # if more than this, cap the subquery
  27. _BLACKLIST_DOMAIN_CAP = 25 # number of domains to use when capped
  28. def _blacklist_exists(LogModel, domain_ids: list[int] | None = None):
  29. """
  30. Return a correlated EXISTS subquery that is True when any active blacklist
  31. domain appears as a substring in LogModel.url.
  32. Runs entirely inside the database engine – avoids passing thousands of LIKE
  33. parameters from Python and crashing with SQLAlchemy's parameter-limit error.
  34. When *domain_ids* is provided, only those specific blacklist entries are
  35. tested — this is the correct way to cap in SQLite, since LIMIT inside a
  36. correlated EXISTS is silently ignored by SQLite.
  37. """
  38. q = (
  39. select(BlacklistDomain.id)
  40. .where(
  41. BlacklistDomain.active == 1,
  42. LogModel.url.like(
  43. literal("%").op("||")(BlacklistDomain.domain).op("||")(literal("%"))
  44. ),
  45. )
  46. .correlate(LogModel.__table__)
  47. )
  48. if domain_ids is not None:
  49. q = q.where(BlacklistDomain.id.in_(domain_ids))
  50. return q.exists()
  51. def _get_parent_domain(url: str) -> str:
  52. if not url:
  53. return "unknown"
  54. u = url.strip().lower()
  55. if not (u.startswith("http://") or u.startswith("https://")):
  56. u = f"http://{u}"
  57. parsed = urlparse(u)
  58. host = (parsed.netloc or parsed.path).split("/")[0].split(":")[0].strip()
  59. if host.startswith("www."):
  60. host = host[4:]
  61. parts = [p for p in host.split(".") if p]
  62. return ".".join(parts[-2:]) if len(parts) >= 2 else host or "unknown"
  63. def _compute_full_aggregation(
  64. db: Session,
  65. ) -> tuple[dict[str, dict[str, int]], int, bool]:
  66. """
  67. Scan all daily log tables and return (user_domain_counts, total_requiere mostrar URLs completas couests, domain_capped).
  68. Key optimisations vs the naive approach:
  69. - SQL GROUP BY (username, url) per table → far fewer rows transferred to Python.
  70. - _get_parent_domain() is called only once per distinct (username, url) pair
  71. instead of once per raw log row.
  72. """
  73. engine = get_engine()
  74. inspector = inspect(engine)
  75. user_domain_counts: dict[str, dict[str, int]] = {}
  76. total_requests: int = 0
  77. all_tables = inspector.get_table_names()
  78. log_tables = sorted(
  79. [
  80. t
  81. for t in all_tables
  82. if t.startswith("log_") and len(t) == 12 and t[4:].isdigit()
  83. ],
  84. reverse=True,
  85. )
  86. # Cap the EXISTS subquery when the blacklist is very large.
  87. # NOTE: LIMIT inside a correlated EXISTS is silently ignored by SQLite,
  88. # so we pre-fetch the capped IDs in Python and use id.in_() instead.
  89. domain_count = (
  90. db.query(func.count(BlacklistDomain.id))
  91. .filter(BlacklistDomain.active == 1)
  92. .scalar()
  93. or 0
  94. )
  95. domain_capped = domain_count > _BLACKLIST_DOMAIN_THRESHOLD
  96. if domain_capped:
  97. domain_ids: list[int] | None = [
  98. row[0]
  99. for row in (
  100. db.query(BlacklistDomain.id)
  101. .filter(BlacklistDomain.active == 1)
  102. .order_by(BlacklistDomain.id)
  103. .limit(_BLACKLIST_DOMAIN_CAP)
  104. .all()
  105. )
  106. ]
  107. logger.debug(
  108. f"Blacklist has {domain_count} entries — capping EXISTS subquery to {len(domain_ids)} domain IDs"
  109. )
  110. else:
  111. domain_ids = None
  112. for log_table in log_tables: # noqa: E501 (loop continues below)
  113. date_str = log_table[4:] # "log_YYYYMMDD" → "YYYYMMDD"
  114. try:
  115. UserModel, LogModel = get_dynamic_models(date_str)
  116. except Exception as exc:
  117. logger.warning(f"Skipping {log_table}: {exc}")
  118. continue
  119. blacklist_exists = _blacklist_exists(LogModel, domain_ids=domain_ids)
  120. # Aggregate at the DB level: one row per distinct (username, url) pair.
  121. rows = (
  122. db.query(
  123. UserModel.username,
  124. LogModel.url,
  125. func.sum(LogModel.request_count).label("total"),
  126. )
  127. .join(UserModel, LogModel.user_id == UserModel.id)
  128. .filter(blacklist_exists)
  129. .group_by(UserModel.username, LogModel.url)
  130. .all()
  131. )
  132. for username, url, total in rows:
  133. domain = _get_parent_domain(url)
  134. count = int(total or 1)
  135. ud = user_domain_counts.setdefault(username, {})
  136. ud[domain] = ud.get(domain, 0) + count
  137. total_requests += count
  138. return user_domain_counts, total_requests, domain_capped
  139. def find_blacklisted_sites(
  140. db: Session, page: int = 1, per_page: int = 10
  141. ) -> dict[str, Any]:
  142. global _cache_data, _cache_time
  143. # Early-exit: no active blacklist entries at all.
  144. _EMPTY_RESULT = {
  145. "results": [],
  146. "domain_capped": False,
  147. "domain_cap": _BLACKLIST_DOMAIN_CAP,
  148. "pagination": {
  149. "total": 0,
  150. "total_requests": 0,
  151. "page": page,
  152. "per_page": per_page,
  153. "total_pages": 0,
  154. },
  155. }
  156. try:
  157. has_active = (
  158. db.query(BlacklistDomain)
  159. .filter(BlacklistDomain.active == 1)
  160. .limit(1)
  161. .first()
  162. )
  163. except SQLAlchemyError:
  164. logger.warning(
  165. "blacklist_domains table is not available — returning empty results"
  166. )
  167. return _EMPTY_RESULT
  168. if not has_active:
  169. return _EMPTY_RESULT
  170. # --- Cache read ---
  171. now = time.monotonic()
  172. with _cache_lock:
  173. if _cache_data is not None and (now - _cache_time) < _CACHE_TTL:
  174. sorted_users = _cache_data["sorted_users"]
  175. total_requests = _cache_data["total_requests"]
  176. domain_capped = _cache_data["domain_capped"]
  177. else:
  178. sorted_users = None
  179. # --- Cache miss: (re)compute ---
  180. if sorted_users is None:
  181. try:
  182. user_domain_counts, total_requests, domain_capped = (
  183. _compute_full_aggregation(db)
  184. )
  185. except SQLAlchemyError:
  186. logger.exception("Database error while searching blacklisted sites")
  187. return {"error": "Error interno del servidor"}
  188. sorted_users = sorted(
  189. user_domain_counts.items(),
  190. key=lambda x: sum(x[1].values()),
  191. reverse=True,
  192. )
  193. with _cache_lock:
  194. _cache_data = {
  195. "sorted_users": sorted_users,
  196. "total_requests": total_requests,
  197. "domain_capped": domain_capped,
  198. }
  199. _cache_time = time.monotonic()
  200. # --- Paginate in-memory (O(per_page)) ---
  201. total_users = len(sorted_users)
  202. start = (page - 1) * per_page
  203. paginated_users = sorted_users[start : start + per_page]
  204. results = []
  205. for username, domain_counts in paginated_users:
  206. for domain, count in sorted(
  207. domain_counts.items(), key=lambda x: x[1], reverse=True
  208. ):
  209. results.append({"usuario": username, "domain": domain, "count": count})
  210. return {
  211. "results": results,
  212. "domain_capped": domain_capped,
  213. "domain_cap": _BLACKLIST_DOMAIN_CAP,
  214. "pagination": {
  215. "total": total_users,
  216. "total_requests": total_requests,
  217. "page": page,
  218. "per_page": per_page,
  219. "total_pages": (total_users + per_page - 1) // per_page,
  220. },
  221. }
  222. def find_blacklisted_sites_by_date(db: Session, specific_date: datetime.date):
  223. results = []
  224. try:
  225. date_suffix = specific_date.strftime("%Y%m%d")
  226. user_table = f"user_{date_suffix}"
  227. log_table = f"log_{date_suffix}"
  228. inspector = inspect(db.get_bind())
  229. if not inspector.has_table(user_table) or not inspector.has_table(log_table):
  230. return []
  231. try:
  232. UserModel, LogModel = get_dynamic_models(date_suffix)
  233. except Exception:
  234. return []
  235. blacklist_exists = _blacklist_exists(LogModel)
  236. query_results = (
  237. db.query(UserModel.username, LogModel.url)
  238. .join(UserModel, LogModel.user_id == UserModel.id)
  239. .filter(blacklist_exists)
  240. .all()
  241. )
  242. formatted_date = specific_date.strftime("%Y-%m-%d")
  243. for row in query_results:
  244. results.append(
  245. {"fecha": formatted_date, "usuario": row.username, "url": row.url}
  246. )
  247. except SQLAlchemyError as e:
  248. logger.error(f"Database error: {e}")
  249. return results