返回 last30days-skill
reddit_session.py
根目录 / skills / last30days / scripts / lib / reddit_session.py
1 """The opt-in logged-in Reddit session layer.
2
3 A user who consented (``REDDIT_BROWSER_CONSENT``, recorded by
4 ``setup --reddit-session``) lends the engine their reddit.com login cookie,
5 read into memory from the one browser setup recorded. With it the engine
6 reads, never writes:
7
8 * post search (``type=posts``, a month window) through Reddit's search
9 fragment, parsed by ``reddit_search.parse_page``;
10 * comment search (``type=comments``): each hit names its thread and carries
11 the matched comment, which stays in the thread's quotes and whose date
12 can keep an older thread in the window;
13 * community search (``type=communities``), then post search inside the top
14 three communities;
15 * thread JSON (``/comments/<id>.json``) as the first hydrator in
16 ``reddit_hydrate``: live scores and comments.
17
18 Nothing calls ``/api/``, a write endpoint, the home feed, the inbox or saved
19 items. The identity check is the first search page itself: a logged-in page
20 carries :data:`LOGGED_IN_MARKER`; every later page is checked again, so a
21 session that expires mid-run is caught. A logged-out page or a 403 on a
22 search page means Reddit no longer honors the session: the path is skipped
23 for six hours under this cookie's fingerprint (a new login clears it) and the
24 detail says ``session session-expired`` with a re-login hint, never "no
25 results". A 403 on one thread drops that thread only.
26
27 Privacy (applied to every item the session returns, whichever layer found
28 the thread): over-18 posts are dropped, private and quarantined subreddits
29 are dropped unless the user named the subreddit (``r/<name>`` in the topic,
30 or ``--dedicated-subreddits``), and only public fields are copied, so viewer
31 fields (votes, saves, reports, moderation state) never enter the pipeline.
32
33 The cookie is held by :class:`Session` only, never logged, never in an error
34 string, and never written anywhere. Each run caps session requests at
35 :data:`REQUEST_CAP`; comparison entities split it. Requests are paced by the
36 session's own limiter (``http.REDDIT_SESSION_LIMITER``) and memoized in the
37 session's own namespace. Never raises into the pipeline.
38 """
39
40 from __future__ import annotations
41
42 import contextlib
43 import contextvars
44 import copy
45 import hashlib
46 import html as _html
47 import json
48 import re
49 import threading
50 import time
51 from dataclasses import dataclass, field
52 from typing import Any, Callable, Iterable, Mapping, Optional
53 from urllib.parse import quote
54
55 from . import dates, env, http, log, reddit_enrich, reddit_health, reddit_listing, reddit_search, snippet
56 from .reddit_refs import LIVE, MatchedComment, ThreadRef, canonical_thread
57
58 PATH = "session"
59 BASE = "https://www.reddit.com"
60 LOGGED_IN_MARKER = "user-logged-in"
61 REQUEST_CAP = 60
62 # Post-search pages per depth; comments, communities and each in-community
63 # search take one page.
64 POST_PAGES = {"quick": 1, "default": 2, "deep": 3}
65 # Threads hydrated through thread JSON per lane call.
66 HYDRATE_LIMITS = {"quick": 8, "default": 15, "deep": 25}
67 COMMUNITY_SEARCHES = 3
68 COMMENTS_PER_THREAD = 10
69 # Two consecutive thread 403s mean the session, not the threads, is refused.
70 _EXPIRED_AFTER_FORBIDDEN = 2
71 _DISCOVER_CACHE_MAX = 64
72 _LOGGED_OUT_403_MARKERS = (
73 "try logging in or creating an account",
74 "your request has been blocked due to a network policy",
75 )
76 _PRIVATE_403_REASONS = frozenset({"private", "quarantined", "gated", "banned"})
77
78 COMMENT_UNIT_MARKER = 'view-events="search/view/comment"'
79 COMMUNITY_UNIT_MARKER = 'view-events="search/view/subreddit"'
80 NO_RESULTS_MARKER = reddit_search.NO_RESULTS_MARKER
81
82 # Page states.
83 OK = "ok"
84 EXPIRED = "session-expired"
85 THROTTLED = "throttled"
86 ERROR = "error"
87
88 # Fields of a thread's JSON that describe the viewer, not the thread. They are
89 # never copied; strip_viewer_fields removes them from a raw row.
90 VIEWER_FIELDS = (
91 "likes", "saved", "clicked", "visited", "hidden", "user_reports", "mod_reports",
92 "mod_reason_by", "mod_reason_title", "mod_note", "approved_by", "approved_at_utc",
93 "banned_by", "banned_at_utc", "removed_by", "num_reports", "report_reasons",
94 "can_mod_post", "can_gild", "author_flair_text", "author_flair_richtext",
95 "author_flair_css_class", "author_flair_template_id", "author_flair_type",
96 "user_reports_dismissed", "mod_reports_dismissed", "ignore_reports",
97 )
98 # Only these subreddit_type values are readable by logged-out users; any other
99 # value (private, gold_only, gold_restricted, employees_only, user, or missing)
100 # is treated as non-public.
101 _PUBLIC_TYPES = frozenset({"public", "restricted", "archived"})
102
103 # The per-lane-call budget owner: the entity (topic) a lane call serves.
104 _entity: contextvars.ContextVar[str] = contextvars.ContextVar("last30days_reddit_session_entity", default="")
105 _current: contextvars.ContextVar[Optional["Session"]] = contextvars.ContextVar(
106 "last30days_reddit_session", default=None,
107 )
108 _named: contextvars.ContextVar[Optional[frozenset[str]]] = contextvars.ContextVar(
109 "last30days_reddit_session_named", default=None,
110 )
111
112 _run_lock = threading.Lock()
113 _run: dict[str, Any] = {"resolved": False, "session": None, "status": None}
114
115
116 def _log(msg: str) -> None:
117 log.source_log("RedditSession", msg, tty_only=False)
118
119
120 def cookie_fp(cookie: str) -> str:
121 """The first 16 hex characters of the cookie's sha256: names a login, reveals nothing."""
122 return hashlib.sha256(str(cookie or "").encode("utf-8")).hexdigest()[:16]
123
124
125 def strip_viewer_fields(row: Mapping[str, Any]) -> dict[str, Any]:
126 """``row`` without the fields that describe the viewer."""
127 return {k: v for k, v in dict(row or {}).items() if k not in VIEWER_FIELDS}
128
129
130 def _sub_key(name: Any) -> str:
131 return str(name or "").strip().removeprefix("r/").strip("/").lower()
132
133
134 def named_subreddits(topic: str, dedicated: Iterable[str] = ()) -> frozenset[str]:
135 """Subreddits the user named: ``r/<name>`` in the topic, plus ``--dedicated-subreddits``."""
136 named = {m.lower() for m in re.findall(r"(?<![A-Za-z0-9_])r/([A-Za-z0-9_]{2,21})", topic or "")}
137 named |= {_sub_key(s) for s in dedicated or []}
138 return frozenset(named - {""})
139
140
141 def _wait_event(
142 event: threading.Event,
143 deadline: Optional[float],
144 cancel: Optional[threading.Event] = None,
145 ) -> bool:
146 """Wait until ``event`` is set, returning False on deadline or cancel."""
147 if event.is_set():
148 return True
149 if cancel is not None and cancel.is_set():
150 return False
151 if cancel is None:
152 if deadline is None:
153 return event.wait()
154 remaining = deadline - time.monotonic()
155 if remaining <= 0:
156 return event.is_set()
157 return event.wait(timeout=remaining)
158 while not event.is_set():
159 if cancel.is_set():
160 return False
161 if deadline is not None:
162 remaining = deadline - time.monotonic()
163 if remaining <= 0:
164 return event.is_set()
165 step = min(0.05, remaining)
166 else:
167 step = 0.05
168 if event.wait(timeout=step):
169 return True
170 return True
171
172
173 @dataclass
174 class _InflightFetch:
175 done: threading.Event = field(default_factory=threading.Event)
176 status: Optional[int] = None
177 body: Optional[str] = None
178 shareable: bool = False
179
180
181 @dataclass
182 class _InflightDiscovery:
183 done: threading.Event = field(default_factory=threading.Event)
184 result: Optional["Discovery"] = None
185 cacheable: bool = False
186
187
188 class Session:
189 """One run's consented session. Holds the cookie; never shows it."""
190
191 def __init__(
192 self,
193 cookie: str,
194 *,
195 browser: str = "",
196 entity_count: int = 1,
197 sc_floor: int = env.REDDIT_SC_MIN_ITEMS_DEFAULT,
198 named: Iterable[str] = (),
199 limiter: Optional[http.RateLimiter] = None,
200 cap: int = REQUEST_CAP,
201 ):
202 self._cookie = str(cookie)
203 self.fp = cookie_fp(cookie)
204 self.browser = browser
205 self.entity_count = max(1, int(entity_count or 1))
206 self.sc_floor = sc_floor
207 self.named = frozenset(_sub_key(s) for s in named) - {""}
208 self.limiter = limiter
209 self.cap = cap
210 self.state = OK
211 self.verified = False
212 self.public_subs: set[str] = set()
213 self._lock = threading.Lock()
214 self._total = 0
215 self._per_entity: dict[str, int] = {}
216 self._fetch_inflight: dict[tuple[str, str], _InflightFetch] = {}
217 self._discover_lock = threading.Lock()
218 self._discover_cache: dict[tuple, "Discovery"] = {}
219 self._discover_inflight: dict[tuple, _InflightDiscovery] = {}
220
221 def __repr__(self) -> str: # never the cookie
222 return f"<reddit Session fp={self.fp} state={self.state}>"
223
224 __str__ = __repr__
225
226 @property
227 def requests(self) -> int:
228 with self._lock:
229 return self._total
230
231 def entity_budget(self) -> int:
232 """Requests each comparison entity may spend: an equal share, at least 1."""
233 return max(1, self.cap // self.entity_count)
234
235 def _take(self, entity: str) -> bool:
236 with self._lock:
237 if self._total >= self.cap:
238 return False
239 if self._per_entity.get(entity, 0) >= self.entity_budget():
240 return False
241 self._total += 1
242 self._per_entity[entity] = self._per_entity.get(entity, 0) + 1
243 return True
244
245 def _refund(self, entity: str) -> None:
246 with self._lock:
247 self._total -= 1
248 self._per_entity[entity] = self._per_entity.get(entity, 1) - 1
249
250 @property
251 def alive(self) -> bool:
252 return self.state == OK
253
254 def fetch(
255 self,
256 url: str,
257 *,
258 accept: str = "text/html",
259 deadline: Optional[float] = None,
260 cancel: Optional[threading.Event] = None,
261 ) -> tuple[Optional[int], Optional[str]]:
262 """One session GET within the run's cap: ``(status, body)``.
263
264 ``(None, None)`` when the cap, deadline, or cancel event leaves no
265 room. Concurrent callers for the same ``(url, accept)`` coalesce onto
266 the in-flight request at zero extra budget cost; memo hits also cost
267 nothing.
268 """
269 key = (url, accept)
270 for _round in range(2):
271 if cancel is not None and cancel.is_set():
272 return None, None
273 if deadline is not None and deadline - time.monotonic() < 1:
274 return None, None
275 with self._lock:
276 inflight = self._fetch_inflight.get(key)
277 owner = inflight is None
278 if owner:
279 inflight = _InflightFetch()
280 self._fetch_inflight[key] = inflight
281 if not owner:
282 if not _wait_event(inflight.done, deadline, cancel):
283 return None, None
284 if inflight.shareable:
285 return inflight.status, inflight.body
286 continue
287 try:
288 entity = _entity.get()
289 if not self._take(entity):
290 return None, None
291 status, body, from_memo = http.reddit_session_get(
292 url, f"reddit_session={self._cookie}", accept=accept,
293 deadline_monotonic=deadline, limiter=self.limiter,
294 )
295 if from_memo:
296 self._refund(entity)
297 inflight.status = status
298 inflight.body = body
299 inflight.shareable = status in (200, 403, 429)
300 return status, body
301 finally:
302 with self._lock:
303 if self._fetch_inflight.get(key) is inflight:
304 self._fetch_inflight.pop(key, None)
305 inflight.done.set()
306 return None, None
307
308 def room(self) -> bool:
309 entity = _entity.get()
310 with self._lock:
311 return self._total < self.cap and self._per_entity.get(entity, 0) < self.entity_budget()
312
313 def mark_public_sub(self, subreddit: Any) -> None:
314 sub_key = _sub_key(subreddit)
315 if sub_key:
316 with self._lock:
317 self.public_subs.add(sub_key)
318
319 def is_public_sub(self, subreddit: Any) -> bool:
320 sub_key = _sub_key(subreddit)
321 if not sub_key:
322 return False
323 with self._lock:
324 return sub_key in self.public_subs
325
326
327 # --- run-level session ---------------------------------------------------------
328
329 def reset_run_state() -> None:
330 """Forget this run's session (call once per command, and from tests)."""
331 with _run_lock:
332 _run.update(resolved=False, session=None, status=None)
333 http.reset_reddit_session_memo()
334
335
336 def gate(config: Mapping[str, Any]) -> tuple[bool, str]:
337 """Whether the session may be used this run (reads no cookie)."""
338 return env.reddit_session_gate(dict(config or {}))
339
340
341 def status() -> Optional[str]:
342 """Why this run has no session after a read attempt, or None."""
343 with _run_lock:
344 return _run.get("status")
345
346
347 def session_for(
348 config: Mapping[str, Any], *, reader: Optional[Callable[..., tuple]] = None, topic: str = "",
349 ) -> Optional[Session]:
350 """This run's session, reading the cookie on first use. None when the gate
351 refuses, the browser has no Reddit login, or a persisted skip for this
352 login is in force."""
353 allowed, _why = gate(config)
354 if not allowed:
355 return None
356 with _run_lock:
357 if _run["resolved"]:
358 return _run["session"]
359 _run["resolved"] = True
360 cookie, read_status = (reader or env.read_reddit_session_cookie)(dict(config))
361 if not cookie:
362 _run["status"] = read_status
363 browser = str(config.get(env.REDDIT_FROM_BROWSER_VAR) or "")
364 hint = {
365 "not-logged-in": f"no reddit.com login in {browser}; log in to reddit.com there",
366 "permission-denied": f"{browser} cookie access was denied",
367 "unsupported-encryption": f"{browser} cookies use an encryption this engine cannot read",
368 }.get(read_status, f"could not read the reddit.com login from {browser}")
369 _log(f"session off this run: {hint}")
370 return None
371 if "_reddit_named_subreddits" in config:
372 session_named = named_subreddits("", config.get("_reddit_named_subreddits") or ())
373 else:
374 session_named = named_subreddits(topic, config.get("_dedicated_subreddits") or [])
375 session = Session(
376 cookie,
377 browser=str(config.get(env.REDDIT_FROM_BROWSER_VAR) or ""),
378 entity_count=int(config.get("_comparison_entity_count") or 1),
379 sc_floor=env.reddit_sc_min_items(dict(config)),
380 named=session_named,
381 )
382 skip = reddit_health.skip_reason(PATH, cookie_fp=session.fp)
383 if skip:
384 reason = (reddit_health.entries().get(PATH) or {}).get("reason") or ""
385 session.state = EXPIRED if reason.startswith(EXPIRED) else reddit_health.SKIPPED_CACHED
386 _log(f"session skipped this run ({session.state}); a new reddit.com login or doctor clears it")
387 _run["session"] = session
388 return session
389
390
391 @contextlib.contextmanager
392 def lane(
393 session: Optional[Session],
394 entity: str = "",
395 *,
396 named: Optional[Iterable[str]] = None,
397 ):
398 """Make ``session`` the Reddit lane's session in this context, spending
399 the budget of ``entity`` (the topic the lane call serves).
400
401 When ``named`` is given, it overrides ``session.named`` in this context so
402 comparison entities sharing a session never inherit each other's
403 private/quarantined subreddit allowlist.
404 """
405 token = _current.set(session)
406 entity_token = _entity.set(entity or "")
407 override = (frozenset(_sub_key(s) for s in named) - {""}) if named is not None else None
408 named_token = _named.set(override)
409 try:
410 yield session
411 finally:
412 _named.reset(named_token)
413 _entity.reset(entity_token)
414 _current.reset(token)
415
416
417 def current() -> Optional[Session]:
418 return _current.get()
419
420
421 def _effective_named(session: Session) -> frozenset[str]:
422 override = _named.get()
423 return session.named if override is None else override
424
425
426 def relogin_hint(session: Session) -> str:
427 return f"log in to reddit.com in {session.browser or 'your browser'}"
428
429
430 # --- page parsers -----------------------------------------------------------------
431
432 def page_state(status: Optional[int], body: Optional[str]) -> str:
433 """What one session search page says about the session."""
434 if status == 200:
435 return OK if LOGGED_IN_MARKER in (body or "") else EXPIRED
436 if status == 403:
437 # A valid session gets this page; a refusal with the cookie attached
438 # is Reddit no longer honoring it.
439 return EXPIRED
440 if status == 429:
441 return THROTTLED
442 return ERROR
443
444
445 _TAG = re.compile(r"<search-telemetry-tracker\b[^>]*>")
446 _CONTEXT = re.compile(r'\bdata-faceplate-tracking-context="([^"]*)"')
447 _TIMEAGO = re.compile(r'<faceplate-timeago\b[^>]*?\bts="([^"]+)"')
448 _VOTES = re.compile(r'<faceplate-number\b[^>]*?\bnumber="(\d+)"[^>]*>\s*</faceplate-number>\s*votes?')
449 _COUNTER = re.compile(r'<faceplate-number\b[^>]*?\bnumber="(\d+)"[^>]*>\s*</faceplate-number>\s*(vote|comment)')
450 _HREF = re.compile(r'\bhref="([^"]*)"')
451 _TAGS = re.compile(r"<[^>]+>")
452
453
454 def _units(text: str, marker: str) -> list[tuple[int, dict]]:
455 """(offset, tracking context) of each result unit carrying ``marker``."""
456 out = []
457 for m in _TAG.finditer(text or ""):
458 tag = m.group(0)
459 if marker not in tag:
460 continue
461 ctx_match = _CONTEXT.search(tag)
462 if not ctx_match:
463 continue
464 try:
465 ctx = json.loads(_html.unescape(ctx_match.group(1)))
466 except (TypeError, ValueError):
467 continue
468 if isinstance(ctx, dict):
469 out.append((m.start(), ctx))
470 return out
471
472
473 def _flags(ctx: Mapping[str, Any]) -> tuple[bool, bool]:
474 """(over_18, quarantined) from a tracking context."""
475 post = ctx.get("post") if isinstance(ctx.get("post"), dict) else {}
476 sub = ctx.get("subreddit") if isinstance(ctx.get("subreddit"), dict) else {}
477 return bool(post.get("nsfw") or sub.get("nsfw")), bool(sub.get("quarantined"))
478
479
480 def _plain(fragment: str) -> str:
481 return " ".join(_html.unescape(_TAGS.sub(" ", fragment or "")).split())
482
483
484 def unrecognized_comments(text: str) -> Optional[str]:
485 """None for a comment-search page (with hits or Reddit's no-results unit), else why not."""
486 if NO_RESULTS_MARKER in (text or ""):
487 return None
488 if COMMENT_UNIT_MARKER in (text or ""):
489 return None if parse_comments(text) else "Reddit comment results no longer parse"
490 return "not a Reddit comment search page"
491
492
493 def unrecognized_communities(text: str) -> Optional[str]:
494 """None for a community-search page, else why not."""
495 if NO_RESULTS_MARKER in (text or ""):
496 return None
497 if COMMUNITY_UNIT_MARKER in (text or ""):
498 return None if parse_communities(text) else "Reddit community results no longer parse"
499 return "not a Reddit community search page"
500
501
502 def parse_comments(text: str) -> list[dict[str, Any]]:
503 """Comment-search hits: the comment, its date and votes, and its thread."""
504 text = text or ""
505 units = _units(text, COMMENT_UNIT_MARKER)
506 hits: list[dict[str, Any]] = []
507 seen: set[str] = set()
508 for i, (start, ctx) in enumerate(units):
509 comment = ctx.get("comment") if isinstance(ctx.get("comment"), dict) else {}
510 post = ctx.get("post") if isinstance(ctx.get("post"), dict) else {}
511 sub = ctx.get("subreddit") if isinstance(ctx.get("subreddit"), dict) else {}
512 comment_id = str(comment.get("id") or "").removeprefix("t1_").lower()
513 post_id = str(post.get("id") or comment.get("post_id") or "").removeprefix("t3_").lower()
514 if not comment_id or not post_id or comment_id in seen:
515 continue
516 seen.add(comment_id)
517 end = units[i + 1][0] if i + 1 < len(units) else len(text)
518 chunk = text[start:end]
519 body_at = chunk.find(f'id="search-comment-t1_{comment_id}-post-rtjson-content"')
520 if body_at < 0:
521 continue
522 body_end = chunk.find("</shreddit-stop-propagation>", body_at)
523 body = _plain(chunk[chunk.find(">", body_at) + 1: body_end if body_end > 0 else None])
524 content_at = chunk.find('data-testid="search-comment-content"')
525 stamps = _TIMEAGO.findall(chunk[content_at:] if content_at >= 0 else chunk)
526 comment_ts = stamps[0] if stamps else None
527 post_stamps = _TIMEAGO.findall(chunk[:content_at]) if content_at > 0 else []
528 counter_at = chunk.find('data-testid="search-counter-row"')
529 votes = _VOTES.search(chunk, body_at, counter_at if counter_at > body_at else len(chunk))
530 counts: dict[str, int] = {}
531 if counter_at >= 0:
532 for number, label in _COUNTER.findall(chunk[counter_at:]):
533 counts.setdefault(label, int(number))
534 permalink = ""
535 for href in _HREF.findall(chunk):
536 href = _html.unescape(href).split("?", 1)[0]
537 if f"/comments/{post_id}/" in href and href.rstrip("/").endswith(comment_id):
538 permalink = href if href.startswith("http") else f"{BASE}{href}"
539 break
540 over_18, quarantined = _flags(ctx)
541 hits.append({
542 "comment_id": comment_id,
543 "post_id": post_id,
544 "title": str(post.get("title") or ""),
545 "subreddit": str(sub.get("name") or ""),
546 "body": body,
547 "comment_created_utc": reddit_listing._to_epoch(comment_ts),
548 "comment_date": reddit_listing._to_date(comment_ts),
549 "comment_score": int(votes.group(1)) if votes else None,
550 "post_date": reddit_listing._to_date(post_stamps[0]) if post_stamps else None,
551 "post_score": counts.get("vote"),
552 "num_comments": counts.get("comment"),
553 "permalink": permalink,
554 "over_18": over_18,
555 "quarantined": quarantined,
556 })
557 return hits
558
559
560 def parse_communities(text: str) -> list[dict[str, Any]]:
561 """Community-search hits, in page order: name, over_18, quarantined."""
562 out: list[dict[str, Any]] = []
563 seen: set[str] = set()
564 for _start, ctx in _units(text or "", COMMUNITY_UNIT_MARKER):
565 sub = ctx.get("subreddit") if isinstance(ctx.get("subreddit"), dict) else {}
566 name = str(sub.get("name") or "").strip()
567 if not name or name.lower() in seen:
568 continue
569 seen.add(name.lower())
570 out.append({"name": name, "over_18": bool(sub.get("nsfw")), "quarantined": bool(sub.get("quarantined"))})
571 return out
572
573
574 def post_flags(text: str) -> dict[str, tuple[bool, bool]]:
575 """(over_18, quarantined) per post id on a post-search page."""
576 out: dict[str, tuple[bool, bool]] = {}
577 for _start, ctx in reddit_search._post_units(text or ""):
578 out[str(ctx["post"]["id"]).removeprefix("t3_").lower()] = _flags(ctx)
579 return out
580
581
582 # --- discovery ----------------------------------------------------------------------
583
584 @dataclass
585 class Discovery:
586 """What one session discovery call found."""
587
588 refs: list[ThreadRef] = field(default_factory=list)
589 # Live search-hit copies, by post id, for threads thread JSON did not reach.
590 hits: dict[str, dict] = field(default_factory=dict)
591 # The matched comment of a comment hit, stored the way an item stores comments.
592 comments: dict[str, dict] = field(default_factory=dict)
593 state: Optional[str] = None
594 dropped_private: int = 0
595 pages: int = 0
596
597
598 def _record(session: Session, state: str, reason: str = "") -> None:
599 """Note a session page state: a refusal persists under this login's fingerprint."""
600 if state == EXPIRED:
601 session.state = EXPIRED
602 reddit_health.record(PATH, reddit_health.BLOCKED, f"{EXPIRED}: {reason}"[:120], cookie_fp=session.fp)
603 elif state == THROTTLED:
604 session.state = THROTTLED
605 reddit_health.record(PATH, reddit_health.THROTTLED, reason)
606 elif state == OK and not session.verified:
607 session.verified = True
608 reddit_health.record(PATH, reddit_health.OK, "session search", cookie_fp=session.fp)
609
610
611 def _search_page(
612 session: Session,
613 url: str,
614 deadline: Optional[float],
615 cancel: Optional[threading.Event] = None,
616 ) -> tuple[str, Optional[str]]:
617 """One search page: ``(state, body)``. A 429 is retried once."""
618 status, body = session.fetch(url, deadline=deadline, cancel=cancel)
619 if status is None and body is None:
620 return ERROR, None
621 state = page_state(status, body)
622 if state == THROTTLED:
623 status, body = session.fetch(url, deadline=deadline, cancel=cancel)
624 state = page_state(status, body) if status is not None else THROTTLED
625 if state == OK:
626 _record(session, OK)
627 elif state in (EXPIRED, THROTTLED):
628 _record(session, state, f"HTTP {status}" if status != 200 else "logged-out page")
629 return state, body
630
631
632 def _allowed(session: Session, subreddit: str, over_18: bool, quarantined: bool, private: bool = False) -> bool:
633 if over_18:
634 return False
635 if (quarantined or private) and _sub_key(subreddit) not in _effective_named(session):
636 return False
637 return True
638
639
640 def _post_hits(session: Session, body: str, topic: str, found: Discovery) -> None:
641 flags = post_flags(body)
642 posts, _cursor = reddit_search.parse_page(body, topic)
643 for post in posts:
644 pid = post["metadata"]["post_id"]
645 over_18, quarantined = flags.get(pid, (False, False))
646 if not _allowed(session, post.get("subreddit", ""), over_18, quarantined):
647 found.dropped_private += 1
648 continue
649 ref = canonical_thread(post.get("url") or pid)
650 if ref is None:
651 continue
652 ref.provenance.add(PATH)
653 ref.title = post.get("title") or ""
654 ref.date = post.get("date")
655 found.refs.append(ref)
656 post["engagement_source"] = LIVE
657 post["why_relevant"] = "Reddit search (logged-in)"
658 found.hits.setdefault(pid, post)
659
660
661 def _comment_hits(session: Session, body: str, found: Discovery) -> None:
662 for hit in parse_comments(body):
663 if not _allowed(session, hit["subreddit"], hit["over_18"], hit["quarantined"]):
664 found.dropped_private += 1
665 continue
666 url = f"{BASE}/r/{hit['subreddit']}/comments/{hit['post_id']}/" if hit["subreddit"] else hit["post_id"]
667 ref = canonical_thread(url)
668 if ref is None:
669 continue
670 ref.provenance.add(PATH)
671 ref.title = hit["title"]
672 ref.date = hit["post_date"]
673 ref.matched_comment = MatchedComment(
674 comment_id=hit["comment_id"], created_utc=hit["comment_created_utc"],
675 permalink=hit["permalink"],
676 )
677 found.refs.append(ref)
678 found.comments.setdefault(hit["post_id"], {
679 "id": hit["comment_id"],
680 "score": hit["comment_score"],
681 "date": hit["comment_date"],
682 "author": "",
683 "excerpt": snippet.cut_quote(hit["body"]),
684 "url": hit["permalink"],
685 "depth": 0,
686 "matched": True,
687 })
688
689
690 def discover(
691 session: Session,
692 topic: str,
693 *,
694 depth: str = "default",
695 deadline: Optional[float] = None,
696 from_date: Optional[str] = None,
697 to_date: Optional[str] = None,
698 cancel: Optional[threading.Event] = None,
699 ) -> Discovery:
700 """Session search for ``topic``: posts, comments, communities, then posts
701 inside the top communities. Stops at the first page that says the session
702 is gone, at the request cap, at ``deadline``, or on ``cancel``. Concurrent
703 callers on the same session for the same ``(topic, depth, window, named)``
704 share one in-flight run. Never raises."""
705 if not session.alive:
706 return Discovery(state=session.state)
707 if cancel is not None and cancel.is_set():
708 return Discovery(state=ERROR)
709 try:
710 window = reddit_search._time_filter(from_date, to_date)
711 except Exception as exc: # defensive: discovery must never raise
712 _log(f"session search failed: {type(exc).__name__}")
713 return Discovery(state=ERROR)
714 key = (str(topic or ""), depth, window, _effective_named(session))
715 fallback: Optional[Discovery] = None
716 for _round in range(2):
717 if not session.alive:
718 if fallback is not None and session.state != EXPIRED:
719 return fallback
720 return Discovery(state=session.state)
721 if cancel is not None and cancel.is_set():
722 return Discovery(state=ERROR)
723 with session._discover_lock:
724 cached = session._discover_cache.get(key)
725 if cached is not None:
726 return copy.deepcopy(cached)
727 slot = session._discover_inflight.get(key)
728 owner = slot is None
729 if owner:
730 slot = _InflightDiscovery()
731 session._discover_inflight[key] = slot
732 if not owner:
733 if not _wait_event(slot.done, deadline, cancel):
734 if cancel is not None and cancel.is_set():
735 return Discovery(state=ERROR)
736 return fallback if fallback is not None else Discovery(state=ERROR)
737 if slot.result is not None and (
738 slot.cacheable or slot.result.state in (EXPIRED, THROTTLED)
739 ):
740 return copy.deepcopy(slot.result)
741 if slot.result is not None and slot.result.refs and slot.result.state == reddit_health.OK:
742 fallback = copy.deepcopy(slot.result)
743 if fallback is not None and (
744 not session.room()
745 or (deadline is not None and deadline - time.monotonic() < 1)
746 ):
747 return fallback
748 continue
749 found = Discovery()
750 cancelled = False
751 complete = False
752 try:
753 complete = _discover(session, topic, depth, deadline, found, window, cancel=cancel)
754 cancelled = bool(cancel is not None and cancel.is_set())
755 except Exception as exc: # the session must never break the lane
756 _log(f"session search failed: {type(exc).__name__}")
757 found.state = found.state or ERROR
758 finally:
759 try:
760 if cancelled:
761 found.state = ERROR
762 elif found.state is None:
763 found.state = reddit_health.OK if found.refs else reddit_health.EMPTY
764 cacheable = (
765 complete
766 and not cancelled
767 and found.pages > 0
768 and found.state in (reddit_health.OK, reddit_health.EMPTY)
769 )
770 snapshot = copy.deepcopy(found)
771 slot.result = snapshot
772 slot.cacheable = cacheable
773 with session._discover_lock:
774 if cacheable and len(session._discover_cache) < _DISCOVER_CACHE_MAX:
775 session._discover_cache[key] = snapshot
776 finally:
777 with session._discover_lock:
778 if session._discover_inflight.get(key) is slot:
779 session._discover_inflight.pop(key, None)
780 slot.done.set()
781 if found.dropped_private:
782 _log(f"dropped {found.dropped_private} over-18, private or quarantined results")
783 if not found.refs and not cancelled and found.state != EXPIRED and fallback is not None:
784 return fallback
785 return found
786 return fallback if fallback is not None else Discovery(state=ERROR)
787
788
789 def _discover(
790 session: Session,
791 topic: str,
792 depth: str,
793 deadline: Optional[float],
794 found: Discovery,
795 window: str = "month",
796 *,
797 cancel: Optional[threading.Event] = None,
798 ) -> bool:
799 """Run all discovery steps; return True only when every step finished cleanly."""
800 cursor: Optional[str] = None
801 for _page in range(POST_PAGES.get(depth, POST_PAGES["default"])):
802 if cancel is not None and cancel.is_set():
803 found.state = ERROR
804 return False
805 state, body = _search_page(
806 session, reddit_search.search_url(topic, window, cursor=cursor), deadline, cancel=cancel,
807 )
808 if state != OK:
809 found.state = state if state != ERROR or not found.refs else None
810 return False
811 found.pages += 1
812 if reddit_search.unrecognized_body(body or ""):
813 break
814 _post_hits(session, body or "", topic, found)
815 cursor = reddit_search.next_cursor(body or "")
816 if not cursor:
817 break
818 if not session.room() or (cancel is not None and cancel.is_set()):
819 return False
820 state, body = _search_page(
821 session, reddit_search.search_url(topic, window, kind="comments", sort="new"), deadline, cancel=cancel,
822 )
823 if state != OK:
824 found.state = state if state in (EXPIRED, THROTTLED) else None
825 return False
826 found.pages += 1
827 if not unrecognized_comments(body or ""):
828 _comment_hits(session, body or "", found)
829 if not session.room() or (cancel is not None and cancel.is_set()):
830 return False
831 state, body = _search_page(
832 session, reddit_search.search_url(topic, kind="communities"), deadline, cancel=cancel,
833 )
834 if state != OK:
835 found.state = state if state in (EXPIRED, THROTTLED) else None
836 return False
837 found.pages += 1
838 communities = [] if unrecognized_communities(body or "") else parse_communities(body or "")
839 chosen = [c["name"] for c in communities if _allowed(session, c["name"], c["over_18"], c["quarantined"])]
840 for name in chosen[:COMMUNITY_SEARCHES]:
841 if not session.room() or (cancel is not None and cancel.is_set()):
842 return False
843 state, body = _search_page(
844 session, reddit_search.search_url(topic, window, subreddit=name), deadline, cancel=cancel,
845 )
846 if state != OK:
847 found.state = state if state in (EXPIRED, THROTTLED) else None
848 return False
849 found.pages += 1
850 if not reddit_search.unrecognized_body(body or ""):
851 _post_hits(session, body or "", topic, found)
852 return True
853
854
855 # --- thread JSON hydrator -------------------------------------------------------------
856
857 DROP = {"_drop": True}
858
859
860 def thread_url(post_id: str) -> str:
861 return f"{BASE}/comments/{quote(post_id, safe='')}.json?limit=20&depth=1&raw_json=1&sort=top"
862
863
864 def thread_post(data: Any, session: Session) -> Optional[dict]:
865 """A thread JSON answer as a Reddit lane item, ``DROP`` when privacy
866 rules exclude it, or None when the answer is not a thread."""
867 if not isinstance(data, list) or not data:
868 return None
869 try:
870 raw = data[0]["data"]["children"][0]["data"]
871 except (KeyError, IndexError, TypeError):
872 return None
873 if not isinstance(raw, dict) or not raw.get("id"):
874 return None
875 row = strip_viewer_fields(raw)
876 subreddit = str(row.get("subreddit") or "")
877 subreddit_type = str(row.get("subreddit_type") or "").strip().lower()
878 is_public = subreddit_type in _PUBLIC_TYPES
879 if not _allowed(session, subreddit, bool(row.get("over_18")), bool(row.get("quarantine")), private=not is_public):
880 return DROP
881 if is_public and not row.get("quarantine"):
882 session.mark_public_sub(subreddit)
883 parsed = reddit_enrich.parse_thread_data(data)
884 comments = reddit_enrich.stored_top_comments(
885 reddit_enrich.get_top_comments(parsed.get("comments") or [], COMMENTS_PER_THREAD)
886 )
887 for comment in comments:
888 comment["depth"] = 0
889 score = row.get("score")
890 num_comments = row.get("num_comments")
891 created = row.get("created_utc")
892 post = {
893 "id": "",
894 "title": str(row.get("title") or ""),
895 "url": f"{BASE}{row.get('permalink') or ''}" if row.get("permalink") else "",
896 "score": score,
897 "num_comments": num_comments,
898 "subreddit": subreddit,
899 "created_utc": created,
900 "author": str(row.get("author") or ""),
901 "selftext": str(row.get("selftext") or "")[:500],
902 "date": dates.timestamp_to_date(created) if created else None,
903 "engagement": {"score": score, "num_comments": num_comments, "upvote_ratio": row.get("upvote_ratio")},
904 "relevance": 0.0,
905 "why_relevant": "Reddit thread (logged-in)",
906 "metadata": {"post_id": str(row.get("id")).lower()},
907 "engagement_source": LIVE,
908 "top_comments": comments,
909 }
910 if comments:
911 post["comments_source"] = PATH
912 return post
913
914
915 def _is_logged_out_403(body: Optional[str]) -> bool:
916 lower = (body or "").lower()
917 return any(marker in lower for marker in _LOGGED_OUT_403_MARKERS)
918
919
920 def _is_private_403(body: Optional[str]) -> bool:
921 text = (body or "").strip()
922 if not text.startswith("{"):
923 return False
924 try:
925 payload = json.loads(text)
926 except ValueError:
927 return False
928 if not isinstance(payload, dict):
929 return False
930 return str(payload.get("reason") or "").strip().lower() in _PRIVATE_403_REASONS
931
932
933 def hydrator(
934 session: Session,
935 found: Optional[Discovery] = None,
936 *,
937 depth: str = "default",
938 deadline: Optional[float] = None,
939 ) -> Callable[[list[ThreadRef]], dict[str, dict]]:
940 """The session hydrator ``reddit_hydrate.hydrate`` calls first.
941
942 Thread JSON for up to ``HYDRATE_LIMITS[depth]`` refs, session search
943 hits first. A thread it cannot reach keeps its live search-hit copy when
944 its subreddit is known to be public this run; otherwise the free chain
945 takes it. A thread 403 drops that thread only.
946 """
947 found = found or Discovery()
948 limit = HYDRATE_LIMITS.get(depth, HYDRATE_LIMITS["default"])
949 bound_named = _named.get()
950
951 def run(refs: list[ThreadRef]) -> dict[str, dict]:
952 out: dict[str, dict] = {}
953 named_token = _named.set(bound_named) if bound_named is not None and _named.get() is None else None
954 try:
955 if session.alive:
956 ordered = sorted(refs, key=lambda r: (PATH not in r.provenance, r.matched_comment is None))
957 forbidden: list[str] = []
958 consecutive_403: list[str] = []
959 logged_out_403: set[str] = set()
960 answered = 0
961 for ref in ordered[:limit]:
962 if not session.alive or not session.room():
963 break
964 status, body = session.fetch(thread_url(ref.post_id), accept="application/json", deadline=deadline)
965 if status is None and body is None:
966 break
967 if status == 403:
968 forbidden.append(ref.post_id)
969 if not _is_private_403(body):
970 consecutive_403.append(ref.post_id)
971 if _is_logged_out_403(body):
972 logged_out_403.add(ref.post_id)
973 if len(consecutive_403) >= _EXPIRED_AFTER_FORBIDDEN:
974 _record(session, EXPIRED, "thread JSON refused")
975 break
976 continue
977 if status == 429:
978 _record(session, THROTTLED, "thread JSON 429")
979 break
980 if status != 200:
981 continue
982 try:
983 post = thread_post(json.loads(body or ""), session)
984 except Exception as exc:
985 _log(f"thread JSON parse failed for {ref.post_id}: {type(exc).__name__}")
986 post = None
987 if post is None:
988 continue
989 answered += 1
990 consecutive_403.clear()
991 out[ref.post_id] = post
992 if session.state == EXPIRED and consecutive_403:
993 # The session, not this trailing streak of threads, was refused:
994 # release only the trailing 403s to the free chain while preserving
995 # any earlier per-thread DROP verdicts.
996 trailing = set(consecutive_403)
997 forbidden = [pid for pid in forbidden if pid not in trailing]
998 elif not answered and not session.verified and len(consecutive_403) == 1:
999 only_pid = consecutive_403[0]
1000 # Only release a single 403 when Reddit positively indicated a
1001 # whole-session refusal; otherwise fail closed with DROP.
1002 if only_pid in logged_out_403:
1003 _record(session, EXPIRED, "thread JSON refused")
1004 forbidden = [pid for pid in forbidden if pid != only_pid]
1005 for pid in forbidden:
1006 out[pid] = dict(DROP)
1007 for ref in refs:
1008 pid = ref.post_id
1009 post = out.get(pid)
1010 matched = found.comments.get(pid)
1011 if post is None and pid in found.hits and session.is_public_sub(found.hits[pid].get("subreddit")):
1012 post = out[pid] = dict(found.hits[pid])
1013 if post is None or post.get("_drop") or not matched:
1014 continue
1015 kept = post.setdefault("top_comments", [])
1016 if not any(str(c.get("id") or "") == matched["id"] or matched["id"] in str(c.get("url") or "") for c in kept):
1017 kept.append(dict(matched))
1018 post["comments_source"] = post.get("comments_source") or PATH
1019 else:
1020 for c in kept:
1021 if str(c.get("id") or "") == matched["id"] or matched["id"] in str(c.get("url") or ""):
1022 c["matched"] = True
1023 # Omit logged-in matched_comment details on refs that thread_post
1024 # never verified (e.g. cap reached or session expired) before the
1025 # archive fallback runs, unless visibility is already confirmed or
1026 # the user explicitly named the subreddit.
1027 allowed_named = _effective_named(session)
1028 for ref in refs:
1029 post = out.get(ref.post_id)
1030 if post is not None and not post.get("_drop"):
1031 if ref.matched_comment is not None:
1032 ref.matched_comment_verified = True
1033 continue
1034 if ref.matched_comment is not None:
1035 if session.is_public_sub(ref.subreddit) or _sub_key(ref.subreddit) in allowed_named:
1036 ref.matched_comment_verified = True
1037 else:
1038 ref.matched_comment_verified = False
1039 ref.matched_comment = None
1040 return out
1041 finally:
1042 if named_token is not None:
1043 _named.reset(named_token)
1044
1045 return run
1046
1047
1048 # Threads that name the topic only in one matched comment fill in only while
1049 # fewer than this many threads name it in their title or body.
1050 COMMENT_ONLY_FILL_BELOW = 8
1051
1052
1053 def topic_bar(topic: str, items: Iterable[dict]) -> list[dict]:
1054 """Session items that name the topic, title or body first.
1055
1056 A thread whose title and body never name the topic, where only a matched
1057 comment does, is often an unrelated conversation with one passing
1058 mention. Such threads are kept only to fill a thin result: while fewer
1059 than ``COMMENT_ONLY_FILL_BELOW`` threads name the topic themselves.
1060 """
1061 from .reddit_discover import names_topic
1062
1063 items = list(items or [])
1064 if not topic:
1065 return items
1066 strong: list[dict] = []
1067 comment_only: list[dict] = []
1068 for item in items:
1069 if any(names_topic(t, topic) for t in (str(item.get("title") or ""), str(item.get("selftext") or "")) if t):
1070 strong.append(item)
1071 continue
1072 matched = [str(c.get("excerpt") or "") for c in item.get("top_comments") or [] if c.get("matched")]
1073 if any(names_topic(t, topic) for t in matched if t):
1074 item["comment_only_match"] = True
1075 comment_only.append(item)
1076 room = max(COMMENT_ONLY_FILL_BELOW - len(strong), 0)
1077 left_out = len(comment_only) - room
1078 if left_out > 0:
1079 _log(f"{left_out} threads that name the topic only in a comment left out")
1080 return strong + comment_only[:room]
1081
1081 lines PYTHON