Skip to content

feat(fetcher): add lobsters_top for Lobsters story listings - #204

Merged
unhappychoice merged 1 commit into
mainfrom
feat/lobsters-top
May 4, 2026
Merged

unhappychoice merged 1 commit into
mainfrom
feat/lobsters-top

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

New lobsters_* fetcher family. First entry: lobsters_top — Lobsters front-page listings (hottest / newest / active), optionally filtered by a single tag. Mirrors the hackernews_* family structure (shared client.rs + per-listing fetcher file).

Ticks the lobsters_top checkbox on #67.

Lobsters front-page listings — hottest / newest / active, optionally filtered by a single tag. Each row shows score, comment count, and title, linked to the story URL (or the Lobsters comment page when there isn't one).

Kind Safety Shapes
cached Safe linked_text_block, text_block, text, markdown_text_block, entries, bars, timeline

Options

Option Type Required Default Description
count integer (1..=25) no 10 Number of stories to display.
kind "hottest" | "newest" | "active" no "hottest" Which Lobsters listing to query. Forced to hottest when tag is set (the tag listing only exposes the hottest variant).
tag string no — Filter to a single Lobsters tag (e.g. "rust", "c++"). Allowed chars: [a-z0-9_+-].

Compatible renderers

Shape Renderers
linked_text_block list_links
text_block animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave, list_plain
text animated_boot, animated_figlet_morph, animated_postfx, animated_scanlines, animated_splitflap, animated_typewriter, animated_wave, text_ascii, text_plain
markdown_text_block text_markdown
entries animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave, grid_table
bars animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave, chart_bar, chart_pie, list_ranking
timeline animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave, list_timeline

Implementation notes

  • New family src/fetcher/lobsters/{mod.rs, client.rs, top.rs} mirrors the hackernews_* family layout.
  • created_at (RFC3339 with .fff fractional seconds, e.g. 2026-05-03T07:03:54.000-05:00) parsed via the existing github::common::parse_timestamp helper for the Timeline shape.
  • Lobsters' tag listing endpoint only exposes the hottest variant — /t/<tag>/newest.json and /t/<tag>/active.json 404. The fetcher silently force-routes to /t/<tag>.json when tag is set, regardless of kind. Documented in the option schema.
  • Negative scores (flagged stories) clamp to 0 for the Bars shape so the bar widget never renders a negative width.
  • Empty url strings (Lobsters Ask-style posts have "url":"") fall back to comments_url, then short_id_url, then a synthesised https://lobste.rs/s/<short_id> so every row that has any link field at all is clickable.

Test plan

  • cargo test --lib fetcher::lobsters — 37 passing
  • cargo test --lib — 1970 passing, 0 regressions
  • cargo test --lib fetcher::lobsters::top::tests::live -- --ignored — live smoke test against real /hottest.json passes
  • cargo run --bin splashboard -- catalog fetcher lobsters_top — option schema and renderer compatibility surface as expected
  • User smoke-test with a multi-shape .splashboard/dashboard.toml (LinkedTextBlock / Entries / Bars / Timeline / MarkdownTextBlock + tag filter) — confirmed
  • cargo fmt --all -- --check
  • cargo clippy --lib -- -D warnings

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added Lobsters integration to fetch front-page stories with configurable sorting options (hottest, newest, active), tag filtering, custom result counts, and multiple display formats including text, markdown, entries, bars, and timeline views.

New `lobsters_*` family fetcher targeting the public lobste.rs JSON API
(`/hottest.json` / `/newest.json` / `/active.json` / `/t/<tag>.json`).
Safety::Safe — host hardcoded, tag normalized to `[a-z0-9_+-]` so config
can't redirect traffic off-host. Tag listing exposes only the hottest
variant on Lobsters' side, so `kind` is silently force-routed there
when `tag` is set.

Seven shapes: `LinkedTextBlock` (default, OSC 8 hyperlinks), `TextBlock`,
`Text` (single headline), `MarkdownTextBlock`, `Entries`, `Bars` (score),
`Timeline` (parses `created_at` into unix seconds via the existing
`github::common::parse_timestamp` helper).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a new Lobsters fetcher family with three components: a shared HTTP client with reusable reqwest::Client singleton and timeout handling, a module orchestrating the family, and a concrete LobstersTopFetcher that fetches story listings with tag filtering, count clamping, and multiple output formats.

Changes

Lobsters Fetcher Family

Layer / File(s) Summary
Shared HTTP Client
src/fetcher/lobsters/client.rs
Defines SITE_BASE constant, constructs a process-wide reqwest::Client singleton via OnceLock with package-version user agent and 10s timeout, and provides get<T>() async helper that performs HTTP GET, maps failures to FetchError::Failed with lobsters-prefixed messages, validates HTTP status, and returns parsed JSON.
Fetcher Implementation
src/fetcher/lobsters/top.rs
Implements LobstersTopFetcher with deserializable Options (count, kind, tag) and Kind enum (hottest/newest/active). Parses options, clamps count, normalizes tag with length/character validation, builds listing path (forcing tag routes to /t/<tag>.json), fetches stories via shared client, and renders output in multiple shapes (text, text blocks, linked text, markdown, entries, bars with clamped scores, timeline with parsed timestamps).
Module Wiring
src/fetcher/lobsters/mod.rs
Exports client and top submodules and implements fetchers() function returning a vector containing LobstersTopFetcher as an Arc<dyn Fetcher>.
Registry Integration
src/fetcher/mod.rs
Declares pub mod lobsters and extends Registry::with_builtins() to register all fetchers returned by lobsters::fetchers(), making the family available by default.
Tests & Documentation
src/fetcher/lobsters/client.rs, src/fetcher/lobsters/top.rs
Comprehensive unit tests covering client reuse, JSON deserialization, HTTP status/parse/request error handling, option parsing/validation, tag normalization rules, listing path routing, rendering correctness per shape including URL/link fallback precedence, timestamp parsing with fallback, count clamping, and an ignored live integration smoke test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

  • #152: Adds a new fetcher family with shared HTTP client infrastructure and modifies src/fetcher/mod.rs to register fetchers via Registry::with_builtins().

Poem

🐰 Through Lobsters fields our fetcher hops,
Gathering stories, filtering tops,
With client singleton and JSON in paw,
The rabbit brings news without flaw! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 65.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing a new lobsters_top fetcher for retrieving Lobsters story listings, which is the primary focus of the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/lobsters-top

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.96970% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.43%. Comparing base (6442ac4) to head (6678665).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/lobsters/top.rs 96.50% 19 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##             main     #204    +/-   ##
========================================
  Coverage   96.42%   96.43%            
========================================
  Files         146      149     +3     
  Lines       42660    43287   +627     
========================================
+ Hits        41135    41743   +608     
- Misses       1525     1544    +19     
Files with missing lines Coverage Δ
src/fetcher/lobsters/client.rs 100.00% <100.00%> (ø)
src/fetcher/lobsters/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 99.08% <100.00%> (+<0.01%) ⬆️
src/fetcher/lobsters/top.rs 96.50% <96.50%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/fetcher/lobsters/top.rs (1)

114-120: ⚡ Quick win

Canonicalize options before hashing the cache key.

fetch() clamps count, lowercases/trims tag, and ignores kind whenever tag is set, but cache_key() hashes the raw TOML. Equivalent configs therefore fragment the cache and can trigger duplicate Lobsters requests. Hash the normalized Options instead of the serialized input table.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/lobsters/top.rs` around lines 114 - 120, cache_key() currently
serializes raw ctx.options which fragments the cache because fetch() normalizes
options (clamps count, lowercases/trims tag, and ignores kind when tag is set);
update cache_key (in src/fetcher/lobsters/top.rs) to canonicalize the Options
the same way fetch() does before serializing: make a normalized copy of the
FetchContext.options (apply count clamping, tag trimming/lowercasing, and clear
kind when tag is present), then call toml::to_string on that normalized Options
and pass the resulting string to cache_key(self.name(), ctx, &extra) so
equivalent configs produce the same cache key.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/fetcher/lobsters/client.rs`:
- Around line 28-40: The get function currently accepts arbitrary URLs; enforce
fixed-host semantics by either (preferred) changing pub async fn get<T:
DeserializeOwned>(url: &str) to accept a path/endpoint and always prefix it with
the lobsters base host (e.g., SITE_BASE or a constant like "https://lobste.rs")
before making the request, or (alternatively) validate the parsed URL's host
inside get and return Err(FetchError::Failed(...)) if the host is not
"lobste.rs"; update the function body (the http().get(...) call and error
messages around it) to use the composed/validated URL and ensure this module can
be classified as Safety::Safe.

In `@src/fetcher/lobsters/top.rs`:
- Around line 345-350: In markdown_row, title and url are injected raw into
Markdown which lets titles with []()_* or URLs with ) break rendering; fix by
escaping markdown-special characters in the title (implement and call an escape
function used by title_or_placeholder or directly in markdown_row, e.g.,
escape_markdown_text that escapes [, ], (, ), `, *, _, and backslashes) and
sanitize/quote the link destination (either percent-encode or wrap the URL in
<...> via an escape_url helper) before using link_for's result, and ensure
markdown_text_block uses the same escaping helpers so rendered rows are safe.

---

Nitpick comments:
In `@src/fetcher/lobsters/top.rs`:
- Around line 114-120: cache_key() currently serializes raw ctx.options which
fragments the cache because fetch() normalizes options (clamps count,
lowercases/trims tag, and ignores kind when tag is set); update cache_key (in
src/fetcher/lobsters/top.rs) to canonicalize the Options the same way fetch()
does before serializing: make a normalized copy of the FetchContext.options
(apply count clamping, tag trimming/lowercasing, and clear kind when tag is
present), then call toml::to_string on that normalized Options and pass the
resulting string to cache_key(self.name(), ctx, &extra) so equivalent configs
produce the same cache key.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: def12213-6464-4a5c-8055-13d6013ca3bd

📥 Commits

Reviewing files that changed from the base of the PR and between 4adc0a3 and 6678665.

📒 Files selected for processing (4)
  • src/fetcher/lobsters/client.rs
  • src/fetcher/lobsters/mod.rs
  • src/fetcher/lobsters/top.rs
  • src/fetcher/mod.rs

Comment on lines +28 to +40
pub async fn get<T: DeserializeOwned>(url: &str) -> Result<T, FetchError> {
let res = http()
.get(url)
.send()
.await
.map_err(|e| FetchError::Failed(format!("lobsters request failed: {e}")))?;
let status = res.status();
if !status.is_success() {
return Err(FetchError::Failed(format!("lobsters {status}")));
}
res.json()
.await
.map_err(|e| FetchError::Failed(format!("lobsters json parse: {e}")))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Make the shared getter fixed-host, not arbitrary-URL.

get() currently accepts any URL, so the family's Safety::Safe guarantee depends on every caller remembering to prepend SITE_BASE correctly. Prefix the host here, or reject non-lobste.rs URLs before sending, so the invariant is enforced once. As per coding guidelines, src/fetcher/**/*.rs: Each fetcher must declare a Safety class: Safe (for local-only reads or fixed-host authenticated network), Network (for trust-gated config-provided URLs), or closed Exec (not supported).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/lobsters/client.rs` around lines 28 - 40, The get function
currently accepts arbitrary URLs; enforce fixed-host semantics by either
(preferred) changing pub async fn get<T: DeserializeOwned>(url: &str) to accept
a path/endpoint and always prefix it with the lobsters base host (e.g.,
SITE_BASE or a constant like "https://lobste.rs") before making the request, or
(alternatively) validate the parsed URL's host inside get and return
Err(FetchError::Failed(...)) if the host is not "lobste.rs"; update the function
body (the http().get(...) call and error messages around it) to use the
composed/validated URL and ensure this module can be classified as Safety::Safe.

Comment on lines +345 to +350
fn markdown_row(it: &Item) -> String {
let title = title_or_placeholder(it);
let meta = meta_label(it);
match link_for(it) {
Some(url) => format!("- **{meta}** [{title}]({url})"),
None => format!("- **{meta}** {title}"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Escape titles and destinations before emitting Markdown.

title and url are inserted raw into Markdown syntax here. A normal Lobsters title containing []()_* or a URL containing ) will break the rendered row or link in markdown_text_block.

Possible fix
+fn escape_markdown_text(text: &str) -> String {
+    text.chars().fold(String::with_capacity(text.len()), |mut out, ch| {
+        if matches!(ch, '\\' | '[' | ']' | '*' | '_' | '`') {
+            out.push('\\');
+        }
+        out.push(ch);
+        out
+    })
+}
+
 fn markdown_row(it: &Item) -> String {
-    let title = title_or_placeholder(it);
+    let title = escape_markdown_text(&title_or_placeholder(it));
     let meta = meta_label(it);
     match link_for(it) {
-        Some(url) => format!("- **{meta}**  [{title}]({url})"),
+        Some(url) => format!("- **{meta}**  [{title}](<{url}>)"),
         None => format!("- **{meta}**  {title}"),
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fetcher/lobsters/top.rs` around lines 345 - 350, In markdown_row, title
and url are injected raw into Markdown which lets titles with []()_* or URLs
with ) break rendering; fix by escaping markdown-special characters in the title
(implement and call an escape function used by title_or_placeholder or directly
in markdown_row, e.g., escape_markdown_text that escapes [, ], (, ), `, *, _,
and backslashes) and sanitize/quote the link destination (either percent-encode
or wrap the URL in <...> via an escape_url helper) before using link_for's
result, and ensure markdown_text_block uses the same escaping helpers so
rendered rows are safe.

@unhappychoice
unhappychoice merged commit 60768e9 into main May 4, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/lobsters-top branch May 4, 2026 06:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant