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:
@@ -69,24 +69,6 @@ func (h *handlers) publishQuarantineEvent(kind string, userID, trackID pgtype.UU
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// publishPlaylistEvent broadcasts a playlist mutation to the owner so
|
|
||||||
// their other clients invalidate the affected playlist (and playlist list)
|
|
||||||
// providers. Public-playlist subscribers are out of scope here — they'd
|
|
||||||
// need a separate "playlists.public_updated" broadcast, deferred until
|
|
||||||
// the multi-user case is exercised.
|
|
||||||
func (h *handlers) publishPlaylistEvent(kind string, ownerID, playlistID pgtype.UUID) {
|
|
||||||
if h.eventbus == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
h.eventbus.Publish(eventbus.Event{
|
|
||||||
Kind: kind,
|
|
||||||
UserID: uuidToString(ownerID),
|
|
||||||
Data: map[string]any{
|
|
||||||
"playlist_id": uuidToString(playlistID),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// publishSystemRebuilt notifies the owner's clients that their system
|
// publishSystemRebuilt notifies the owner's clients that their system
|
||||||
// playlists (and You-might-like rows) were regenerated, so they invalidate
|
// playlists (and You-might-like rows) were regenerated, so they invalidate
|
||||||
// the home / system-playlist providers and a stale active queue can re-pull.
|
// the home / system-playlist providers and a stale active queue can re-pull.
|
||||||
|
|||||||
+59
-18
@@ -183,7 +183,10 @@ func (h *handlers) maybeKickBackgroundBuild(ctx context.Context, userID pgtype.U
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// createPlaylistBody's ID is optional: a client that makes a playlist
|
||||||
|
// offline picks its id, so a retry of the same create finds the same list.
|
||||||
type createPlaylistBody struct {
|
type createPlaylistBody struct {
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
IsPublic bool `json:"is_public"`
|
IsPublic bool `json:"is_public"`
|
||||||
@@ -200,12 +203,19 @@ func (h *handlers) handleCreatePlaylist(w http.ResponseWriter, r *http.Request)
|
|||||||
if !decodeBody(w, r, &body) {
|
if !decodeBody(w, r, &body) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
row, err := h.playlists.Create(r.Context(), caller.ID, body.Name, body.Description, body.IsPublic)
|
var id pgtype.UUID
|
||||||
|
if body.ID != "" {
|
||||||
|
var ok bool
|
||||||
|
if id, ok = parseUUID(body.ID); !ok {
|
||||||
|
writeErr(w, apierror.BadRequest("bad_request", "invalid playlist id"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
row, err := h.playlists.CreateWithID(r.Context(), caller.ID, id, body.Name, body.Description, body.IsPublic)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writePlaylistErr(w, err, "create")
|
h.writePlaylistErr(w, err, "create")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.publishPlaylistEvent("playlist.created", caller.ID, row.ID)
|
|
||||||
writeJSON(w, http.StatusOK, playlistRowToView(row))
|
writeJSON(w, http.StatusOK, playlistRowToView(row))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,7 +271,6 @@ func (h *handlers) handleUpdatePlaylist(w http.ResponseWriter, r *http.Request)
|
|||||||
h.writePlaylistErr(w, err, "update")
|
h.writePlaylistErr(w, err, "update")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.publishPlaylistEvent("playlist.updated", caller.ID, playlistID)
|
|
||||||
writeJSON(w, http.StatusOK, playlistRowToView(row))
|
writeJSON(w, http.StatusOK, playlistRowToView(row))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,7 +289,6 @@ func (h *handlers) handleDeletePlaylist(w http.ResponseWriter, r *http.Request)
|
|||||||
h.writePlaylistErr(w, err, "delete")
|
h.writePlaylistErr(w, err, "delete")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.publishPlaylistEvent("playlist.deleted", caller.ID, playlistID)
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,20 +312,14 @@ func (h *handlers) handleAppendTracks(w http.ResponseWriter, r *http.Request) {
|
|||||||
if !decodeBody(w, r, &body) {
|
if !decodeBody(w, r, &body) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
trackIDs := make([]pgtype.UUID, 0, len(body.TrackIDs))
|
trackIDs, ok := parseTrackIDs(w, body.TrackIDs)
|
||||||
for _, s := range body.TrackIDs {
|
if !ok {
|
||||||
u, ok := parseUUID(s)
|
return
|
||||||
if !ok {
|
|
||||||
writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid track id %q", s)))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
trackIDs = append(trackIDs, u)
|
|
||||||
}
|
}
|
||||||
if err := h.playlists.AppendTracks(r.Context(), caller.ID, playlistID, trackIDs); err != nil {
|
if err := h.playlists.AppendTracks(r.Context(), caller.ID, playlistID, trackIDs); err != nil {
|
||||||
h.writePlaylistErr(w, err, "append tracks")
|
h.writePlaylistErr(w, err, "append tracks")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID)
|
|
||||||
detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID)
|
detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writePlaylistErr(w, err, "get-after-append")
|
h.writePlaylistErr(w, err, "get-after-append")
|
||||||
@@ -344,11 +346,19 @@ func (h *handlers) handleRemovePlaylistTrack(w http.ResponseWriter, r *http.Requ
|
|||||||
writeErr(w, apierror.BadRequest("bad_request", "invalid position"))
|
writeErr(w, apierror.BadRequest("bad_request", "invalid position"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := h.playlists.RemoveTrack(r.Context(), caller.ID, playlistID, int32(pos64)); err != nil {
|
// track_id, when sent, names the song the caller expects at position;
|
||||||
|
// if another song is there now, nothing is removed (409).
|
||||||
|
var expect pgtype.UUID
|
||||||
|
if raw := r.URL.Query().Get("track_id"); raw != "" {
|
||||||
|
if expect, ok = parseUUID(raw); !ok {
|
||||||
|
writeErr(w, apierror.BadRequest("bad_request", "invalid track id"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := h.playlists.RemoveTrack(r.Context(), caller.ID, playlistID, int32(pos64), expect); err != nil {
|
||||||
h.writePlaylistErr(w, err, "remove track")
|
h.writePlaylistErr(w, err, "remove track")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID)
|
|
||||||
detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID)
|
detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writePlaylistErr(w, err, "get-after-remove")
|
h.writePlaylistErr(w, err, "get-after-remove")
|
||||||
@@ -357,8 +367,13 @@ func (h *handlers) handleRemovePlaylistTrack(w http.ResponseWriter, r *http.Requ
|
|||||||
writeJSON(w, http.StatusOK, playlistDetailToView(detail))
|
writeJSON(w, http.StatusOK, playlistDetailToView(detail))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reorderTracksBody carries the new order one of two ways:
|
||||||
|
// ordered_positions, a permutation of every position, or track_ids, the
|
||||||
|
// songs in their new order (see playlists.Service.ReorderTracks), which a
|
||||||
|
// client can safely send again.
|
||||||
type reorderTracksBody struct {
|
type reorderTracksBody struct {
|
||||||
OrderedPositions []int32 `json:"ordered_positions"`
|
OrderedPositions []int32 `json:"ordered_positions"`
|
||||||
|
TrackIDs []string `json:"track_ids"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleReorderPlaylist implements PUT /api/playlists/{id}/tracks. Owner
|
// handleReorderPlaylist implements PUT /api/playlists/{id}/tracks. Owner
|
||||||
@@ -377,11 +392,20 @@ func (h *handlers) handleReorderPlaylist(w http.ResponseWriter, r *http.Request)
|
|||||||
if !decodeBody(w, r, &body) {
|
if !decodeBody(w, r, &body) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := h.playlists.Reorder(r.Context(), caller.ID, playlistID, body.OrderedPositions); err != nil {
|
var err error
|
||||||
|
if body.TrackIDs != nil {
|
||||||
|
trackIDs, ok := parseTrackIDs(w, body.TrackIDs)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = h.playlists.ReorderTracks(r.Context(), caller.ID, playlistID, trackIDs)
|
||||||
|
} else {
|
||||||
|
err = h.playlists.Reorder(r.Context(), caller.ID, playlistID, body.OrderedPositions)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
h.writePlaylistErr(w, err, "reorder")
|
h.writePlaylistErr(w, err, "reorder")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID)
|
|
||||||
detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID)
|
detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writePlaylistErr(w, err, "get-after-reorder")
|
h.writePlaylistErr(w, err, "get-after-reorder")
|
||||||
@@ -390,6 +414,21 @@ func (h *handlers) handleReorderPlaylist(w http.ResponseWriter, r *http.Request)
|
|||||||
writeJSON(w, http.StatusOK, playlistDetailToView(detail))
|
writeJSON(w, http.StatusOK, playlistDetailToView(detail))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parseTrackIDs parses a body's track ids, or answers 400 naming the first
|
||||||
|
// one that isn't an id and returns false.
|
||||||
|
func parseTrackIDs(w http.ResponseWriter, raw []string) ([]pgtype.UUID, bool) {
|
||||||
|
out := make([]pgtype.UUID, 0, len(raw))
|
||||||
|
for _, s := range raw {
|
||||||
|
u, ok := parseUUID(s)
|
||||||
|
if !ok {
|
||||||
|
writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid track id %q", s)))
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
out = append(out, u)
|
||||||
|
}
|
||||||
|
return out, true
|
||||||
|
}
|
||||||
|
|
||||||
// handleGetPlaylistCover serves the cached collage from disk. The
|
// handleGetPlaylistCover serves the cached collage from disk. The
|
||||||
// playlist visibility check (owner-or-public) runs in the service Get
|
// playlist visibility check (owner-or-public) runs in the service Get
|
||||||
// call before we look at cover_path, so we don't leak the existence of
|
// call before we look at cover_path, so we don't leak the existence of
|
||||||
@@ -435,6 +474,8 @@ func (h *handlers) writePlaylistErr(w http.ResponseWriter, err error, op string)
|
|||||||
writeErr(w, apierror.Forbidden("system_playlist_readonly", "system-generated playlists cannot be edited"))
|
writeErr(w, apierror.Forbidden("system_playlist_readonly", "system-generated playlists cannot be edited"))
|
||||||
case errors.Is(err, playlists.ErrInvalidInput):
|
case errors.Is(err, playlists.ErrInvalidInput):
|
||||||
writeErr(w, apierror.BadRequest("bad_request", err.Error()))
|
writeErr(w, apierror.BadRequest("bad_request", err.Error()))
|
||||||
|
case errors.Is(err, playlists.ErrListChanged):
|
||||||
|
writeErr(w, apierror.Conflict("list_changed", "the playlist has changed; reload it and try again"))
|
||||||
case errors.Is(err, playlists.ErrTrackNotFound):
|
case errors.Is(err, playlists.ErrTrackNotFound):
|
||||||
writeErr(w, apierror.BadRequest("bad_request", "one of the supplied track ids does not exist"))
|
writeErr(w, apierror.BadRequest("bad_request", "one of the supplied track ids does not exist"))
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -57,20 +57,26 @@ func (q *Queries) AppendPlaylistTrack(ctx context.Context, arg AppendPlaylistTra
|
|||||||
}
|
}
|
||||||
|
|
||||||
const createPlaylist = `-- name: CreatePlaylist :one
|
const createPlaylist = `-- name: CreatePlaylist :one
|
||||||
INSERT INTO playlists (user_id, name, description, is_public)
|
INSERT INTO playlists (id, user_id, name, description, is_public)
|
||||||
VALUES ($1, $2, $3, $4)
|
VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3, $4, $5)
|
||||||
|
ON CONFLICT (id) DO NOTHING
|
||||||
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank
|
RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreatePlaylistParams struct {
|
type CreatePlaylistParams struct {
|
||||||
|
ID pgtype.UUID
|
||||||
UserID pgtype.UUID
|
UserID pgtype.UUID
|
||||||
Name string
|
Name string
|
||||||
Description string
|
Description string
|
||||||
IsPublic bool
|
IsPublic bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// id is the client's own id for the list, or NULL for a new one. A client
|
||||||
|
// that made the list offline sends its id again on every retry, so an id
|
||||||
|
// already taken inserts nothing and returns no row.
|
||||||
func (q *Queries) CreatePlaylist(ctx context.Context, arg CreatePlaylistParams) (Playlist, error) {
|
func (q *Queries) CreatePlaylist(ctx context.Context, arg CreatePlaylistParams) (Playlist, error) {
|
||||||
row := q.db.QueryRow(ctx, createPlaylist,
|
row := q.db.QueryRow(ctx, createPlaylist,
|
||||||
|
arg.ID,
|
||||||
arg.UserID,
|
arg.UserID,
|
||||||
arg.Name,
|
arg.Name,
|
||||||
arg.Description,
|
arg.Description,
|
||||||
@@ -309,6 +315,41 @@ func (q *Queries) ListPlaylistCoverAlbums(ctx context.Context, playlistIds []pgt
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listPlaylistEntriesForUpdate = `-- name: ListPlaylistEntriesForUpdate :many
|
||||||
|
SELECT position, track_id
|
||||||
|
FROM playlist_tracks
|
||||||
|
WHERE playlist_id = $1
|
||||||
|
ORDER BY position
|
||||||
|
FOR UPDATE
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListPlaylistEntriesForUpdateRow struct {
|
||||||
|
Position int32
|
||||||
|
TrackID pgtype.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
// The track at each position, locking the rows while a reorder rewrites
|
||||||
|
// them.
|
||||||
|
func (q *Queries) ListPlaylistEntriesForUpdate(ctx context.Context, playlistID pgtype.UUID) ([]ListPlaylistEntriesForUpdateRow, error) {
|
||||||
|
rows, err := q.db.Query(ctx, listPlaylistEntriesForUpdate, playlistID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []ListPlaylistEntriesForUpdateRow
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListPlaylistEntriesForUpdateRow
|
||||||
|
if err := rows.Scan(&i.Position, &i.TrackID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const listPlaylistTracks = `-- name: ListPlaylistTracks :many
|
const listPlaylistTracks = `-- name: ListPlaylistTracks :many
|
||||||
SELECT pt.playlist_id, pt.position, pt.track_id, pt.title, pt.artist_name, pt.album_title, pt.duration_sec, pt.added_at, pt.pick_kind,
|
SELECT pt.playlist_id, pt.position, pt.track_id, pt.title, pt.artist_name, pt.album_title, pt.duration_sec, pt.added_at, pt.pick_kind,
|
||||||
t.id AS live_track_id,
|
t.id AS live_track_id,
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
-- name: CreatePlaylist :one
|
-- name: CreatePlaylist :one
|
||||||
INSERT INTO playlists (user_id, name, description, is_public)
|
-- id is the client's own id for the list, or NULL for a new one. A client
|
||||||
VALUES ($1, $2, $3, $4)
|
-- that made the list offline sends its id again on every retry, so an id
|
||||||
|
-- already taken inserts nothing and returns no row.
|
||||||
|
INSERT INTO playlists (id, user_id, name, description, is_public)
|
||||||
|
VALUES (COALESCE(sqlc.narg(id)::uuid, gen_random_uuid()), sqlc.arg(user_id), sqlc.arg(name), sqlc.arg(description), sqlc.arg(is_public))
|
||||||
|
ON CONFLICT (id) DO NOTHING
|
||||||
RETURNING *;
|
RETURNING *;
|
||||||
|
|
||||||
-- name: GetPlaylist :one
|
-- name: GetPlaylist :one
|
||||||
@@ -49,6 +53,15 @@ UPDATE playlists SET cover_path = $2, updated_at = now() WHERE id = $1;
|
|||||||
DELETE FROM playlists WHERE id = $1
|
DELETE FROM playlists WHERE id = $1
|
||||||
RETURNING id, cover_path;
|
RETURNING id, cover_path;
|
||||||
|
|
||||||
|
-- name: ListPlaylistEntriesForUpdate :many
|
||||||
|
-- The track at each position, locking the rows while a reorder rewrites
|
||||||
|
-- them.
|
||||||
|
SELECT position, track_id
|
||||||
|
FROM playlist_tracks
|
||||||
|
WHERE playlist_id = $1
|
||||||
|
ORDER BY position
|
||||||
|
FOR UPDATE;
|
||||||
|
|
||||||
-- name: ListPlaylistTracks :many
|
-- name: ListPlaylistTracks :many
|
||||||
-- Joined to tracks for the live track id (the service layer derives the
|
-- Joined to tracks for the live track id (the service layer derives the
|
||||||
-- stream URL from it); LEFT JOIN preserves the row when track_id is NULL
|
-- stream URL from it); LEFT JOIN preserves the row when track_id is NULL
|
||||||
|
|||||||
@@ -8,3 +8,6 @@ type RankedCandidate = rankedCandidate
|
|||||||
|
|
||||||
// OneCopyPerSong is oneCopyPerSong, for tests.
|
// OneCopyPerSong is oneCopyPerSong, for tests.
|
||||||
var OneCopyPerSong = oneCopyPerSong
|
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/apierror"
|
||||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||||
|
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
||||||
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -42,6 +43,7 @@ var (
|
|||||||
ErrInvalidInput = errors.New("playlists: invalid input")
|
ErrInvalidInput = errors.New("playlists: invalid input")
|
||||||
ErrTrackNotFound = errors.New("playlists: track not found")
|
ErrTrackNotFound = errors.New("playlists: track not found")
|
||||||
ErrSystemPlaylistReadonly = errors.New("playlists: system playlist is read-only")
|
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.
|
// Service wires the sqlc queries + on-disk cover-art directory together.
|
||||||
@@ -52,6 +54,7 @@ type Service struct {
|
|||||||
pool *pgxpool.Pool
|
pool *pgxpool.Pool
|
||||||
logger *slog.Logger
|
logger *slog.Logger
|
||||||
dataDir string
|
dataDir string
|
||||||
|
bus *eventbus.Bus
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewService constructs a Service. A nil logger gets slog.Default().
|
// 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}
|
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 /
|
// PlaylistRow is the wire shape returned by Create / Update / List /
|
||||||
// the embedded portion of Get. owner_username is denormalized in via
|
// the embedded portion of Get. owner_username is denormalized in via
|
||||||
// the JOIN on users so callers don't have to resolve it themselves.
|
// 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.
|
// 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) {
|
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 == "" {
|
if name == "" {
|
||||||
return nil, fmt.Errorf("%w: name required", ErrInvalidInput)
|
return nil, fmt.Errorf("%w: name required", ErrInvalidInput)
|
||||||
}
|
}
|
||||||
q := dbq.New(s.pool)
|
q := dbq.New(s.pool)
|
||||||
row, err := q.CreatePlaylist(ctx, dbq.CreatePlaylistParams{
|
row, err := q.CreatePlaylist(ctx, dbq.CreatePlaylistParams{
|
||||||
|
ID: id,
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
Name: name,
|
Name: name,
|
||||||
Description: description,
|
Description: description,
|
||||||
IsPublic: isPublic,
|
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)
|
return nil, fmt.Errorf("create playlist: %w", err)
|
||||||
}
|
}
|
||||||
if err := syncpkg.LogChange(ctx, s.pool, syncpkg.EntityPlaylist,
|
if err := syncpkg.LogChange(ctx, s.pool, syncpkg.EntityPlaylist,
|
||||||
syncpkg.FormatUUID(row.ID), syncpkg.OpUpsert); err != nil {
|
syncpkg.FormatUUID(row.ID), syncpkg.OpUpsert); err != nil {
|
||||||
s.logger.Warn("playlists: LogChange create failed", "playlist_id", row.ID, "err", err)
|
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)
|
full, err := q.GetPlaylist(ctx, row.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("get-after-create: %w", err)
|
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 {
|
syncpkg.FormatUUID(updated.ID), syncpkg.OpUpsert); err != nil {
|
||||||
s.logger.Warn("playlists: LogChange update failed", "playlist_id", updated.ID, "err", err)
|
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)
|
full, err := q.GetPlaylist(ctx, updated.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("get-after-update: %w", err)
|
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 {
|
syncpkg.FormatUUID(deleted.ID), syncpkg.OpDelete); err != nil {
|
||||||
s.logger.Warn("playlists: LogChange delete failed", "playlist_id", deleted.ID, "err", err)
|
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 != "" {
|
if deleted.CoverPath != nil && *deleted.CoverPath != "" {
|
||||||
full := filepath.Join(s.dataDir, *deleted.CoverPath)
|
full := filepath.Join(s.dataDir, *deleted.CoverPath)
|
||||||
if rerr := os.Remove(full); rerr != nil && !errors.Is(rerr, os.ErrNotExist) {
|
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
|
// RemoveTrack deletes the row at `position` and renumbers subsequent
|
||||||
// rows to close the gap. Triggers cover regeneration after.
|
// rows to close the gap. With a valid expect, the row must hold that
|
||||||
func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.UUID, position int32) error {
|
// track, or nothing is removed and the answer is ErrListChanged: a client
|
||||||
return s.RemovePositions(ctx, callerID, playlistID, []int32{position})
|
// 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
|
// 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
|
// position repeated is removed once; one with no row is ErrNotFound and
|
||||||
// removes nothing.
|
// removes nothing.
|
||||||
func (s *Service) RemovePositions(ctx context.Context, callerID, playlistID pgtype.UUID, positions []int32) error {
|
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 {
|
if len(positions) == 0 {
|
||||||
return fmt.Errorf("%w: at least one position required", ErrInvalidInput)
|
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)
|
return fmt.Errorf("lookup track at position: %w", err)
|
||||||
}
|
}
|
||||||
|
if expect.Valid && deletedTrackID != expect {
|
||||||
|
return ErrListChanged
|
||||||
|
}
|
||||||
if err := tq.DeletePlaylistTrack(ctx, dbq.DeletePlaylistTrackParams{
|
if err := tq.DeletePlaylistTrack(ctx, dbq.DeletePlaylistTrackParams{
|
||||||
PlaylistID: playlistID,
|
PlaylistID: playlistID,
|
||||||
Position: position,
|
Position: position,
|
||||||
@@ -479,6 +520,7 @@ func (s *Service) changeTracks(ctx context.Context, callerID, playlistID pgtype.
|
|||||||
if err := tx.Commit(ctx); err != nil {
|
if err := tx.Commit(ctx); err != nil {
|
||||||
return fmt.Errorf("commit: %w", err)
|
return fmt.Errorf("commit: %w", err)
|
||||||
}
|
}
|
||||||
|
s.publish("playlist.tracks_changed", callerID, playlistID)
|
||||||
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil {
|
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil {
|
||||||
s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr)
|
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
|
// 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].
|
// (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 {
|
func (s *Service) Reorder(ctx context.Context, callerID, playlistID pgtype.UUID, orderedPositions []int32) error {
|
||||||
pl, err := editable(ctx, dbq.New(s.pool), callerID, playlistID)
|
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
||||||
if err != nil {
|
entries, err := dbq.New(tx).ListPlaylistEntriesForUpdate(ctx, playlistID)
|
||||||
return err
|
if err != nil {
|
||||||
}
|
return fmt.Errorf("list entries: %w", 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)
|
|
||||||
}
|
}
|
||||||
if _, dup := seen[p]; dup {
|
n := int32(len(entries))
|
||||||
return fmt.Errorf("%w: position %d duplicated", ErrInvalidInput, p)
|
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
|
// ReorderTracks puts the playlist's songs in the order trackIDs gives.
|
||||||
// range of valid positions and the unique PK) then write the new
|
// Entries it doesn't name (a song that has left the library, or one added
|
||||||
// positions one by one. Single transaction.
|
// since the caller last looked) keep their places, and the named ones are
|
||||||
tx, err := s.pool.Begin(ctx)
|
// arranged among the places left; a track id the playlist doesn't hold is
|
||||||
if err != nil {
|
// skipped. Sending the same order twice changes nothing the second time,
|
||||||
return fmt.Errorf("begin tx: %w", err)
|
// 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 {
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
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,
|
if _, err := tx.Exec(ctx,
|
||||||
`UPDATE playlist_tracks SET position = position + 10000 WHERE playlist_id = $1`,
|
`UPDATE playlist_tracks SET position = position + 10000 WHERE playlist_id = $1`,
|
||||||
playlistID); err != nil {
|
playlistID); err != nil {
|
||||||
return fmt.Errorf("offset positions: %w", err)
|
return fmt.Errorf("offset positions: %w", err)
|
||||||
}
|
}
|
||||||
for newPos, oldPos := range orderedPositions {
|
for newPos, oldPos := range perm {
|
||||||
if _, err := tx.Exec(ctx,
|
if _, err := tx.Exec(ctx,
|
||||||
`UPDATE playlist_tracks SET position = $1 WHERE playlist_id = $2 AND position = $3`,
|
`UPDATE playlist_tracks SET position = $1 WHERE playlist_id = $2 AND position = $3`,
|
||||||
int32(newPos), playlistID, oldPos+10000); err != nil {
|
int32(newPos), playlistID, oldPos+10000); err != nil {
|
||||||
return fmt.Errorf("write new position: %w", err)
|
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
|
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 {
|
func playlistFromGetRow(r dbq.GetPlaylistRow) *PlaylistRow {
|
||||||
return &PlaylistRow{
|
return &PlaylistRow{
|
||||||
ID: r.ID,
|
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})
|
_ = svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID, t3.ID})
|
||||||
|
|
||||||
// Remove the middle one (position 1).
|
// 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)
|
t.Fatalf("RemoveTrack: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -145,7 +145,6 @@ func (s *Server) Router() http.Handler {
|
|||||||
)
|
)
|
||||||
quarantineSvc := quarantine.NewService(s.Pool, s.DataDir)
|
quarantineSvc := quarantine.NewService(s.Pool, s.DataDir)
|
||||||
tracksSvc := tracks.NewService(s.Pool, s.Logger, s.DataDir)
|
tracksSvc := tracks.NewService(s.Pool, s.Logger, s.DataDir)
|
||||||
playlistsSvc := playlists.NewService(s.Pool, s.Logger, s.DataDir)
|
|
||||||
smtpSender := mailer.NewSMTPSender(s.Pool, s.Logger.With("component", "mailer"))
|
smtpSender := mailer.NewSMTPSender(s.Pool, s.Logger.With("component", "mailer"))
|
||||||
// Live-event bus for SSE subscribers, one per process: producers in
|
// Live-event bus for SSE subscribers, one per process: producers in
|
||||||
// playevents / scanner publish into the same instance.
|
// playevents / scanner publish into the same instance.
|
||||||
@@ -156,6 +155,8 @@ func (s *Server) Router() http.Handler {
|
|||||||
if bus == nil {
|
if bus == nil {
|
||||||
bus = eventbus.New()
|
bus = eventbus.New()
|
||||||
}
|
}
|
||||||
|
playlistsSvc := playlists.NewService(s.Pool, s.Logger, s.DataDir)
|
||||||
|
playlistsSvc.PublishTo(bus)
|
||||||
recSettings := s.RecSettings
|
recSettings := s.RecSettings
|
||||||
if recSettings == nil {
|
if recSettings == nil {
|
||||||
// Test contexts construct Server directly without main.go's
|
// Test contexts construct Server directly without main.go's
|
||||||
|
|||||||
Reference in New Issue
Block a user