Skip to content

feat(fetcher): wikipedia_* family — on_this_day / featured / random - #152

Merged
unhappychoice merged 2 commits into
mainfrom
feat/wikipedia-fetchers
Apr 26, 2026
Merged

unhappychoice merged 2 commits into
mainfrom
feat/wikipedia-fetchers

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Apr 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the wikipedia_* fetcher family on top of the public Wikipedia REST
API. Three fetchers, one shared HTTP client, all Safety::Safe.

  • wikipedia_on_this_day — historical events for today's MM/DD via
    feed/onthisday/{kind}/{MM}/{DD}.
  • wikipedia_featured — today's Featured Article (TFA) via
    feed/featured/{YYYY}/{MM}/{DD}.
  • wikipedia_random — a random page summary via
    page/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 PageSummary parses the {title, extract, content_urls, thumbnail} triplet that featured / random / on_this_day
event-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.org regardless of the lang option —
config can pick a language subdomain (en / ja / etc.) but can't
redirect traffic outside Wikipedia. Same shape as github_* where
repo varies but the host stays api.github.com.

Decisions worth flagging at review

  • Text shape for on_this_day = selected[0] headline. Deterministic
    per kind, not random — matches the rest of splashboard's
    determinism-by-default posture (quote_of_day, calendar today). Holidays
    have no year, so the label drops the YYYY — prefix instead of
    prefixing a stranded dash.
  • Text shape for featured / random = "<title>: <first sentence>"
    using a naive ". " split. Returns the trimmed extract verbatim if no
    period boundary is found.
  • Shape ordering. [LinkedTextBlock, TextBlock, Text] so
    default_shape() lands on LinkedTextBlock for every fetcher.
  • wikipedia_random cache TTL. Uses the runtime default
    (refresh_interval) — no per-fetcher tuning. Users who want a "did you
    know"-style sticky article set refresh_interval themselves.

Catalog: ticks wikipedia_on_this_day / wikipedia_featured /
wikipedia_random in #67. Unblocks #150 (home_feed body 2 = on_this_day +
weather; body 3 fallback uses featured).

Reference (mirrors auto-generated docs)

wikipedia_on_this_day

  • Kind: cached
  • Safety: Safe
  • Shapes: linked_text_block, text_block, text
Option Type Required Default Description
kind `"selected" | "events" | "births" | "deaths" | "holidays" | "all"` no \"selected\" Which slice of the on-this-day feed to fetch. selected is the curated highlights.
limit integer (1..=30) no 5 Maximum number of events to display.
lang string (Wikipedia language code, e.g. \"en\" / \"ja\") no \"en\" Wikipedia language edition to query.

Compatible renderers (per shape):

  • linked_text_block → list_links
  • text_block → animated_boot, animated_postfx, animated_scanlines, animated_splitflap, animated_wave, list_plain, text_plain
  • text → animated_boot, animated_figlet_morph, animated_postfx, animated_scanlines, animated_splitflap, animated_typewriter, animated_wave, text_ascii, text_plain

wikipedia_featured

  • Kind: cached
  • Safety: Safe
  • Shapes: linked_text_block, text_block, text
Option Type Required Default Description
lang string (Wikipedia language code) no \"en\" Wikipedia language edition. The TFA endpoint is best populated for \"en\".

wikipedia_random

  • Kind: cached
  • Safety: Safe
  • Shapes: linked_text_block, text_block, text
Option Type Required Default Description
lang string (Wikipedia language code) no \"en\" Wikipedia language edition.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets -- -D warnings
  • cargo test (724 passed, 7 ignored)
  • Live smoke tests against the real Wikipedia REST API for all three
    endpoints (cargo test wikipedia -- --ignored) — confirmed payload
    shapes match PageSummary / OnThisDayResponse / FeaturedResponse.
  • Local smoke test: cargo run --bin splashboard with all three
    fetchers in three shapes each — confirmed clickable rows, extract
    preview, and headline distillation all render.
  • Verify rendering with lang = "ja" on wikipedia_featured — TFA
    may be sparser; reviewer can sanity-check.

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features
    • Added Wikipedia integration with three new fetchers: Featured Article (daily featured content), On This Day (historical events, births, deaths, and holidays), and Random Page summary.
    • Support for multiple languages and configurable output formats (text preview, text block, linked content).
    • Intelligent caching for improved performance and reduced API calls.

…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]>
@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 3 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e30e7623-8fdd-4ff7-a38a-4d9b267b382e

📥 Commits

Reviewing files that changed from the base of the PR and between 9743585 and ffac4f1.

📒 Files selected for processing (1)
  • src/fetcher/mod.rs
📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
Module Registration
src/fetcher/mod.rs
Adds pub mod wikipedia and extends Registry::with_builtins() to register all Wikipedia fetchers.
Shared Wikipedia Client
src/fetcher/wikipedia/client.rs
Provides centralized HTTP client, REST API base URL construction, JSON deserialization, PageSummary struct, URL/sentence extraction utilities, and shape-based rendering logic for page summaries.
Wikipedia Fetcher Implementations
src/fetcher/wikipedia/featured.rs, src/fetcher/wikipedia/on_this_day.rs, src/fetcher/wikipedia/random.rs
Three fetcher implementations (Featured Article, On This Day, Random Page) that parse TOML options, construct REST API endpoints, fetch data, parse responses, and render summaries into multiple Shape formats via the shared client.
Module Exports
src/fetcher/wikipedia/mod.rs
Defines pub mod client, pub mod featured, pub mod on_this_day, pub mod random and exports a fetchers() function that returns the three fetcher implementations.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • #28: Adds the foundational fetcher framework and trait system that these Wikipedia fetchers implement.
  • #114: Demonstrates the same pattern of adding a new fetcher module and registering it in Registry::with_builtins().
  • #88: Shows parallel fetcher module addition and registry extension pattern.

Poem

🐰 Hopping through Wikipedia's halls,
Three new fetchers answer the calls,
Featured, random, and days gone by,
Knowledge fetched from the web on high! 📚
Shared clients help them dance and play,
Splashboard learns more each day!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.53% 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 summarizes the main change: addition of three Wikipedia fetchers (on_this_day, featured, random) to the fetcher family, which is the primary focus of this 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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/wikipedia-fetchers

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

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

@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: 3

🧹 Nitpick comments (2)
src/fetcher/wikipedia/client.rs (1)

106-121: render_page_summary's catch-all silently coerces unsupported shapes into LinkedTextBlock.

The match arm _ => Body::LinkedTextBlock(...) accepts any of the 11 non-Text/TextBlock Shape variants. The runtime is supposed to validate shape pairings against shapes() before reaching this point, so in practice only LinkedTextBlock lands 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 either unreachable!() 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 into github::common for generic option/cache/payload helpers couples unrelated fetcher families.

All three Wikipedia fetchers (random.rs, featured.rs, on_this_day.rs) import cache_key, parse_options, and payload from crate::fetcher::github::common. These are entirely generic utilities:

  • payload(body) wraps a Body in a Payload struct with None values
  • parse_options<T>(raw) deserializes TOML via serde generically
  • cache_key(name, ctx, extra) builds a SHA256-hashed cache key using name/shape/format/extra

None contain GitHub-specific logic. The github::common module itself conflates two concerns: generic helpers for all fetchers alongside GitHub-specific utilities like RepoSlug and slug_from_url() (which hard-code github.com validation).

Consider promoting the generic helpers to a neutral location (e.g. crate::fetcher::common or alongside existing patterns in crate::fetcher::mod) so both github and wikipedia families 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a0d9f8 and 9743585.

📒 Files selected for processing (6)
  • src/fetcher/mod.rs
  • src/fetcher/wikipedia/client.rs
  • src/fetcher/wikipedia/featured.rs
  • src/fetcher/wikipedia/mod.rs
  • src/fetcher/wikipedia/on_this_day.rs
  • src/fetcher/wikipedia/random.rs

Comment on lines +38 to +40
pub fn rest_api_base(lang: &str) -> String {
format!("https://{lang}.wikipedia.org{REST_API_PATH}")
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm `regex` is (or isn't) already in the dep graph.
rg -nP '^regex\s*=' Cargo.toml

Repository: unhappychoice/splashboard

Length of output: 51


🏁 Script executed:

cat -n src/fetcher/wikipedia/client.rs

Repository: unhappychoice/splashboard

Length of output: 12142


🏁 Script executed:

find src/fetcher/wikipedia -name "*.rs" -type f | head -20

Repository: unhappychoice/splashboard

Length of output: 233


🏁 Script executed:

grep -n "fetch_tfa\|fetch_random\|fetch_events" src/fetcher/wikipedia/*.rs

Repository: 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.rs

Repository: 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.rs

Repository: unhappychoice/splashboard

Length of output: 1946


🏁 Script executed:

grep -n "parse_options\|struct Options" src/fetcher/wikipedia/*.rs | head -20

Repository: 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.rs

Repository: unhappychoice/splashboard

Length of output: 844


🏁 Script executed:

rg -n "Safety::Safe" src/fetcher/wikipedia/*.rs

Repository: 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/*.rs

Repository: 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.

Comment on lines +184 to +191
Kind::All => {
let mut all = self.selected;
all.extend(self.events);
all.extend(self.births);
all.extend(self.deaths);
all.extend(self.holidays);
all
}

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 | 🟡 Minor

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.

Comment on lines +78 to +80
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?;

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 | 🟡 Minor

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.

Suggested change
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.

@unhappychoice
unhappychoice merged commit c4e8ee2 into main Apr 26, 2026
@unhappychoice
unhappychoice deleted the feat/wikipedia-fetchers branch April 26, 2026 07:13
@codecov

codecov Bot commented Apr 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.79796% with 172 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.08%. Comparing base (4a0d9f8) to head (ffac4f1).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/wikipedia/on_this_day.rs 76.02% 64 Missing ⚠️
src/fetcher/wikipedia/featured.rs 43.42% 43 Missing ⚠️
src/fetcher/wikipedia/random.rs 37.50% 35 Missing ⚠️
src/fetcher/wikipedia/client.rs 83.42% 30 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Files with missing lines Coverage Δ
src/fetcher/mod.rs 83.49% <100.00%> (+0.15%) ⬆️
src/fetcher/wikipedia/mod.rs 100.00% <100.00%> (ø)
src/fetcher/wikipedia/client.rs 83.42% <83.42%> (ø)
src/fetcher/wikipedia/random.rs 37.50% <37.50%> (ø)
src/fetcher/wikipedia/featured.rs 43.42% <43.42%> (ø)
src/fetcher/wikipedia/on_this_day.rs 76.02% <76.02%> (ø)
🚀 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.

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