| 1 | """Per-path health for the Reddit stream, and the served-path detail. |
| 2 | |
| 3 | The Reddit stream reaches threads through several paths: Reddit's own site |
| 4 | search (``search``), the keyless web rungs (``brave``, ``ddg``, ``startpage``), |
| 5 | subreddit listings (``listing``), the Arctic Shift archive (``arctic``) and the |
| 6 | ScrapeCreators backfill (``sc``). Each path keeps a state for the run, and the |
| 7 | decisive ones persist across runs, the way the grok build audit persists its |
| 8 | pass and fail verdicts while an inconclusive result stays in memory: |
| 9 | |
| 10 | * ``blocked`` (a 403, a challenge page, or a logged-out marker on a search |
| 11 | page) persists for :data:`SKIP_TTL_SECONDS`. Later runs skip the path |
| 12 | without asking it until the skip expires, ``doctor`` clears it, or the |
| 13 | cookie fingerprint it was recorded under changes. |
| 14 | * ``ok`` persists too: it clears any skip and dates the last good answer. |
| 15 | * ``throttled`` (a 429 that survived its one retry) skips the path for the |
| 16 | rest of this run only and is never written. |
| 17 | * ``error`` and ``empty`` skip nothing. |
| 18 | |
| 19 | The cache is ``reddit-health.json`` in the last30days config dir, written by |
| 20 | atomic replace:: |
| 21 | |
| 22 | {"schema": 1, "paths": {"brave": {"state": "blocked", "at": "<iso>", |
| 23 | "reason": "HTTP 403", "cookie_fp": null}}} |
| 24 | |
| 25 | ``cookie_fp`` is the first 16 hex characters of a session cookie's sha256, |
| 26 | never the cookie. No keyless path has a cookie, so nothing writes it yet. |
| 27 | |
| 28 | :func:`served_detail` turns one lane call's path states and the items it |
| 29 | delivered into the ``source_status`` detail line, in a fixed vocabulary: |
| 30 | path tokens ``session``, ``host``, ``search``, ``web``, ``listing``, |
| 31 | ``arctic``, ``sc``; failure tokens ``session-expired``, ``blocked``, |
| 32 | ``throttled``, ``skipped-cached`` and ``down``. Example: |
| 33 | ``web+arctic served 14; search blocked``. Never raises. |
| 34 | """ |
| 35 | |
| 36 | from __future__ import annotations |
| 37 | |
| 38 | import contextlib |
| 39 | import json |
| 40 | import os |
| 41 | import stat |
| 42 | import threading |
| 43 | from datetime import datetime, timedelta, timezone |
| 44 | from pathlib import Path |
| 45 | from typing import Any, Iterable, Mapping, Optional |
| 46 | |
| 47 | from . import env, log, private_files |
| 48 | |
| 49 | SCHEMA = 1 |
| 50 | CACHE_FILENAME = "reddit-health.json" |
| 51 | SKIP_TTL_SECONDS = 6 * 3600 |
| 52 | |
| 53 | WEB_RUNGS = ("brave", "ddg", "startpage") |
| 54 | PATHS = ("search", *WEB_RUNGS, "arctic") |
| 55 | |
| 56 | OK = "ok" |
| 57 | EMPTY = "empty" |
| 58 | ERROR = "error" |
| 59 | THROTTLED = "throttled" |
| 60 | BLOCKED = "blocked" |
| 61 | SKIPPED_CACHED = "skipped-cached" |
| 62 | SESSION_EXPIRED = "session-expired" |
| 63 | DOWN = "down" |
| 64 | # States that persist (pass and fail); the rest stay in this run's memory. |
| 65 | _PERSISTED = frozenset({OK, BLOCKED}) |
| 66 | # States that take a path out of the rest of the run. |
| 67 | _RUN_DOWN = frozenset({BLOCKED, THROTTLED}) |
| 68 | # Failure tokens the detail line uses, per state. |
| 69 | _FAILURE_TOKEN = { |
| 70 | BLOCKED: BLOCKED, |
| 71 | THROTTLED: THROTTLED, |
| 72 | SKIPPED_CACHED: SKIPPED_CACHED, |
| 73 | SESSION_EXPIRED: SESSION_EXPIRED, |
| 74 | ERROR: DOWN, |
| 75 | DOWN: DOWN, |
| 76 | } |
| 77 | SERVED_ORDER = ("session", "host", "search", "web", "listing", "arctic", "sc") |
| 78 | _FAILURE_ORDER = ("session", "search", *WEB_RUNGS, "web", "listing", "arctic", "sc") |
| 79 | _DETAIL_LIMIT = 140 |
| 80 | |
| 81 | _LOCK = threading.Lock() |
| 82 | _RUN: dict[str, str] = {} |
| 83 | _seeded = False |
| 84 | |
| 85 | |
| 86 | def _log(msg: str) -> None: |
| 87 | log.source_log("RedditHealth", msg, tty_only=False) |
| 88 | |
| 89 | |
| 90 | def _now(now: Optional[datetime]) -> datetime: |
| 91 | return now or datetime.now(timezone.utc) |
| 92 | |
| 93 | |
| 94 | def cache_path() -> Optional[Path]: |
| 95 | return env.CONFIG_DIR / CACHE_FILENAME if env.CONFIG_DIR is not None else None |
| 96 | |
| 97 | |
| 98 | def _read() -> dict[str, dict[str, Any]]: |
| 99 | path = cache_path() |
| 100 | if path is None: |
| 101 | return {} |
| 102 | try: |
| 103 | data = json.loads(path.read_text(encoding="utf-8")) |
| 104 | except (OSError, ValueError): |
| 105 | return {} |
| 106 | if not isinstance(data, dict) or data.get("schema") != SCHEMA: |
| 107 | return {} |
| 108 | paths = data.get("paths") |
| 109 | if not isinstance(paths, dict): |
| 110 | return {} |
| 111 | return {k: v for k, v in paths.items() if isinstance(v, dict)} |
| 112 | |
| 113 | |
| 114 | @contextlib.contextmanager |
| 115 | def _file_lock(path: Optional[Path]): |
| 116 | """Serialize read-modify-write on ``reddit-health.json`` across processes. |
| 117 | |
| 118 | Yields ``True`` when the cross-process lock is held, or ``False`` when no |
| 119 | cache path is configured or locking failed (callers must skip disk writes |
| 120 | when ``False`` so concurrent writers cannot clobber each other). |
| 121 | """ |
| 122 | if path is None: |
| 123 | yield False |
| 124 | return |
| 125 | # Persistent sidecar lock file keeps writers on the same inode across atomic replaces. |
| 126 | lock_path = path.with_suffix(".lock") |
| 127 | fd: Optional[int] = None |
| 128 | locked = False |
| 129 | try: |
| 130 | path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 131 | flags = ( |
| 132 | os.O_CREAT |
| 133 | | os.O_RDWR |
| 134 | | getattr(os, "O_NOFOLLOW", 0) |
| 135 | | getattr(os, "O_CLOEXEC", 0) |
| 136 | ) |
| 137 | fd = os.open(lock_path, flags, 0o600) |
| 138 | if os.name == "posix": |
| 139 | st = os.fstat(fd) |
| 140 | if not stat.S_ISREG(st.st_mode): |
| 141 | raise OSError(f"Expected a regular lock file: {lock_path}") |
| 142 | import fcntl |
| 143 | |
| 144 | fcntl.flock(fd, fcntl.LOCK_EX) |
| 145 | locked = True |
| 146 | elif os.name == "nt": |
| 147 | import msvcrt |
| 148 | |
| 149 | os.lseek(fd, 0, os.SEEK_SET) |
| 150 | msvcrt.locking(fd, msvcrt.LK_LOCK, 1) |
| 151 | locked = True |
| 152 | except OSError as exc: |
| 153 | _log(f"could not lock Reddit path health: {exc}") |
| 154 | if fd is not None: |
| 155 | try: |
| 156 | os.close(fd) |
| 157 | except OSError: |
| 158 | pass |
| 159 | fd = None |
| 160 | try: |
| 161 | yield locked |
| 162 | finally: |
| 163 | if fd is not None: |
| 164 | try: |
| 165 | if locked: |
| 166 | if os.name == "posix": |
| 167 | import fcntl |
| 168 | |
| 169 | fcntl.flock(fd, fcntl.LOCK_UN) |
| 170 | elif os.name == "nt": |
| 171 | import msvcrt |
| 172 | |
| 173 | os.lseek(fd, 0, os.SEEK_SET) |
| 174 | msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) |
| 175 | except OSError: |
| 176 | pass |
| 177 | finally: |
| 178 | try: |
| 179 | os.close(fd) |
| 180 | except OSError: |
| 181 | pass |
| 182 | |
| 183 | |
| 184 | def _write(paths: Mapping[str, Any]) -> None: |
| 185 | path = cache_path() |
| 186 | if path is None: |
| 187 | return |
| 188 | payload = json.dumps({"schema": SCHEMA, "paths": dict(paths)}, indent=2, sort_keys=True) |
| 189 | try: |
| 190 | path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 191 | private_files.replace_private_text(path, payload) |
| 192 | except OSError as exc: |
| 193 | _log(f"could not save Reddit path health: {exc}") |
| 194 | |
| 195 | |
| 196 | def _parse_at(value: Any) -> Optional[datetime]: |
| 197 | try: |
| 198 | at = datetime.fromisoformat(str(value)) |
| 199 | except (TypeError, ValueError): |
| 200 | return None |
| 201 | return at if at.tzinfo else at.replace(tzinfo=timezone.utc) |
| 202 | |
| 203 | |
| 204 | def entries() -> dict[str, dict[str, Any]]: |
| 205 | """The persisted entry for each path that has one (doctor's view).""" |
| 206 | return _read() |
| 207 | |
| 208 | |
| 209 | def skip_until( |
| 210 | path: str, cookie_fp: Optional[str] = None, now: Optional[datetime] = None, |
| 211 | ) -> Optional[datetime]: |
| 212 | """When a persisted skip on ``path`` lifts, or None when it is not skipped. |
| 213 | |
| 214 | A skip recorded under another cookie fingerprint does not apply. |
| 215 | """ |
| 216 | entry = _read().get(path) |
| 217 | if not entry or entry.get("state") != BLOCKED: |
| 218 | return None |
| 219 | if (entry.get("cookie_fp") or None) != (cookie_fp or None): |
| 220 | return None |
| 221 | at = _parse_at(entry.get("at")) |
| 222 | if at is None: |
| 223 | return None |
| 224 | until = at + timedelta(seconds=SKIP_TTL_SECONDS) |
| 225 | return until if until > _now(now) else None |
| 226 | |
| 227 | |
| 228 | def run_state(path: str) -> Optional[str]: |
| 229 | """This run's recorded state for ``path``, if any.""" |
| 230 | with _LOCK: |
| 231 | return _RUN.get(path) |
| 232 | |
| 233 | |
| 234 | def skip_reason( |
| 235 | path: str, cookie_fp: Optional[str] = None, now: Optional[datetime] = None, |
| 236 | ) -> Optional[str]: |
| 237 | """Why ``path`` should not be asked this run: ``blocked`` or ``throttled`` |
| 238 | (it failed earlier this run), ``skipped-cached`` (a persisted skip), or |
| 239 | None when it may run.""" |
| 240 | state = run_state(path) |
| 241 | if state in _RUN_DOWN or state == SKIPPED_CACHED: |
| 242 | return state |
| 243 | if skip_until(path, cookie_fp, now) is not None: |
| 244 | with _LOCK: |
| 245 | _RUN.setdefault(path, SKIPPED_CACHED) |
| 246 | return SKIPPED_CACHED |
| 247 | return None |
| 248 | |
| 249 | |
| 250 | def record( |
| 251 | path: str, |
| 252 | state: str, |
| 253 | reason: str = "", |
| 254 | *, |
| 255 | cookie_fp: Optional[str] = None, |
| 256 | now: Optional[datetime] = None, |
| 257 | ) -> None: |
| 258 | """Note ``path``'s answer this run; ``ok`` and ``blocked`` also persist.""" |
| 259 | if not path or not state: |
| 260 | return |
| 261 | with _LOCK: |
| 262 | current = _RUN.get(path) |
| 263 | # A path already down this run stays down for it; never let a stale |
| 264 | # in-flight OK clobber a persisted BLOCKED cooldown on disk. |
| 265 | if current in _RUN_DOWN and state == OK: |
| 266 | return |
| 267 | if current == BLOCKED and state != BLOCKED: |
| 268 | return |
| 269 | if current not in _RUN_DOWN or state == BLOCKED: |
| 270 | _RUN[path] = state |
| 271 | if state not in _PERSISTED: |
| 272 | return |
| 273 | with _file_lock(cache_path()) as locked: |
| 274 | if not locked: |
| 275 | return |
| 276 | paths = _read() |
| 277 | previous = paths.get(path) or {} |
| 278 | if state == OK and previous.get("state") == OK: |
| 279 | # Re-dating a good answer on every run is churn; one write a TTL is plenty. |
| 280 | at = _parse_at(previous.get("at")) |
| 281 | if at is not None and _now(now) - at < timedelta(seconds=SKIP_TTL_SECONDS): |
| 282 | return |
| 283 | paths[path] = { |
| 284 | "state": state, |
| 285 | "at": _now(now).isoformat(), |
| 286 | "reason": str(reason or "")[:120], |
| 287 | "cookie_fp": cookie_fp or None, |
| 288 | } |
| 289 | _write(paths) |
| 290 | if state == BLOCKED: |
| 291 | _log(f"{path} refused this network ({reason or 'blocked'}); skipping it for " |
| 292 | f"{SKIP_TTL_SECONDS // 3600} h") |
| 293 | |
| 294 | |
| 295 | def cached_web_skips(now: Optional[datetime] = None) -> dict[str, str]: |
| 296 | """The web rungs a persisted skip takes out of this run.""" |
| 297 | return {rung: BLOCKED for rung in WEB_RUNGS if skip_until(rung, now=now) is not None} |
| 298 | |
| 299 | |
| 300 | def seed_web_rungs(now: Optional[datetime] = None) -> dict[str, str]: |
| 301 | """Once per run, start the keyless web ladder with the rungs a persisted |
| 302 | skip takes out. Returns the rungs seeded this call.""" |
| 303 | global _seeded |
| 304 | with _LOCK: |
| 305 | if _seeded: |
| 306 | return {} |
| 307 | _seeded = True |
| 308 | skips = cached_web_skips(now) |
| 309 | if skips: |
| 310 | from . import web_search_keyless |
| 311 | |
| 312 | web_search_keyless.seed_rung_health(skips) |
| 313 | with _LOCK: |
| 314 | for rung in skips: |
| 315 | _RUN.setdefault(rung, SKIPPED_CACHED) |
| 316 | _log(f"skipping {', '.join(skips)} this run (blocked within the last " |
| 317 | f"{SKIP_TTL_SECONDS // 3600} h)") |
| 318 | return skips |
| 319 | |
| 320 | |
| 321 | def clear() -> list[str]: |
| 322 | """Drop every persisted skip and this run's states (doctor). Returns the |
| 323 | paths whose skip was still in force.""" |
| 324 | global _seeded |
| 325 | cleared: list[str] = [] |
| 326 | with _LOCK: |
| 327 | with _file_lock(cache_path()) as locked: |
| 328 | if locked: |
| 329 | paths = _read() |
| 330 | cleared = [p for p in paths if paths[p].get("state") == BLOCKED] |
| 331 | if paths: |
| 332 | _write({}) |
| 333 | _RUN.clear() |
| 334 | _seeded = False |
| 335 | return cleared |
| 336 | |
| 337 | |
| 338 | def reset_run_state() -> None: |
| 339 | """Forget this run's path states (call between runs in one process).""" |
| 340 | global _seeded |
| 341 | with _LOCK: |
| 342 | _RUN.clear() |
| 343 | _seeded = False |
| 344 | |
| 345 | |
| 346 | # --- served-path detail ----------------------------------------------------- |
| 347 | |
| 348 | def served_paths(items: Iterable[Mapping[str, Any]]) -> set[str]: |
| 349 | """The paths that delivered ``items``: their discovery provenance, plus |
| 350 | ``arctic`` for a thread whose score or comments came from the archive.""" |
| 351 | served: set[str] = set() |
| 352 | for item in items or []: |
| 353 | if not isinstance(item, Mapping): |
| 354 | continue |
| 355 | served.update(p for p in item.get("provenance") or [] if p in SERVED_ORDER) |
| 356 | if str(item.get("engagement_source") or "").startswith("arctic") or "arctic" in str( |
| 357 | item.get("comments_source") or "" |
| 358 | ): |
| 359 | served.add("arctic") |
| 360 | return served |
| 361 | |
| 362 | |
| 363 | def failures(paths: Mapping[str, str]) -> list[str]: |
| 364 | """``"<path> <token>"`` for every failed path, in a fixed order.""" |
| 365 | out = [] |
| 366 | for path in _FAILURE_ORDER: |
| 367 | token = _FAILURE_TOKEN.get(paths.get(path) or "") |
| 368 | if token: |
| 369 | out.append(f"{path} {token}") |
| 370 | return out |
| 371 | |
| 372 | |
| 373 | def every_path_failed(paths: Mapping[str, str]) -> bool: |
| 374 | """True when every path this lane asked failed (none answered, even empty).""" |
| 375 | asked = {p: s for p, s in paths.items() if p != "web" and s} |
| 376 | if not asked: |
| 377 | return False |
| 378 | return all(s in _FAILURE_TOKEN for s in asked.values()) |
| 379 | |
| 380 | |
| 381 | def failure_outcome(paths: Mapping[str, str]) -> tuple[str, str]: |
| 382 | """The source outcome when every path failed: ``(state, detail)``. |
| 383 | |
| 384 | A transport failure, never no-results: ``rate-limited`` when every |
| 385 | failed path was throttled (the run can only wait), else ``unreachable``. |
| 386 | """ |
| 387 | from . import health |
| 388 | |
| 389 | states = {s for p, s in paths.items() if p != "web" and s in _FAILURE_TOKEN} |
| 390 | detail = served_detail([], paths) |
| 391 | if states == {THROTTLED}: |
| 392 | return health.RATE_LIMITED, f"{detail}; rate-limited (HTTP 429)" |
| 393 | return health.UNREACHABLE, detail |
| 394 | |
| 395 | |
| 396 | def served_detail( |
| 397 | items: Iterable[Mapping[str, Any]], |
| 398 | paths: Optional[Mapping[str, str]] = None, |
| 399 | *, |
| 400 | extra: Iterable[str] = (), |
| 401 | count: Optional[int] = None, |
| 402 | ) -> str: |
| 403 | """The detail line for one Reddit lane call (see the module docstring). |
| 404 | |
| 405 | ``extra`` names paths that served beyond the items' own provenance (such as |
| 406 | ``sc`` after a backfill); ``count`` overrides the item count. |
| 407 | """ |
| 408 | items = [i for i in items or [] if isinstance(i, Mapping)] |
| 409 | served = served_paths(items) | set(extra) |
| 410 | total = len(items) if count is None else count |
| 411 | parts = [] |
| 412 | if total: |
| 413 | named = "+".join(p for p in SERVED_ORDER if p in served) or "reddit" |
| 414 | parts.append(f"{named} served {total}") |
| 415 | else: |
| 416 | parts.append("no path served") |
| 417 | detail = "; ".join([*parts, *failures(paths or {})]) |
| 418 | if len(detail) > _DETAIL_LIMIT: |
| 419 | detail = detail[:_DETAIL_LIMIT - 3].rstrip("; ") + "..." |
| 420 | return detail |
| 421 | |
| 422 | |
| 423 | def parse_detail(detail: Optional[str]) -> dict[str, str]: |
| 424 | """Each path's last-run outcome read back from a detail line: ``served`` |
| 425 | or a failure token. Doctor reads ``last-report.json`` through this.""" |
| 426 | out: dict[str, str] = {} |
| 427 | for part in str(detail or "").split(";"): |
| 428 | words = part.strip().split() |
| 429 | if len(words) >= 3 and words[1] == "served": |
| 430 | for path in words[0].split("+"): |
| 431 | if path in SERVED_ORDER: |
| 432 | out.setdefault(path, "served") |
| 433 | elif len(words) == 2 and words[1] in _FAILURE_TOKEN.values(): |
| 434 | out.setdefault(words[0], words[1]) |
| 435 | return out |
| 436 | |
| 437 | |
| 438 | # --- doctor's live check ---------------------------------------------------- |
| 439 | # |
| 440 | # The keyless floor's two halves, probed the way the lane asks them: Brave's |
| 441 | # HTML results for a month-filtered site:reddit.com query (discovery), and an |
| 442 | # Arctic Shift /posts/ids lookup (hydration). Neither reads a cookie. |
| 443 | |
| 444 | PROBE_THREAD_ID = "1gzqsxk" |
| 445 | |
| 446 | |
| 447 | def brave_probe_url() -> str: |
| 448 | from urllib.parse import urlencode |
| 449 | |
| 450 | from . import web_search_keyless |
| 451 | |
| 452 | query = urlencode({"q": "site:reddit.com reddit", "source": "web", "tf": "pm"}) |
| 453 | return f"{web_search_keyless._BRAVE_HTML_URL}?{query}" |
| 454 | |
| 455 | |
| 456 | def arctic_probe_url() -> str: |
| 457 | from . import reddit_arctic |
| 458 | |
| 459 | return f"{reddit_arctic.API}?ids={PROBE_THREAD_ID}" |
| 460 | |
| 461 | |
| 462 | def arctic_listing_probe_url() -> str: |
| 463 | """Probe the same subreddit listing endpoint used by the fallback lane.""" |
| 464 | from . import reddit_arctic |
| 465 | |
| 466 | return f"{reddit_arctic.SEARCH_API}?subreddit=python&limit=1&sort=desc" |
| 467 | |
| 468 | |
| 469 | def brave_probe_body(text: str) -> Optional[str]: |
| 470 | """None when the page is Brave results the lane can parse, else why not.""" |
| 471 | from . import web_search_keyless |
| 472 | |
| 473 | if web_search_keyless.parse_brave(text or "", 3): |
| 474 | return None |
| 475 | return "no Brave results on the page" |
| 476 | |
| 477 | |
| 478 | def arctic_probe_body(text: str) -> Optional[str]: |
| 479 | """None when the body is an Arctic Shift /posts/ids answer, else why not.""" |
| 480 | try: |
| 481 | data = json.loads(text or "") |
| 482 | except ValueError: |
| 483 | return "not an Arctic Shift JSON answer" |
| 484 | if isinstance(data, dict) and isinstance(data.get("data"), list): |
| 485 | return None |
| 486 | return "not an Arctic Shift /posts/ids answer" |
| 487 |