chore: remove code left from acquisition and Discover suggestions, and uncalled queries

Nothing reached any of it:
- MusicBrainz search (artists, albums, songs), artist lookups and the
  query escaping they used. The release-group lookups the duplicate
  resolver uses stay.
- Release-group covers, and artist-level tags for artists not in the
  library.
- Nine named queries with no caller (CountTracksByArtist went with the
  previous commit), two of them describing request-progress reporting.

The MusicBrainz client's retry and not-found tests now drive the
release-group lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 22:02:00 -05:00
co-authored by Claude Opus 5.5
parent 987c2a68fa
commit 14aa3dcd5e
28 changed files with 10 additions and 817 deletions
-35
View File
@@ -8,7 +8,6 @@ import (
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
@@ -173,37 +172,3 @@ func sleep(ctx context.Context, d time.Duration) error {
return nil
}
}
// luceneSpecial are the characters MusicBrainz's search syntax gives meaning.
const luceneSpecial = `+-&|!(){}[]^"~*?:\/`
// Escape makes text typed by a person safe to put in a search query, so
// "AM/FM" or "Moon O)))" searches for what was typed rather than failing to
// parse.
func Escape(s string) string {
var b strings.Builder
for _, r := range s {
if strings.ContainsRune(luceneSpecial, r) {
b.WriteByte('\\')
}
b.WriteRune(r)
}
return b.String()
}
// fieldQuery searches each field for the escaped text.
func fieldQuery(text string, fields ...string) string {
t := Escape(strings.TrimSpace(text))
parts := make([]string, len(fields))
for i, f := range fields {
parts[i] = f + ":(" + t + ")"
}
return strings.Join(parts, " OR ")
}
func searchLimit(limit int) string {
if limit <= 0 || limit > 100 {
limit = 25
}
return strconv.Itoa(limit)
}
+6 -121
View File
@@ -3,10 +3,8 @@ package musicbrainz
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"sync/atomic"
"testing"
"time"
@@ -17,119 +15,6 @@ func testClient(srv *httptest.Server) *Client {
return &Client{BaseURL: srv.URL, Pace: &Pacer{}, Backoff: time.Millisecond}
}
func TestEscape_KeepsWhatWasTyped(t *testing.T) {
for in, want := range map[string]string{
"Signal Tower": "Signal Tower",
"AM/FM": `AM\/FM`,
"Moon O)))": `Moon O\)\)\)`,
`"Odd" Al`: `\"Odd\" Al`,
} {
if got := Escape(in); got != want {
t.Errorf("Escape(%q) = %q, want %q", in, got, want)
}
}
}
func TestSearchReleaseGroups_AsksTitleAndArtistAndReadsCredits(t *testing.T) {
var query, agent atomic.Value
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query.Store(r.URL.Query().Get("query"))
agent.Store(r.Header.Get("User-Agent"))
_, _ = w.Write([]byte(`{"release-groups": [{
"id": "rg1", "title": "OK Calculator", "primary-type": "Album", "secondary-types": [],
"first-release-date": "1997-05-21",
"artist-credit": [{"name": "Signal Tower", "joinphrase": "", "artist": {"id": "a1", "name": "Signal Tower"}}]
}]}`))
}))
defer srv.Close()
got, err := testClient(srv).SearchReleaseGroups(context.Background(), "ok calculator", 10)
if err != nil {
t.Fatal(err)
}
if q := query.Load(); q != "releasegroup:(ok calculator) OR artist:(ok calculator)" {
t.Errorf("query = %q", q)
}
if agent.Load() != UserAgent {
t.Errorf("User-Agent = %q", agent.Load())
}
if len(got) != 1 || got[0].MBID != "rg1" || got[0].Year() != "1997" || got[0].ArtistCredit != "Signal Tower" || got[0].ArtistMBIDs[0] != "a1" {
t.Errorf("got %+v", got)
}
}
func TestSearchReleaseGroupsBy_AsksForBothTitleAndArtist(t *testing.T) {
var query atomic.Value
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query.Store(r.URL.Query().Get("query"))
_, _ = w.Write([]byte(`{"release-groups": [{"id": "rg1", "title": "Highway to Nowhere",
"artist-credit": [{"name": "AM/FM", "artist": {"id": "a1"}}]}]}`))
}))
defer srv.Close()
got, err := testClient(srv).SearchReleaseGroupsBy(context.Background(), " AM/FM ", "Highway to Nowhere", 10)
if err != nil {
t.Fatal(err)
}
if q := query.Load(); q != `releasegroup:(Highway to Nowhere) AND artist:(AM\/FM)` {
t.Errorf("query = %q", q)
}
if len(got) != 1 || got[0].MBID != "rg1" || got[0].ArtistMBIDs[0] != "a1" {
t.Errorf("got %+v", got)
}
}
func TestSearchRecordings_FilesASongUnderItsAlbum(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"recordings": [{
"id": "rec1", "title": "Karma Patrol", "length": 264000,
"artist-credit": [{"name": "Signal Tower", "artist": {"id": "a1"}}],
"releases": [
{"id": "r1", "status": "Official", "release-group": {"id": "rg-live", "title": "Live", "primary-type": "Album", "secondary-types": ["Live"]}},
{"id": "r2", "status": "Official", "release-group": {"id": "rg1", "title": "OK Calculator", "primary-type": "Album"}}
]
}]}`))
}))
defer srv.Close()
got, err := testClient(srv).SearchRecordings(context.Background(), "karma patrol", 5)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].ReleaseGroup.MBID != "rg1" || got[0].LengthMs != 264000 {
t.Errorf("got %+v, want it filed under the studio album", got)
}
}
func TestArtistReleaseGroups_PagesUntilTheCount(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
if r.URL.Query().Get("artist") != "a1" {
t.Errorf("artist = %q", r.URL.Query().Get("artist"))
}
// 3 in all, two per page.
var items string
for i := offset; i < offset+2 && i < 3; i++ {
if items != "" {
items += ","
}
items += fmt.Sprintf(`{"id": "rg%d", "title": "T%d", "primary-type": "Album"}`, i, i)
}
_, _ = fmt.Fprintf(w, `{"release-group-count": 3, "release-groups": [%s]}`, items)
}))
defer srv.Close()
got, err := testClient(srv).ArtistReleaseGroups(context.Background(), "a1")
if err != nil {
t.Fatal(err)
}
if len(got) != 3 || calls.Load() != 2 {
t.Errorf("got %d groups in %d calls, want 3 in 2", len(got), calls.Load())
}
}
func TestReleaseGroupReleases_ReadsMediaAndTracks(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("inc") != "media recordings" {
@@ -171,12 +56,12 @@ func TestGet_ThrottleIsRetriedThenUnreachable(t *testing.T) {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
_, _ = w.Write([]byte(`{"artists": [{"id": "a1", "name": "Signal Tower"}]}`))
_, _ = w.Write([]byte(`{"id": "rg1", "title": "Paper Boats"}`))
}))
defer srv.Close()
got, err := testClient(srv).SearchArtists(context.Background(), "signal tower", 5)
if err != nil || len(got) != 1 || calls.Load() != 2 {
got, err := testClient(srv).ReleaseGroup(context.Background(), "rg1")
if err != nil || got.Title != "Paper Boats" || calls.Load() != 2 {
t.Fatalf("a throttled first answer should be retried: %v, %+v, %d calls", err, got, calls.Load())
}
@@ -184,7 +69,7 @@ func TestGet_ThrottleIsRetriedThenUnreachable(t *testing.T) {
w.WriteHeader(http.StatusBadGateway)
}))
defer down.Close()
if _, err := testClient(down).SearchArtists(context.Background(), "x", 5); !errors.Is(err, ErrUnreachable) {
if _, err := testClient(down).ReleaseGroup(context.Background(), "rg1"); !errors.Is(err, ErrUnreachable) {
t.Errorf("err = %v, want ErrUnreachable", err)
}
}
@@ -193,13 +78,13 @@ func TestGet_NotFoundAndNoServer(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
if _, err := testClient(srv).Artist(context.Background(), "nope"); !errors.Is(err, ErrNotFound) {
if _, err := testClient(srv).ReleaseGroup(context.Background(), "nope"); !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound", err)
}
srv.Close()
c := testClient(srv)
c.Retries = -1
if _, err := c.Artist(context.Background(), "a1"); !errors.Is(err, ErrUnreachable) {
if _, err := c.ReleaseGroup(context.Background(), "rg1"); !errors.Is(err, ErrUnreachable) {
t.Errorf("a closed server: err = %v, want ErrUnreachable", err)
}
}
-185
View File
@@ -7,16 +7,6 @@ import (
"strings"
)
// Artist is a MusicBrainz artist.
type Artist struct {
MBID string
Name string
SortName string
Disambiguation string
Type string // Person, Group, Orchestra, …; may be empty
Country string
}
// ReleaseGroup is what a person calls an album: one work, released any
// number of times.
type ReleaseGroup struct {
@@ -31,14 +21,6 @@ type ReleaseGroup struct {
ArtistMBIDs []string
}
// Year is the first release's year, or "".
func (g ReleaseGroup) Year() string {
if len(g.FirstReleaseDate) >= 4 {
return g.FirstReleaseDate[:4]
}
return ""
}
// Release is one issue of a release group: a pressing, an edition, a
// digital release, each with its own track list.
type Release struct {
@@ -98,18 +80,6 @@ type Track struct {
RecordingMBID string
}
// Recording is a piece of audio, as a search returns it.
type Recording struct {
MBID string
Title string
LengthMs int
ArtistCredit string
ArtistMBIDs []string
// ReleaseGroup is the group the recording is best known from: the first
// official album it appears on, else the first release listed.
ReleaseGroup ReleaseGroup
}
// --- wire shapes ---
type wireCredit struct {
@@ -138,19 +108,6 @@ func credit(cs []wireCredit) (string, []string) {
return b.String(), ids
}
type wireArtist struct {
ID string `json:"id"`
Name string `json:"name"`
SortName string `json:"sort-name"`
Disambiguation string `json:"disambiguation"`
Type string `json:"type"`
Country string `json:"country"`
}
func (w wireArtist) artist() Artist {
return Artist{MBID: w.ID, Name: w.Name, SortName: w.SortName, Disambiguation: w.Disambiguation, Type: w.Type, Country: w.Country}
}
type wireReleaseGroup struct {
ID string `json:"id"`
Title string `json:"title"`
@@ -192,7 +149,6 @@ type wireRelease struct {
Format string `json:"format"`
Tracks []wireTrack `json:"tracks"`
} `json:"media"`
ReleaseGroup *wireReleaseGroup `json:"release-group"`
}
func (w wireRelease) release() Release {
@@ -217,149 +173,8 @@ func (w wireRelease) release() Release {
return r
}
// --- searches ---
// SearchArtists finds artists by name or alias.
func (c *Client) SearchArtists(ctx context.Context, text string, limit int) ([]Artist, error) {
var resp struct {
Artists []wireArtist `json:"artists"`
}
q := url.Values{"query": {fieldQuery(text, "artist", "alias")}, "limit": {searchLimit(limit)}}
if err := c.get(ctx, "/artist", q, &resp); err != nil {
return nil, err
}
out := make([]Artist, 0, len(resp.Artists))
for _, a := range resp.Artists {
out = append(out, a.artist())
}
return out, nil
}
// SearchReleaseGroups finds albums by title or by artist, so "signal tower ok
// computer" and "ok calculator" both find OK Calculator.
func (c *Client) SearchReleaseGroups(ctx context.Context, text string, limit int) ([]ReleaseGroup, error) {
var resp struct {
ReleaseGroups []wireReleaseGroup `json:"release-groups"`
}
q := url.Values{"query": {fieldQuery(text, "releasegroup", "artist")}, "limit": {searchLimit(limit)}}
if err := c.get(ctx, "/release-group", q, &resp); err != nil {
return nil, err
}
out := make([]ReleaseGroup, 0, len(resp.ReleaseGroups))
for _, g := range resp.ReleaseGroups {
out = append(out, g.group())
}
return out, nil
}
// SearchReleaseGroupsBy finds an artist's albums by title: both must
// match, where SearchReleaseGroups takes either. It is for naming an album
// already in hand, not for a person's search box.
func (c *Client) SearchReleaseGroupsBy(ctx context.Context, artist, title string, limit int) ([]ReleaseGroup, error) {
var resp struct {
ReleaseGroups []wireReleaseGroup `json:"release-groups"`
}
query := "releasegroup:(" + Escape(strings.TrimSpace(title)) + ") AND artist:(" + Escape(strings.TrimSpace(artist)) + ")"
q := url.Values{"query": {query}, "limit": {searchLimit(limit)}}
if err := c.get(ctx, "/release-group", q, &resp); err != nil {
return nil, err
}
out := make([]ReleaseGroup, 0, len(resp.ReleaseGroups))
for _, g := range resp.ReleaseGroups {
out = append(out, g.group())
}
return out, nil
}
// SearchRecordings finds songs by title or by artist.
func (c *Client) SearchRecordings(ctx context.Context, text string, limit int) ([]Recording, error) {
var resp struct {
Recordings []struct {
ID string `json:"id"`
Title string `json:"title"`
Length *int `json:"length"`
ArtistCredit []wireCredit `json:"artist-credit"`
Releases []wireRelease `json:"releases"`
} `json:"recordings"`
}
q := url.Values{"query": {fieldQuery(text, "recording", "artist")}, "limit": {searchLimit(limit)}}
if err := c.get(ctx, "/recording", q, &resp); err != nil {
return nil, err
}
out := make([]Recording, 0, len(resp.Recordings))
for _, r := range resp.Recordings {
name, ids := credit(r.ArtistCredit)
rec := Recording{MBID: r.ID, Title: r.Title, ArtistCredit: name, ArtistMBIDs: ids}
if r.Length != nil {
rec.LengthMs = *r.Length
}
rec.ReleaseGroup = bestKnownFrom(r.Releases)
out = append(out, rec)
}
return out, nil
}
// bestKnownFrom picks the release group a recording should be filed under
// in a search result: the first official album, else the first release.
func bestKnownFrom(releases []wireRelease) ReleaseGroup {
var first *wireReleaseGroup
for _, r := range releases {
if r.ReleaseGroup == nil || r.ReleaseGroup.ID == "" {
continue
}
if first == nil {
first = r.ReleaseGroup
}
if r.Status == "Official" && r.ReleaseGroup.PrimaryType == "Album" && len(r.ReleaseGroup.SecondaryTypes) == 0 {
return r.ReleaseGroup.group()
}
}
if first == nil {
return ReleaseGroup{}
}
return first.group()
}
// --- lookups and browses ---
// Artist looks one artist up by MBID.
func (c *Client) Artist(ctx context.Context, mbid string) (Artist, error) {
var w wireArtist
if err := c.get(ctx, "/artist/"+url.PathEscape(mbid), nil, &w); err != nil {
return Artist{}, err
}
if w.ID == "" {
return Artist{}, ErrBadResponse
}
return w.artist(), nil
}
// ArtistReleaseGroups lists every release group the artist is credited on,
// paging through MusicBrainz's browse.
func (c *Client) ArtistReleaseGroups(ctx context.Context, artistMBID string) ([]ReleaseGroup, error) {
var out []ReleaseGroup
for page := 0; page < maxPages; page++ {
var resp struct {
Count int `json:"release-group-count"`
ReleaseGroups []wireReleaseGroup `json:"release-groups"`
}
q := url.Values{
"artist": {artistMBID}, "inc": {"artist-credits"},
"limit": {strconv.Itoa(pageSize)}, "offset": {strconv.Itoa(len(out))},
}
if err := c.get(ctx, "/release-group", q, &resp); err != nil {
return nil, err
}
for _, g := range resp.ReleaseGroups {
out = append(out, g.group())
}
if len(resp.ReleaseGroups) == 0 || len(out) >= resp.Count {
break
}
}
return out, nil
}
// ReleaseGroupReleases lists every release of a release group with its
// media and track lists.
func (c *Client) ReleaseGroupReleases(ctx context.Context, groupMBID string) ([]Release, error) {