blacklist_users.py 9.5 KB

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