Repository navigation
feat(fetcher): add lobsters_top for Lobsters story listings - #204
Conversation
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]>
📝 WalkthroughWalkthroughAdds a new Lobsters fetcher family with three components: a shared HTTP client with reusable ChangesLobsters Fetcher Family
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Review rate limit: 0/1 reviews remaining, refill in 60 minutes.Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/fetcher/lobsters/top.rs (1)
114-120: ⚡ Quick winCanonicalize options before hashing the cache key.
fetch()clampscount, lowercases/trimstag, and ignoreskindwhenevertagis set, butcache_key()hashes the raw TOML. Equivalent configs therefore fragment the cache and can trigger duplicate Lobsters requests. Hash the normalizedOptionsinstead 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
📒 Files selected for processing (4)
src/fetcher/lobsters/client.rssrc/fetcher/lobsters/mod.rssrc/fetcher/lobsters/top.rssrc/fetcher/mod.rs
| 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}"))) |
There was a problem hiding this comment.
🛠️ 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.
| 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}"), |
There was a problem hiding this comment.
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.
Summary
New
lobsters_*fetcher family. First entry:lobsters_top— Lobsters front-page listings (hottest/newest/active), optionally filtered by a single tag. Mirrors thehackernews_*family structure (sharedclient.rs+ per-listing fetcher file).Ticks the
lobsters_topcheckbox 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).linked_text_block,text_block,text,markdown_text_block,entries,bars,timelineOptions
countkind"hottest"|"newest"|"active""hottest"hottestwhentagis set (the tag listing only exposes the hottest variant).tag"rust","c++"). Allowed chars:[a-z0-9_+-].Compatible renderers
linked_text_blocklist_linkstext_blockanimated_boot,animated_postfx,animated_scanlines,animated_splitflap,animated_wave,list_plaintextanimated_boot,animated_figlet_morph,animated_postfx,animated_scanlines,animated_splitflap,animated_typewriter,animated_wave,text_ascii,text_plainmarkdown_text_blocktext_markdownentriesanimated_boot,animated_postfx,animated_scanlines,animated_splitflap,animated_wave,grid_tablebarsanimated_boot,animated_postfx,animated_scanlines,animated_splitflap,animated_wave,chart_bar,chart_pie,list_rankingtimelineanimated_boot,animated_postfx,animated_scanlines,animated_splitflap,animated_wave,list_timelineImplementation notes
src/fetcher/lobsters/{mod.rs, client.rs, top.rs}mirrors thehackernews_*family layout.created_at(RFC3339 with.ffffractional seconds, e.g.2026-05-03T07:03:54.000-05:00) parsed via the existinggithub::common::parse_timestamphelper for the Timeline shape./t/<tag>/newest.jsonand/t/<tag>/active.json404. The fetcher silently force-routes to/t/<tag>.jsonwhentagis set, regardless ofkind. Documented in the option schema.Barsshape so the bar widget never renders a negative width.urlstrings (Lobsters Ask-style posts have"url":"") fall back tocomments_url, thenshort_id_url, then a synthesisedhttps://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 passingcargo test --lib— 1970 passing, 0 regressionscargo test --lib fetcher::lobsters::top::tests::live -- --ignored— live smoke test against real/hottest.jsonpassescargo run --bin splashboard -- catalog fetcher lobsters_top— option schema and renderer compatibility surface as expected.splashboard/dashboard.toml(LinkedTextBlock / Entries / Bars / Timeline / MarkdownTextBlock + tag filter) — confirmedcargo fmt --all -- --checkcargo clippy --lib -- -D warnings🤖 Generated with Claude Code
Summary by CodeRabbit