Live reads go through an operator proxy pool (round-robin over the newest 100 entries, cooling on connect failures, no direct fallback); stored clearances are replayed only on the exit that earned them. Identity, clearance, solver and Turnstile rungs escalate automatically. fetch_pages reads up to 12 URLs four at a time with per-item isolation. report/reports/reports_update keep a durable queue of unreadable pages for the operator. Ships a pinned multi-stage image (non-root 10001, data in /data), an ordered CI with static gates, tests on 3.12 and 3.13 at 85% coverage, an offline image smoke, and sha/latest publishing gated on main.
144 lines
4.7 KiB
Python
144 lines
4.7 KiB
Python
"""Durable, host-deduplicated reports about pages that could not be read.
|
|
|
|
The model writes a report when a rung is exhausted and the content was needed;
|
|
the operator reads them newest-first and closes them one by one. Entries live in
|
|
an append-only-then-rewritten JSONL file with one row per open host+category, so
|
|
repeating a failure increments ``hits`` rather than piling up duplicates.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
from dataclasses import asdict, dataclass, field
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
from secrets import token_hex
|
|
from threading import Lock
|
|
from time import time
|
|
|
|
_PATH = Path(os.environ.get("MCP_REPORT_FILE", Path(__file__).with_name(".reports.jsonl")))
|
|
_MAX_ROWS = 2000
|
|
_lock = Lock()
|
|
|
|
CATEGORIES = {
|
|
"cloudflare_challenge": "Interstitial, `cf-mitigated`, or a solver that kept failing.",
|
|
"turnstile": "A Turnstile widget gated the content or the token was rejected.",
|
|
"js_required": "The served HTML is a shell; the text appears only after script runs.",
|
|
"login_paywall": "Login, cookie wall, or subscription gate.",
|
|
"robots_denied": "The site blocks datacenter exits or the page regardless of identity.",
|
|
"http_error": "A 4xx/5xx the ladder could not clear.",
|
|
"rate_limited": "429 that outlived the deadline.",
|
|
"content_missing": "The page loaded but the needed text is absent from it.",
|
|
"selector_no_match": "A selector or heading from the outline returned nothing useful.",
|
|
"other": "Anything else; say which in the note.",
|
|
}
|
|
|
|
STATUSES = ("open", "closed", "ignored")
|
|
|
|
|
|
@dataclass
|
|
class Report:
|
|
host: str
|
|
category: str
|
|
needed: str
|
|
url: str = ""
|
|
attempts: list[str] = field(default_factory=list)
|
|
note: str = ""
|
|
snapshot: str = ""
|
|
route: str = ""
|
|
proxy: str = ""
|
|
user_agent: str = ""
|
|
error: str = ""
|
|
status: str = "open"
|
|
hits: int = 1
|
|
id: str = ""
|
|
first_seen: str = ""
|
|
last_seen: str = ""
|
|
|
|
def key(self) -> str:
|
|
return f"{self.host}|{self.category}"
|
|
|
|
|
|
def _now() -> str:
|
|
return datetime.now(UTC).isoformat(timespec="seconds")
|
|
|
|
|
|
def _load() -> list[Report]:
|
|
try:
|
|
lines = _PATH.read_text("utf-8").splitlines()
|
|
except OSError:
|
|
return []
|
|
rows: list[Report] = []
|
|
for line in lines:
|
|
if not line.strip():
|
|
continue
|
|
try:
|
|
raw = json.loads(line)
|
|
rows.append(Report(**{name: raw[name] for name in Report.__dataclass_fields__ if name in raw}))
|
|
except (ValueError, TypeError):
|
|
continue
|
|
return rows
|
|
|
|
|
|
def _save(rows: list[Report]) -> None:
|
|
temporary = _PATH.with_suffix(".tmp")
|
|
text = "\n".join(json.dumps(asdict(row), ensure_ascii=False) for row in rows[-_MAX_ROWS:])
|
|
temporary.write_text(text + ("\n" if text else ""), "utf-8")
|
|
os.replace(temporary, _PATH)
|
|
|
|
|
|
def add(entry: Report) -> Report:
|
|
"""Insert, or bump the open row for the same host and category."""
|
|
entry.host = entry.host.lower().removeprefix("www.")
|
|
entry.category = entry.category if entry.category in CATEGORIES else "other"
|
|
with _lock:
|
|
rows = _load()
|
|
stamp = _now()
|
|
for row in rows:
|
|
if row.status == "open" and row.key() == entry.key():
|
|
row.hits += 1
|
|
row.last_seen = stamp
|
|
row.attempts = sorted({*row.attempts, *entry.attempts})
|
|
row.error = entry.error or row.error
|
|
row.snapshot = entry.snapshot or row.snapshot
|
|
if entry.note:
|
|
row.note = f"{row.note}\n{entry.note}".strip()
|
|
_save(rows)
|
|
return row
|
|
entry.id = f"{int(time())}-{token_hex(3)}"
|
|
entry.first_seen = entry.last_seen = stamp
|
|
rows.append(entry)
|
|
_save(rows)
|
|
return entry
|
|
|
|
|
|
def listing(status: str = "open", limit: int = 40) -> list[Report]:
|
|
with _lock:
|
|
rows = [row for row in _load() if status == "all" or row.status == status]
|
|
rows.sort(key=lambda row: (-row.hits, row.last_seen))
|
|
return rows[:limit]
|
|
|
|
|
|
def update(entry_id: str, status: str, note: str = "") -> Report:
|
|
if status not in STATUSES:
|
|
raise ValueError(f"status must be one of {', '.join(STATUSES)}")
|
|
with _lock:
|
|
rows = _load()
|
|
for row in rows:
|
|
if row.id == entry_id:
|
|
row.status = status
|
|
if note:
|
|
row.note = f"{row.note}\n{note}".strip()
|
|
row.last_seen = _now()
|
|
_save(rows)
|
|
return row
|
|
raise ValueError(f"No report with id {entry_id!r}")
|
|
|
|
|
|
def counts() -> dict[str, int]:
|
|
with _lock:
|
|
rows = _load()
|
|
result = {status: 0 for status in STATUSES}
|
|
for row in rows:
|
|
result[row.status] = result.get(row.status, 0) + 1
|
|
return result
|