Skip to content

feat(fetcher): add lastfm_* family (5 fetchers + shared scaffold) - #248

Merged
unhappychoice merged 8 commits into
mainfrom
feat/lastfm-family
May 19, 2026
Merged

unhappychoice merged 8 commits into
mainfrom
feat/lastfm-family

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the lastfm_* fetcher family — five fetchers covering a Last.fm user's daily listening statistics plus the global "what the world is playing right now" chart. Ticks the lastfm_* candidates on the catalog roadmap (#67).

name what it shows
1 lastfm_scrobbles_today Today's scrobbles + currently-playing track
2 lastfm_top_artists Top artists for a rolling window (7day/1month/.../overall)
3 lastfm_top_tracks Top tracks, same period contract
4 lastfm_top_albums Top albums, same period contract (album artwork in ImageLinkedList)
5 lastfm_charts Global chart of top artists or top tracks across every Last.fm scrobble

Safety: All five are Safety::Safe. Host is hardcoded (ws.audioscrobbler.com); config-provided fields (user, period, kind, …) only change which resource within the fixed host is queried. Same model as github_*.

Auth: LASTFM_API_KEY (free, https://www.last.fm/api/account/create). Drop it in $HOME/.splashboard/secrets.toml.

Shared infra: One PR, six commits — client.rs + common.rs + top.rs factor out the cross-sibling code so each top_* sibling is ~200 lines and adds the same 10 shapes through a single rendering surface.

Compatible with these renderers (from generated docs)

lastfm_scrobbles_today

Today's scrobbles for a Last.fm user, with the currently-playing track surfaced when one is in flight. Reads user.getRecentTracks since UTC midnight; intentionally bounded to today so the cached splash doesn't drift across day boundaries.

Kind Safety Shapes
cached Safe linked_text_block, image_linked_list, text_block, text, markdown_text_block, entries, badge, timeline
Option Type Required Default Description
user string yes — Last.fm username whose scrobbles to read.
limit integer (1..=50) no 10 Maximum number of recently scrobbled tracks to show (excluding the currently-playing slot).

Renderers: list_links, list_cards, list_plain, list_timeline, text_plain, text_ascii, text_markdown, grid_table, status_badge, plus the animated_* post-process wrappers.

lastfm_top_artists

Top artists for a Last.fm user over a rolling window (7day default, also 1month / 3month / 6month / 12month / overall). Mirrors the profile page's Top Artists tab.

Kind Safety Shapes
cached Safe linked_text_block, image_linked_list, text_block, text, markdown_text_block, entries, ratio, number_series, bars, badge
Option Type Required Default Description
user string yes — Last.fm username whose top artists to read.
period "7day" | "1month" | "3month" | "6month" | "12month" | "overall" no "7day" Rolling window for the ranking.
limit integer (1..=50) no 10 Number of artists to display.

Renderers: list_links, list_cards, list_plain, list_ranking, text_plain, text_ascii, text_markdown, grid_table, gauge_battery, gauge_circle, gauge_line, gauge_segment, gauge_thermometer, chart_bar, chart_pie, chart_sparkline, chart_histogram, status_badge, plus the animated_* post-process wrappers.

lastfm_top_tracks

Top tracks for a Last.fm user over a rolling window. Mirrors the profile page's Top Tracks tab.

Same shape table + option contract as lastfm_top_artists. Row mapping pulls the artist into the secondary label so titles render as "Track — Artist" automatically.

lastfm_top_albums

Top albums for a Last.fm user over a rolling window. Mirrors the profile page's Top Albums tab. ImageLinkedList carries the album artwork from Last.fm's image set.

Same shape table + option contract as lastfm_top_artists. Album artwork is consistently populated by Last.fm (more than for individual tracks), so the list_cards rendering is where this sibling pulls ahead visually.

lastfm_charts

Last.fm's global chart of top artists or top tracks across every scrobble — "what the world is listening to right now". No user binding, no rolling window. The Last.fm slot in the *_trending family alongside crypto_trending / huggingface_trending.

Kind Safety Shapes
cached Safe linked_text_block, image_linked_list, text_block, text, markdown_text_block, entries, bars
Option Type Required Default Description
kind "artists" | "tracks" no "artists" Which Last.fm chart to rank.
limit integer (1..=50) no 10 Number of chart entries to display.

Renderers: list_links, list_cards, list_plain, list_ranking, text_plain, text_ascii, text_markdown, grid_table, chart_bar, chart_pie, plus the animated_* post-process wrappers.

Note on sort order: chart.* endpoints rank by listener count, not playcount, so the response order doesn't always match the playcount values we surface. fetch_rows sorts by playcount descending and reassigns ranks after parsing so row order, rank prefix, and chart_bar length all tell the same story. Caught during the smoke test (commit 5f9f350).

Implementation notes

  • Shared client (lastfm/client.rs): fixed-host HTTP + LASTFM_API_KEY resolution + a get_json helper that detects Last.fm's HTTP-200 error envelope ({"error":N,"message":...}) before deserializing into the caller's target type.
  • Shared top.rs rendering surface factors the playcount-ranked-list shape table out of the three lastfm_top_* siblings so each one stays around 200 lines. Period (SevenDay default), TopRow, and one helper per shape live there; siblings only carry the per-endpoint DTO + parse path.
  • user.getRecentTracks vs user.getTopTracks use different artist representations ({"#text": "..."} vs {"name": "..."}); each sibling carries its own DTO since attempting to unify them adds more complexity than the duplication.
  • Image filtering: Last.fm tags artwork-less entities with a known placeholder hash (2a96cbd8b46e442fc41c2b86b821562f). common::best_image filters it out so an ImageLinkedList of placeholder-only rows doesn't surface the same gray square on every row.

Test plan

  • cargo test — 2840+ tests pass (113 new under fetcher::lastfm).
  • cargo clippy --all-targets -- -D warnings — clean.
  • cargo fmt --all -- --check — clean.
  • cargo run --bin splashboard -- catalog fetcher lastfm_scrobbles_today (and siblings) — every fetcher exposes the expected shape list + option schema.
  • Smoke-test against the real Last.fm API via a throwaway .splashboard/dashboard.toml exercising every sibling at the LinkedTextBlock / Bars / ImageLinkedList / Ratio / Badge shapes. Confirmed end-to-end with LASTFM_API_KEY set.

Catalog

Ticks the following candidates on #67:

  • lastfm_scrobbles_today
  • lastfm_top_artist_week (generalised to lastfm_top_artists with a period option — _week becomes period = "7day")
  • new: lastfm_top_tracks, lastfm_top_albums, lastfm_charts (sibling expansions matching Last.fm's user.getTop* and chart.* endpoint set; the music_charts open box can also tick on the lastfm side)

Catalog body update will land on merge.

🤖 Generated with Claude Code

Summary by CodeRabbit

New Features

  • Integrated Last.fm API providing access to global music charts displaying top artists and tracks worldwide, user's scrobbled tracks for today, and personalized period-based top lists for artists, tracks, and albums with customizable display formats including text, images, badges, and more.

Review Change Stack

unhappychoice and others added 8 commits May 19, 2026 21:15
Introduces the `lastfm_*` family with the first sibling: today's scrobbles for a
Last.fm user, surfacing the currently-playing track when one is in flight.

Shared infrastructure for the family is split into two modules so the
subsequent `lastfm_top_*` and `lastfm_charts` siblings can reuse it without
churn:

- `lastfm/client.rs`: fixed-host HTTP (`ws.audioscrobbler.com`), API key
  resolution from `LASTFM_API_KEY`, and a `get_json` helper that detects
  Last.fm's HTTP-200 error envelope (`{"error":N,"message":...}`) before
  handing bytes to the caller's deserializer.
- `lastfm/common.rs`: image-URL picking that filters the well-known
  placeholder hash so `ImageLinkedList` rows don't all share the same gray
  square, plus count parsing and `k/M` formatting helpers.

`lastfm_scrobbles_today` accepts a required `user` and an optional `limit`
(1..=50, default 10), reads `user.getRecentTracks?from=midnight-UTC-today`,
and emits 8 shapes: LinkedTextBlock (default) / ImageLinkedList / TextBlock
/ Text / MarkdownTextBlock / Entries / Badge / Timeline. Refresh interval
is 5 minutes so the splash reflects "what I'm playing now" within a coffee
break.

Ratio / NumberSeries / PointSeries / Bars / Image / Calendar / Heatmap
deliberately rejected: no natural denominator, no chronological-ranking
contract, and the "top tracks today" Bars angle is the territory of the
follow-up `lastfm_top_tracks` sibling.

Safety: `Safety::Safe`. Same model as `github_*` — the host never moves;
`user` only picks which resource within `ws.audioscrobbler.com` is queried.

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

Lifts the playcount-ranked-list rendering surface out of the upcoming
`lastfm_top_artists` / `top_tracks` / `top_albums` siblings so each one
stays around 200 lines and adds the same 10 shapes via a common code path
rather than three near-identical copies.

- `Period` enum mirrors Last.fm's accepted `period` values (`7day` /
  `1month` / `3month` / `6month` / `12month` / `overall`), default
  `SevenDay`. `as_param` keeps the param mapping explicit so a future
  serde rename can't drift one side.
- `TopRow` normalises the three sibling endpoints into one row shape:
  rank, primary label (artist / track / album), optional secondary label
  (artist for tracks/albums), playcount, URL, optional image URL.
- Per-shape helpers cover Text / TextBlock / MarkdownTextBlock /
  LinkedTextBlock / ImageLinkedList / Entries / Ratio (top share +
  denominator) / NumberSeries / Bars / Badge. `image_linked_body` calls
  through `thumbnails::download_many` so artwork is cached once per URL
  across siblings.
- Empty-list handling lives in this module: helpers accept an
  `empty_label` argument so each sibling can phrase its quiet-window
  fallback ("no top tracks this 7d", etc.) without duplicating the
  Option-empty branching.

No consumers yet — the next commits wire `top_artists`, `top_tracks`, and
`top_albums` against this surface in turn.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
First consumer of the shared `lastfm/top.rs` rendering surface: a user's
top artists for a rolling window via `user.getTopArtists`.

Options: required `user`, optional `period` (default `"7day"`, also
`"1month"` / `"3month"` / `"6month"` / `"12month"` / `"overall"`),
optional `limit` (1..=50, default 10).

Shapes (10): LinkedTextBlock (default) / ImageLinkedList / TextBlock /
Text / MarkdownTextBlock / Entries / Ratio (top artist's share of the
window total, denominator carrying the sum) / NumberSeries (playcounts
as a sparkline) / Bars / Badge.

Rank prefers Last.fm's own `@attr.rank` when present, falling back to
the 1-indexed position so a malformed response still renders rather
than disappearing. Playcounts that don't parse collapse to zero
(`parse_count` shared from `common`).

Cache key partitions on period + shape so switching `"7day"` to
`"1month"` doesn't serve a stale snapshot.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sibling of `lastfm_top_artists`: a user's top tracks for a rolling
window via `user.getTopTracks`. Same option contract (`user` / `period`
/ `limit`) and same 10 shapes via the shared `lastfm/top.rs` surface.

Difference from `top_artists` lives in the row mapping: the API nests
the artist as a proper `{"name": "..."}` object (rather than the
`{"#text": "..."}` form `user.getRecentTracks` uses), so each row's
secondary label populates from `artist.name`. Empty strings collapse to
`None` so a malformed response renders the track without a stray
trailing dash.

Rendering helpers receive `secondary = Some(artist)` and emit
`"Track — Artist"` titles automatically — no per-sibling rewrite of
the row format.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Third user-stats sibling: a user's top albums for a rolling window via
`user.getTopAlbums`. Same option contract (`user` / `period` / `limit`)
and same 10 shapes via the shared `lastfm/top.rs` surface.

Row mapping mirrors `lastfm_top_tracks` exactly — both endpoints return
`{name, playcount, artist: {name}, url, image, @attr: {rank}}` rows,
just under a different envelope key (`topalbums.album` vs
`toptracks.track`). Album titles surface as `"Album — Artist"` via the
shared secondary-label rendering.

Album artwork via the `image` array is the only practical difference at
the user-facing level: `ImageLinkedList` rows show the actual cover art
because Last.fm consistently populates `image` for albums (unlike tracks
where the array is often only the placeholder).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Last sibling of the `lastfm_*` batch: Last.fm's global "right now" chart
of top artists or top tracks across every scrobble. The Last.fm slot in
the `*_trending` family alongside `crypto_trending` /
`huggingface_trending` / `wikipedia_trending` / `reddit_trending`.

Options: `kind = "artists" | "tracks"` (default `artists`),
`limit` (1..=50, default 10). No `user`, no `period` — `chart.*`
endpoints don't carry either.

Shapes (7): LinkedTextBlock (default) / ImageLinkedList / TextBlock /
Text / MarkdownTextBlock / Entries / Bars. Matches the
`huggingface_trending` shape table exactly. Deliberately drops
Ratio / NumberSeries / Badge / Timeline: those carry user-binding
semantics ("your top share", "your daily activity") that don't apply
to a world-wide chart, and including them with stand-in values would
read as fake.

Per-kind branching lives inside `fetch_rows` (one endpoint per kind,
each with its own DTO since Last.fm's `chart.getTopArtists` returns
naked artists while `chart.getTopTracks` nests `{artist: {name}}` —
same shape difference as the `user.getTop*` siblings).

Closes the lastfm_* batch — 5 fetchers across one PR, sharing the
`client.rs` + `common.rs` + `top.rs` scaffold introduced earlier in
the branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The `_helpers_reference_check` function and accompanying `top::self`
import were a stale defensive measure from when I was unsure whether
the dead_code lint would flag direct-by-name imports of unused
helpers. Every helper is actually invoked by `render_body` or
`sample_body`, so the function is dead weight — top_tracks /
top_albums / charts ship without it and compile cleanly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`chart.getTopArtists` / `chart.getTopTracks` rank globally by listener
count, not by playcount, so the response order doesn't always match the
playcount values we surface in `count_label` ("N plays") or `Bars`. The
result is a "world chart" widget where row 2 looks bigger than row 1
under `chart_bar`, or rank prefixes drift from the visible numbers.

Sort by playcount descending after parsing and reassign 1-indexed ranks
so the row order, the rank prefix, and the bar length all tell the same
story. `artist_row` / `track_row` now mint rows with a placeholder rank
that `fetch_rows` overwrites once the order is settled.

`user.getTop*` siblings don't have this issue: those endpoints sort by
the user's own playcount by definition, which is exactly the metric we
display.

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

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces a complete Last.fm fetcher family with five integrated fetchers: charts (global top artists/tracks), scrobbles today (user's recent activity), and top artists/tracks/albums (user's top-ranked entities by period). All share a unified HTTP client, rendering helpers, and registry wiring.

Changes

Last.fm Fetcher Family

Layer / File(s) Summary
HTTP client and common helpers
src/fetcher/lastfm/client.rs, src/fetcher/lastfm/common.rs
Singleton reqwest::Client with API key resolution, JSON response parsing with Last.fm error-envelope detection, plus shared utilities for best-image selection, count parsing/formatting, and pluralization.
Shared top- rendering model and helpers*
src/fetcher/lastfm/top.rs
Normalized TopRow data model and Period enum, with rendering helpers for text, markdown, linked text, image lists, entries, ratio, bars, and badge output shapes.
Top artists fetcher
src/fetcher/lastfm/top_artists.rs
Retrieves user top artists via user.getTopArtists with configurable period/limit, maps API responses into TopRow, renders via shared helpers, includes sample generation and comprehensive tests.
Top tracks fetcher
src/fetcher/lastfm/top_tracks.rs
Retrieves user top tracks via user.getTopTracks with period/limit configuration, extracts nested artist names into secondary labels, uses shared rendering and full validation suite.
Top albums fetcher
src/fetcher/lastfm/top_albums.rs
Retrieves user top albums via user.getTopAlbums, maps album/artist names to TopRow primary/secondary labels, delegates to shared renderers and includes sample/test coverage.
Scrobbles today fetcher
src/fetcher/lastfm/scrobbles_today.rs
Displays user tracks scrobbled since midnight UTC via user.getRecentTracks, detects/prioritizes now-playing, enforces limit with truncation, renders across multiple shapes with timestamp fallbacks and empty-state handling.
Charts fetcher with playcount reordering
src/fetcher/lastfm/charts.rs
Global charts for top artists/tracks via chart.getTop*, supports kind/limit configuration, re-sorts and re-ranks rows by displayed playcount metric (overriding API listener-count ordering), includes sample bodies and reranking validation tests.
Module entrypoint and registry wiring
src/fetcher/lastfm/mod.rs, src/fetcher/mod.rs
Exposes five Last.fm fetchers via fetchers(), registers them in the built-in fetcher registry alongside other families.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • unhappychoice/splashboard#28: Establishes the async fetcher runtime and Fetcher trait that the Last.fm family implements and extends.
  • unhappychoice/splashboard#234: Also extends Registry::with_builtins() to register a new built-in fetcher family (net::*), following the same registration pattern used here.
  • unhappychoice/splashboard#161: Introduces the required Fetcher::description() trait method that all five Last.fm fetchers implement.

Poem

🐰 Last.fm hops so deep, from charts to scrobbles bright,
TopRows ranked and reordered, now-playing takes flight,
Five fetchers hop together, HTTP client leads the way,
Shared helpers parse the playcounts—splashboard learns to play! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.96% 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 clearly and concisely summarizes the main change: adding a family of five Last.fm fetchers with shared infrastructure, using standard conventional commit format.
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/lastfm-family

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.

@codecov

codecov Bot commented May 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.03371% with 333 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.80%. Comparing base (e5bdf6b) to head (5f9f350).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/fetcher/lastfm/scrobbles_today.rs 86.28% 79 Missing ⚠️
src/fetcher/lastfm/top.rs 80.47% 57 Missing ⚠️
src/fetcher/lastfm/top_albums.rs 85.07% 40 Missing ⚠️
src/fetcher/lastfm/top_artists.rs 85.96% 40 Missing ⚠️
src/fetcher/lastfm/top_tracks.rs 85.34% 40 Missing ⚠️
src/fetcher/lastfm/charts.rs 86.77% 39 Missing ⚠️
src/fetcher/lastfm/client.rs 70.31% 38 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #248      +/-   ##
==========================================
- Coverage   95.17%   94.80%   -0.38%     
==========================================
  Files         222      231       +9     
  Lines       58658    60883    +2225     
==========================================
+ Hits        55830    57722    +1892     
- Misses       2828     3161     +333     
Files with missing lines Coverage Δ
src/fetcher/lastfm/common.rs 100.00% <100.00%> (ø)
src/fetcher/lastfm/mod.rs 100.00% <100.00%> (ø)
src/fetcher/mod.rs 99.00% <100.00%> (+<0.01%) ⬆️
src/fetcher/lastfm/client.rs 70.31% <70.31%> (ø)
src/fetcher/lastfm/charts.rs 86.77% <86.77%> (ø)
src/fetcher/lastfm/top_albums.rs 85.07% <85.07%> (ø)
src/fetcher/lastfm/top_artists.rs 85.96% <85.96%> (ø)
src/fetcher/lastfm/top_tracks.rs 85.34% <85.34%> (ø)
src/fetcher/lastfm/top.rs 80.47% <80.47%> (ø)
src/fetcher/lastfm/scrobbles_today.rs 86.28% <86.28%> (ø)
🚀 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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fetcher/lastfm/client.rs`:
- Around line 73-84: In parse_json (async fn parse_json<T: DeserializeOwned>),
stop calling res.bytes() which buffers the whole body; instead iterate the
response stream with res.chunk() (or .bytes_stream()) and accumulate chunks into
a buffer while checking the cumulative size with saturating_add against
MAX_BYTES before appending so you can return Err(FetchError::Failed(...)) as
soon as the limit would be exceeded; after the loop deserialize from the
accumulated buffer to T and preserve the existing error wrapping for
read/deserialize failures.

In `@src/fetcher/lastfm/top.rs`:
- Around line 177-179: Replace usages of r.primary in image/badge title
formatting with r.display_title() so the rendered titles include artist context;
e.g. change format!("#{} {}", r.rank, r.primary) to format!("#{} {}", r.rank,
r.display_title()) in the ImageLinkedItem construction and make the same swap at
the other mapped renderer (the block around lines 255-257) so all image/badge
renderers use display_title() consistently.
🪄 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: 06ac9070-bdf0-4fd5-8aa2-bf063e76622d

📥 Commits

Reviewing files that changed from the base of the PR and between 04d8ce5 and 5f9f350.

📒 Files selected for processing (10)
  • src/fetcher/lastfm/charts.rs
  • src/fetcher/lastfm/client.rs
  • src/fetcher/lastfm/common.rs
  • src/fetcher/lastfm/mod.rs
  • src/fetcher/lastfm/scrobbles_today.rs
  • src/fetcher/lastfm/top.rs
  • src/fetcher/lastfm/top_albums.rs
  • src/fetcher/lastfm/top_artists.rs
  • src/fetcher/lastfm/top_tracks.rs
  • src/fetcher/mod.rs

Comment on lines +73 to +84
async fn parse_json<T: DeserializeOwned>(res: reqwest::Response) -> Result<T, FetchError> {
let status = res.status();
let bytes = res
.bytes()
.await
.map_err(|e| FetchError::Failed(format!("lastfm read body: {e}")))?;
if bytes.len() > MAX_BYTES {
return Err(FetchError::Failed(format!(
"lastfm response too large ({} bytes, cap {MAX_BYTES})",
bytes.len()
)));
}

@coderabbitai coderabbitai Bot May 19, 2026 •

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

🧩 Analysis chain

🌐 Web query:

In reqwest 0.12, does Response::bytes() buffer the entire body in memory, and is Response::chunk() appropriate for enforcing a strict max response size during reads?

💡 Result:

In reqwest 0.12, Response::bytes does buffer the entire response body in memory. Its implementation collects the full body into a Bytes value (it calls BodyExt::collect on the response body) [1]. Response::chunk is appropriate for enforcing a strict max response size during reads, because it streams the body incrementally (it returns Option chunks until the response body is exhausted) [2][1]. You can accumulate the received chunk lengths and stop with an error once you exceed your maximum; unlike bytes, chunk avoids collecting the whole body up front [2][1]. Note: reqwest itself doesn’t expose a built-in “max response bytes” wrapper on Response::chunk in the core API; the common approach is to enforce the limit while iterating chunks, or use a separate limited-body wrapper. An upstream discussion suggests wrapping the response body with http_body_util::Limited as an alternative/middleware approach [3].

Citations:


🏁 Script executed:

# Check the actual file and lines around 73-84
cat -n src/fetcher/lastfm/client.rs | sed -n '70,90p'

Repository: unhappychoice/splashboard

Length of output: 991


🏁 Script executed:

# Find MAX_BYTES constant
rg "MAX_BYTES" src/fetcher/lastfm/client.rs -B 2 -A 2

Repository: unhappychoice/splashboard

Length of output: 564


🏁 Script executed:

# Check if there are similar streaming patterns in the codebase
rg "chunk\(\)" src/ -t rs -A 3 | head -50

Repository: unhappychoice/splashboard

Length of output: 96


🏁 Script executed:

# Search for chunk() usage patterns with correct syntax
rg "chunk()" src/ -A 3 -B 1 2>/dev/null | head -50

Repository: unhappychoice/splashboard

Length of output: 3355


🏁 Script executed:

# Also check the full parse_json function to understand context better
cat -n src/fetcher/lastfm/client.rs | sed -n '73,100p'

Repository: unhappychoice/splashboard

Length of output: 1381


Use streaming-based response size enforcement, not post-buffer checks.

Line 76 calls .bytes() which buffers the entire response body in memory before line 79 applies the MAX_BYTES check. This allows the full 5 MB payload to be allocated even when the limit is enforced. Per reqwest 0.12 API, Response::chunk() supports incremental streaming, enabling the size limit to be enforced while reading rather than after.

The suggested fix using a while let Some(chunk) loop with saturating_add is correct: it checks the cumulative size before each append and returns early if the limit would be exceeded, preventing large allocations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/lastfm/client.rs` around lines 73 - 84, In parse_json (async fn
parse_json<T: DeserializeOwned>), stop calling res.bytes() which buffers the
whole body; instead iterate the response stream with res.chunk() (or
.bytes_stream()) and accumulate chunks into a buffer while checking the
cumulative size with saturating_add against MAX_BYTES before appending so you
can return Err(FetchError::Failed(...)) as soon as the limit would be exceeded;
after the loop deserialize from the accumulated buffer to T and preserve the
existing error wrapping for read/deserialize failures.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Skipping in this PR — adopting streaming chunk() only here would split the codebase into two response-handling patterns while the rest of the fetcher/ family (huggingface_trending, crypto_trending, crypto_watchlist, stock_watchlist, random_cat, random_dog, nasa_apod, youtube, ...) all use the same res.bytes() then post-buffer length check.

The practical risk is bounded: ws.audioscrobbler.com is a fixed host, the MAX_BYTES cap is 5 MB, and a real Last.fm response is KB-scale. The right place to harden this is a cross-cutting refactor that adds a fetcher::http::get_capped_json helper and migrates every Network-class fetcher to it in one go, so the family stays consistent. Tracking that separately.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@unhappychoice, that's a sound call — keeping the family consistent and doing the hardening as a single cross-cutting refactor (a shared fetcher::http::get_capped_json helper) is a much cleaner path than patching one fetcher in isolation.

Would you like me to open a GitHub issue to track the cross-cutting refactor? I can capture the motivation, the affected fetchers, and the proposed get_capped_json helper shape so it's ready to pick up whenever you get to it.

🐇 (nodding thoughtfully)

Comment thread src/fetcher/lastfm/top.rs
Comment on lines +177 to +179
.map(|(r, path)| ImageLinkedItem {
title: format!("#{} {}", r.rank, r.primary),
url: Some(r.url.clone()),

@coderabbitai coderabbitai Bot May 19, 2026 •

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 | ⚡ Quick win

Use display_title() in image/badge renderers to keep track/album titles consistent.

Line 178 and Line 256 use only primary, which drops artist context for tracks/albums and diverges from the Track — Artist title contract used elsewhere.

💡 Suggested fix
 pub async fn image_linked_body(rows: &[TopRow]) -> Body {
@@
         .zip(paths)
         .map(|(r, path)| ImageLinkedItem {
-            title: format!("#{} {}", r.rank, r.primary),
+            title: format!("#{} {}", r.rank, r.display_title()),
             url: Some(r.url.clone()),
             thumbnail_path: path.map(|p| p.to_string_lossy().into_owned()),
             subtitle: subtitle(r),
         })
         .collect();
@@
 pub fn badge_body(rows: &[TopRow], period: Period) -> Body {
     let (status, label) = match rows.first() {
-        Some(top) => (Status::Ok, format!("`#1` {}", top.primary)),
+        Some(top) => (Status::Ok, format!("`#1` {}", top.display_title())),
         None => (Status::Warn, format!("quiet ({})", period.label())),
     };
     Body::Badge(BadgeData { status, label })
 }

Also applies to: 255-257

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/lastfm/top.rs` around lines 177 - 179, Replace usages of
r.primary in image/badge title formatting with r.display_title() so the rendered
titles include artist context; e.g. change format!("#{} {}", r.rank, r.primary)
to format!("#{} {}", r.rank, r.display_title()) in the ImageLinkedItem
construction and make the same swap at the other mapped renderer (the block
around lines 255-257) so all image/badge renderers use display_title()
consistently.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Skipping in this PR — the title/subtitle split here is intentional, and applying display_title() to both renderers introduces problems:

image_linked_body (line 178): the artist already lives in the row's subtitle (see subtitle() at line 187), so top_tracks renders as title #1 Strawberry Swing + subtitle Coldplay · 120 plays. Swapping to display_title() makes it #1 Strawberry Swing — Coldplay + the same subtitle, duplicating the artist on every row. That matches what huggingface_trending::image_linked_body does too (title = entity id, subtitle = meta) — the family convention is single-tier titles, with the secondary metadata pushed below.

badge_body (line 256): badges are deliberately compact pills. scrobbles_today::badge_body does the same (♪ {nowp.name} — artist deliberately dropped). clock_state, gauge_battery, and linear_cycle badges are all short labels for the same reason. top_artists has no secondary so display_title() is a no-op there; for top_tracks/top_albums the artist context belongs in the multi-row shapes (linked_text_block rows, text_block lines), not in a single-pill status indicator.

If the duplication-on-image-cards angle ever flips (e.g. we redesign list_cards to drop the subtitle column), we can revisit.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@unhappychoice, that's a clear and well-reasoned explanation — the subtitle-carries-secondary convention for image cards and the compact-pill contract for badges both make sense, and the huggingface_trending / scrobbles_today parallels confirm this is intentional family-wide behaviour rather than an oversight. Happy to withdraw the suggestion.

Would you like me to resolve this review comment?

(°ヘ°) 🐰


✏️ Learnings added
Learnt from: unhappychoice
Repo: unhappychoice/splashboard PR: 248
File: src/fetcher/lastfm/top.rs:177-179
Timestamp: 2026-05-19T13:30:21.964Z
Learning: In `src/fetcher/lastfm/top.rs`, `image_linked_body` intentionally uses only `r.primary` (not `display_title()`) for the `ImageLinkedItem` title. The secondary/artist label is already rendered in the `subtitle()` helper (which appends it alongside playcount), so using `display_title()` would duplicate the artist. This mirrors the `huggingface_trending::image_linked_body` family convention: title = entity name, subtitle = meta/secondary.

Learnt from: unhappychoice
Repo: unhappychoice/splashboard PR: 248
File: src/fetcher/lastfm/top.rs:177-179
Timestamp: 2026-05-19T13:30:21.964Z
Learning: In `src/fetcher/lastfm/top.rs`, `badge_body` intentionally uses only `top.primary` (not `display_title()`) for the badge label. Badges are compact pills and deliberately drop the secondary/artist context, consistent with `scrobbles_today::badge_body` and other badge renderers (`clock_state`, `gauge_battery`, `linear_cycle`). Full titles (with secondary) belong in multi-row shapes like `linked_text_block` and `text_block`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@unhappychoice
unhappychoice merged commit 1768208 into main May 19, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/lastfm-family branch May 19, 2026 13:31
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