sonda/internal/catalog/catalog.go
tgiachi f6a4166849 fix(catalog): keep albums apart, align album counts, reject bad search text
- fix(storage): tracks of two albums with the same title (Greatest Hits, Live)
  no longer interleave in a listing: the album id is part of the order
- fix(storage): an artist's album_count and GET /albums?artist_id= now mean
  the same thing: albums the artist owns plus albums where it is credited on a
  playable track; a property test checks it for every artist and library
- fix(catalog): a NUL byte or invalid UTF-8 in q is a 400 instead of a broken
  SQL statement and a 500
- fix(api): clamp paging values with math.MaxInt32 so the package also builds
  on 32-bit targets
- docs: search ignores case, including accented letters, but not accents
  ("bjork" does not find "Bjork"); the earlier comments said otherwise
- test: same-title albums across a page boundary, NUL and invalid UTF-8
2026-11-11 13:47:31 +01:00

182 lines
4.9 KiB
Go

// Package catalog is the read side of the library: browsing and searching
// artists, albums and tracks.
//
// Only tracks with at least one file that is not flagged missing are visible,
// so everything the catalog shows can be played. File paths are never part of
// the data returned here.
package catalog
import (
"context"
"errors"
"fmt"
"strings"
"unicode/utf8"
)
// Errors returned by the service.
var (
ErrNotFound = errors.New("not found")
ErrInvalidQuery = errors.New("invalid query")
)
// Paging and search bounds.
const (
DefaultLimit = 50
MaxLimit = 200
MaxQueryLen = 200 // characters
)
// Filter selects and pages a list. Zero IDs mean "any". Each list uses the
// fields that make sense for it and ignores the others.
type Filter struct {
Query string // case-insensitive substring of the name or title (accents are kept)
LibraryID int64 // only items with a playable file in this library
ArtistID int64 // albums: album artist; tracks: credited artist
AlbumID int64 // tracks only
Limit int
Offset int
}
// Page is one page of a list together with the size of the whole result.
type Page[T any] struct {
Items []T
Total int
Limit int
Offset int
}
// ArtistRef and AlbumRef are the short forms used inside other items.
type ArtistRef struct {
ID int64
Name string
}
type AlbumRef struct {
ID int64
Title string
}
// Artist is an artist with the amount of music that can be played.
type Artist struct {
ID int64
Name string
AlbumCount int
TrackCount int
}
// Album is an album with its album artist, if it has one.
type Album struct {
ID int64
Title string
Artist *ArtistRef
TrackCount int
DurationMs int64
}
// Track is a playable track. Format is that of its first playable file.
type Track struct {
ID int64
Title string
DurationMs int64
TrackNo int
DiscNo int
Album *AlbumRef
Artists []ArtistRef
Format string
}
// Store reads the catalog. Lists are ordered deterministically and must load
// related data in batches. Get methods return ErrNotFound for an id that does
// not exist or has nothing playable.
type Store interface {
ListArtists(ctx context.Context, f Filter) (Page[Artist], error)
ListAlbums(ctx context.Context, f Filter) (Page[Album], error)
ListTracks(ctx context.Context, f Filter) (Page[Track], error)
GetArtist(ctx context.Context, id int64) (Artist, error)
GetAlbum(ctx context.Context, id int64) (Album, error)
GetTrack(ctx context.Context, id int64) (Track, error)
}
// Service validates queries and reads the catalog.
type Service struct{ store Store }
// NewService builds a Service.
func NewService(store Store) *Service { return &Service{store: store} }
// normalize validates f and fills in the paging defaults.
func normalize(f Filter) (Filter, error) {
if f.Limit < 0 || f.Offset < 0 {
return f, fmt.Errorf("%w: limit and offset cannot be negative", ErrInvalidQuery)
}
if f.LibraryID < 0 || f.ArtistID < 0 || f.AlbumID < 0 {
return f, fmt.Errorf("%w: ids cannot be negative", ErrInvalidQuery)
}
switch {
case f.Limit == 0:
f.Limit = DefaultLimit
case f.Limit > MaxLimit:
f.Limit = MaxLimit
}
// The text ends up inside the SQL statement text: a NUL byte cannot be
// represented there, and PostgreSQL rejects bytes that are not UTF-8.
if strings.IndexByte(f.Query, 0) >= 0 || !utf8.ValidString(f.Query) {
return f, fmt.Errorf("%w: q is not valid text", ErrInvalidQuery)
}
f.Query = strings.TrimSpace(f.Query)
if utf8.RuneCountInString(f.Query) > MaxQueryLen {
return f, fmt.Errorf("%w: q is longer than %d characters", ErrInvalidQuery, MaxQueryLen)
}
return f, nil
}
// Artists lists artists that have something playable.
func (s *Service) Artists(ctx context.Context, f Filter) (Page[Artist], error) {
f, err := normalize(f)
if err != nil {
return Page[Artist]{}, err
}
return s.store.ListArtists(ctx, f)
}
// Albums lists albums that have something playable.
func (s *Service) Albums(ctx context.Context, f Filter) (Page[Album], error) {
f, err := normalize(f)
if err != nil {
return Page[Album]{}, err
}
return s.store.ListAlbums(ctx, f)
}
// Tracks lists playable tracks.
func (s *Service) Tracks(ctx context.Context, f Filter) (Page[Track], error) {
f, err := normalize(f)
if err != nil {
return Page[Track]{}, err
}
return s.store.ListTracks(ctx, f)
}
// Artist returns one artist.
func (s *Service) Artist(ctx context.Context, id int64) (Artist, error) {
if id <= 0 {
return Artist{}, ErrNotFound
}
return s.store.GetArtist(ctx, id)
}
// Album returns one album.
func (s *Service) Album(ctx context.Context, id int64) (Album, error) {
if id <= 0 {
return Album{}, ErrNotFound
}
return s.store.GetAlbum(ctx, id)
}
// Track returns one track.
func (s *Service) Track(ctx context.Context, id int64) (Track, error) {
if id <= 0 {
return Track{}, ErrNotFound
}
return s.store.GetTrack(ctx, id)
}