feat(playlists): changes a phone queues offline are safe to send twice (#8023)
release / go (push) Successful in 1m59s
release / web (push) Successful in 1m23s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m38s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 5m22s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
release / go (push) Successful in 1m59s
release / web (push) Successful in 1m23s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m38s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 5m22s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
- A new playlist can carry the client's own id; sending the create again finds the same list. - Removing a song can name the song expected at that position; if another song is there now, nothing is removed (409 list_changed). - A reorder can give the songs in their new order (track_ids); sending it again changes nothing. - The playlist service tells the owner's clients about every change itself, so a change made from a Subsonic app refreshes the web and Android apps too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,3 +8,6 @@ type RankedCandidate = rankedCandidate
|
||||
|
||||
// OneCopyPerSong is oneCopyPerSong, for tests.
|
||||
var OneCopyPerSong = oneCopyPerSong
|
||||
|
||||
// OrderByTracks is orderByTracks, for tests.
|
||||
var OrderByTracks = orderByTracks
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package playlists_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
|
||||
)
|
||||
|
||||
// The writes a phone queues while offline may reach the server more than
|
||||
// once. These tests send each one twice and check the second changes
|
||||
// nothing.
|
||||
|
||||
func id(b byte) pgtype.UUID { return pgtype.UUID{Bytes: [16]byte{b}, Valid: true} }
|
||||
|
||||
func TestOrderByTracks_ArrangesNamedEntriesInTheirOwnPlaces(t *testing.T) {
|
||||
a, b, c, x := id(1), id(2), id(3), id(9)
|
||||
gone := pgtype.UUID{}
|
||||
cases := []struct {
|
||||
name string
|
||||
current, want []pgtype.UUID
|
||||
perm []int32
|
||||
}{
|
||||
{"swap two around an entry left alone", []pgtype.UUID{a, gone, b, c}, []pgtype.UUID{c, a}, []int32{3, 1, 2, 0}},
|
||||
{"an id not in the list is skipped", []pgtype.UUID{a, b}, []pgtype.UUID{x, b, a}, []int32{1, 0}},
|
||||
{"a song listed twice matches its entries in turn", []pgtype.UUID{a, b, a}, []pgtype.UUID{a, a, b}, []int32{0, 2, 1}},
|
||||
{"the current order is the identity", []pgtype.UUID{a, b, c}, []pgtype.UUID{a, b, c}, []int32{0, 1, 2}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := playlists.OrderByTracks(tc.current, tc.want); !slices.Equal(got, tc.perm) {
|
||||
t.Errorf("%s: perm = %v, want %v", tc.name, got, tc.perm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateWithID_ASecondSendFindsTheSameList(t *testing.T) {
|
||||
pool := newPool(t)
|
||||
alice := seedUser(t, pool, "alice")
|
||||
bob := seedUser(t, pool, "bob")
|
||||
svc := playlists.NewService(pool, nil, t.TempDir())
|
||||
ctx := context.Background()
|
||||
chosen := randomUUID()
|
||||
|
||||
first, err := svc.CreateWithID(ctx, alice.ID, chosen, "Road Songs", "", false)
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if first.ID != chosen {
|
||||
t.Fatalf("id = %s, want the client's %s", uuidString(first.ID), uuidString(chosen))
|
||||
}
|
||||
again, err := svc.CreateWithID(ctx, alice.ID, chosen, "Road Songs", "", false)
|
||||
if err != nil || again.ID != chosen {
|
||||
t.Fatalf("second send: %v, id %s; want the same list", err, uuidString(again.ID))
|
||||
}
|
||||
lists, err := svc.List(ctx, alice.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(lists) != 1 {
|
||||
t.Errorf("alice has %d lists, want 1", len(lists))
|
||||
}
|
||||
if _, err := svc.CreateWithID(ctx, bob.ID, chosen, "Mine now", "", false); !errors.Is(err, playlists.ErrInvalidInput) {
|
||||
t.Errorf("bob reusing alice's id: %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveTrack_ASecondSendRemovesNothingMore(t *testing.T) {
|
||||
pool := newPool(t)
|
||||
user := seedUser(t, pool, "alice")
|
||||
a := seedTrack(t, pool, "A", "Artist")
|
||||
b := seedTrack(t, pool, "B", "Artist")
|
||||
c := seedTrack(t, pool, "C", "Artist")
|
||||
svc := playlists.NewService(pool, nil, t.TempDir())
|
||||
ctx := context.Background()
|
||||
pl, _ := svc.Create(ctx, user.ID, "Test", "", false)
|
||||
_ = svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, b.ID, c.ID})
|
||||
|
||||
if err := svc.RemoveTrack(ctx, user.ID, pl.ID, 1, b.ID); err != nil {
|
||||
t.Fatalf("remove B: %v", err)
|
||||
}
|
||||
// C has moved into position 1; the same request must not take it.
|
||||
if err := svc.RemoveTrack(ctx, user.ID, pl.ID, 1, b.ID); !errors.Is(err, playlists.ErrListChanged) {
|
||||
t.Errorf("second send: %v, want ErrListChanged", err)
|
||||
}
|
||||
got, _ := svc.Get(ctx, user.ID, pl.ID)
|
||||
if titles := trackTitles(got); !slices.Equal(titles, []string{"A", "C"}) {
|
||||
t.Errorf("tracks = %v, want A, C", titles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReorderTracks_ASecondSendChangesNothing(t *testing.T) {
|
||||
pool := newPool(t)
|
||||
user := seedUser(t, pool, "alice")
|
||||
a := seedTrack(t, pool, "A", "Artist")
|
||||
b := seedTrack(t, pool, "B", "Artist")
|
||||
c := seedTrack(t, pool, "C", "Artist")
|
||||
svc := playlists.NewService(pool, nil, t.TempDir())
|
||||
ctx := context.Background()
|
||||
pl, _ := svc.Create(ctx, user.ID, "Test", "", false)
|
||||
_ = svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, b.ID, c.ID})
|
||||
|
||||
for range 2 {
|
||||
if err := svc.ReorderTracks(ctx, user.ID, pl.ID, []pgtype.UUID{c.ID, a.ID, b.ID}); err != nil {
|
||||
t.Fatalf("reorder: %v", err)
|
||||
}
|
||||
got, _ := svc.Get(ctx, user.ID, pl.ID)
|
||||
if titles := trackTitles(got); !slices.Equal(titles, []string{"C", "A", "B"}) {
|
||||
t.Errorf("tracks = %v, want C, A, B", titles)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every change tells the owner's clients, whichever client made it.
|
||||
func TestChanges_TellTheOwnersClients(t *testing.T) {
|
||||
pool := newPool(t)
|
||||
user := seedUser(t, pool, "alice")
|
||||
a := seedTrack(t, pool, "A", "Artist")
|
||||
bus := eventbus.New()
|
||||
events, stop := bus.Subscribe(16)
|
||||
defer stop()
|
||||
svc := playlists.NewService(pool, nil, t.TempDir())
|
||||
svc.PublishTo(bus)
|
||||
ctx := context.Background()
|
||||
|
||||
pl, _ := svc.Create(ctx, user.ID, "Test", "", false)
|
||||
name := "Renamed"
|
||||
_, _ = svc.Update(ctx, user.ID, pl.ID, playlists.UpdateInput{Name: &name})
|
||||
_ = svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID})
|
||||
_ = svc.Delete(ctx, user.ID, pl.ID)
|
||||
|
||||
var kinds []string
|
||||
for range 4 {
|
||||
select {
|
||||
case e := <-events:
|
||||
if e.UserID != uuidString(user.ID) || e.Data["playlist_id"] != uuidString(pl.ID) {
|
||||
t.Errorf("%s went to %s about %v", e.Kind, e.UserID, e.Data["playlist_id"])
|
||||
}
|
||||
kinds = append(kinds, e.Kind)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("events so far %v, want four", kinds)
|
||||
}
|
||||
}
|
||||
want := []string{"playlist.created", "playlist.updated", "playlist.tracks_changed", "playlist.deleted"}
|
||||
if !slices.Equal(kinds, want) {
|
||||
t.Errorf("events = %v, want %v", kinds, want)
|
||||
}
|
||||
}
|
||||
|
||||
func trackTitles(d *playlists.PlaylistDetail) []string {
|
||||
out := make([]string, 0, len(d.Tracks))
|
||||
for _, tr := range d.Tracks {
|
||||
out = append(out, tr.Title)
|
||||
}
|
||||
return out
|
||||
}
|
||||
+137
-46
@@ -27,6 +27,7 @@ import (
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
||||
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
||||
)
|
||||
|
||||
@@ -42,6 +43,7 @@ var (
|
||||
ErrInvalidInput = errors.New("playlists: invalid input")
|
||||
ErrTrackNotFound = errors.New("playlists: track not found")
|
||||
ErrSystemPlaylistReadonly = errors.New("playlists: system playlist is read-only")
|
||||
ErrListChanged = errors.New("playlists: the list changed")
|
||||
)
|
||||
|
||||
// Service wires the sqlc queries + on-disk cover-art directory together.
|
||||
@@ -52,6 +54,7 @@ type Service struct {
|
||||
pool *pgxpool.Pool
|
||||
logger *slog.Logger
|
||||
dataDir string
|
||||
bus *eventbus.Bus
|
||||
}
|
||||
|
||||
// NewService constructs a Service. A nil logger gets slog.Default().
|
||||
@@ -62,6 +65,12 @@ func NewService(pool *pgxpool.Pool, logger *slog.Logger, dataDir string) *Servic
|
||||
return &Service{pool: pool, logger: logger, dataDir: dataDir}
|
||||
}
|
||||
|
||||
// PublishTo makes every change to a playlist, from any client, tell the
|
||||
// owner's signed-in clients through bus, so each can refresh what it shows.
|
||||
func (s *Service) PublishTo(bus *eventbus.Bus) {
|
||||
s.bus = bus
|
||||
}
|
||||
|
||||
// PlaylistRow is the wire shape returned by Create / Update / List /
|
||||
// the embedded portion of Get. owner_username is denormalized in via
|
||||
// the JOIN on users so callers don't have to resolve it themselves.
|
||||
@@ -127,29 +136,47 @@ type PlaylistTrack struct {
|
||||
}
|
||||
|
||||
// Create makes a new playlist owned by userID.
|
||||
//
|
||||
// The post-create GetPlaylist call exists to pick up owner_username
|
||||
// from the users JOIN — CreatePlaylist returns only playlist columns,
|
||||
// not the joined username, so we'd otherwise have to resolve it twice
|
||||
// in the API layer.
|
||||
func (s *Service) Create(ctx context.Context, userID pgtype.UUID, name, description string, isPublic bool) (*PlaylistRow, error) {
|
||||
return s.CreateWithID(ctx, userID, pgtype.UUID{}, name, description, isPublic)
|
||||
}
|
||||
|
||||
// CreateWithID makes a new playlist owned by userID under id, the id a
|
||||
// client chose for it, or a new id when id is not valid. A client that
|
||||
// made the list while offline sends the same id on every retry, so when
|
||||
// userID already owns a list with that id, that list is returned
|
||||
// unchanged. An id another user's list holds is ErrInvalidInput.
|
||||
func (s *Service) CreateWithID(ctx context.Context, userID, id pgtype.UUID, name, description string, isPublic bool) (*PlaylistRow, error) {
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("%w: name required", ErrInvalidInput)
|
||||
}
|
||||
q := dbq.New(s.pool)
|
||||
row, err := q.CreatePlaylist(ctx, dbq.CreatePlaylistParams{
|
||||
ID: id,
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
Description: description,
|
||||
IsPublic: isPublic,
|
||||
})
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
existing, gerr := q.GetPlaylist(ctx, id)
|
||||
if gerr != nil {
|
||||
return nil, fmt.Errorf("get existing playlist: %w", gerr)
|
||||
}
|
||||
if !pgtypeUUIDEqual(existing.UserID, userID) || existing.Kind != "user" {
|
||||
return nil, fmt.Errorf("%w: playlist id already in use", ErrInvalidInput)
|
||||
}
|
||||
return playlistFromGetRow(existing), nil
|
||||
case err != nil:
|
||||
return nil, fmt.Errorf("create playlist: %w", err)
|
||||
}
|
||||
if err := syncpkg.LogChange(ctx, s.pool, syncpkg.EntityPlaylist,
|
||||
syncpkg.FormatUUID(row.ID), syncpkg.OpUpsert); err != nil {
|
||||
s.logger.Warn("playlists: LogChange create failed", "playlist_id", row.ID, "err", err)
|
||||
}
|
||||
s.publish("playlist.created", userID, row.ID)
|
||||
// CreatePlaylist returns the playlist's own columns; the owner's
|
||||
// username comes from GetPlaylist's join.
|
||||
full, err := q.GetPlaylist(ctx, row.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get-after-create: %w", err)
|
||||
@@ -311,6 +338,7 @@ func (s *Service) Update(ctx context.Context, callerID, playlistID pgtype.UUID,
|
||||
syncpkg.FormatUUID(updated.ID), syncpkg.OpUpsert); err != nil {
|
||||
s.logger.Warn("playlists: LogChange update failed", "playlist_id", updated.ID, "err", err)
|
||||
}
|
||||
s.publish("playlist.updated", callerID, playlistID)
|
||||
full, err := q.GetPlaylist(ctx, updated.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get-after-update: %w", err)
|
||||
@@ -337,6 +365,7 @@ func (s *Service) Delete(ctx context.Context, callerID, playlistID pgtype.UUID)
|
||||
syncpkg.FormatUUID(deleted.ID), syncpkg.OpDelete); err != nil {
|
||||
s.logger.Warn("playlists: LogChange delete failed", "playlist_id", deleted.ID, "err", err)
|
||||
}
|
||||
s.publish("playlist.deleted", callerID, playlistID)
|
||||
if deleted.CoverPath != nil && *deleted.CoverPath != "" {
|
||||
full := filepath.Join(s.dataDir, *deleted.CoverPath)
|
||||
if rerr := os.Remove(full); rerr != nil && !errors.Is(rerr, os.ErrNotExist) {
|
||||
@@ -405,9 +434,12 @@ func (s *Service) ReplaceTracks(ctx context.Context, callerID, playlistID pgtype
|
||||
}
|
||||
|
||||
// RemoveTrack deletes the row at `position` and renumbers subsequent
|
||||
// rows to close the gap. Triggers cover regeneration after.
|
||||
func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.UUID, position int32) error {
|
||||
return s.RemovePositions(ctx, callerID, playlistID, []int32{position})
|
||||
// rows to close the gap. With a valid expect, the row must hold that
|
||||
// track, or nothing is removed and the answer is ErrListChanged: a client
|
||||
// replaying a removal it made offline must not take out whichever song has
|
||||
// since moved into that place.
|
||||
func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.UUID, position int32, expect pgtype.UUID) error {
|
||||
return s.removePositions(ctx, callerID, playlistID, []int32{position}, expect)
|
||||
}
|
||||
|
||||
// RemovePositions deletes the rows at the given positions, all counted
|
||||
@@ -415,6 +447,12 @@ func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.U
|
||||
// position repeated is removed once; one with no row is ErrNotFound and
|
||||
// removes nothing.
|
||||
func (s *Service) RemovePositions(ctx context.Context, callerID, playlistID pgtype.UUID, positions []int32) error {
|
||||
return s.removePositions(ctx, callerID, playlistID, positions, pgtype.UUID{})
|
||||
}
|
||||
|
||||
// removePositions removes the rows at positions; a valid expect is the
|
||||
// track the single row must hold (see RemoveTrack).
|
||||
func (s *Service) removePositions(ctx context.Context, callerID, playlistID pgtype.UUID, positions []int32, expect pgtype.UUID) error {
|
||||
if len(positions) == 0 {
|
||||
return fmt.Errorf("%w: at least one position required", ErrInvalidInput)
|
||||
}
|
||||
@@ -437,6 +475,9 @@ func (s *Service) RemovePositions(ctx context.Context, callerID, playlistID pgty
|
||||
}
|
||||
return fmt.Errorf("lookup track at position: %w", err)
|
||||
}
|
||||
if expect.Valid && deletedTrackID != expect {
|
||||
return ErrListChanged
|
||||
}
|
||||
if err := tq.DeletePlaylistTrack(ctx, dbq.DeletePlaylistTrackParams{
|
||||
PlaylistID: playlistID,
|
||||
Position: position,
|
||||
@@ -479,6 +520,7 @@ func (s *Service) changeTracks(ctx context.Context, callerID, playlistID pgtype.
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
s.publish("playlist.tracks_changed", callerID, playlistID)
|
||||
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil {
|
||||
s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr)
|
||||
}
|
||||
@@ -524,61 +566,110 @@ func logTrackChange(ctx context.Context, tx pgx.Tx, playlistID, trackID pgtype.U
|
||||
// tracks at positions [0, 1, 2, 3] and the caller wants the order
|
||||
// (old[3], old[0], old[1], old[2]), they send [3, 0, 1, 2].
|
||||
func (s *Service) Reorder(ctx context.Context, callerID, playlistID pgtype.UUID, orderedPositions []int32) error {
|
||||
pl, err := editable(ctx, dbq.New(s.pool), callerID, playlistID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if int32(len(orderedPositions)) != pl.TrackCount {
|
||||
return fmt.Errorf("%w: expected %d positions, got %d", ErrInvalidInput, pl.TrackCount, len(orderedPositions))
|
||||
}
|
||||
seen := make(map[int32]struct{}, len(orderedPositions))
|
||||
for _, p := range orderedPositions {
|
||||
if p < 0 || p >= pl.TrackCount {
|
||||
return fmt.Errorf("%w: position %d out of range", ErrInvalidInput, p)
|
||||
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
||||
entries, err := dbq.New(tx).ListPlaylistEntriesForUpdate(ctx, playlistID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list entries: %w", err)
|
||||
}
|
||||
if _, dup := seen[p]; dup {
|
||||
return fmt.Errorf("%w: position %d duplicated", ErrInvalidInput, p)
|
||||
n := int32(len(entries))
|
||||
if int32(len(orderedPositions)) != n {
|
||||
return fmt.Errorf("%w: expected %d positions, got %d", ErrInvalidInput, n, len(orderedPositions))
|
||||
}
|
||||
seen[p] = struct{}{}
|
||||
}
|
||||
seen := make(map[int32]struct{}, n)
|
||||
for _, p := range orderedPositions {
|
||||
if p < 0 || p >= n {
|
||||
return fmt.Errorf("%w: position %d out of range", ErrInvalidInput, p)
|
||||
}
|
||||
if _, dup := seen[p]; dup {
|
||||
return fmt.Errorf("%w: position %d duplicated", ErrInvalidInput, p)
|
||||
}
|
||||
seen[p] = struct{}{}
|
||||
}
|
||||
return writeOrder(ctx, tx, playlistID, orderedPositions)
|
||||
})
|
||||
}
|
||||
|
||||
// Rewrite strategy: bump every row's position by +10000 first (out of
|
||||
// range of valid positions and the unique PK) then write the new
|
||||
// positions one by one. Single transaction.
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
// ReorderTracks puts the playlist's songs in the order trackIDs gives.
|
||||
// Entries it doesn't name (a song that has left the library, or one added
|
||||
// since the caller last looked) keep their places, and the named ones are
|
||||
// arranged among the places left; a track id the playlist doesn't hold is
|
||||
// skipped. Sending the same order twice changes nothing the second time,
|
||||
// which is what lets a client replay a reorder it made offline.
|
||||
func (s *Service) ReorderTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
|
||||
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
||||
entries, err := dbq.New(tx).ListPlaylistEntriesForUpdate(ctx, playlistID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list entries: %w", err)
|
||||
}
|
||||
current := make([]pgtype.UUID, len(entries))
|
||||
for i, e := range entries {
|
||||
current[i] = e.TrackID
|
||||
}
|
||||
return writeOrder(ctx, tx, playlistID, orderByTracks(current, trackIDs))
|
||||
})
|
||||
}
|
||||
|
||||
// orderByTracks returns the permutation Reorder takes (new position i
|
||||
// holds old position perm[i]) that puts the entries holding want's tracks
|
||||
// in want's order, within the positions those entries hold now. A track
|
||||
// listed twice matches its entries in turn.
|
||||
func orderByTracks(current, want []pgtype.UUID) []int32 {
|
||||
at := make(map[[16]byte][]int32, len(current))
|
||||
for i, id := range current {
|
||||
if id.Valid {
|
||||
at[id.Bytes] = append(at[id.Bytes], int32(i))
|
||||
}
|
||||
}
|
||||
picked := make([]int32, 0, len(want))
|
||||
for _, id := range want {
|
||||
if q := at[id.Bytes]; id.Valid && len(q) > 0 {
|
||||
picked = append(picked, q[0])
|
||||
at[id.Bytes] = q[1:]
|
||||
}
|
||||
}
|
||||
slots := slices.Clone(picked)
|
||||
slices.Sort(slots)
|
||||
perm := make([]int32, len(current))
|
||||
for i := range perm {
|
||||
perm[i] = int32(i)
|
||||
}
|
||||
for k, slot := range slots {
|
||||
perm[slot] = picked[k]
|
||||
}
|
||||
return perm
|
||||
}
|
||||
|
||||
// writeOrder moves the row at position perm[i] to position i. Every row
|
||||
// first moves out of the range of valid positions, so no two rows ever
|
||||
// hold one position mid-rewrite.
|
||||
func writeOrder(ctx context.Context, tx pgx.Tx, playlistID pgtype.UUID, perm []int32) error {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`UPDATE playlist_tracks SET position = position + 10000 WHERE playlist_id = $1`,
|
||||
playlistID); err != nil {
|
||||
return fmt.Errorf("offset positions: %w", err)
|
||||
}
|
||||
for newPos, oldPos := range orderedPositions {
|
||||
for newPos, oldPos := range perm {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`UPDATE playlist_tracks SET position = $1 WHERE playlist_id = $2 AND position = $3`,
|
||||
int32(newPos), playlistID, oldPos+10000); err != nil {
|
||||
return fmt.Errorf("write new position: %w", err)
|
||||
}
|
||||
}
|
||||
if err := dbq.New(tx).UpdatePlaylistRollups(ctx, playlistID); err != nil {
|
||||
return fmt.Errorf("update rollups: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
|
||||
// Always regenerate the cover. Reasoning about which moves matter is
|
||||
// more error-prone than just doing the work; the collage is cheap.
|
||||
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil {
|
||||
s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// publish tells the owner's signed-in clients that a playlist changed.
|
||||
func (s *Service) publish(kind string, ownerID, playlistID pgtype.UUID) {
|
||||
if s.bus == nil {
|
||||
return
|
||||
}
|
||||
s.bus.Publish(eventbus.Event{
|
||||
Kind: kind,
|
||||
UserID: syncpkg.FormatUUID(ownerID),
|
||||
Data: map[string]any{"playlist_id": syncpkg.FormatUUID(playlistID)},
|
||||
})
|
||||
}
|
||||
|
||||
func playlistFromGetRow(r dbq.GetPlaylistRow) *PlaylistRow {
|
||||
return &PlaylistRow{
|
||||
ID: r.ID,
|
||||
|
||||
@@ -385,7 +385,7 @@ func TestRemoveTrack_RenumbersPositions(t *testing.T) {
|
||||
_ = svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID, t3.ID})
|
||||
|
||||
// Remove the middle one (position 1).
|
||||
if err := svc.RemoveTrack(context.Background(), user.ID, pl.ID, 1); err != nil {
|
||||
if err := svc.RemoveTrack(context.Background(), user.ID, pl.ID, 1, pgtype.UUID{}); err != nil {
|
||||
t.Fatalf("RemoveTrack: %v", err)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user