diff --git a/internal/api/events_publish.go b/internal/api/events_publish.go index 4a3d17d4..182af2cd 100644 --- a/internal/api/events_publish.go +++ b/internal/api/events_publish.go @@ -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 // playlists (and You-might-like rows) were regenerated, so they invalidate // the home / system-playlist providers and a stale active queue can re-pull. diff --git a/internal/api/playlists.go b/internal/api/playlists.go index 97efecf6..d4c9eabb 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -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 { + ID string `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description"` IsPublic bool `json:"is_public"` @@ -200,12 +203,19 @@ func (h *handlers) handleCreatePlaylist(w http.ResponseWriter, r *http.Request) if !decodeBody(w, r, &body) { 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 { h.writePlaylistErr(w, err, "create") return } - h.publishPlaylistEvent("playlist.created", caller.ID, row.ID) 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") return } - h.publishPlaylistEvent("playlist.updated", caller.ID, playlistID) 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") return } - h.publishPlaylistEvent("playlist.deleted", caller.ID, playlistID) w.WriteHeader(http.StatusNoContent) } @@ -304,20 +312,14 @@ func (h *handlers) handleAppendTracks(w http.ResponseWriter, r *http.Request) { if !decodeBody(w, r, &body) { return } - trackIDs := make([]pgtype.UUID, 0, len(body.TrackIDs)) - for _, s := range body.TrackIDs { - u, ok := parseUUID(s) - if !ok { - writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid track id %q", s))) - return - } - trackIDs = append(trackIDs, u) + trackIDs, ok := parseTrackIDs(w, body.TrackIDs) + if !ok { + return } if err := h.playlists.AppendTracks(r.Context(), caller.ID, playlistID, trackIDs); err != nil { h.writePlaylistErr(w, err, "append tracks") return } - h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID) detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID) if err != nil { 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")) 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") return } - h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID) detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID) if err != nil { 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)) } +// 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 { - OrderedPositions []int32 `json:"ordered_positions"` + OrderedPositions []int32 `json:"ordered_positions"` + TrackIDs []string `json:"track_ids"` } // 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) { 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") return } - h.publishPlaylistEvent("playlist.tracks_changed", caller.ID, playlistID) detail, err := h.playlists.Get(r.Context(), caller.ID, playlistID) if err != nil { 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)) } +// 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 // 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 @@ -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")) case errors.Is(err, playlists.ErrInvalidInput): 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): writeErr(w, apierror.BadRequest("bad_request", "one of the supplied track ids does not exist")) default: diff --git a/internal/db/dbq/playlists.sql.go b/internal/db/dbq/playlists.sql.go index 78fe80f0..3f6d6e6d 100644 --- a/internal/db/dbq/playlists.sql.go +++ b/internal/db/dbq/playlists.sql.go @@ -57,20 +57,26 @@ func (q *Queries) AppendPlaylistTrack(ctx context.Context, arg AppendPlaylistTra } const createPlaylist = `-- name: CreatePlaylist :one -INSERT INTO playlists (user_id, name, description, is_public) -VALUES ($1, $2, $3, $4) +INSERT INTO playlists (id, user_id, name, description, is_public) +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 ` type CreatePlaylistParams struct { + ID pgtype.UUID UserID pgtype.UUID Name string Description string 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) { row := q.db.QueryRow(ctx, createPlaylist, + arg.ID, arg.UserID, arg.Name, arg.Description, @@ -309,6 +315,41 @@ func (q *Queries) ListPlaylistCoverAlbums(ctx context.Context, playlistIds []pgt 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 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, diff --git a/internal/db/queries/playlists.sql b/internal/db/queries/playlists.sql index bf127bed..92527b7d 100644 --- a/internal/db/queries/playlists.sql +++ b/internal/db/queries/playlists.sql @@ -1,6 +1,10 @@ -- name: CreatePlaylist :one -INSERT INTO playlists (user_id, name, description, is_public) -VALUES ($1, $2, $3, $4) +-- 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. +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 *; -- 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 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 -- 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 diff --git a/internal/playlists/export_test.go b/internal/playlists/export_test.go index 26920459..60cc6eb3 100644 --- a/internal/playlists/export_test.go +++ b/internal/playlists/export_test.go @@ -8,3 +8,6 @@ type RankedCandidate = rankedCandidate // OneCopyPerSong is oneCopyPerSong, for tests. var OneCopyPerSong = oneCopyPerSong + +// OrderByTracks is orderByTracks, for tests. +var OrderByTracks = orderByTracks diff --git a/internal/playlists/offline_replay_test.go b/internal/playlists/offline_replay_test.go new file mode 100644 index 00000000..20d582b2 --- /dev/null +++ b/internal/playlists/offline_replay_test.go @@ -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 +} diff --git a/internal/playlists/service.go b/internal/playlists/service.go index f9e6df7d..531b3d84 100644 --- a/internal/playlists/service.go +++ b/internal/playlists/service.go @@ -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, diff --git a/internal/playlists/service_test.go b/internal/playlists/service_test.go index b98b08b4..e80b4621 100644 --- a/internal/playlists/service_test.go +++ b/internal/playlists/service_test.go @@ -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) } diff --git a/internal/server/server.go b/internal/server/server.go index 4a0994b1..b419b754 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -145,7 +145,6 @@ func (s *Server) Router() http.Handler { ) quarantineSvc := quarantine.NewService(s.Pool, 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")) // Live-event bus for SSE subscribers, one per process: producers in // playevents / scanner publish into the same instance. @@ -156,6 +155,8 @@ func (s *Server) Router() http.Handler { if bus == nil { bus = eventbus.New() } + playlistsSvc := playlists.NewService(s.Pool, s.Logger, s.DataDir) + playlistsSvc.PublishTo(bus) recSettings := s.RecSettings if recSettings == nil { // Test contexts construct Server directly without main.go's