Skip to content

Commit 5f9f350

Browse files
unhappychoiceclaude
andcommitted
fix(fetcher/lastfm): sort lastfm_charts rows by playcount desc
`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]>
1 parent 0e1611e commit 5f9f350

1 file changed

Lines changed: 64 additions & 33 deletions

File tree

‎src/fetcher/lastfm/charts.rs‎

Lines changed: 64 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -133,33 +133,40 @@ impl Fetcher for LastfmCharts {
133133
async fn fetch_rows(kind: Kind, limit: usize) -> Result<Vec<TopRow>, FetchError> {
134134
let limit_str = limit.to_string();
135135
let params = [("limit", limit_str.as_str())];
136-
match kind {
136+
let mut rows = match kind {
137137
Kind::Artists => {
138138
let raw: ChartArtistsResponse = client::get_json(kind.method(), &params).await?;
139-
Ok(raw
140-
.artists
139+
raw.artists
141140
.artist
142141
.into_iter()
143-
.enumerate()
144-
.map(|(i, a)| artist_row(a, i))
145-
.collect())
142+
.map(artist_row)
143+
.collect::<Vec<_>>()
146144
}
147145
Kind::Tracks => {
148146
let raw: ChartTracksResponse = client::get_json(kind.method(), &params).await?;
149-
Ok(raw
150-
.tracks
147+
raw.tracks
151148
.track
152149
.into_iter()
153-
.enumerate()
154-
.map(|(i, t)| track_row(t, i))
155-
.collect())
150+
.map(track_row)
151+
.collect::<Vec<_>>()
156152
}
157-
}
153+
};
154+
// Last.fm's `chart.*` endpoints rank by global listener count, not playcount, so the
155+
// response order doesn't always match the playcount values we surface in `Bars` /
156+
// `count_label` ("N plays"). Sort by displayed metric and reassign ranks so the row
157+
// order, the rank prefix, and the bar lengths all tell the same story.
158+
rows.sort_by_key(|r| std::cmp::Reverse(r.playcount));
159+
rows.iter_mut()
160+
.enumerate()
161+
.for_each(|(i, r)| r.rank = i + 1);
162+
Ok(rows)
158163
}
159164

160-
fn artist_row(raw: RawChartArtist, index: usize) -> TopRow {
165+
fn artist_row(raw: RawChartArtist) -> TopRow {
161166
TopRow {
162-
rank: index + 1,
167+
// `rank` is reassigned by `fetch_rows` after the playcount sort; the placeholder
168+
// here just keeps the row structurally valid until then.
169+
rank: 0,
163170
primary: raw.name,
164171
secondary: None,
165172
playcount: parse_count(&raw.playcount),
@@ -168,9 +175,9 @@ fn artist_row(raw: RawChartArtist, index: usize) -> TopRow {
168175
}
169176
}
170177

171-
fn track_row(raw: RawChartTrack, index: usize) -> TopRow {
178+
fn track_row(raw: RawChartTrack) -> TopRow {
172179
TopRow {
173-
rank: index + 1,
180+
rank: 0,
174181
primary: raw.name,
175182
secondary: raw.artist.name.filter(|s| !s.is_empty()),
176183
playcount: parse_count(&raw.playcount),
@@ -359,7 +366,7 @@ mod tests {
359366
}
360367

361368
#[test]
362-
fn artist_row_assigns_position_rank_and_no_secondary() {
369+
fn artist_row_carries_primary_and_no_secondary() {
363370
let json = r##"{
364371
"artists": {
365372
"artist": [
@@ -373,14 +380,9 @@ mod tests {
373380
}
374381
}"##;
375382
let raw: ChartArtistsResponse = serde_json::from_str(json).unwrap();
376-
let rows: Vec<TopRow> = raw
377-
.artists
378-
.artist
379-
.into_iter()
380-
.enumerate()
381-
.map(|(i, a)| artist_row(a, i))
382-
.collect();
383-
assert_eq!(rows[0].rank, 1);
383+
let rows: Vec<TopRow> = raw.artists.artist.into_iter().map(artist_row).collect();
384+
// Rank stays at the placeholder until `fetch_rows` runs sort_and_rerank.
385+
assert_eq!(rows[0].rank, 0);
384386
assert_eq!(rows[0].primary, "Taylor Swift");
385387
assert!(rows[0].secondary.is_none());
386388
assert_eq!(rows[0].playcount, 12_400_000);
@@ -406,19 +408,48 @@ mod tests {
406408
}
407409
}"##;
408410
let raw: ChartTracksResponse = serde_json::from_str(json).unwrap();
409-
let rows: Vec<TopRow> = raw
410-
.tracks
411-
.track
412-
.into_iter()
413-
.enumerate()
414-
.map(|(i, t)| track_row(t, i))
415-
.collect();
416-
assert_eq!(rows[0].rank, 1);
411+
let rows: Vec<TopRow> = raw.tracks.track.into_iter().map(track_row).collect();
412+
assert_eq!(rows[0].rank, 0);
417413
assert_eq!(rows[0].primary, "Anti-Hero");
418414
assert_eq!(rows[0].secondary.as_deref(), Some("Taylor Swift"));
419415
assert_eq!(rows[0].playcount, 5_400_000);
420416
}
421417

418+
#[tokio::test]
419+
async fn fetch_rows_reorders_unsorted_api_responses_by_playcount() {
420+
// Last.fm's `chart.*` endpoints rank by listener count, not playcount, so any
421+
// playcount-based renderer (chart_bar, list_ranking) needs the rows sorted by the
422+
// metric we surface. This locks the post-parse ordering contract.
423+
//
424+
// We exercise it by parsing a hand-crafted out-of-order JSON through the same
425+
// `artist_row` + sort path `fetch_rows` uses, since touching the network from a
426+
// unit test isn't an option.
427+
let json = r##"{
428+
"artists": {
429+
"artist": [
430+
{"name": "Mid", "playcount": "300", "url": "https://x", "image": []},
431+
{"name": "Top", "playcount": "1000", "url": "https://x", "image": []},
432+
{"name": "Low", "playcount": "100", "url": "https://x", "image": []}
433+
]
434+
}
435+
}"##;
436+
let raw: ChartArtistsResponse = serde_json::from_str(json).unwrap();
437+
let mut rows: Vec<TopRow> = raw.artists.artist.into_iter().map(artist_row).collect();
438+
rows.sort_by_key(|r| std::cmp::Reverse(r.playcount));
439+
rows.iter_mut()
440+
.enumerate()
441+
.for_each(|(i, r)| r.rank = i + 1);
442+
443+
assert_eq!(rows[0].primary, "Top");
444+
assert_eq!(rows[0].rank, 1);
445+
assert_eq!(rows[1].primary, "Mid");
446+
assert_eq!(rows[1].rank, 2);
447+
assert_eq!(rows[2].primary, "Low");
448+
assert_eq!(rows[2].rank, 3);
449+
assert!(rows[0].playcount >= rows[1].playcount);
450+
assert!(rows[1].playcount >= rows[2].playcount);
451+
}
452+
422453
#[test]
423454
fn empty_label_differs_per_kind() {
424455
assert_eq!(Kind::Artists.empty_label(), "no chart artists");

0 commit comments

Comments
 (0)