Spaces:
Running

ioc-core / src /services /stats.py
hellium1999's picture
feat: Implement dashboard statistics service with in-memory cache, async Supabase persistence, and expose it via the unified API.
33dee12
Raw History Blame
16.6 kB
"""Dashboard stats service with in-memory read cache and async Supabase writes.
Architecture:
- log_lookup() appends to memory instantly + fires a background Supabase INSERT
- Dashboard reads (get_stats, get_trend, etc.) serve from in-memory cache (~0ms)
- On startup, hydrates last 30 days from Supabase into memory
- Failed Supabase writes are retried with exponential backoff
- Zero data loss on container restart (every record hits Supabase immediately)
"""
import logging
import threading
import time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from src.config.supabase import get_supabase_client
logger = logging.getLogger(__name__)
class StatsService:
"""Service for dashboard statistics with in-memory cache and async persistence."""
TABLE_NAME = "ioc_stats"
MAX_RECORDS = 10_000 # In-memory cap (~5MB)
HYDRATION_DAYS = 30 # Days to load from Supabase on startup
RETRY_INTERVAL = 5 # Base retry interval (seconds)
MAX_BACKOFF = 300 # Max retry interval (5 minutes)
HYDRATION_RETRIES = 5 # Max hydration retry attempts
HYDRATION_RETRY_BASE = 2 # Base delay for hydration retry (seconds)
HYDRATION_BG_INTERVAL = 30 # Background hydration retry interval (seconds)
def __init__(self):
self._lock = threading.Lock()
self._records: list[dict] = [] # All in-memory records (for reads)
self._failed_queue: list[dict] = [] # Records that failed Supabase write
self._supabase = get_supabase_client()
self._current_backoff = self.RETRY_INTERVAL
self._hydrated = False # Track if hydration succeeded
# Thread pool for fire-and-forget Supabase writes
self._write_pool = ThreadPoolExecutor(
max_workers=2,
thread_name_prefix="supabase-write",
)
# Hydrate from Supabase on startup (with retries)
self._hydrate_with_retry()
# Start retry thread for failed writes
self._retry_thread = threading.Thread(
target=self._retry_loop,
daemon=True,
name="supabase-retry",
)
self._retry_thread.start()
# If hydration failed, start background thread to keep trying
if not self._hydrated:
self._hydration_thread = threading.Thread(
target=self._background_hydration_loop,
daemon=True,
name="supabase-hydration",
)
self._hydration_thread.start()
logger.info(
f"StatsService initialized: {len(self._records)} records hydrated, "
f"supabase={'connected' if self._supabase else 'unavailable'}"
)
@property
def enabled(self) -> bool:
"""Always enabled β€” in-memory is the primary store."""
return True
# ─── Write Path ────────────────────────────────────────────────
def log_lookup(
self,
ioc_value: str,
ioc_type: str,
verdict: str | None = None,
country_code: str | None = None,
) -> bool:
"""
Log an IOC lookup.
1. SYNC: Append to in-memory list (instant, for dashboard reads)
2. ASYNC: Fire-and-forget INSERT to Supabase (non-blocking)
Returns:
True (always succeeds β€” memory write can't fail)
"""
record = {
"ioc_value": ioc_value[:255],
"ioc_type": ioc_type.lower(),
"verdict": (verdict or "unknown").lower(),
"created_at": datetime.now(timezone.utc).isoformat(),
}
if country_code:
record["country_code"] = country_code.upper()[:2]
# 1. SYNC: Store in memory (instant)
with self._lock:
self._records.append(record)
if len(self._records) > self.MAX_RECORDS:
self._records = self._records[-self.MAX_RECORDS:]
# 2. ASYNC: Fire-and-forget write to Supabase
self._write_pool.submit(self._write_to_supabase, record)
logger.debug(f"Logged lookup: {ioc_type}/{verdict}")
return True
def _write_to_supabase(self, record: dict) -> None:
"""Background thread: write a single record to Supabase."""
if not self._supabase:
# Queue for retry when Supabase becomes available
with self._lock:
self._failed_queue.append(record)
return
try:
# Build clean insert data (exclude None values)
data = {k: v for k, v in record.items() if v is not None}
self._supabase.table(self.TABLE_NAME).insert(data).execute()
except Exception as e:
logger.warning(f"Supabase write failed, queued for retry: {e}")
with self._lock:
self._failed_queue.append(record)
# ─── Retry Loop ────────────────────────────────────────────────
def _retry_loop(self) -> None:
"""Daemon thread: retries failed Supabase writes with exponential backoff."""
while True:
time.sleep(self._current_backoff)
# Atomically grab the failed queue
with self._lock:
if not self._failed_queue:
# Nothing to retry β€” reset backoff
self._current_backoff = self.RETRY_INTERVAL
continue
batch = self._failed_queue.copy()
self._failed_queue.clear()
if not self._supabase:
# Supabase still not available β€” put records back
with self._lock:
self._failed_queue.extend(batch)
self._current_backoff = min(
self._current_backoff * 2, self.MAX_BACKOFF
)
logger.debug(
f"Supabase unavailable, {len(batch)} records pending, "
f"retry in {self._current_backoff}s"
)
continue
# Try batch insert
try:
clean_batch = [
{k: v for k, v in r.items() if v is not None}
for r in batch
]
self._supabase.table(self.TABLE_NAME).insert(clean_batch).execute()
self._current_backoff = self.RETRY_INTERVAL
logger.info(f"Retry flush: {len(batch)} records written to Supabase")
except Exception as e:
logger.warning(
f"Retry flush failed ({len(batch)} records), "
f"next retry in {self._current_backoff}s: {e}"
)
# Put records back for next attempt
with self._lock:
self._failed_queue.extend(batch)
self._current_backoff = min(
self._current_backoff * 2, self.MAX_BACKOFF
)
# ─── Read Path (all from memory) ──────────────────────────────
def get_stats(self, days: int = 7) -> dict:
"""Get aggregated statistics from in-memory cache."""
days = max(1, min(365, days))
since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
today_start = datetime.now(timezone.utc).replace(
hour=0, minute=0, second=0, microsecond=0
).isoformat()
with self._lock:
filtered = [r for r in self._records if r["created_at"] >= since]
total = len(filtered)
by_type: dict[str, int] = {}
by_verdict: dict[str, int] = {}
threats = 0
today_count = 0
for r in filtered:
ioc_type = r.get("ioc_type", "unknown")
verdict = r.get("verdict", "unknown")
by_type[ioc_type] = by_type.get(ioc_type, 0) + 1
by_verdict[verdict] = by_verdict.get(verdict, 0) + 1
if verdict in ("malicious", "suspicious"):
threats += 1
if r["created_at"] >= today_start:
today_count += 1
threat_rate = round((threats / total * 100), 1) if total > 0 else 0
return {
"total": total,
"today": today_count,
"threats": threats,
"threat_rate": threat_rate,
"by_type": by_type,
"by_verdict": by_verdict,
}
def get_trend(self, days: int = 7) -> list[dict]:
"""Get daily trend data from in-memory cache."""
days = max(1, min(365, days))
since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
with self._lock:
filtered = [r for r in self._records if r["created_at"] >= since]
# Group by day
daily: dict[str, dict] = {}
for r in filtered:
date_key = r["created_at"][:10] # YYYY-MM-DD
verdict = r.get("verdict", "unknown")
if date_key not in daily:
daily[date_key] = {"date": date_key, "total": 0, "threats": 0}
daily[date_key]["total"] += 1
if verdict in ("malicious", "suspicious"):
daily[date_key]["threats"] += 1
# Return sorted by date
return sorted(daily.values(), key=lambda x: x["date"])
def get_recent(self, limit: int = 20) -> list[dict]:
"""Get recent IOC lookups from in-memory cache."""
limit = max(1, min(100, limit))
with self._lock:
# Return most recent N, newest first
recent = self._records[-limit:]
# Return in reverse chronological order
return [
{
"ioc_value": r["ioc_value"],
"ioc_type": r["ioc_type"],
"verdict": r["verdict"],
"created_at": r["created_at"],
}
for r in reversed(recent)
]
def get_top_iocs(self, limit: int = 10, days: int = 30) -> list[dict]:
"""Get most frequently searched IOCs from in-memory cache."""
limit = max(1, min(50, limit))
since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
with self._lock:
filtered = [r for r in self._records if r["created_at"] >= since]
# Count occurrences
counter: Counter[str] = Counter()
type_map: dict[str, str] = {}
for r in filtered:
key = f"{r['ioc_type']}:{r['ioc_value']}"
counter[key] += 1
type_map[key] = r["ioc_type"]
# Build sorted result
result = []
for key, count in counter.most_common(limit):
ioc_type, ioc_value = key.split(":", 1)
result.append({
"ioc_value": ioc_value,
"ioc_type": ioc_type,
"count": count,
})
return result
def get_geo_stats(self, days: int = 30) -> list[dict]:
"""Get geographic distribution from in-memory cache."""
since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
with self._lock:
filtered = [
r for r in self._records
if r["created_at"] >= since and r.get("country_code")
]
counter: Counter[str] = Counter()
for r in filtered:
counter[r["country_code"]] += 1
return [
{"country": cc, "count": count}
for cc, count in counter.most_common()
]
# ─── Startup Hydration ─────────────────────────────────────────
def _hydrate_with_retry(self) -> None:
"""Attempt hydration with retries using exponential backoff."""
for attempt in range(1, self.HYDRATION_RETRIES + 1):
if self._hydrate():
return # Success
if attempt < self.HYDRATION_RETRIES:
delay = self.HYDRATION_RETRY_BASE ** attempt
logger.warning(
f"Hydration attempt {attempt}/{self.HYDRATION_RETRIES} failed, "
f"retrying in {delay}s..."
)
time.sleep(delay)
logger.warning(
f"All {self.HYDRATION_RETRIES} hydration attempts failed β€” "
f"will keep retrying in background every {self.HYDRATION_BG_INTERVAL}s"
)
def _background_hydration_loop(self) -> None:
"""Daemon thread: keeps retrying hydration until it succeeds."""
while not self._hydrated:
time.sleep(self.HYDRATION_BG_INTERVAL)
logger.info("Background hydration: retrying Supabase connection...")
# Re-initialize the Supabase client in case the issue was transient
get_supabase_client.cache_clear()
self._supabase = get_supabase_client()
if self._hydrate():
logger.info(
f"Background hydration succeeded! "
f"{len(self._records)} records loaded."
)
return
def _hydrate(self) -> bool:
"""Load historical data from Supabase into memory.
Paginates in batches of 1,000 (Supabase PostgREST row limit)
to ensure ALL records within the hydration window are loaded.
Returns:
True if hydration succeeded, False otherwise.
"""
if not self._supabase:
# Re-initialize in case env vars are now available
get_supabase_client.cache_clear()
self._supabase = get_supabase_client()
if not self._supabase:
logger.warning("Supabase unavailable β€” cannot hydrate")
return False
try:
since = (
datetime.now(timezone.utc) - timedelta(days=self.HYDRATION_DAYS)
).isoformat()
all_records: list[dict] = []
page_size = 1000 # Supabase PostgREST max per request
offset = 0
while len(all_records) < self.MAX_RECORDS:
response = (
self._supabase.table(self.TABLE_NAME)
.select("ioc_value, ioc_type, verdict, country_code, created_at")
.gte("created_at", since)
.order("created_at")
.range(offset, offset + page_size - 1)
.execute()
)
batch = response.data or []
if not batch:
break # No more records
all_records.extend(batch)
offset += page_size
if len(batch) < page_size:
break # Last page
# Trim to MAX_RECORDS if needed
all_records = all_records[:self.MAX_RECORDS]
with self._lock:
self._records = [
{
"ioc_value": r.get("ioc_value", ""),
"ioc_type": r.get("ioc_type", "unknown"),
"verdict": r.get("verdict", "unknown"),
"country_code": r.get("country_code"),
"created_at": r.get("created_at", ""),
}
for r in all_records
]
self._hydrated = True
logger.info(f"Hydrated {len(all_records)} records from Supabase ({offset // page_size + (1 if offset % page_size else 0)} pages)")
return True
except Exception as e:
logger.warning(f"Supabase hydration failed β€” starting empty: {e}")
return False
# ─── Status / Diagnostics ──────────────────────────────────────
def get_status(self) -> dict:
"""Get service status for diagnostics."""
with self._lock:
return {
"records_in_memory": len(self._records),
"pending_retries": len(self._failed_queue),
"supabase_connected": self._supabase is not None,
"hydrated": self._hydrated,
"retry_backoff_seconds": self._current_backoff,
}
# Global service instance
stats_service = StatsService()