Repository navigation
feat(fetcher): wikipedia_* family — on_this_day / featured / random - #152
Conversation
…ia_random
Wraps the Wikipedia REST API (`*.wikipedia.org/api/rest_v1/...`) behind a
shared family client. All three fetchers are Safety::Safe — the `lang`
option picks a language subdomain but cannot escape `wikipedia.org`.
- `wikipedia_on_this_day` — historical events for today's MM/DD via
`feed/onthisday/{kind}/{MM}/{DD}`. Multi-shape (LinkedTextBlock default
+ TextBlock + Text). `kind` covers `selected` / `events` / `births` /
`deaths` / `holidays` / `all`.
- `wikipedia_featured` — today's TFA via `feed/featured/{YYYY}/{MM}/{DD}`.
Same shape table.
- `wikipedia_random` — random page summary via `page/random/summary`.
Same shape table.
`PageSummary` lives in the shared client and is reused by featured /
random rendering and on_this_day's per-event link target.
Catalog: ticks 3 boxes in #67. Unblocks #150 (home_feed body 2).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 50 minutes and 3 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📝 WalkthroughWalkthroughThis PR adds a complete Wikipedia fetcher module system with three implementations (featured articles, on-this-day, random pages), a shared HTTP client with response parsing and rendering utilities, and registers all fetchers in the application's fetcher registry. Changes
Sequence DiagramsequenceDiagram
participant User
participant Fetcher as Wikipedia<br/>Fetcher
participant Client as Wikipedia<br/>Client
participant API as Wikipedia<br/>REST API
participant Render as Shape<br/>Renderer
User->>Fetcher: fetch(options)
Fetcher->>Fetcher: parse options (lang, shape)
Fetcher->>Fetcher: build endpoint URL
Fetcher->>Client: get::<Response>(url)
Client->>API: GET /api/rest_v1/...
API-->>Client: JSON response
Client->>Client: deserialize to PageSummary
Client-->>Fetcher: PageSummary
Fetcher->>Render: render_page_summary(summary, shape)
Render->>Render: extract URL & sentences
Render-->>Fetcher: Body (Text/Link variants)
Fetcher-->>User: FetchResult
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 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 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
src/fetcher/wikipedia/client.rs (1)
106-121:render_page_summary's catch-all silently coerces unsupported shapes intoLinkedTextBlock.The match arm
_ => Body::LinkedTextBlock(...)accepts any of the 11 non-Text/TextBlockShapevariants. The runtime is supposed to validate shape pairings againstshapes()before reaching this point, so in practice onlyLinkedTextBlocklands here — but if that validation is ever bypassed or a future shape is added, callers get silently wrong output. Making the supported shape explicit and eitherunreachable!()or returning the canonical sample for the rest would localize the assumption.♻️ Suggested refactor
pub fn render_page_summary(summary: &PageSummary, shape: Shape) -> Body { match shape { Shape::Text => Body::Text(TextData { value: text_line(summary), }), Shape::TextBlock => Body::TextBlock(TextBlockData { lines: text_block_lines(summary), }), - _ => Body::LinkedTextBlock(LinkedTextBlockData { + Shape::LinkedTextBlock => Body::LinkedTextBlock(LinkedTextBlockData { items: vec![LinkedLine { text: summary.title.clone(), url: summary.url(), }], }), + other => unreachable!( + "render_page_summary called with unsupported shape {other:?}; \ + runtime should have validated against shapes()" + ), } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/wikipedia/client.rs` around lines 106 - 121, render_page_summary currently uses a catch-all `_` arm that silently coerces any non-Text/TextBlock Shape into a LinkedTextBlock; change the match to explicitly handle Shape::LinkedTextBlock and remove the `_` fallback — for any other Shape variants either call unreachable!() (if you are certain they cannot occur) or return a canonical sample/placeholder Body to make the assumption explicit. Update the match in render_page_summary accordingly, referencing the function name render_page_summary, the Shape enum and Body::LinkedTextBlock/Body::Text/Body::TextBlock arms so the unsupported shapes are no longer silently converted.src/fetcher/wikipedia/random.rs (1)
11-11: Reaching intogithub::commonfor generic option/cache/payload helpers couples unrelated fetcher families.All three Wikipedia fetchers (
random.rs,featured.rs,on_this_day.rs) importcache_key,parse_options, andpayloadfromcrate::fetcher::github::common. These are entirely generic utilities:
payload(body)wraps a Body in a Payload struct with None valuesparse_options<T>(raw)deserializes TOML via serde genericallycache_key(name, ctx, extra)builds a SHA256-hashed cache key using name/shape/format/extraNone contain GitHub-specific logic. The
github::commonmodule itself conflates two concerns: generic helpers for all fetchers alongside GitHub-specific utilities likeRepoSlugandslug_from_url()(which hard-code github.com validation).Consider promoting the generic helpers to a neutral location (e.g.
crate::fetcher::commonor alongside existing patterns incrate::fetcher::mod) so bothgithubandwikipediafamilies consume them from there. This decouples unrelated fetcher modules and isolates domain-specific code.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/wikipedia/random.rs` at line 11, The Wikipedia fetchers import generic helpers (cache_key, parse_options, payload) from crate::fetcher::github::common which couples unrelated modules; extract these three functions into a neutral module (e.g. create crate::fetcher::common or add them to crate::fetcher::mod) and update callers (random.rs, featured.rs, on_this_day.rs and any github code) to import cache_key, parse_options, and payload from the new common module instead of github::common; ensure the github::common keeps only GitHub-specific items (or re-exports the new common helpers if needed) and run the build to fix any import paths.
🤖 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/wikipedia/client.rs`:
- Around line 38-40: The URL builder rest_api_base interpolates unvalidated lang
into the host allowing host escape; add a small allowlist validator (e.g.,
validate_lang) that ensures lang only contains valid BCP47-like subtags
(lowercase ASCII letters, digits and hyphens, no dots or slashes, e.g. check
chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c=='-' ) and
length constraints like 2–35) and call it before constructing the URL (either
inside rest_api_base or immediately after parsing opts.lang in fetch_tfa,
fetch_random, and fetch_events) so any invalid lang returns an error instead of
being interpolated into the hostname.
In `@src/fetcher/wikipedia/on_this_day.rs`:
- Around line 184-191: Kind::All currently concatenates self.selected,
self.events, self.births, self.deaths, self.holidays which biases render_body's
take(limit) toward selected; replace this with an interleaving (round-robin)
builder that pulls items from each slice in order until you reach the requested
limit (or slices are exhausted) so each category gets represented; implement the
logic where Kind::All returns a Vec by looping index = 0.. and for each slice
(self.selected, self.events, self.births, self.deaths, self.holidays) push
slice.get(index).cloned() while result.len() < limit, preserving per-slice order
and stopping when no more items or limit reached; alternatively, if you prefer
not to change behavior, update the option schema/docs near render_body to
explicitly state the bias toward selected when using Kind::All.
In `@src/fetcher/wikipedia/random.rs`:
- Around line 78-80: The code currently uses
opts.lang.as_deref().unwrap_or(DEFAULT_LANG) which treats empty or
whitespace-only strings as valid and produces malformed URLs; implement a helper
fn normalize_lang(opt: Option<&str>) -> &str in super::client that trims
whitespace and returns DEFAULT_LANG when opt is None or the trimmed string is
empty, then replace uses like in random.rs (around parse_options, Options,
DEFAULT_LANG, fetch_random), featured.rs, and on_this_day.rs to call
normalize_lang(opts.lang.as_deref()) so empty or whitespace langs are normalized
to DEFAULT_LANG before building Wikipedia URLs.
---
Nitpick comments:
In `@src/fetcher/wikipedia/client.rs`:
- Around line 106-121: render_page_summary currently uses a catch-all `_` arm
that silently coerces any non-Text/TextBlock Shape into a LinkedTextBlock;
change the match to explicitly handle Shape::LinkedTextBlock and remove the `_`
fallback — for any other Shape variants either call unreachable!() (if you are
certain they cannot occur) or return a canonical sample/placeholder Body to make
the assumption explicit. Update the match in render_page_summary accordingly,
referencing the function name render_page_summary, the Shape enum and
Body::LinkedTextBlock/Body::Text/Body::TextBlock arms so the unsupported shapes
are no longer silently converted.
In `@src/fetcher/wikipedia/random.rs`:
- Line 11: The Wikipedia fetchers import generic helpers (cache_key,
parse_options, payload) from crate::fetcher::github::common which couples
unrelated modules; extract these three functions into a neutral module (e.g.
create crate::fetcher::common or add them to crate::fetcher::mod) and update
callers (random.rs, featured.rs, on_this_day.rs and any github code) to import
cache_key, parse_options, and payload from the new common module instead of
github::common; ensure the github::common keeps only GitHub-specific items (or
re-exports the new common helpers if needed) and run the build to fix any import
paths.
🪄 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: 3478b00f-7af4-454b-a22a-58859d180248
📒 Files selected for processing (6)
src/fetcher/mod.rssrc/fetcher/wikipedia/client.rssrc/fetcher/wikipedia/featured.rssrc/fetcher/wikipedia/mod.rssrc/fetcher/wikipedia/on_this_day.rssrc/fetcher/wikipedia/random.rs
| pub fn rest_api_base(lang: &str) -> String { | ||
| format!("https://{lang}.wikipedia.org{REST_API_PATH}") | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm `regex` is (or isn't) already in the dep graph.
rg -nP '^regex\s*=' Cargo.tomlRepository: unhappychoice/splashboard
Length of output: 51
🏁 Script executed:
cat -n src/fetcher/wikipedia/client.rsRepository: unhappychoice/splashboard
Length of output: 12142
🏁 Script executed:
find src/fetcher/wikipedia -name "*.rs" -type f | head -20Repository: unhappychoice/splashboard
Length of output: 233
🏁 Script executed:
grep -n "fetch_tfa\|fetch_random\|fetch_events" src/fetcher/wikipedia/*.rsRepository: unhappychoice/splashboard
Length of output: 956
🏁 Script executed:
sed -n '81,90p' src/fetcher/wikipedia/featured.rs
sed -n '143,155p' src/fetcher/wikipedia/on_this_day.rs
sed -n '80,90p' src/fetcher/wikipedia/random.rsRepository: unhappychoice/splashboard
Length of output: 1209
🏁 Script executed:
sed -n '70,95p' src/fetcher/wikipedia/featured.rs
sed -n '70,95p' src/fetcher/wikipedia/random.rsRepository: unhappychoice/splashboard
Length of output: 1946
🏁 Script executed:
grep -n "parse_options\|struct Options" src/fetcher/wikipedia/*.rs | head -20Repository: unhappychoice/splashboard
Length of output: 970
🏁 Script executed:
sed -n '35,45p' src/fetcher/wikipedia/featured.rs
sed -n '54,65p' src/fetcher/wikipedia/on_this_day.rs
sed -n '34,45p' src/fetcher/wikipedia/random.rsRepository: unhappychoice/splashboard
Length of output: 844
🏁 Script executed:
rg -n "Safety::Safe" src/fetcher/wikipedia/*.rsRepository: unhappychoice/splashboard
Length of output: 693
🏁 Script executed:
cat -n src/fetcher/wikipedia/featured.rs | sed -n '1,10p'
cat -n src/fetcher/wikipedia/on_this_day.rs | sed -n '1,10p'Repository: unhappychoice/splashboard
Length of output: 1023
🏁 Script executed:
rg -n "let lang = " src/fetcher/wikipedia/*.rsRepository: unhappychoice/splashboard
Length of output: 377
rest_api_base interpolates lang into the host without validation — the documented Safety::Safe claim doesn't hold.
format!("https://{lang}.wikipedia.org{REST_API_PATH}") accepts arbitrary characters from user config. A lang like "evil.example.com/" produces https://evil.example.com/.wikipedia.org/api/rest_v1/..., which reqwest parses as host=evil.example.com (the path becomes /.wikipedia.org/api/rest_v1/...). This breaks the explicit Safety contract documented in client.rs (line 2-4) and repeated in all three fetcher modules: "host stays inside *.wikipedia.org regardless of which language code the config supplies."
All three entry points are affected: fetch_tfa, fetch_random, and fetch_events all pull lang directly from user config and pass it to rest_api_base unvalidated.
A small allowlist validator (e.g., ^[a-z]{2,3}(-[a-z0-9]+)*$ for IETF BCP 47 subtags) would close this. Since regex is not in the dependency graph, a hand-rolled chars().all(...) check suffices.
🛡️ Suggested fix
+pub fn validate_lang(lang: &str) -> Result<&str, FetchError> {
+ // IETF BCP 47 subtag pattern: 2–3 letter language code, optionally followed by
+ // hyphenated script/region codes (e.g., "en", "zh-Hans", "pt-BR")
+ const VALID_LANG_PATTERN: &str = r"^[a-z]{2,3}(-[a-z0-9]+)*$";
+ if lang.chars().all(|c| c.is_ascii_lowercase() || c == '-')
+ && !lang.is_empty()
+ && !lang.ends_with('-')
+ && !lang.contains("--")
+ {
+ Ok(lang)
+ } else {
+ Err(FetchError::Failed(format!("invalid wikipedia lang: {lang:?}")))
+ }
+}Then call validate_lang(lang)? in rest_api_base before constructing the URL, or inline the check in each of fetch_tfa, fetch_random, and fetch_events immediately after parsing opts.lang.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/wikipedia/client.rs` around lines 38 - 40, The URL builder
rest_api_base interpolates unvalidated lang into the host allowing host escape;
add a small allowlist validator (e.g., validate_lang) that ensures lang only
contains valid BCP47-like subtags (lowercase ASCII letters, digits and hyphens,
no dots or slashes, e.g. check chars().all(|c| c.is_ascii_lowercase() ||
c.is_ascii_digit() || c=='-' ) and length constraints like 2–35) and call it
before constructing the URL (either inside rest_api_base or immediately after
parsing opts.lang in fetch_tfa, fetch_random, and fetch_events) so any invalid
lang returns an error instead of being interpolated into the hostname.
| Kind::All => { | ||
| let mut all = self.selected; | ||
| all.extend(self.events); | ||
| all.extend(self.births); | ||
| all.extend(self.deaths); | ||
| all.extend(self.holidays); | ||
| all | ||
| } |
There was a problem hiding this comment.
Kind::All ordering biases the limit toward selected and starves the other slices.
With kind = "all" and the default limit = 5, the user effectively sees only selected entries on most days because the response's selected block is concatenated first and then truncated by take(limit) in render_body. If "all" is meant to be a mixed view, consider interleaving (round-robin across the five slices) or at least documenting the bias in the option schema.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/wikipedia/on_this_day.rs` around lines 184 - 191, Kind::All
currently concatenates self.selected, self.events, self.births, self.deaths,
self.holidays which biases render_body's take(limit) toward selected; replace
this with an interleaving (round-robin) builder that pulls items from each slice
in order until you reach the requested limit (or slices are exhausted) so each
category gets represented; implement the logic where Kind::All returns a Vec by
looping index = 0.. and for each slice (self.selected, self.events, self.births,
self.deaths, self.holidays) push slice.get(index).cloned() while result.len() <
limit, preserving per-slice order and stopping when no more items or limit
reached; alternatively, if you prefer not to change behavior, update the option
schema/docs near render_body to explicitly state the bias toward selected when
using Kind::All.
| let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?; | ||
| let lang = opts.lang.as_deref().unwrap_or(DEFAULT_LANG); | ||
| let summary = fetch_random(lang).await?; |
There was a problem hiding this comment.
Empty lang string slips past the default and produces a malformed URL.
opts.lang.as_deref().unwrap_or(DEFAULT_LANG) only substitutes the default when lang is None. A user who writes lang = "" (or whitespace) gets https://.wikipedia.org/api/rest_v1/..., which fails as an opaque "wikipedia request failed" rather than a clear config error. Same code shape exists in featured.rs:80 and on_this_day.rs:138, so a small helper would cover all three.
🛡️ Suggested defensive normalization (apply at the shared call site)
- let lang = opts.lang.as_deref().unwrap_or(DEFAULT_LANG);
+ let lang = opts
+ .lang
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .unwrap_or(DEFAULT_LANG);Or, even better, add a fn normalize_lang(opt: Option<&str>) -> &str to super::client and reuse it across all three fetchers.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?; | |
| let lang = opts.lang.as_deref().unwrap_or(DEFAULT_LANG); | |
| let summary = fetch_random(lang).await?; | |
| let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?; | |
| let lang = opts | |
| .lang | |
| .as_deref() | |
| .map(str::trim) | |
| .filter(|s| !s.is_empty()) | |
| .unwrap_or(DEFAULT_LANG); | |
| let summary = fetch_random(lang).await?; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/wikipedia/random.rs` around lines 78 - 80, The code currently
uses opts.lang.as_deref().unwrap_or(DEFAULT_LANG) which treats empty or
whitespace-only strings as valid and produces malformed URLs; implement a helper
fn normalize_lang(opt: Option<&str>) -> &str in super::client that trims
whitespace and returns DEFAULT_LANG when opt is None or the trimmed string is
empty, then replace uses like in random.rs (around parse_options, Options,
DEFAULT_LANG, fetch_random), featured.rs, and on_this_day.rs to call
normalize_lang(opts.lang.as_deref()) so empty or whitespace langs are normalized
to DEFAULT_LANG before building Wikipedia URLs.
# Conflicts: # src/fetcher/mod.rs
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #152 +/- ##
==========================================
- Coverage 78.29% 78.08% -0.22%
==========================================
Files 107 112 +5
Lines 20429 21018 +589
==========================================
+ Hits 15995 16412 +417
- Misses 4434 4606 +172
🚀 New features to boost your workflow:
|
Summary
Adds the
wikipedia_*fetcher family on top of the public Wikipedia RESTAPI. Three fetchers, one shared HTTP client, all Safety::Safe.
wikipedia_on_this_day— historical events for today's MM/DD viafeed/onthisday/{kind}/{MM}/{DD}.wikipedia_featured— today's Featured Article (TFA) viafeed/featured/{YYYY}/{MM}/{DD}.wikipedia_random— a random page summary viapage/random/summary.Each fetcher emits
LinkedTextBlock(default) /TextBlock/Text—the link is the primary affordance, and the other shapes are opt-down
fallbacks for layouts that don't want OSC 8 chrome (TextBlock) or that
want a single-line distillation (Text).
Why these three together
hackernews_*shipped with one client + several fetchers in the same PR(#148). Same pattern here: one Wikipedia REST client, three sibling
fetchers. The shared
PageSummaryparses the{title, extract, content_urls, thumbnail}triplet that featured / random / on_this_dayevent-pages all return, so featured + random reuse a single rendering
helper and on_this_day reuses only
url()for per-event links.Safety: why Safe, not Network
The host stays inside
*.wikipedia.orgregardless of thelangoption —config can pick a language subdomain (
en/ja/ etc.) but can'tredirect traffic outside Wikipedia. Same shape as
github_*whererepovaries but the host staysapi.github.com.Decisions worth flagging at review
Textshape for on_this_day =selected[0]headline. Deterministicper
kind, not random — matches the rest of splashboard'sdeterminism-by-default posture (quote_of_day, calendar today). Holidays
have no
year, so the label drops theYYYY —prefix instead ofprefixing a stranded dash.
Textshape for featured / random ="<title>: <first sentence>"using a naive
". "split. Returns the trimmed extract verbatim if noperiod boundary is found.
[LinkedTextBlock, TextBlock, Text]sodefault_shape()lands onLinkedTextBlockfor every fetcher.wikipedia_randomcache TTL. Uses the runtime default(
refresh_interval) — no per-fetcher tuning. Users who want a "did youknow"-style sticky article set
refresh_intervalthemselves.Catalog: ticks
wikipedia_on_this_day/wikipedia_featured/wikipedia_randomin #67. Unblocks #150 (home_feed body 2 = on_this_day +weather; body 3 fallback uses featured).
Reference (mirrors auto-generated docs)
wikipedia_on_this_daylinked_text_block,text_block,textkind\"selected\"selectedis the curated highlights.limit5lang\"en\"/\"ja\")\"en\"Compatible renderers (per shape):
linked_text_block→list_linkstext_block→animated_boot,animated_postfx,animated_scanlines,animated_splitflap,animated_wave,list_plain,text_plaintext→animated_boot,animated_figlet_morph,animated_postfx,animated_scanlines,animated_splitflap,animated_typewriter,animated_wave,text_ascii,text_plainwikipedia_featuredlinked_text_block,text_block,textlang\"en\"\"en\".wikipedia_randomlinked_text_block,text_block,textlang\"en\"Test plan
cargo fmt --all -- --checkcargo clippy --all-targets -- -D warningscargo test(724 passed, 7 ignored)endpoints (
cargo test wikipedia -- --ignored) — confirmed payloadshapes match
PageSummary/OnThisDayResponse/FeaturedResponse.cargo run --bin splashboardwith all threefetchers in three shapes each — confirmed clickable rows, extract
preview, and headline distillation all render.
lang = "ja"onwikipedia_featured— TFAmay be sparser; reviewer can sanity-check.
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes