sonda/internal/storage/playlists_test.go
tgiachi f900a22904 feat(playlists): a user keeps playlists of tracks
Each user can make playlists: a name (1 to 200 characters), an optional
description and an ordered list of tracks, where a track may appear more than once
(each place has its own item id). The API makes, lists, renames and deletes
playlists, and adds tracks (at the end or at a position), lists them, moves one and
removes one; positions count from 0 without gaps.

A playlist is its owner's alone: somebody else's answers playlist_not_found (404),
as one that does not exist. A track whose files were deleted or moved stays in the
playlist and is listed with available false. Deleting a user deletes their
playlists. Limits: 1,000 playlists per user, 10,000 tracks per playlist, 500 tracks
per request.

Changes of one playlist are serialised by locking its row, so two requests at once
keep the positions unique on PostgreSQL too. Migration 0019, OpenAPI spec, contract
test, README and the web API types follow. The web app comes separately.

Closes #89
2026-11-12 16:55:25 +01:00

449 lines
15 KiB
Go

package storage
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/playlists"
)
// plEnv is two users and four tracks (a, b, c, d), each 60 seconds long.
type plEnv struct {
t *testing.T
db *bun.DB
repo *PlaylistRepo
alice int64
bob int64
tracks map[string]int64
now time.Time
}
func newPlEnv(t *testing.T, db *bun.DB) *plEnv {
t.Helper()
ctx := context.Background()
users := NewUserRepo(db)
a, err := users.CreateUser(ctx, "alice@example.org", "hash", false)
if err != nil {
t.Fatal(err)
}
b, err := users.CreateUser(ctx, "bob@example.org", "hash", false)
if err != nil {
t.Fatal(err)
}
lib := NewLibraryRepo(db)
l, err := lib.CreateLibrary(ctx, "m", "/lib/m")
if err != nil {
t.Fatal(err)
}
e := &plEnv{t: t, db: db, repo: NewPlaylistRepo(db), alice: a.ID, bob: b.ID, tracks: map[string]int64{}, now: time.Unix(1_700_000_000, 0)}
for i, title := range []string{"a", "b", "c", "d"} {
if _, err := lib.SaveFile(ctx, l.ID, pf("x/"+title+".flac", title, "Album", "Band", i+1, 1, "flac", "Band"), 0); err != nil {
t.Fatal(err)
}
var id int64
if err := db.QueryRow("SELECT id FROM tracks WHERE title = ?", title).Scan(&id); err != nil {
t.Fatal(err)
}
e.tracks[title] = id
}
return e
}
// tick moves the clock on, so "changed last" has an order.
func (e *plEnv) tick() time.Time { e.now = e.now.Add(time.Minute); return e.now }
func (e *plEnv) create(user int64, name string) playlists.Playlist {
e.t.Helper()
p, err := e.repo.Create(context.Background(), user, name, "", e.tick())
if err != nil {
e.t.Fatal(err)
}
return p
}
// add puts tracks by name (at the end when pos < 0).
func (e *plEnv) add(user, id int64, pos int, names ...string) (playlists.Playlist, error) {
e.t.Helper()
ids := make([]int64, len(names))
for i, n := range names {
ids[i] = e.tracks[n]
}
var p *int
if pos >= 0 {
p = &pos
}
return e.repo.AddTracks(context.Background(), user, id, ids, p, e.tick())
}
// order is the titles of a playlist in order.
func (e *plEnv) order(user, id int64) []string {
e.t.Helper()
items, total, err := e.repo.Items(context.Background(), user, id, 1000, 0)
if err != nil {
e.t.Fatal(err)
}
if total != len(items) {
e.t.Fatalf("total = %d, items = %d", total, len(items))
}
out := make([]string, len(items))
for i, it := range items {
if it.Position != i {
e.t.Fatalf("item %d has position %d: positions must count from 0 without gaps", i, it.Position)
}
out[i] = it.Track.Title
}
return out
}
func (e *plEnv) itemIDs(id int64) []int64 {
e.t.Helper()
items, _, err := e.repo.Items(context.Background(), e.alice, id, 1000, 0)
if err != nil {
e.t.Fatal(err)
}
ids := make([]int64, len(items))
for i, it := range items {
ids[i] = it.ID
}
return ids
}
func plBackends(t *testing.T, fn func(t *testing.T, e *plEnv)) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { fn(t, newPlEnv(t, db)) })
}
func TestPlaylistsAreCreatedListedAndKeptApartPerUser(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
first := e.create(e.alice, "First")
second := e.create(e.alice, "Second")
other := e.create(e.bob, "Bobs")
if first.ID == 0 || first.Name != "First" || first.TrackCount != 0 || first.DurationMs != 0 || first.CreatedAt.IsZero() {
t.Errorf("first = %+v", first)
}
got, total, err := e.repo.List(ctx, e.alice, 10, 0)
if err != nil || total != 2 || len(got) != 2 || got[0].ID != second.ID || got[1].ID != first.ID {
t.Fatalf("list = %+v total %d err %v: the one changed last comes first", got, total, err)
}
// Changing the first one puts it on top.
if _, err := e.add(e.alice, first.ID, -1, "a"); err != nil {
t.Fatal(err)
}
got, _, _ = e.repo.List(ctx, e.alice, 10, 0)
if got[0].ID != first.ID || got[0].TrackCount != 1 || got[0].DurationMs != 60000 {
t.Errorf("after adding: %+v", got[0])
}
if page, total, _ := e.repo.List(ctx, e.alice, 1, 1); len(page) != 1 || total != 2 || page[0].ID != second.ID {
t.Errorf("page 2 = %+v total %d", page, total)
}
if _, err := e.repo.Get(ctx, e.alice, other.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user's playlist: err = %v, want ErrNotFound", err)
}
if _, err := e.repo.Get(ctx, e.alice, 99999); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
if mine, total, _ := e.repo.List(ctx, e.bob, 10, 0); total != 1 || mine[0].ID != other.ID {
t.Errorf("bob sees %+v", mine)
}
})
}
func TestAddingAtTheEndAndInTheMiddleKeepsTheOrderWithoutGaps(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
p := e.create(e.alice, "P")
got, err := e.add(e.alice, p.ID, -1, "a", "b", "a")
if err != nil || got.TrackCount != 3 || got.DurationMs != 180000 {
t.Fatalf("playlist = %+v err %v", got, err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "b", "a"}) {
t.Fatalf("order = %v: a track can be there twice", o)
}
if ids := e.itemIDs(p.ID); ids[0] == ids[2] {
t.Error("the same track twice must be two items")
}
if _, err := e.add(e.alice, p.ID, 1, "c", "d"); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "c", "d", "b", "a"}) {
t.Errorf("order = %v, want c and d at 1 and 2", o)
}
if _, err := e.add(e.alice, p.ID, 0, "d"); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"d", "a", "c", "d", "b", "a"}) {
t.Errorf("order = %v, want d first", o)
}
if _, err := e.add(e.alice, p.ID, 6, "b"); err != nil { // the end, as a position
t.Errorf("a position at the end: %v", err)
}
if _, err := e.add(e.alice, p.ID, 8, "b"); !errors.Is(err, playlists.ErrPosition) {
t.Errorf("a position beyond the end: err = %v, want ErrPosition", err)
}
})
}
func TestAddingAnUnknownTrackOrToAnotherUsersPlaylistChangesNothing(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.repo.AddTracks(ctx, e.alice, p.ID, []int64{e.tracks["a"], 99999}, nil, e.tick()); !errors.Is(err, playlists.ErrTrackNotFound) {
t.Errorf("unknown track: err = %v", err)
}
if o := e.order(e.alice, p.ID); len(o) != 0 {
t.Errorf("order = %v: nothing must be added when one track is unknown", o)
}
if _, err := e.add(e.bob, p.ID, -1, "a"); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user's playlist: err = %v", err)
}
if _, err := e.add(e.alice, 99999, -1, "a"); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
})
}
func TestRemovingAnItemClosesTheGap(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
other := e.create(e.alice, "Other")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
if _, err := e.add(e.alice, other.ID, -1, "a"); err != nil {
t.Fatal(err)
}
ids := e.itemIDs(p.ID)
if err := e.repo.RemoveItem(ctx, e.alice, p.ID, ids[1], e.tick()); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "c", "d"}) {
t.Errorf("order = %v", o)
}
if err := e.repo.RemoveItem(ctx, e.alice, p.ID, ids[1], e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("a second time: err = %v", err)
}
if err := e.repo.RemoveItem(ctx, e.alice, other.ID, ids[0], e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("an item of another playlist: err = %v", err)
}
if err := e.repo.RemoveItem(ctx, e.bob, p.ID, ids[0], e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != 3 || got.DurationMs != 180000 {
t.Errorf("after removing: %+v", got)
}
})
}
func TestMovingAnItem(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
move := func(from, to int) error {
return e.repo.MoveItem(ctx, e.alice, p.ID, e.itemIDs(p.ID)[from], to, e.tick())
}
for _, step := range []struct {
from, to int
want []string
}{
{0, 2, []string{"b", "c", "a", "d"}},
{3, 0, []string{"d", "b", "c", "a"}},
{1, 1, []string{"d", "b", "c", "a"}},
{2, 3, []string{"d", "b", "a", "c"}},
{3, 2, []string{"d", "b", "c", "a"}},
{0, 3, []string{"b", "c", "a", "d"}},
} {
if err := move(step.from, step.to); err != nil {
t.Fatalf("move %d to %d: %v", step.from, step.to, err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, step.want) {
t.Fatalf("after %d to %d: order = %v, want %v", step.from, step.to, o, step.want)
}
}
if err := move(0, 4); !errors.Is(err, playlists.ErrPosition) {
t.Errorf("beyond the end: err = %v", err)
}
if err := e.repo.MoveItem(ctx, e.alice, p.ID, 99999, 0, e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("unknown item: err = %v", err)
}
if err := e.repo.MoveItem(ctx, e.bob, p.ID, e.itemIDs(p.ID)[0], 0, e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
})
}
func TestATrackWithoutFilesStaysAndIsListedAsNotAvailable(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b"); err != nil {
t.Fatal(err)
}
if _, err := e.db.ExecContext(ctx, "UPDATE audio_files SET missing_at = ? WHERE track_id = ?", 1_700_000_100, e.tracks["a"]); err != nil {
t.Fatal(err)
}
items, total, err := e.repo.Items(ctx, e.alice, p.ID, 10, 0)
if err != nil || total != 2 || len(items) != 2 {
t.Fatalf("items = %+v total %d err %v: the track must stay", items, total, err)
}
if items[0].Available || items[0].Track.Title != "a" || items[0].Track.Album == nil || len(items[0].Track.Artists) != 1 {
t.Errorf("the missing one = %+v", items[0])
}
if !items[1].Available || items[1].Track.Format != "flac" {
t.Errorf("the other = %+v", items[1])
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != 2 {
t.Errorf("track count = %d, want both", got.TrackCount)
}
})
}
func TestItemsArePaged(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
items, total, err := e.repo.Items(ctx, e.alice, p.ID, 2, 1)
if err != nil || total != 4 || len(items) != 2 || items[0].Track.Title != "b" || items[1].Position != 2 {
t.Errorf("page = %+v total %d err %v", items, total, err)
}
if items, total, _ := e.repo.Items(ctx, e.alice, p.ID, 2, 10); len(items) != 0 || total != 4 {
t.Errorf("beyond the end = %+v total %d", items, total)
}
if _, _, err := e.repo.Items(ctx, e.bob, p.ID, 2, 0); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
})
}
func TestUpdatingAndDeletingAPlaylist(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p, err := e.repo.Create(ctx, e.alice, "Old", "about it", e.tick())
if err != nil {
t.Fatal(err)
}
if _, err := e.add(e.alice, p.ID, -1, "a", "b"); err != nil {
t.Fatal(err)
}
name, empty := "New", ""
got, err := e.repo.Update(ctx, e.alice, p.ID, &name, nil, e.tick())
if err != nil || got.Name != "New" || got.Description != "about it" || got.TrackCount != 2 {
t.Errorf("name only: %+v err %v", got, err)
}
got, err = e.repo.Update(ctx, e.alice, p.ID, nil, &empty, e.tick())
if err != nil || got.Name != "New" || got.Description != "" {
t.Errorf("description only: %+v err %v", got, err)
}
if _, err := e.repo.Update(ctx, e.bob, p.ID, &name, nil, e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user updates: err = %v", err)
}
if err := e.repo.Delete(ctx, e.bob, p.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user deletes: err = %v", err)
}
if err := e.repo.Delete(ctx, e.alice, p.ID); err != nil {
t.Fatal(err)
}
if err := e.repo.Delete(ctx, e.alice, p.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("a second time: err = %v", err)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM playlist_items"); n != 0 {
t.Errorf("%d items left", n)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM tracks"); n != 4 {
t.Errorf("%d tracks left, want all 4", n)
}
})
}
func TestDeletingAUserDeletesTheirPlaylists(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
p := e.create(e.alice, "P")
keep := e.create(e.bob, "Keep")
if _, err := e.add(e.alice, p.ID, -1, "a"); err != nil {
t.Fatal(err)
}
if err := NewUserRepo(e.db).DeleteUser(context.Background(), e.alice); err != nil {
t.Fatal(err)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM playlists"); n != 1 {
t.Errorf("%d playlists, want only bob's", n)
}
if _, err := e.repo.Get(context.Background(), e.bob, keep.ID); err != nil {
t.Errorf("bob's: %v", err)
}
})
}
func TestThereAreLimitsOnPlaylistsAndOnTheirSize(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "Big")
// Fill the playlist up to the limit with a direct insert, 1,000 rows at a time.
for start := 0; start < playlists.MaxItems; start += 1000 {
rows := make([]playlistItemRow, 0, 1000)
for i := start; i < start+1000; i++ {
rows = append(rows, playlistItemRow{PlaylistID: p.ID, TrackID: e.tracks["a"], Position: i, AddedAt: 1})
}
if _, err := e.db.NewInsert().Model(&rows).Exec(ctx); err != nil {
t.Fatal(err)
}
}
if _, err := e.add(e.alice, p.ID, -1, "b"); !errors.Is(err, playlists.ErrTooMany) {
t.Errorf("one more than %d: err = %v, want ErrTooMany", playlists.MaxItems, err)
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != playlists.MaxItems {
t.Errorf("track count = %d", got.TrackCount)
}
for i := 1; i < playlists.MaxPlaylists; i++ {
if _, err := e.repo.Create(ctx, e.alice, "x", "", e.tick()); err != nil {
t.Fatalf("playlist %d: %v", i+1, err)
}
}
if _, err := e.repo.Create(ctx, e.alice, "one more", "", e.tick()); !errors.Is(err, playlists.ErrTooMany) {
t.Errorf("one more than %d playlists: err = %v", playlists.MaxPlaylists, err)
}
if _, err := e.repo.Create(ctx, e.bob, "bobs", "", e.tick()); err != nil {
t.Errorf("the limit is per user: %v", err)
}
})
}
func TestAddingAtTheSameTimeKeepsEveryPositionUnique(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
var wg sync.WaitGroup
errs := make(chan error, 8)
for g := 0; g < 8; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
if _, err := e.repo.AddTracks(ctx, e.alice, p.ID, []int64{e.tracks["a"], e.tracks["b"]}, nil, time.Now()); err != nil {
errs <- err
return
}
}
}()
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); len(o) != 48 {
t.Errorf("%d items, want 48", len(o))
}
})
}