pryscraper/cache.py
cryptorugmunch a7c30b12cd
Some checks failed
CI / lint (push) Failing after 2s
CI / typecheck (push) Failing after 2s
CI / test (push) Failing after 2s
CI / Secret scan (gitleaks) (push) Failing after 1s
CI / Security audit (bandit) (push) Failing after 2s
chore(lint): auto-fix 253 of 283 ruff issues (F401, I001, E402, RUF100, UP037, SIM105)
Mass ruff auto-fix:
  - ruff check --fix: 109 issues fixed (F401 unused imports,
    I001 unsorted imports, UP037 quoted annotations, SIM105
    suppressible exception, RUF100 unused-noqa)
  - ruff check --fix --unsafe-fixes: 22 additional issues
  - ruff format: 70 files reformatted
  - Manual pass: fix 16 misplaced import httpx lines
  - Manual pass: fix remaining E402 (import-after-docstring)

Result: 283 errors -> 30 errors.

The remaining 30 are real issues that need manual review:
  5 F401 unused-import (likely auto-generated stubs)
  5 F821 undefined-name (real bugs in code that references
    redis/pydantic/LLMRegistry without imports)
  3 BLE001 (the compliance LLM fallback is intentional; the
    other two are real)
  3 RUF012 mutable-class-default
  3 SIM105, 3 SIM117, 2 E722, 2 E741
  1 B007, 1 B025, 1 E402, 1 RUF200 (pyproject.toml issue)

Tests: 436/437 pass (1 pre-existing SSE sandbox failure).
format check + import sort: now clean.
make ci: still gated on the 30 remaining real issues.
Follow-up: triage the 30 issues file-by-file.
2026-07-02 21:51:25 +02:00

86 lines
2.7 KiB
Python

"""Pry — in-memory LRU cache with Redis persistence.
Prevents re-scraping the same URL within TTL window."""
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Rug Munch Media LLC
#
# Part of Pry — https://git.rugmunch.io/RugMunchMedia/pryscraper
# Licensed under MIT. See LICENSE.
import hashlib
import json
import time
from collections import OrderedDict
class ResponseCache:
"""Two-tier cache: local LRU + optional Redis persistence.
Default TTL: 300 seconds (5 min) for pages, 3600 (1 hr) for API calls.
"""
def __init__(self, capacity: int = 500, redis_url: str | None = None):
self.capacity = capacity
self._cache: OrderedDict = OrderedDict()
self._redis = None
self._redis_url = redis_url
self._hits = 0
self._misses = 0
def _key(self, url: str, options: dict | None = None) -> str:
"""Generate cache key from URL + options."""
opt_str = json.dumps(options or {}, sort_keys=True)
raw = f"{url}:{opt_str}"
return hashlib.md5(raw.encode()).hexdigest()
def get(self, url: str, options: dict | None = None) -> dict | None:
"""Get cached response if fresh."""
key = self._key(url, options)
now = time.time()
# Check local cache
if key in self._cache:
entry = self._cache[key]
if entry["expires"] > now:
self._hits += 1
self._cache.move_to_end(key)
return entry["data"]
else:
del self._cache[key]
self._misses += 1
return None
def set(self, url: str, data: dict, options: dict | None = None, ttl: int = 300):
"""Cache a response with TTL in seconds."""
key = self._key(url, options)
entry = {"data": data, "expires": time.time() + ttl, "cached_at": time.time()}
# Evict oldest if at capacity
if len(self._cache) >= self.capacity:
self._cache.popitem(last=False)
self._cache[key] = entry
def stats(self) -> dict:
"""Get cache hit/miss statistics."""
total = self._hits + self._misses
return {
"size": len(self._cache),
"capacity": self.capacity,
"hits": self._hits,
"misses": self._misses,
"hit_rate": round(self._hits / total * 100, 1) if total > 0 else 0,
}
def invalidate(self, url: str):
"""Remove cached entry for a URL."""
keys_to_remove = [k for k, v in self._cache.items() if v["data"].get("url") == url]
for k in keys_to_remove:
del self._cache[k]
def clear(self):
"""Clear entire cache."""
self._cache.clear()
self._hits = 0
self._misses = 0