|
| 1 | +""" |
| 2 | +╔══════════════════════════════════════════════════════════════════════════════╗ |
| 3 | +║ ║ |
| 4 | +║ STEALTH-RUNNER — IP Quality Scoring & Persistence (SR-151) ║ |
| 5 | +║ ║ |
| 6 | +╠══════════════════════════════════════════════════════════════════════════════╣ |
| 7 | +║ ║ |
| 8 | +║ ZWECK / PURPOSE: ║ |
| 9 | +║ ──────────────── ║ |
| 10 | +║ IP-Quality Scoring Modul mit JSONL Persistence fuer Proxy-Events. ║ |
| 11 | +║ Speichert alle Proxy-Outcomes in tagesrotierenden Log-Dateien. ║ |
| 12 | +║ ║ |
| 13 | +║ SCORING FORMULA: ║ |
| 14 | +║ ───────────────── ║ |
| 15 | +║ Score = base(100) + success_count*2 - fail_count*5 - ban_count*10 ║ |
| 16 | +║ Clamped to [0, 200]. ║ |
| 17 | +║ ║ |
| 18 | +║ PERSISTENCE: ║ |
| 19 | +║ ──────────── ║ |
| 20 | +║ JSONL Format in logs/ip-quality-YYYY-MM-DD.jsonl (taeglich rotiert). ║ |
| 21 | +║ Append-only fuer Audit Trail und Analyse. ║ |
| 22 | +║ ║ |
| 23 | +║ JSONL LINE FORMAT: ║ |
| 24 | +║ ────────────────── ║ |
| 25 | +║ {"ts": "ISO8601", "label": "proxy-name", "country": "DE", ║ |
| 26 | +║ "outcome": "success|fail|banned", "score_before": 100, "score_after": 102}║ |
| 27 | +║ ║ |
| 28 | +╚══════════════════════════════════════════════════════════════════════════════╝ |
| 29 | +
|
| 30 | +Closes #151 |
| 31 | +""" |
| 32 | + |
| 33 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 34 | +# IMPORTS |
| 35 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 36 | + |
| 37 | +import json |
| 38 | +import logging |
| 39 | +import threading |
| 40 | +from pathlib import Path |
| 41 | +from datetime import datetime, timezone |
| 42 | +from typing import TYPE_CHECKING |
| 43 | + |
| 44 | +if TYPE_CHECKING: |
| 45 | + from .proxy_pool import ProxyEntry |
| 46 | + |
| 47 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 48 | +# LOGGING |
| 49 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 50 | + |
| 51 | +logger = logging.getLogger(__name__) |
| 52 | + |
| 53 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 54 | +# CONSTANTS |
| 55 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 56 | + |
| 57 | +# Basis-Score fuer neue Proxies |
| 58 | +BASE_SCORE = 100 |
| 59 | + |
| 60 | +# Score-Gewichtung (identisch mit ProxyEntry.score property) |
| 61 | +SUCCESS_WEIGHT = 2 # +2 pro Erfolg |
| 62 | +FAIL_WEIGHT = 5 # -5 pro Fehler |
| 63 | +BAN_WEIGHT = 10 # -10 pro Ban |
| 64 | + |
| 65 | +# Score-Grenzen |
| 66 | +MIN_SCORE = 0 |
| 67 | +MAX_SCORE = 200 |
| 68 | + |
| 69 | +# Cold-Schwelle (Proxies unter diesem Score sind "cold") |
| 70 | +COLD_THRESHOLD = 10 |
| 71 | + |
| 72 | +# Log-Verzeichnis (relativ zum Projekt-Root) |
| 73 | +LOG_DIR = Path("logs") |
| 74 | + |
| 75 | +# File Lock fuer Thread-Safety beim Schreiben |
| 76 | +_write_lock = threading.Lock() |
| 77 | + |
| 78 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 79 | +# FUNCTIONS |
| 80 | +# ═══════════════════════════════════════════════════════════════════════════════ |
| 81 | + |
| 82 | + |
| 83 | +def score( |
| 84 | + success_count: int = 0, |
| 85 | + fail_count: int = 0, |
| 86 | + ban_count: int = 0 |
| 87 | +) -> int: |
| 88 | + """ |
| 89 | + Berechnet den IP-Quality Score nach der Formel: |
| 90 | + Score = base(100) + success_count*2 - fail_count*5 - ban_count*10 |
| 91 | +
|
| 92 | + WARUM diese Gewichtung? |
| 93 | + → success*2: Langsames Wachstum, belohnt konsistente Performance. |
| 94 | + → fail*5: Moderate Bestrafung, ein paar Fehler sind akzeptabel. |
| 95 | + → ban*10: Harte Bestrafung, Bans deuten auf kompromittierte IP hin. |
| 96 | +
|
| 97 | + Args: |
| 98 | + success_count: Anzahl erfolgreicher Requests. |
| 99 | + fail_count: Anzahl fehlgeschlagener Requests. |
| 100 | + ban_count: Anzahl Ban-Events (403/429). |
| 101 | +
|
| 102 | + Returns: |
| 103 | + int: Score zwischen 0 und 200 (clamped). |
| 104 | +
|
| 105 | + Example: |
| 106 | + >>> score(success_count=10, fail_count=2, ban_count=0) |
| 107 | + 110 # 100 + 20 - 10 - 0 |
| 108 | + >>> score(success_count=0, fail_count=0, ban_count=5) |
| 109 | + 50 # 100 + 0 - 0 - 50 |
| 110 | + """ |
| 111 | + raw = ( |
| 112 | + BASE_SCORE |
| 113 | + + (success_count * SUCCESS_WEIGHT) |
| 114 | + - (fail_count * FAIL_WEIGHT) |
| 115 | + - (ban_count * BAN_WEIGHT) |
| 116 | + ) |
| 117 | + return max(MIN_SCORE, min(MAX_SCORE, raw)) |
| 118 | + |
| 119 | + |
| 120 | +def is_cold(score_value: int) -> bool: |
| 121 | + """ |
| 122 | + Prueft ob ein Score als "cold" gilt (< 10). |
| 123 | +
|
| 124 | + Cold Proxies werden bei der Auswahl deprioritized aber nicht geloescht. |
| 125 | + Sie koennen sich erholen wenn sie wieder erfolgreiche Requests haben. |
| 126 | +
|
| 127 | + Args: |
| 128 | + score_value: Der zu pruefende Score. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + bool: True wenn Score < 10. |
| 132 | + """ |
| 133 | + return score_value < COLD_THRESHOLD |
| 134 | + |
| 135 | + |
| 136 | +def get_log_path() -> Path: |
| 137 | + """ |
| 138 | + Liefert den Pfad zur heutigen Log-Datei. |
| 139 | +
|
| 140 | + FORMAT: logs/ip-quality-YYYY-MM-DD.jsonl |
| 141 | +
|
| 142 | + WARUM taeglich rotieren? |
| 143 | + → Kleinere Dateien, einfacher zu analysieren. |
| 144 | + → Alte Logs koennen archiviert/geloescht werden. |
| 145 | + → Timestamp im Dateinamen fuer einfache Filterung. |
| 146 | +
|
| 147 | + Returns: |
| 148 | + Path: Pfad zur heutigen Log-Datei. |
| 149 | + """ |
| 150 | + today = datetime.now(timezone.utc).strftime("%Y-%m-%d") |
| 151 | + return LOG_DIR / f"ip-quality-{today}.jsonl" |
| 152 | + |
| 153 | + |
| 154 | +def persist_event( |
| 155 | + entry: "ProxyEntry", |
| 156 | + outcome: str, |
| 157 | + score_before: int, |
| 158 | + score_after: int |
| 159 | +) -> None: |
| 160 | + """ |
| 161 | + Persistiert ein Proxy-Event in die tagesrotierte JSONL-Datei. |
| 162 | +
|
| 163 | + JSONL LINE FORMAT: |
| 164 | + { |
| 165 | + "ts": "2024-01-15T12:34:56.789Z", |
| 166 | + "label": "residential-de-1", |
| 167 | + "country": "DE", |
| 168 | + "outcome": "success", |
| 169 | + "score_before": 100, |
| 170 | + "score_after": 102 |
| 171 | + } |
| 172 | +
|
| 173 | + THREAD-SAFETY: |
| 174 | + Verwendet _write_lock um Race Conditions zu vermeiden. |
| 175 | + Mehrere Threads koennen gleichzeitig Events loggen. |
| 176 | +
|
| 177 | + Args: |
| 178 | + entry: Der ProxyEntry fuer den das Event aufgezeichnet wird. |
| 179 | + outcome: "success", "fail", oder "banned". |
| 180 | + score_before: Score vor dem Event. |
| 181 | + score_after: Score nach dem Event. |
| 182 | + """ |
| 183 | + with _write_lock: |
| 184 | + try: |
| 185 | + # Log-Verzeichnis erstellen falls nicht vorhanden |
| 186 | + LOG_DIR.mkdir(parents=True, exist_ok=True) |
| 187 | + |
| 188 | + # Event-Daten |
| 189 | + event = { |
| 190 | + "ts": datetime.now(timezone.utc).isoformat(), |
| 191 | + "label": entry.label, |
| 192 | + "country": entry.country, |
| 193 | + "outcome": outcome, |
| 194 | + "score_before": score_before, |
| 195 | + "score_after": score_after, |
| 196 | + } |
| 197 | + |
| 198 | + # Append to JSONL (eine JSON-Zeile pro Event) |
| 199 | + log_path = get_log_path() |
| 200 | + with open(log_path, "a", encoding="utf-8") as f: |
| 201 | + f.write(json.dumps(event) + "\n") |
| 202 | + |
| 203 | + logger.debug(f"Event persistiert: {entry.label} → {outcome}") |
| 204 | + |
| 205 | + except Exception as e: |
| 206 | + # Logging-Fehler sollten den Hauptfluss nicht blockieren |
| 207 | + logger.warning(f"Fehler beim Persistieren von Event: {e}") |
| 208 | + |
| 209 | + |
| 210 | +def load_events(date_str: str = None) -> list: |
| 211 | + """ |
| 212 | + Laedt Events aus einer JSONL-Datei. |
| 213 | +
|
| 214 | + Args: |
| 215 | + date_str: Datum im Format YYYY-MM-DD. Default: heute. |
| 216 | +
|
| 217 | + Returns: |
| 218 | + list: Liste von Event-Dicts. |
| 219 | +
|
| 220 | + Example: |
| 221 | + >>> events = load_events("2024-01-15") |
| 222 | + >>> len(events) |
| 223 | + 42 |
| 224 | + """ |
| 225 | + if date_str is None: |
| 226 | + date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d") |
| 227 | + |
| 228 | + log_path = LOG_DIR / f"ip-quality-{date_str}.jsonl" |
| 229 | + |
| 230 | + if not log_path.exists(): |
| 231 | + return [] |
| 232 | + |
| 233 | + events = [] |
| 234 | + with open(log_path, "r", encoding="utf-8") as f: |
| 235 | + for line in f: |
| 236 | + line = line.strip() |
| 237 | + if line: |
| 238 | + try: |
| 239 | + events.append(json.loads(line)) |
| 240 | + except json.JSONDecodeError: |
| 241 | + logger.warning(f"Ungueltige JSON-Zeile: {line[:50]}...") |
| 242 | + |
| 243 | + return events |
| 244 | + |
| 245 | + |
| 246 | +def aggregate_stats(date_str: str = None) -> dict: |
| 247 | + """ |
| 248 | + Aggregiert Statistiken aus Events fuer ein Datum. |
| 249 | +
|
| 250 | + Args: |
| 251 | + date_str: Datum im Format YYYY-MM-DD. Default: heute. |
| 252 | +
|
| 253 | + Returns: |
| 254 | + dict: { |
| 255 | + "total_events": int, |
| 256 | + "success_count": int, |
| 257 | + "fail_count": int, |
| 258 | + "ban_count": int, |
| 259 | + "by_proxy": {label: {"success": n, "fail": n, "banned": n}} |
| 260 | + } |
| 261 | + """ |
| 262 | + events = load_events(date_str) |
| 263 | + |
| 264 | + stats = { |
| 265 | + "total_events": len(events), |
| 266 | + "success_count": 0, |
| 267 | + "fail_count": 0, |
| 268 | + "ban_count": 0, |
| 269 | + "by_proxy": {}, |
| 270 | + } |
| 271 | + |
| 272 | + for event in events: |
| 273 | + outcome = event.get("outcome", "") |
| 274 | + label = event.get("label", "unknown") |
| 275 | + |
| 276 | + if outcome == "success": |
| 277 | + stats["success_count"] += 1 |
| 278 | + elif outcome == "fail": |
| 279 | + stats["fail_count"] += 1 |
| 280 | + elif outcome == "banned": |
| 281 | + stats["ban_count"] += 1 |
| 282 | + |
| 283 | + if label not in stats["by_proxy"]: |
| 284 | + stats["by_proxy"][label] = {"success": 0, "fail": 0, "banned": 0} |
| 285 | + |
| 286 | + if outcome in ("success", "fail", "banned"): |
| 287 | + stats["by_proxy"][label][outcome] += 1 |
| 288 | + |
| 289 | + return stats |
0 commit comments