| 1 | """Host-found Reddit threads: the ``--reddit-threads`` lane. |
| 2 | |
| 3 | A host with its own web search collects ``reddit.com/r/<sub>/comments/<id>`` |
| 4 | URLs during its pre-research search and writes them to a ``.json`` file. The |
| 5 | engine reads only the thread identity from each entry and rehydrates every |
| 6 | thread itself (session thread JSON when a consented session is open, else |
| 7 | Arctic Shift), so a title, score or text the host wrote is never used. |
| 8 | |
| 9 | Shape (``schema: "last30days-reddit-threads/1"``):: |
| 10 | |
| 11 | { |
| 12 | "schema": "last30days-reddit-threads/1", |
| 13 | "topic": "<the run topic>", |
| 14 | "threads": [{"url": "https://www.reddit.com/r/<sub>/comments/<id>/..."}, {"id": "<base36>"}] |
| 15 | } |
| 16 | |
| 17 | Every other field, at the top level or in an entry, is ignored; an entry with |
| 18 | extra fields is counted once as ``extra-fields``. The reader is strict at the |
| 19 | envelope level (an unreadable, oversized, malformed or off-topic file fails |
| 20 | closed with an exit-2 contract error) and lenient per entry (a bad entry is |
| 21 | dropped with a named counter). At most ``MAX_THREADS`` entries are used. |
| 22 | |
| 23 | Unlike the single-serve X envelope, the refs serve the whole run: the first |
| 24 | Reddit stream hydrates them once, the window and the topic bar drop what does |
| 25 | not belong, and each kept thread then goes to the planner subquery whose terms |
| 26 | its hydrated title matches best. |
| 27 | |
| 28 | Security contract: contract errors name the path and the field, never a |
| 29 | field value, and nothing the host wrote reaches an outcome detail. |
| 30 | """ |
| 31 | |
| 32 | from __future__ import annotations |
| 33 | |
| 34 | import contextlib |
| 35 | import contextvars |
| 36 | import copy |
| 37 | import hashlib |
| 38 | import json |
| 39 | import os |
| 40 | import re |
| 41 | import stat |
| 42 | import sys |
| 43 | import threading |
| 44 | from dataclasses import dataclass, field |
| 45 | from pathlib import Path |
| 46 | from typing import Any, Callable, Iterable, Optional |
| 47 | from urllib.parse import urlsplit |
| 48 | |
| 49 | try: |
| 50 | import fcntl |
| 51 | except ImportError: |
| 52 | fcntl = None # type: ignore[assignment] |
| 53 | |
| 54 | from . import env, log, reddit_discover, reddit_hydrate |
| 55 | from .reddit_refs import UNKNOWN, ThreadRef, canonical_thread |
| 56 | |
| 57 | SCHEMA = "last30days-reddit-threads/1" |
| 58 | STDIN = "-" |
| 59 | |
| 60 | # Input bounds. Named so the runbook and the receipts can quote them. |
| 61 | MAX_BYTES = 1024 * 1024 |
| 62 | MAX_ENTRIES = 1000 |
| 63 | MAX_THREADS = 50 |
| 64 | MAX_FIELD_CHARS = 2048 |
| 65 | |
| 66 | ENTRY_FIELDS = frozenset({"url", "id"}) |
| 67 | # Counters, in receipt order. The first group is judged when the file is |
| 68 | # read; the last three after the engine hydrated the threads. |
| 69 | COUNTERS = ( |
| 70 | "non-reddit", |
| 71 | "redirect", |
| 72 | "share-link", |
| 73 | "not-a-thread", |
| 74 | "invalid", |
| 75 | "duplicate", |
| 76 | "truncated", |
| 77 | "extra-fields", |
| 78 | "unhydrated", |
| 79 | "out-of-window", |
| 80 | "off-topic", |
| 81 | ) |
| 82 | |
| 83 | _REMEDY = ( |
| 84 | "Rewrite the file to the last30days-reddit-threads/1 shape, or re-run " |
| 85 | "without --reddit-threads." |
| 86 | ) |
| 87 | |
| 88 | # Directories the envelope must never be read from: the engine's own config |
| 89 | # dir (which holds .env) and the usual credential stores. Checked after |
| 90 | # realpath so a symlink cannot reach in. |
| 91 | _CREDENTIAL_STORES = ( |
| 92 | "~/.config/last30days", |
| 93 | "~/.config/gh", |
| 94 | "~/.aws", |
| 95 | "~/.ssh", |
| 96 | "~/.netrc", |
| 97 | "~/.xurl", |
| 98 | "~/.grok", |
| 99 | ) |
| 100 | |
| 101 | _REDDIT_SUFFIXES = ("reddit.com", "redd.it") |
| 102 | _REDIRECT_HOST = re.compile( |
| 103 | r"(^|\.)(google\.[a-z.]+|vertexaisearch\.cloud\.google\.com|bing\.com|" |
| 104 | r"duckduckgo\.com|search\.brave\.com|t\.co|out\.reddit\.com)$" |
| 105 | ) |
| 106 | _CONTROL_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]") |
| 107 | _TOPIC_STRIP = "\"'“”‘’ \t" |
| 108 | |
| 109 | SessionHydratorFactory = Callable[[], Optional[reddit_hydrate.SessionHydrator]] |
| 110 | |
| 111 | |
| 112 | class EnvelopeContractError(Exception): |
| 113 | """The envelope failed its contract. The CLI maps this to exit code 2. |
| 114 | The message names the path and the offending field only.""" |
| 115 | |
| 116 | def __init__(self, message: str) -> None: |
| 117 | super().__init__(message) |
| 118 | self.message = message |
| 119 | |
| 120 | |
| 121 | @dataclass |
| 122 | class Served: |
| 123 | """One subquery's share of the host threads. |
| 124 | |
| 125 | ``arctic_state`` and ``note`` are set only on the call that hydrated the |
| 126 | refs, so the lane records the archive's health and its detail note once. |
| 127 | """ |
| 128 | |
| 129 | items: list[dict] |
| 130 | arctic_state: str = "" |
| 131 | note: str = "" |
| 132 | |
| 133 | |
| 134 | @dataclass |
| 135 | class Envelope: |
| 136 | """A validated ``--reddit-threads`` file, ready to serve the run.""" |
| 137 | |
| 138 | path: str |
| 139 | sha256: str |
| 140 | topic: str |
| 141 | refs: list[ThreadRef] |
| 142 | counters: dict[str, int] |
| 143 | total: int |
| 144 | notes: list[str] = field(default_factory=list) |
| 145 | _lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False) |
| 146 | _subqueries: list[tuple[str, tuple[str, ...]]] = field(default_factory=list, repr=False) |
| 147 | _kept: Optional[list[dict]] = field(default=None, repr=False) |
| 148 | _routes: dict[str, list[dict]] = field(default_factory=dict, repr=False) |
| 149 | _served: set[str] = field(default_factory=set, repr=False) |
| 150 | |
| 151 | @property |
| 152 | def accepted(self) -> int: |
| 153 | return len(self.refs) |
| 154 | |
| 155 | def bind_subqueries(self, subqueries: Iterable[tuple[str, Iterable[str]]]) -> None: |
| 156 | """Name the planner subqueries the Reddit stream runs for, with the |
| 157 | query strings (search and ranking) each one is judged by.""" |
| 158 | with self._lock: |
| 159 | self._subqueries = [ |
| 160 | (str(label), tuple(q for q in queries if q)) for label, queries in subqueries |
| 161 | ] |
| 162 | |
| 163 | def serve( |
| 164 | self, |
| 165 | label: str, |
| 166 | *, |
| 167 | depth: str = "default", |
| 168 | from_date: Optional[str] = None, |
| 169 | to_date: Optional[str] = None, |
| 170 | subreddits: Optional[list[str]] = None, |
| 171 | dedicated: Optional[list[str]] = None, |
| 172 | session_hydrator: SessionHydratorFactory = lambda: None, |
| 173 | deadline: Optional[float] = None, |
| 174 | ) -> Served: |
| 175 | """The host threads routed to subquery ``label``. |
| 176 | |
| 177 | The first call hydrates every ref (through the session when the |
| 178 | caller passes one, else Arctic Shift), drops threads outside the |
| 179 | window or off the topic bar, and routes the rest (see ``_route``). |
| 180 | Each label is served once; an unbound run serves everything to the |
| 181 | first caller. |
| 182 | Never raises. |
| 183 | """ |
| 184 | with self._lock: |
| 185 | served = Served(items=[]) |
| 186 | if self._kept is None: |
| 187 | served.arctic_state, served.note = self._hydrate( |
| 188 | depth=depth, from_date=from_date, to_date=to_date, |
| 189 | subreddits=subreddits, dedicated=dedicated, |
| 190 | session_hydrator=session_hydrator, deadline=deadline, |
| 191 | ) |
| 192 | self._route() |
| 193 | key = label if self._subqueries else "" |
| 194 | if key in self._served: |
| 195 | return served |
| 196 | self._served.add(key) |
| 197 | served.items = copy.deepcopy(self._routes.get(key) or []) |
| 198 | return served |
| 199 | |
| 200 | def receipt(self) -> str: |
| 201 | dropped = ", ".join( |
| 202 | f"{name} {count}" for name, count in self.counters.items() if count |
| 203 | ) or "none" |
| 204 | line = f"host Reddit threads: accepted {self.accepted} of {self.total} (dropped: {dropped})" |
| 205 | if self._kept is not None: |
| 206 | line += f"; kept {len(self._kept)} after hydration" |
| 207 | if self.notes: |
| 208 | line += "; notes: " + "; ".join(self.notes) |
| 209 | return line |
| 210 | |
| 211 | # -- internals -------------------------------------------------------- |
| 212 | |
| 213 | def _hydrate( |
| 214 | self, |
| 215 | *, |
| 216 | depth: str, |
| 217 | from_date: Optional[str], |
| 218 | to_date: Optional[str], |
| 219 | subreddits: Optional[list[str]], |
| 220 | dedicated: Optional[list[str]], |
| 221 | session_hydrator: SessionHydratorFactory, |
| 222 | deadline: Optional[float], |
| 223 | ) -> tuple[str, str]: |
| 224 | self._kept = [] |
| 225 | if not self.refs: |
| 226 | return "", "" |
| 227 | try: |
| 228 | hydrator = session_hydrator() |
| 229 | extra = {"session_hydrator": hydrator} if hydrator is not None else {} |
| 230 | # No window and no comments yet: the window is judged here so the |
| 231 | # out-of-window count is honest, and comment slots go only to |
| 232 | # threads that stay. |
| 233 | hydrated = reddit_hydrate.hydrate( |
| 234 | self.refs, topic=self.topic, depth=depth, comments=False, |
| 235 | deadline=deadline, **extra, |
| 236 | ) |
| 237 | except Exception as exc: # the host lane must never break the Reddit stream |
| 238 | _log(f"host thread hydration failed: {type(exc).__name__}") |
| 239 | return "", "" |
| 240 | in_window: list[dict] = [] |
| 241 | for item in hydrated.items: |
| 242 | if item.get("engagement_source") == UNKNOWN and not item.get("title"): |
| 243 | self.counters["unhydrated"] += 1 |
| 244 | elif not reddit_hydrate.in_window(item, from_date, to_date): |
| 245 | self.counters["out-of-window"] += 1 |
| 246 | else: |
| 247 | in_window.append(item) |
| 248 | bar = reddit_discover.apply_bar( |
| 249 | self.topic, in_window, subreddits=subreddits, dedicated=dedicated, |
| 250 | ) |
| 251 | self.counters["off-topic"] += len(bar.dropped) |
| 252 | kept = bar.kept |
| 253 | arctic_state = hydrated.arctic_state |
| 254 | if kept and arctic_state not in ("down", "throttled"): |
| 255 | try: |
| 256 | reddit_hydrate.attach_comments(kept, depth, deadline) |
| 257 | except Exception as exc: # comments are a bonus, never a failure |
| 258 | _log(f"host thread comments failed: {type(exc).__name__}") |
| 259 | for item in kept: |
| 260 | item["topic_bar"] = True |
| 261 | self._kept = kept |
| 262 | _log(self.receipt()) |
| 263 | note = f"host kept {len(kept)} of {self.total}" if self.total else "" |
| 264 | return arctic_state, note |
| 265 | |
| 266 | def _route(self) -> None: |
| 267 | """Send each kept thread to the subquery whose terms its title matches best. |
| 268 | |
| 269 | A subquery's match is how many of its informative query terms the |
| 270 | title contains, so a thread about one angle reaches that angle's |
| 271 | stream rather than only the broad primary one. A tie, or a title |
| 272 | that matches no terms, goes to the earliest such subquery, so every |
| 273 | kept thread is served exactly once. |
| 274 | """ |
| 275 | from .relevance import PreparedQuery, tokenize |
| 276 | |
| 277 | self._routes = {} |
| 278 | kept = self._kept or [] |
| 279 | if not self._subqueries: |
| 280 | self._routes[""] = list(kept) |
| 281 | return |
| 282 | prepared = [ |
| 283 | [PreparedQuery(q).informative_q_tokens for q in queries] |
| 284 | for _, queries in self._subqueries |
| 285 | ] |
| 286 | for item in kept: |
| 287 | title_tokens = tokenize(str(item.get("title") or "")) |
| 288 | scores = [ |
| 289 | max((len(terms & title_tokens) for terms in terms_list), default=0) |
| 290 | for terms_list in prepared |
| 291 | ] |
| 292 | best = scores.index(max(scores)) |
| 293 | self._routes.setdefault(self._subqueries[best][0], []).append(item) |
| 294 | |
| 295 | |
| 296 | # --------------------------------------------------------------------------- |
| 297 | # Lane context: the pipeline opens it around one Reddit stream call |
| 298 | # --------------------------------------------------------------------------- |
| 299 | |
| 300 | _current: contextvars.ContextVar[Optional[tuple[Envelope, str]]] = contextvars.ContextVar( |
| 301 | "last30days_reddit_envelope", default=None, |
| 302 | ) |
| 303 | |
| 304 | |
| 305 | @contextlib.contextmanager |
| 306 | def lane(envelope: Optional[Envelope], label: str = ""): |
| 307 | """Make ``envelope`` the Reddit lane's host threads for subquery ``label``.""" |
| 308 | token = _current.set((envelope, label) if envelope is not None else None) |
| 309 | try: |
| 310 | yield envelope |
| 311 | finally: |
| 312 | _current.reset(token) |
| 313 | |
| 314 | |
| 315 | def current() -> Optional[tuple[Envelope, str]]: |
| 316 | return _current.get() |
| 317 | |
| 318 | |
| 319 | # --------------------------------------------------------------------------- |
| 320 | # Reader |
| 321 | # --------------------------------------------------------------------------- |
| 322 | |
| 323 | |
| 324 | def _log(msg: str) -> None: |
| 325 | log.source_log("reddit", msg, tty_only=False) |
| 326 | |
| 327 | |
| 328 | def _stat(path: Path) -> os.stat_result: |
| 329 | """Seam for tests: the size and type check runs before any read.""" |
| 330 | return os.lstat(path) |
| 331 | |
| 332 | |
| 333 | def _raw_protected_roots() -> list[Path]: |
| 334 | roots: list[Path] = [] |
| 335 | for candidate in (env.CONFIG_DIR, getattr(env, "CONFIG_FILE", None)): |
| 336 | if candidate: |
| 337 | roots.append(Path(candidate)) |
| 338 | for store in _CREDENTIAL_STORES: |
| 339 | roots.append(Path(store).expanduser()) |
| 340 | return roots |
| 341 | |
| 342 | |
| 343 | def _protected_roots() -> list[Path]: |
| 344 | return [Path(os.path.realpath(root)) for root in _raw_protected_roots()] |
| 345 | |
| 346 | |
| 347 | _DARWIN_F_GETPATH = 50 |
| 348 | _DARWIN_MAXPATHLEN = 1024 |
| 349 | |
| 350 | |
| 351 | def _norm_parts(path: Path) -> tuple[str, ...]: |
| 352 | if sys.platform == "darwin": |
| 353 | return tuple(part.casefold() for part in path.parts) |
| 354 | if sys.platform == "win32": |
| 355 | return tuple(os.path.normcase(part) for part in path.parts) |
| 356 | return path.parts |
| 357 | |
| 358 | |
| 359 | def _is_under(path: Path, roots: Iterable[Path]) -> bool: |
| 360 | p_parts = _norm_parts(path) |
| 361 | for root in roots: |
| 362 | r_parts = _norm_parts(root) |
| 363 | if r_parts and len(p_parts) >= len(r_parts) and p_parts[:len(r_parts)] == r_parts: |
| 364 | return True |
| 365 | return False |
| 366 | |
| 367 | |
| 368 | def _inside_protected(real: Path) -> bool: |
| 369 | return _is_under(real, _protected_roots()) |
| 370 | |
| 371 | |
| 372 | def _win32_fd_real_path(fd: int) -> Optional[Path]: |
| 373 | """Canonical path of an open Windows file descriptor via ``GetFinalPathNameByHandleW``.""" |
| 374 | try: |
| 375 | import ctypes |
| 376 | import msvcrt |
| 377 | |
| 378 | handle = msvcrt.get_osfhandle(fd) |
| 379 | kernel32 = ctypes.windll.kernel32 |
| 380 | get_path = kernel32.GetFinalPathNameByHandleW |
| 381 | get_path.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint32, ctypes.c_uint32] |
| 382 | get_path.restype = ctypes.c_uint32 |
| 383 | needed = get_path(handle, None, 0, 0) |
| 384 | if not needed: |
| 385 | return None |
| 386 | buf = ctypes.create_unicode_buffer(needed + 1) |
| 387 | written = get_path(handle, buf, len(buf), 0) |
| 388 | if not written or written >= len(buf): |
| 389 | return None |
| 390 | raw = buf.value |
| 391 | except (AttributeError, ImportError, OSError, ValueError): |
| 392 | return None |
| 393 | if raw.startswith("\\\\?\\UNC\\"): |
| 394 | raw = "\\\\" + raw[8:] |
| 395 | elif raw.startswith("\\\\?\\"): |
| 396 | raw = raw[4:] |
| 397 | if not raw: |
| 398 | return None |
| 399 | try: |
| 400 | return Path(os.path.realpath(raw)) |
| 401 | except (OSError, ValueError): |
| 402 | return None |
| 403 | |
| 404 | |
| 405 | def _fd_real_path(fd: int) -> Optional[Path]: |
| 406 | """Canonical path of an open descriptor (Windows handle, macOS ``F_GETPATH``, Linux ``/proc/self/fd``).""" |
| 407 | if sys.platform == "win32": |
| 408 | return _win32_fd_real_path(fd) |
| 409 | target: Optional[str] = None |
| 410 | if sys.platform == "darwin" and fcntl is not None: |
| 411 | f_getpath = getattr(fcntl, "F_GETPATH", _DARWIN_F_GETPATH) |
| 412 | try: |
| 413 | raw = fcntl.fcntl(fd, f_getpath, b"\x00" * _DARWIN_MAXPATHLEN) |
| 414 | except (OSError, ValueError): |
| 415 | return None |
| 416 | if isinstance(raw, (bytes, bytearray)): |
| 417 | target = os.fsdecode(bytes(raw).split(b"\x00", 1)[0]) |
| 418 | elif isinstance(raw, str): |
| 419 | target = raw.split("\x00", 1)[0] |
| 420 | else: |
| 421 | try: |
| 422 | target = os.readlink(f"/proc/self/fd/{fd}") |
| 423 | except OSError: |
| 424 | return None |
| 425 | if not target or not target.startswith("/"): |
| 426 | return None |
| 427 | try: |
| 428 | return Path(os.path.realpath(target)) |
| 429 | except (OSError, ValueError): |
| 430 | return None |
| 431 | |
| 432 | |
| 433 | def _normalize_topic(value: Any) -> str: |
| 434 | cleaned = _CONTROL_RE.sub("", str(value or "")) |
| 435 | cleaned = cleaned.strip(_TOPIC_STRIP).casefold() |
| 436 | return " ".join(cleaned.split()) |
| 437 | |
| 438 | |
| 439 | def looks_inline_json(value: str) -> bool: |
| 440 | """True when a ``--reddit-threads`` argument is JSON text rather than a path.""" |
| 441 | stripped = value.strip() |
| 442 | return stripped.startswith(("{", "[")) or "\n" in value |
| 443 | |
| 444 | |
| 445 | def _rejection(text: str) -> str: |
| 446 | """The counter for a value ``canonical_thread`` refused.""" |
| 447 | candidate = text if "://" in text else "https://" + text |
| 448 | try: |
| 449 | parts = urlsplit(candidate) |
| 450 | host = (parts.hostname or "").lower() |
| 451 | except ValueError: |
| 452 | return "invalid" |
| 453 | if "/" not in text and "." not in text: |
| 454 | return "invalid" |
| 455 | if not host: |
| 456 | return "invalid" |
| 457 | if _REDIRECT_HOST.search(host): |
| 458 | return "redirect" |
| 459 | if not any(host == s or host.endswith("." + s) for s in _REDDIT_SUFFIXES): |
| 460 | return "non-reddit" |
| 461 | segments = [s for s in parts.path.split("/") if s] |
| 462 | if "s" in segments[:3] and len(segments) >= 3 and segments[0].lower() == "r": |
| 463 | return "share-link" |
| 464 | return "not-a-thread" |
| 465 | |
| 466 | |
| 467 | def _entry_ref(entry: Any, counters: dict[str, int]) -> Optional[ThreadRef]: |
| 468 | if not isinstance(entry, dict): |
| 469 | counters["invalid"] += 1 |
| 470 | return None |
| 471 | if set(entry) - ENTRY_FIELDS: |
| 472 | counters["extra-fields"] += 1 |
| 473 | raw = entry.get("url") |
| 474 | if not (isinstance(raw, str) and raw.strip()): |
| 475 | raw = entry.get("id") |
| 476 | if not isinstance(raw, str) or not raw.strip() or len(raw) > MAX_FIELD_CHARS: |
| 477 | counters["invalid"] += 1 |
| 478 | return None |
| 479 | text = _CONTROL_RE.sub("", raw).strip() |
| 480 | ref = canonical_thread(text) |
| 481 | if ref is None: |
| 482 | counters[_rejection(text)] += 1 |
| 483 | return None |
| 484 | ref.provenance = {"host"} |
| 485 | return ref |
| 486 | |
| 487 | |
| 488 | def _read_bytes(raw_path: str, fail: Callable[[str], EnvelopeContractError]) -> bytes: |
| 489 | if raw_path == STDIN: |
| 490 | try: |
| 491 | stream = sys.stdin.buffer |
| 492 | data = stream.read(MAX_BYTES + 1) |
| 493 | except (OSError, AttributeError, ValueError) as exc: |
| 494 | raise fail(f"cannot be read ({type(exc).__name__})") from None |
| 495 | if not isinstance(data, (bytes, bytearray)): |
| 496 | raise fail("cannot be read (TypeError)") |
| 497 | if len(data) > MAX_BYTES: |
| 498 | raise fail(f"exceeds the {MAX_BYTES // 1024} KiB limit") |
| 499 | return bytes(data) |
| 500 | try: |
| 501 | abs_path = Path(os.path.abspath(raw_path)) |
| 502 | real = Path(os.path.realpath(raw_path)) |
| 503 | except (OSError, ValueError) as exc: |
| 504 | raise fail(f"cannot be read ({type(exc).__name__})") from None |
| 505 | raw_roots = [Path(os.path.abspath(root)) for root in _raw_protected_roots()] |
| 506 | if _is_under(abs_path, raw_roots) or _inside_protected(real): |
| 507 | raise fail("is inside a configuration or credential directory") |
| 508 | try: |
| 509 | info = _stat(real) |
| 510 | except OSError as exc: |
| 511 | raise fail(f"cannot be read ({type(exc).__name__})") from None |
| 512 | if not stat.S_ISREG(info.st_mode): |
| 513 | raise fail("is not a regular file") |
| 514 | if real.suffix.lower() != ".json": |
| 515 | raise fail("must be a .json file") |
| 516 | if info.st_size > MAX_BYTES: |
| 517 | raise fail(f"exceeds the {MAX_BYTES // 1024} KiB limit") |
| 518 | open_flags = ( |
| 519 | os.O_RDONLY |
| 520 | | getattr(os, "O_BINARY", 0) |
| 521 | | getattr(os, "O_NOFOLLOW", 0) |
| 522 | | getattr(os, "O_NONBLOCK", 0) |
| 523 | | getattr(os, "O_CLOEXEC", 0) |
| 524 | ) |
| 525 | try: |
| 526 | # Open without following a raced symlink or blocking on a raced FIFO, |
| 527 | # then confirm the opened descriptor is the same regular file. |
| 528 | fd = os.open(real, open_flags) |
| 529 | handle = None |
| 530 | try: |
| 531 | finfo = os.fstat(fd) |
| 532 | if not stat.S_ISREG(finfo.st_mode): |
| 533 | raise fail("is not a regular file") |
| 534 | if (finfo.st_dev, finfo.st_ino) != (info.st_dev, info.st_ino): |
| 535 | raise fail("changed while being read") |
| 536 | fd_real = _fd_real_path(fd) |
| 537 | if fd_real is None: |
| 538 | raise fail("could not be verified safely") |
| 539 | if _inside_protected(fd_real): |
| 540 | raise fail("is inside a configuration or credential directory") |
| 541 | if finfo.st_size > MAX_BYTES: |
| 542 | raise fail(f"exceeds the {MAX_BYTES // 1024} KiB limit") |
| 543 | handle = os.fdopen(fd, "rb") |
| 544 | except BaseException: |
| 545 | if handle is None: |
| 546 | try: |
| 547 | os.close(fd) |
| 548 | except OSError: |
| 549 | pass |
| 550 | raise |
| 551 | with handle: |
| 552 | data = handle.read(MAX_BYTES + 1) |
| 553 | except OSError as exc: |
| 554 | raise fail(f"cannot be read ({type(exc).__name__})") from None |
| 555 | if len(data) > MAX_BYTES: |
| 556 | raise fail(f"exceeds the {MAX_BYTES // 1024} KiB limit") |
| 557 | return data |
| 558 | |
| 559 | |
| 560 | def read(path: str | os.PathLike[str], topic: str) -> Envelope: |
| 561 | """Validate a ``--reddit-threads`` file (or ``-`` for stdin) for this run. |
| 562 | |
| 563 | ``topic`` is the run topic. Raises ``EnvelopeContractError`` (exit 2) for |
| 564 | every fail-closed case; a bad entry is only counted. |
| 565 | """ |
| 566 | raw_path = os.fspath(path) |
| 567 | |
| 568 | def fail(what: str) -> EnvelopeContractError: |
| 569 | where = "on stdin" if raw_path == STDIN else raw_path |
| 570 | return EnvelopeContractError(f"--reddit-threads file {where} {what}. {_REMEDY}") |
| 571 | |
| 572 | data = _read_bytes(raw_path, fail) |
| 573 | digest = hashlib.sha256(data).hexdigest() |
| 574 | try: |
| 575 | payload = json.loads(data.decode("utf-8")) |
| 576 | except UnicodeDecodeError: |
| 577 | raise fail("is not valid UTF-8") from None |
| 578 | except (RecursionError, MemoryError): |
| 579 | raise fail("is too deeply nested or too large to parse") from None |
| 580 | except ValueError: |
| 581 | raise fail("is not valid JSON") from None |
| 582 | |
| 583 | if not isinstance(payload, dict): |
| 584 | raise fail("must be a JSON object") |
| 585 | if payload.get("schema") != SCHEMA: |
| 586 | raise fail('has a missing or unsupported "schema" field') |
| 587 | if not _normalize_topic(topic) or _normalize_topic(payload.get("topic")) != _normalize_topic(topic): |
| 588 | raise fail('has a "topic" field that does not match this run\'s topic') |
| 589 | entries = payload.get("threads") |
| 590 | if not isinstance(entries, list): |
| 591 | raise fail('has a "threads" field that is not a list') |
| 592 | if not entries: |
| 593 | raise fail('has an empty "threads" list (omit --reddit-threads when no thread was found)') |
| 594 | if len(entries) > MAX_ENTRIES: |
| 595 | raise fail(f'has more than {MAX_ENTRIES} entries in "threads"') |
| 596 | |
| 597 | counters = {name: 0 for name in COUNTERS} |
| 598 | notes: list[str] = [] |
| 599 | refs: list[ThreadRef] = [] |
| 600 | seen: set[str] = set() |
| 601 | for entry in entries: |
| 602 | ref = _entry_ref(entry, counters) |
| 603 | if ref is None: |
| 604 | continue |
| 605 | if ref.post_id in seen: |
| 606 | counters["duplicate"] += 1 |
| 607 | continue |
| 608 | if len(refs) >= MAX_THREADS: |
| 609 | counters["truncated"] += 1 |
| 610 | continue |
| 611 | seen.add(ref.post_id) |
| 612 | refs.append(ref) |
| 613 | if counters["truncated"]: |
| 614 | notes.append(f"only the first {MAX_THREADS} threads are used") |
| 615 | |
| 616 | envelope = Envelope( |
| 617 | path=raw_path, sha256=digest, topic=topic, refs=refs, |
| 618 | counters=counters, total=len(entries), notes=notes, |
| 619 | ) |
| 620 | _log(envelope.receipt()) |
| 621 | return envelope |
| 622 |