| 1 | """dev.to (Forem) source for last30days. |
| 2 | |
| 3 | Uses the public Forem API at dev.to (no key): |
| 4 | |
| 5 | - ``/api/articles?tag=<tag>&top=<days>`` returns the most-engaged articles for |
| 6 | a tag in the window. Precise, but only as good as the tag. |
| 7 | - ``/api/articles/search?q=<term>&top=<days>`` is free-text search sorted |
| 8 | roughly by recency. Single distinctive terms match well; multi-word queries |
| 9 | match loosely, so every search hit must pass the engine's token-overlap |
| 10 | relevance check before it is kept. |
| 11 | - ``/api/comments?a_id=<id>`` returns the comment tree for an article. |
| 12 | |
| 13 | The source is off by default. Host-inferred tags (``--devto-tags``) turn it |
| 14 | on for a run; ``INCLUDE_SOURCES=devto`` or ``--search devto`` turn it on |
| 15 | without tags, in which case only the keyword search runs. An unknown tag |
| 16 | returns ``[]`` with HTTP 200, so a wrong tag stays quiet instead of failing. |
| 17 | |
| 18 | Both endpoints count ``top`` back from now and accept no end date, sort, or |
| 19 | date-range parameter. A window that ends before today therefore pages |
| 20 | through everything published since its start and filters locally, within |
| 21 | ``HISTORICAL_MAX_PAGES`` and ``HISTORICAL_BUDGET_SECONDS``. |
| 22 | """ |
| 23 | |
| 24 | from __future__ import annotations |
| 25 | |
| 26 | import datetime |
| 27 | import html |
| 28 | import re |
| 29 | import threading |
| 30 | import time |
| 31 | import urllib.parse |
| 32 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 33 | from concurrent.futures import TimeoutError as FuturesTimeout |
| 34 | from typing import Any |
| 35 | |
| 36 | from . import http, log |
| 37 | from .relevance import token_overlap_relevance |
| 38 | |
| 39 | ARTICLES_URL = "https://dev.to/api/articles" |
| 40 | SEARCH_URL = "https://dev.to/api/articles/search" |
| 41 | COMMENTS_URL = "https://dev.to/api/comments" |
| 42 | _SEARCH_HEADERS = {"Accept": "application/vnd.forem.api-v1+json"} |
| 43 | |
| 44 | TAG_LIMITS = {"quick": 1, "default": 2, "deep": 3} |
| 45 | SEARCH_PER_PAGE = {"quick": 10, "default": 20, "deep": 30} |
| 46 | TAG_PER_PAGE = 30 |
| 47 | ENRICH_LIMIT = 3 |
| 48 | MAX_COMMENTS = 5 |
| 49 | # Search hits below this token-overlap score are dropped. Same bar as the |
| 50 | # keyless Reddit lane: it keeps "kubernetes" hits and drops the newest-posts |
| 51 | # noise a loose multi-word query ("claude code") returns. |
| 52 | SEARCH_RELEVANCE_FLOOR = 0.25 |
| 53 | # Total wall-clock cap per request. The socket timeout alone bounds each |
| 54 | # read, so a response trickling in small chunks could otherwise run on. |
| 55 | REQUEST_DEADLINE_SECONDS = 20.0 |
| 56 | # Forem's per_page ceiling. A busy term ("kubernetes") has ~4,000 search hits |
| 57 | # over 78 days, about 2 MB and 4-5 s per full page. |
| 58 | HISTORICAL_PER_PAGE = 1000 |
| 59 | HISTORICAL_MAX_PAGES = 10 |
| 60 | HISTORICAL_BUDGET_SECONDS = 45.0 |
| 61 | ENRICH_WAIT_SECONDS = 25.0 |
| 62 | |
| 63 | _TAG_RE = re.compile(r"[^a-z0-9]") |
| 64 | # Bot comments on dev.to ("Official Platform Update ... tr.ee/dev-to") hide |
| 65 | # phishing behind link shorteners; real discussion rarely needs one. |
| 66 | _SHORTENER_RE = re.compile( |
| 67 | r"\b(?:bit\.ly|tinyurl\.com|tr\.ee|shorturl\.at|t\.co|rb\.gy|cutt\.ly|is\.gd|ow\.ly|tiny\.cc)/", |
| 68 | re.IGNORECASE, |
| 69 | ) |
| 70 | |
| 71 | |
| 72 | def _log(msg: str) -> None: |
| 73 | log.source_log("dev.to", msg, tty_only=False) |
| 74 | |
| 75 | |
| 76 | def normalize_tag(value: str) -> str: |
| 77 | return _TAG_RE.sub("", (value or "").lower().lstrip("#")) |
| 78 | |
| 79 | |
| 80 | def resolve_tags(tags: list[str] | None, depth: str = "default") -> list[str]: |
| 81 | """Normalize and dedupe host-supplied tags, capped by depth.""" |
| 82 | resolved: list[str] = [] |
| 83 | for tag in (normalize_tag(t) for t in (tags or [])): |
| 84 | if tag and tag not in resolved: |
| 85 | resolved.append(tag) |
| 86 | return resolved[: TAG_LIMITS.get(depth, TAG_LIMITS["default"])] |
| 87 | |
| 88 | |
| 89 | def _today() -> datetime.date: |
| 90 | return datetime.datetime.now(datetime.timezone.utc).date() |
| 91 | |
| 92 | |
| 93 | def _is_historical(to_date: str | None) -> bool: |
| 94 | return bool(to_date) and str(to_date) < _today().isoformat() |
| 95 | |
| 96 | |
| 97 | def _window_days(from_date: str | None, to_date: str | None) -> int: |
| 98 | try: |
| 99 | start = datetime.date.fromisoformat(from_date or "") |
| 100 | # Forem counts top=N back from now, including for historical windows, |
| 101 | # so the reach always runs to today and _in_window enforces to_date. |
| 102 | # The extra day keeps all of from_date: a now-anchored cutoff of |
| 103 | # exactly N days lands partway through it. |
| 104 | return max(1, (_today() - start).days + 1) |
| 105 | except ValueError: |
| 106 | return 30 |
| 107 | |
| 108 | |
| 109 | # The pipeline calls a source once per subquery, and the tag feed does not |
| 110 | # depend on the subquery, so identical URLs are fetched once per process. |
| 111 | _RESPONSE_CACHE: dict[str, list[dict[str, Any]]] = {} |
| 112 | _URL_LOCKS: dict[str, threading.Lock] = {} |
| 113 | _LOCKS_GUARD = threading.Lock() |
| 114 | |
| 115 | |
| 116 | def clear_cache() -> None: |
| 117 | with _LOCKS_GUARD: |
| 118 | _RESPONSE_CACHE.clear() |
| 119 | _URL_LOCKS.clear() |
| 120 | |
| 121 | |
| 122 | def _get_list( |
| 123 | url: str, headers: dict[str, str] | None = None, deadline: float | None = None, |
| 124 | ) -> list[dict[str, Any]]: |
| 125 | # Concurrent subquery streams can request the same URL; the per-URL lock |
| 126 | # makes the second caller wait for the first fetch instead of repeating it. |
| 127 | with _LOCKS_GUARD: |
| 128 | lock = _URL_LOCKS.setdefault(url, threading.Lock()) |
| 129 | with lock: |
| 130 | if url not in _RESPONSE_CACHE: |
| 131 | data = http.request( |
| 132 | "GET", url, headers=headers, timeout=15, retries=2, |
| 133 | deadline_monotonic=min( |
| 134 | time.monotonic() + REQUEST_DEADLINE_SECONDS, |
| 135 | deadline if deadline is not None else float("inf"), |
| 136 | ), |
| 137 | owned_get=True, |
| 138 | ) |
| 139 | if not isinstance(data, list): |
| 140 | # Forem list endpoints always return a JSON array; anything |
| 141 | # else is a changed or error response, not "no matches". |
| 142 | raise ValueError(f"unexpected dev.to response shape: {type(data).__name__}") |
| 143 | _RESPONSE_CACHE[url] = [row for row in data if isinstance(row, dict)] |
| 144 | return [dict(row) for row in _RESPONSE_CACHE[url]] |
| 145 | |
| 146 | |
| 147 | def _published(article: dict[str, Any]) -> str: |
| 148 | return str(article.get("published_at") or "")[:10] |
| 149 | |
| 150 | |
| 151 | def _fetch_rows( |
| 152 | base_url: str, |
| 153 | params: dict[str, Any], |
| 154 | to_date: str | None, |
| 155 | *, |
| 156 | label: str, |
| 157 | deadline: float, |
| 158 | headers: dict[str, str] | None = None, |
| 159 | ) -> list[dict[str, Any]]: |
| 160 | """Fetch one page for a current window, or page through a past one. |
| 161 | |
| 162 | Every page after the first stops at ``deadline``, which the caller shares |
| 163 | across all endpoints so a deep run's tags cannot each spend the budget. |
| 164 | """ |
| 165 | if not _is_historical(to_date): |
| 166 | return _get_list(f"{base_url}?{urllib.parse.urlencode(params)}", headers=headers) |
| 167 | rows: list[dict[str, Any]] = [] |
| 168 | for page in range(1, HISTORICAL_MAX_PAGES + 1): |
| 169 | if page > 1 and time.monotonic() >= deadline: |
| 170 | _log(f"{label}: stopped after {page - 1} pages at the time budget; older in-window articles may be missing") |
| 171 | return rows |
| 172 | page_params = {**params, "per_page": HISTORICAL_PER_PAGE, "page": page} |
| 173 | url = f"{base_url}?{urllib.parse.urlencode(page_params)}" |
| 174 | try: |
| 175 | batch = _get_list(url, headers=headers, deadline=deadline if page > 1 else None) |
| 176 | except Exception as exc: |
| 177 | if page == 1: |
| 178 | raise |
| 179 | _log(f"{label}: page {page} failed ({exc}); keeping the {page - 1} pages fetched") |
| 180 | return rows |
| 181 | rows.extend(batch) |
| 182 | # top=N bounds the result set at from_date, so a short page is the end. |
| 183 | if len(batch) < HISTORICAL_PER_PAGE: |
| 184 | return rows |
| 185 | _log(f"{label}: stopped at {HISTORICAL_MAX_PAGES} pages; older in-window articles may be missing") |
| 186 | return rows |
| 187 | |
| 188 | |
| 189 | def _top_engaged(rows: list[dict[str, Any]], limit: int) -> list[dict[str, Any]]: |
| 190 | return sorted( |
| 191 | rows, |
| 192 | key=lambda row: int(row.get("public_reactions_count") or row.get("positive_reactions_count") or 0), |
| 193 | reverse=True, |
| 194 | )[:limit] |
| 195 | |
| 196 | |
| 197 | def _in_window(article: dict[str, Any], from_date: str | None, to_date: str | None) -> bool: |
| 198 | published = _published(article) |
| 199 | if not published: |
| 200 | return True |
| 201 | if from_date and published < from_date: |
| 202 | return False |
| 203 | if to_date and published > to_date: |
| 204 | return False |
| 205 | return True |
| 206 | |
| 207 | |
| 208 | def _article_text(article: dict[str, Any]) -> str: |
| 209 | tags = article.get("tag_list") or [] |
| 210 | if isinstance(tags, str): |
| 211 | tags = [t.strip() for t in tags.split(",")] |
| 212 | return " ".join([str(article.get("title") or ""), str(article.get("description") or ""), " ".join(tags)]) |
| 213 | |
| 214 | |
| 215 | def search_devto( |
| 216 | topic: str, |
| 217 | from_date: str | None = None, |
| 218 | to_date: str | None = None, |
| 219 | *, |
| 220 | depth: str = "default", |
| 221 | tags: list[str] | None = None, |
| 222 | search_query: str | None = None, |
| 223 | ) -> dict[str, Any]: |
| 224 | """Fetch tag-feed and keyword-search articles for the topic. |
| 225 | |
| 226 | Returns ``{"articles": [...], "tags": [...], "errors": [...]}``. A failed |
| 227 | endpoint is recorded in ``errors`` and the other endpoint still counts. |
| 228 | """ |
| 229 | days = _window_days(from_date, to_date) |
| 230 | historical = _is_historical(to_date) |
| 231 | paging_deadline = time.monotonic() + HISTORICAL_BUDGET_SECONDS |
| 232 | resolved_tags = resolve_tags(tags, depth) |
| 233 | articles: dict[int, dict[str, Any]] = {} |
| 234 | errors: list[str] = [] |
| 235 | |
| 236 | for tag in resolved_tags: |
| 237 | params = {"tag": tag, "top": days, "per_page": TAG_PER_PAGE} |
| 238 | try: |
| 239 | rows = _fetch_rows(ARTICLES_URL, params, to_date, label=f"tag '{tag}'", deadline=paging_deadline) |
| 240 | except Exception as exc: |
| 241 | errors.append(f"tag {tag}: {exc}") |
| 242 | _log(f"tag feed failed for '{tag}': {exc}") |
| 243 | continue |
| 244 | rows = [row for row in rows if row.get("id") is not None and _in_window(row, from_date, to_date)] |
| 245 | if historical: |
| 246 | rows = _top_engaged(rows, TAG_PER_PAGE) |
| 247 | kept = 0 |
| 248 | for row in rows: |
| 249 | row.setdefault("_devto_match", f"tag:{tag}") |
| 250 | articles.setdefault(row["id"], row) |
| 251 | kept += 1 |
| 252 | _log(f"tag '{tag}': {kept} articles in window") |
| 253 | |
| 254 | # Planner queries quote phrases for engines with phrase syntax; Forem |
| 255 | # search treats the quotes as literal characters. |
| 256 | query = (search_query or topic or "").replace('"', " ").strip() |
| 257 | query = " ".join(query.split()) |
| 258 | if query: |
| 259 | per_page = SEARCH_PER_PAGE.get(depth, SEARCH_PER_PAGE["default"]) |
| 260 | params = {"q": query, "top": days, "per_page": per_page} |
| 261 | try: |
| 262 | rows = _fetch_rows( |
| 263 | SEARCH_URL, params, to_date, label=f"search '{query}'", |
| 264 | deadline=paging_deadline, headers=_SEARCH_HEADERS, |
| 265 | ) |
| 266 | except Exception as exc: |
| 267 | errors.append(f"search: {exc}") |
| 268 | _log(f"search failed for '{query}': {exc}") |
| 269 | rows = [] |
| 270 | kept = dropped = 0 |
| 271 | relevant = [] |
| 272 | for row in rows: |
| 273 | if row.get("id") is None or not _in_window(row, from_date, to_date): |
| 274 | continue |
| 275 | if token_overlap_relevance(topic or query, _article_text(row)) < SEARCH_RELEVANCE_FLOOR: |
| 276 | dropped += 1 |
| 277 | continue |
| 278 | relevant.append(row) |
| 279 | if historical: |
| 280 | # A current window keeps the newest page; a past one keeps the |
| 281 | # most-engaged in-window hits so the item count stays comparable. |
| 282 | relevant = _top_engaged(relevant, per_page) |
| 283 | for row in relevant: |
| 284 | row.setdefault("_devto_match", "search") |
| 285 | articles.setdefault(row["id"], row) |
| 286 | kept += 1 |
| 287 | _log(f"search '{query}': kept {kept}, dropped {dropped} off-topic") |
| 288 | |
| 289 | result: dict[str, Any] = {"articles": list(articles.values()), "tags": resolved_tags, "errors": errors} |
| 290 | attempted = len(resolved_tags) + (1 if query else 0) |
| 291 | if attempted and len(errors) == attempted: |
| 292 | # Every endpoint failed: surface it so the run reports a source |
| 293 | # failure instead of a quiet empty result. |
| 294 | result["error"] = "; ".join(errors) |
| 295 | return result |
| 296 | |
| 297 | |
| 298 | def parse_devto_response(response: dict[str, Any], query: str = "") -> list[dict[str, Any]]: |
| 299 | """Map Forem articles to engine item dicts (the HN item shape).""" |
| 300 | items: list[dict[str, Any]] = [] |
| 301 | for article in response.get("articles") or []: |
| 302 | reactions = int(article.get("public_reactions_count") or article.get("positive_reactions_count") or 0) |
| 303 | comments = int(article.get("comments_count") or 0) |
| 304 | user = article.get("user") or {} |
| 305 | content_score = token_overlap_relevance(query, _article_text(article)) if query else 0.5 |
| 306 | relevance = min(1.0, 0.7 * content_score + min(0.3, (reactions + comments) / 100)) |
| 307 | tags = article.get("tag_list") or [] |
| 308 | if isinstance(tags, str): |
| 309 | tags = [t.strip() for t in tags.split(",") if t.strip()] |
| 310 | items.append({ |
| 311 | "id": str(article.get("id")), |
| 312 | "title": str(article.get("title") or "").strip(), |
| 313 | "url": str(article.get("url") or ""), |
| 314 | "author": str(user.get("username") or user.get("name") or ""), |
| 315 | "date": str(article.get("published_at") or "")[:10] or None, |
| 316 | "text": str(article.get("description") or "").strip(), |
| 317 | "engagement": {"reactions": reactions, "comments": comments}, |
| 318 | "relevance": round(relevance, 2), |
| 319 | "why_relevant": f"dev.to article ({article.get('_devto_match', 'match')})", |
| 320 | "metadata": { |
| 321 | "tags": tags, |
| 322 | "reading_time_minutes": article.get("reading_time_minutes"), |
| 323 | "ai_disclosure_level": article.get("ai_disclosure_level"), |
| 324 | "match": article.get("_devto_match"), |
| 325 | }, |
| 326 | }) |
| 327 | return items |
| 328 | |
| 329 | |
| 330 | def _strip_html(text: str) -> str: |
| 331 | text = re.sub(r"<(br|/p)\s*/?>", "\n", text or "", flags=re.IGNORECASE) |
| 332 | text = re.sub(r"<[^>]+>", "", text) |
| 333 | return html.unescape(text).strip() |
| 334 | |
| 335 | |
| 336 | def _fetch_comments(article_id: str, deadline: float | None = None) -> list[dict[str, Any]]: |
| 337 | if deadline is not None and time.monotonic() >= deadline: |
| 338 | return [] |
| 339 | url = f"{COMMENTS_URL}?{urllib.parse.urlencode({'a_id': article_id})}" |
| 340 | try: |
| 341 | rows = _get_list(url, deadline=deadline) |
| 342 | except Exception as exc: |
| 343 | _log(f"comments failed for article {article_id}: {exc}") |
| 344 | return [] |
| 345 | comments = [] |
| 346 | for row in rows: |
| 347 | body_html = str(row.get("body_html") or "") |
| 348 | text = _strip_html(body_html) |
| 349 | # Check the raw HTML too: a shortener can hide in an href. |
| 350 | if not text or _SHORTENER_RE.search(html.unescape(body_html)): |
| 351 | continue |
| 352 | user = row.get("user") or {} |
| 353 | comments.append({ |
| 354 | "author": str(user.get("username") or user.get("name") or ""), |
| 355 | "text": text[:300] + "..." if len(text) > 300 else text, |
| 356 | # The comments API exposes no like count; direct replies are the |
| 357 | # only engagement signal it returns. |
| 358 | "replies": len(row.get("children") or []), |
| 359 | "ai_disclosure_level": row.get("ai_disclosure_level"), |
| 360 | }) |
| 361 | comments.sort(key=lambda c: c["replies"], reverse=True) |
| 362 | return comments[:MAX_COMMENTS] |
| 363 | |
| 364 | |
| 365 | def enrich_source_items( |
| 366 | items: list[Any], |
| 367 | top_k: int = ENRICH_LIMIT, |
| 368 | deadline: float | None = None, |
| 369 | ) -> list[Any]: |
| 370 | """Attach top comments to the first ``top_k`` ranked SourceItems with comments. |
| 371 | |
| 372 | Runs from ``_finalize_items_by_source`` so the comment calls land on the |
| 373 | articles that survived relevance pruning and dedupe, not on high-engagement |
| 374 | tag-feed articles the ranking later drops. |
| 375 | """ |
| 376 | from .normalize import _remap_comments |
| 377 | |
| 378 | targets = [] |
| 379 | for item in items: |
| 380 | if len(targets) >= top_k: |
| 381 | break |
| 382 | if getattr(item, "source", None) != "devto": |
| 383 | continue |
| 384 | if (item.metadata or {}).get("top_comments"): |
| 385 | continue |
| 386 | if not (item.engagement or {}).get("comments"): |
| 387 | continue |
| 388 | targets.append(item) |
| 389 | if not targets: |
| 390 | return items |
| 391 | wait_budget = ENRICH_WAIT_SECONDS |
| 392 | if deadline is not None: |
| 393 | remaining = deadline - time.monotonic() |
| 394 | if remaining <= 0: |
| 395 | _log("comment enrichment skipped: no time left") |
| 396 | return items |
| 397 | wait_budget = min(wait_budget, remaining) |
| 398 | executor = ThreadPoolExecutor(max_workers=len(targets)) |
| 399 | futures = { |
| 400 | ( |
| 401 | http.submit_with_context(executor, _fetch_comments, item.item_id, deadline) |
| 402 | if deadline is not None |
| 403 | else http.submit_with_context(executor, _fetch_comments, item.item_id) |
| 404 | ): item |
| 405 | for item in targets |
| 406 | } |
| 407 | try: |
| 408 | for future in as_completed(futures, timeout=wait_budget): |
| 409 | item = futures[future] |
| 410 | item.metadata["top_comments"] = _remap_comments( |
| 411 | future.result(), |
| 412 | score_keys=("replies",), |
| 413 | excerpt_keys=("text", "excerpt"), |
| 414 | preserve_absent_score=True, |
| 415 | ) |
| 416 | except FuturesTimeout: |
| 417 | _log("comment enrichment hit its time limit; keeping the comments that arrived") |
| 418 | finally: |
| 419 | # Never block report finalization on a straggling comment fetch. |
| 420 | executor.shutdown(wait=False, cancel_futures=True) |
| 421 | attached = sum(1 for item in targets if item.metadata.get("top_comments")) |
| 422 | _log(f"attached comments to {attached} of {len(targets)} top articles") |
| 423 | return items |
| 424 |