"""Privacy-safe usage log (v21). One metadata record per run: country (Cloudflare header), host, channel (page/api), coarse client family, route, language, outcome state, cost, passes and number of uploads. NEVER an IP address, a name, the request text, or any document name/content. The record goes to the Space logs (``USAGE {...}``) and, for runs that attempted the AI report, to the RailNexus notify address by e-mail from a daemon thread so the user is never delayed. Everything here swallows its own exceptions: logging can never break the app. """ from __future__ import annotations import json import threading from datetime import datetime, timezone from typing import Any AI_STATES = frozenset({"ANALYZED", "FAILED", "CAPPED", "EXHAUSTED", "INTERRUPTED"}) _API_MARKERS = ("gradio_client", "httpx", "python", "curl", "node", "okhttp", "go-http") def _header(gr_request: Any, name: str) -> str: try: headers = gr_request.headers # only specific headers are ever read; never an IP one return str(headers.get(name) or "").strip() except Exception: # noqa: BLE001 return "" def request_meta(gr_request: Any) -> dict[str, str]: """Coarse, non-identifying facts from the request headers (None -> all unknown).""" country = _header(gr_request, "cf-ipcountry").upper() or "??" host = _header(gr_request, "x-forwarded-host") or _header(gr_request, "host") ua = _header(gr_request, "user-agent") low = ua.lower() is_api = (not ua) or ("mozilla" not in low) or any(m in low for m in _API_MARKERS) if is_api: channel = "api" client = ua.split("/", 1)[0].strip()[:40] if ua else "" client = client or "none" else: channel = "page" if any(t in low for t in ("edg/", "edga/", "edgios/")): client = "Edge" elif "chrome" in low or "crios" in low: client = "Chrome" elif "safari" in low: client = "Safari" elif "firefox" in low or "fxios" in low: client = "Firefox" else: client = "other-browser" return {"country": country[:8], "host": host[:100], "channel": channel, "client": client} def build_record(route: str, language: str, state: str, cost_usd: Any, passes: Any, docs_count: Any, meta: dict[str, str]) -> dict[str, Any]: try: cost = float(cost_usd or 0) except (TypeError, ValueError): cost = 0.0 return { "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"), "route": route, "language": language, "state": state, "cost_usd": cost, "passes": int(passes or 0), "docs_count": int(docs_count or 0), "country": meta.get("country", "??"), "host": meta.get("host", ""), "channel": meta.get("channel", "api"), "client": meta.get("client", "none"), } def log_line(record: dict[str, Any]) -> None: print("USAGE " + json.dumps(record, ensure_ascii=False), flush=True) def _notify_blocking(record: dict[str, Any]) -> None: try: from web import email_delivery if not email_delivery.delivery_status()["configured"]: return cfg = email_delivery.ses_config() client = email_delivery._make_client(cfg) subject = (f"RailNexus Value — uso del informe IA ({record['route']}, " f"{record['country']}, ${float(record['cost_usd']):.2f})") body = "\n".join([f"{k}: {v}" for k, v in record.items()] + ["", "Este aviso no contiene IP, nombre, documentos ni el contenido de la consulta."]) email_delivery._send(client, cfg["from_address"], cfg["notify_address"], subject, body) except Exception as exc: # noqa: BLE001 print(f"USAGE notify failed: {type(exc).__name__}", flush=True) def notify(record: dict[str, Any]) -> threading.Thread | None: """E-mail the record from a daemon thread (AI-attempt states only). Returns the thread.""" try: if record.get("state") not in AI_STATES: return None thread = threading.Thread(target=_notify_blocking, args=(dict(record),), daemon=True) thread.start() return thread except Exception as exc: # noqa: BLE001 print(f"USAGE notify failed: {type(exc).__name__}", flush=True) return None def record_run(route: str, language: str, state: str, cost_usd: Any, passes: Any, docs_count: Any, gr_request: Any) -> None: try: record = build_record(route, language, state, cost_usd, passes, docs_count, request_meta(gr_request)) log_line(record) notify(record) except Exception as exc: # noqa: BLE001 try: print(f"USAGE log failed: {type(exc).__name__}", flush=True) except Exception: # noqa: BLE001 pass