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

- 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:
2026-11-26 10:22:40 -05:00
co-authored by Claude Opus 5.5
parent 1df91678ba
commit a77f3ae6ff
9 changed files with 421 additions and 88 deletions
+137 -46
View File
@@ -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,