diff --git a/internal/api/library_sync.go b/internal/api/library_sync.go index e95e6448..034233ef 100644 --- a/internal/api/library_sync.go +++ b/internal/api/library_sync.go @@ -41,8 +41,7 @@ type syncResponse struct { // has handed out // - 401 / 500 — standard envelope errors func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { - user, ok := requireUser(w, r) - if !ok { + if _, ok := requireUser(w, r); !ok { return } ctx := r.Context() @@ -121,7 +120,7 @@ func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { } } - upserts, err := h.hydrateUpserts(ctx, q, user.ID, upsertIDs) + upserts, err := h.hydrateUpserts(ctx, q, upsertIDs) if err != nil { writeErrWithLog(w, h.logger, "library_sync: hydrateUpserts", err) return @@ -141,16 +140,11 @@ func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) { } // hydrateUpserts loads the current row payloads for each upserted id, -// keyed by entity type (string form). Returns json.RawMessage values so -// each entity's full sqlc row shape passes through unchanged. -// -// Per-user entities (likes, playlists, playlist_tracks) are scoped to -// userID — the change log is global but each user only sees rows that -// concern them. +// keyed by entity type (string form). The log covers the shared library +// only (artists, albums, tracks), so every caller sees the same rows. func (h *handlers) hydrateUpserts( ctx context.Context, q *dbq.Queries, - userID pgtype.UUID, ids map[syncpkg.EntityType][]string, ) (map[string][]json.RawMessage, error) { out := map[string][]json.RawMessage{} @@ -197,73 +191,9 @@ func (h *handlers) hydrateUpserts( } } - userIDStr := syncpkg.FormatUUID(userID) - - if rows := ids[syncpkg.EntityLikeTrack]; len(rows) > 0 { - out["like_track"] = scopedLikeRows(rows, userIDStr, "track_id") - } - if rows := ids[syncpkg.EntityLikeAlbum]; len(rows) > 0 { - out["like_album"] = scopedLikeRows(rows, userIDStr, "album_id") - } - if rows := ids[syncpkg.EntityLikeArtist]; len(rows) > 0 { - out["like_artist"] = scopedLikeRows(rows, userIDStr, "artist_id") - } - - if rows := ids[syncpkg.EntityPlaylist]; len(rows) > 0 { - uuids := stringsToUUIDs(rows) - playlists, err := q.GetPlaylistsByIDs(ctx, uuids) - if err != nil { - return nil, err - } - for _, p := range playlists { - // Filter: only return playlists owned by this user OR public ones - if syncpkg.FormatUUID(p.UserID) != userIDStr && !p.IsPublic { - continue - } - b, _ := json.Marshal(toPlaylistSyncView(p)) - out["playlist"] = append(out["playlist"], b) - } - } - if rows := ids[syncpkg.EntityPlaylistTrack]; len(rows) > 0 { - // playlist_track ids are ":" — we don't know - // playlist ownership here without a JOIN. Pass through; client - // reconciles against its locally-cached playlists. - var msgs []json.RawMessage - for _, id := range rows { - parts := splitOnce(id, ":") - if len(parts) != 2 { - continue - } - b, _ := json.Marshal(map[string]string{ - "playlist_id": parts[0], - "track_id": parts[1], - }) - msgs = append(msgs, b) - } - out["playlist_track"] = msgs - } return out, nil } -// scopedLikeRows filters composite-key like rows to those owned by userID -// and emits {user_id, } JSON shapes. entityKey is "track_id", -// "album_id", or "artist_id" depending on the like table. -func scopedLikeRows(rows []string, userIDStr, entityKey string) []json.RawMessage { - var msgs []json.RawMessage - for _, id := range rows { - parts := splitOnce(id, ":") - if len(parts) != 2 || parts[0] != userIDStr { - continue - } - b, _ := json.Marshal(map[string]string{ - "user_id": parts[0], - entityKey: parts[1], - }) - msgs = append(msgs, b) - } - return msgs -} - // stringsToUUIDs parses each string as a pgtype.UUID. Invalid entries // are skipped silently — they can't have come from a valid scan/mutation. func stringsToUUIDs(strs []string) []pgtype.UUID { @@ -277,14 +207,3 @@ func stringsToUUIDs(strs []string) []pgtype.UUID { } return out } - -// splitOnce returns [before, after] split at the first occurrence of sep, -// or [s] if sep doesn't appear. Used for composite-key parsing. -func splitOnce(s, sep string) []string { - for i := 0; i+len(sep) <= len(s); i++ { - if s[i:i+len(sep)] == sep { - return []string{s[:i], s[i+len(sep):]} - } - } - return []string{s} -} diff --git a/internal/api/library_sync_test.go b/internal/api/library_sync_test.go index 8b4aef78..b3a3690c 100644 --- a/internal/api/library_sync_test.go +++ b/internal/api/library_sync_test.go @@ -146,66 +146,8 @@ func TestLibrarySync_DeleteIsReflected(t *testing.T) { } } -func TestLibrarySync_LikeRowScopedToUser(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - u := seedUser(t, pool, "alice", "x", false) - other := seedUser(t, pool, "bob", "x", false) - - // Two like_track rows: one for u, one for other. u's call should - // see only their own row. - ctx := context.Background() - tx, _ := pool.Begin(ctx) - _ = sync.LogChange(ctx, tx, sync.EntityLikeTrack, - sync.EncodeLikeID(sync.FormatUUID(u.ID), "11111111-1111-1111-1111-111111111111"), - sync.OpUpsert) - _ = sync.LogChange(ctx, tx, sync.EntityLikeTrack, - sync.EncodeLikeID(sync.FormatUUID(other.ID), "22222222-2222-2222-2222-222222222222"), - sync.OpUpsert) - _ = tx.Commit(ctx) - - w := callLibrarySync(h, u, "0") - if w.Code != http.StatusOK { - t.Fatalf("status = %d body = %s", w.Code, w.Body.String()) - } - var body struct { - Upserts map[string][]json.RawMessage `json:"upserts"` - } - if err := json.NewDecoder(w.Body).Decode(&body); err != nil { - t.Fatalf("decode: %v", err) - } - got := body.Upserts["like_track"] - if len(got) != 1 { - t.Fatalf("expected 1 like row scoped to alice, got %d", len(got)) - } -} - // Pure unit tests below — run even with -short. -func TestSplitOnce(t *testing.T) { - cases := []struct { - in, sep string - want []string - }{ - {"a:b", ":", []string{"a", "b"}}, - {"a:b:c", ":", []string{"a", "b:c"}}, - {"abc", ":", []string{"abc"}}, - {":x", ":", []string{"", "x"}}, - } - for _, c := range cases { - got := splitOnce(c.in, c.sep) - if len(got) != len(c.want) { - t.Errorf("splitOnce(%q,%q): len got=%d want=%d", c.in, c.sep, len(got), len(c.want)) - continue - } - for i := range got { - if got[i] != c.want[i] { - t.Errorf("splitOnce(%q,%q)[%d] = %q want %q", c.in, c.sep, i, got[i], c.want[i]) - } - } - } -} - // A server restored from an older backup has handed out fewer cursors than an // app remembers; the app is told to reset rather than wait for ids it would // then skip. A compacted log is not that: the cursor the server handed out diff --git a/internal/api/library_sync_views.go b/internal/api/library_sync_views.go index f3cbd994..c904d610 100644 --- a/internal/api/library_sync_views.go +++ b/internal/api/library_sync_views.go @@ -124,29 +124,3 @@ func toTrackSyncView(t dbq.Track, g library.ReplayGain) trackSyncView { TrackPeak: g.TrackPeak, } } - -type playlistSyncView struct { - ID string `json:"id"` - UserID string `json:"user_id"` - Name string `json:"name"` - Description string `json:"description"` - IsPublic bool `json:"is_public"` - CoverPath *string `json:"cover_path"` - TrackCount int32 `json:"track_count"` - DurationSec int32 `json:"duration_sec"` - SystemVariant *string `json:"system_variant"` -} - -func toPlaylistSyncView(p dbq.Playlist) playlistSyncView { - return playlistSyncView{ - ID: syncpkg.FormatUUID(p.ID), - UserID: syncpkg.FormatUUID(p.UserID), - Name: p.Name, - Description: p.Description, - IsPublic: p.IsPublic, - CoverPath: p.CoverPath, - TrackCount: p.TrackCount, - DurationSec: p.DurationSec, - SystemVariant: p.SystemVariant, - } -} diff --git a/internal/api/library_sync_views_test.go b/internal/api/library_sync_views_test.go index c583eab7..25a9d035 100644 --- a/internal/api/library_sync_views_test.go +++ b/internal/api/library_sync_views_test.go @@ -123,27 +123,3 @@ func TestSyncViews_CarryReplayGain(t *testing.T) { t.Errorf("unmeasured track_gain = %v (present %v), want an explicit null", v, ok) } } - -func TestPlaylistSyncView_WireKeys(t *testing.T) { - variant := "discover" - p := dbq.Playlist{ - ID: validUUID, UserID: validUUID, Name: "Test", - IsPublic: true, TrackCount: 5, DurationSec: 600, - SystemVariant: &variant, - } - b, err := json.Marshal(toPlaylistSyncView(p)) - if err != nil { - t.Fatal(err) - } - assertJSONKeys(t, "playlist", b, []string{ - "id", "user_id", "name", "description", - "is_public", "cover_path", "track_count", - "duration_sec", "system_variant", - }) - // Sanity: system_variant carries the value, not just present. - var m map[string]any - _ = json.Unmarshal(b, &m) - if got := m["system_variant"]; got != "discover" { - t.Errorf("system_variant: want 'discover', got %v", got) - } -} diff --git a/internal/api/likes.go b/internal/api/likes.go index 955ea06a..30834886 100644 --- a/internal/api/likes.go +++ b/internal/api/likes.go @@ -11,21 +11,8 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" - syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) -// logLikeChange writes a library_changes row for a like / unlike. Best- -// effort: a failure here means the next sync may miss the row, but the -// HTTP response still succeeds. Cheap consequence — the user's other -// device sees the like once it manually pulls, or once a later like/unlike -// on the same entity emits a fresh log row. -func (h *handlers) logLikeChange(r *http.Request, et syncpkg.EntityType, userID, entityID pgtype.UUID, op syncpkg.Op) { - if err := syncpkg.LogChange(r.Context(), h.pool, et, - syncpkg.EncodeLikeID(syncpkg.FormatUUID(userID), syncpkg.FormatUUID(entityID)), op); err != nil { - h.logger.Warn("api: LogChange like", "kind", et, "user", userID, "entity", entityID, "err", err) - } -} - type likedIDsResponse struct { TrackIDs []string `json:"track_ids"` AlbumIDs []string `json:"album_ids"` @@ -63,7 +50,6 @@ func (h *handlers) handleLikeTrack(w http.ResponseWriter, r *http.Request) { // The like is on the song: every copy it reached changes on // the client too. for _, t := range withTrack(id, liked) { - h.logLikeChange(r, syncpkg.EntityLikeTrack, user.ID, t, syncpkg.OpUpsert) h.publishLikeEvent(user.ID, t, "track", true) } w.WriteHeader(http.StatusNoContent) @@ -102,7 +88,6 @@ func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) { // Don't fail the response — soft-delete is best-effort. } for _, t := range withTrack(id, unliked) { - h.logLikeChange(r, syncpkg.EntityLikeTrack, user.ID, t, syncpkg.OpDelete) h.publishLikeEvent(user.ID, t, "track", false) } w.WriteHeader(http.StatusNoContent) @@ -132,7 +117,6 @@ func (h *handlers) handleLikeAlbum(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("insert failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeAlbum, user.ID, id, syncpkg.OpUpsert) h.publishLikeEvent(user.ID, id, "album", true) w.WriteHeader(http.StatusNoContent) } @@ -151,7 +135,6 @@ func (h *handlers) handleUnlikeAlbum(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("delete failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeAlbum, user.ID, id, syncpkg.OpDelete) h.publishLikeEvent(user.ID, id, "album", false) w.WriteHeader(http.StatusNoContent) } @@ -180,7 +163,6 @@ func (h *handlers) handleLikeArtist(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("insert failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeArtist, user.ID, id, syncpkg.OpUpsert) h.publishLikeEvent(user.ID, id, "artist", true) w.WriteHeader(http.StatusNoContent) } @@ -199,7 +181,6 @@ func (h *handlers) handleUnlikeArtist(w http.ResponseWriter, r *http.Request) { writeErr(w, apierror.InternalMsg("delete failed", err)) return } - h.logLikeChange(r, syncpkg.EntityLikeArtist, user.ID, id, syncpkg.OpDelete) h.publishLikeEvent(user.ID, id, "artist", false) w.WriteHeader(http.StatusNoContent) } diff --git a/internal/db/db.go b/internal/db/db.go index dc63596c..e6f84a80 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -5,7 +5,6 @@ import ( "embed" "errors" "fmt" - "io/fs" "log/slog" "github.com/golang-migrate/migrate/v4" @@ -17,16 +16,6 @@ import ( //go:embed migrations/*.sql var migrationsFS embed.FS -// MigrationsFS exposes the embedded migration set for callers that need -// raw access (e.g. tests that construct their own migration runner). -func MigrationsFS() fs.FS { - sub, err := fs.Sub(migrationsFS, "migrations") - if err != nil { - panic(fmt.Sprintf("db: sub fs: %v", err)) - } - return sub -} - // Open establishes a pgx connection pool. The caller owns the returned pool // and must Close() it on shutdown. func Open(ctx context.Context, dsn string) (*pgxpool.Pool, error) { diff --git a/internal/db/migrations/0112_sync_log_library_only.down.sql b/internal/db/migrations/0112_sync_log_library_only.down.sql new file mode 100644 index 00000000..dbd9391d --- /dev/null +++ b/internal/db/migrations/0112_sync_log_library_only.down.sql @@ -0,0 +1,2 @@ +-- The cleared rows were never read; there is nothing to put back. +SELECT 1; diff --git a/internal/db/migrations/0112_sync_log_library_only.up.sql b/internal/db/migrations/0112_sync_log_library_only.up.sql new file mode 100644 index 00000000..c5043a44 --- /dev/null +++ b/internal/db/migrations/0112_sync_log_library_only.up.sql @@ -0,0 +1,7 @@ +-- The delta sync (GET /api/library/sync) carries the shared library only: +-- artists, albums and tracks. Likes and playlists reach the apps through +-- their own endpoints and live events, so their rows here were written and +-- never read. Clear them. The entity_type check still admits the old +-- values, so a backup from before this change still restores; nothing +-- writes them any more. +DELETE FROM library_changes WHERE entity_type NOT IN ('artist', 'album', 'track'); diff --git a/internal/library/duplicate_merge.go b/internal/library/duplicate_merge.go index 6bced5fd..d8c0b88d 100644 --- a/internal/library/duplicate_merge.go +++ b/internal/library/duplicate_merge.go @@ -187,7 +187,6 @@ func foldTrackInto( ctx context.Context, tq *dbq.Queries, survivorID, loserID pgtype.UUID, changes *mergeChanges, ) (foldResult, error) { var f foldResult - survivorKey := syncpkg.FormatUUID(survivorID) loserKey := syncpkg.FormatUUID(loserID) n, err := tq.MergeRepointPlayEvents(ctx, dbq.MergeRepointPlayEventsParams{SurvivorID: survivorID, LoserID: loserID}) @@ -212,21 +211,13 @@ func foldTrackInto( return f, fmt.Errorf("move playlist entries: %w", err) } f.PlaylistEntries = len(playlists) - for _, pl := range playlists { - plKey := syncpkg.FormatUUID(pl) - changes.playlistDelete(syncpkg.EncodePlaylistTrackID(plKey, loserKey)) - changes.playlistUpsert(syncpkg.EncodePlaylistTrackID(plKey, survivorKey)) - } users, err := tq.MergeCopyGeneralLikes(ctx, dbq.MergeCopyGeneralLikesParams{SurvivorID: survivorID, LoserID: loserID}) if err != nil { return f, fmt.Errorf("move likes: %w", err) } for _, u := range users { - userKey := syncpkg.FormatUUID(u) - f.Likers = append(f.Likers, userKey) - changes.likeDelete(syncpkg.EncodeLikeID(userKey, loserKey)) - changes.likeUpsert(syncpkg.EncodeLikeID(userKey, survivorKey)) + f.Likers = append(f.Likers, syncpkg.FormatUUID(u)) } if _, err := tq.MergeCopyTrackTags(ctx, dbq.MergeCopyTrackTagsParams{SurvivorID: survivorID, LoserID: loserID}); err != nil { @@ -297,10 +288,9 @@ func mergedCopyOf(m dbq.ListDuplicateGroupMergeMembersRow) MergedCopy { } // mergeChanges collects the sync-log entries a merge owes clients' caches, each -// once: a user who liked two removed copies still gets one upsert for the -// survivor. +// once: the removed copies' tracks. type mergeChanges struct { - tracks, likeDeletes, likeUpserts, playlistDeletes, playlistUpserts map[string]struct{} + tracks map[string]struct{} } func addTo(set *map[string]struct{}, id string) { @@ -310,11 +300,7 @@ func addTo(set *map[string]struct{}, id string) { (*set)[id] = struct{}{} } -func (c *mergeChanges) trackDelete(id string) { addTo(&c.tracks, id) } -func (c *mergeChanges) likeDelete(id string) { addTo(&c.likeDeletes, id) } -func (c *mergeChanges) likeUpsert(id string) { addTo(&c.likeUpserts, id) } -func (c *mergeChanges) playlistDelete(id string) { addTo(&c.playlistDeletes, id) } -func (c *mergeChanges) playlistUpsert(id string) { addTo(&c.playlistUpserts, id) } +func (c *mergeChanges) trackDelete(id string) { addTo(&c.tracks, id) } func (c *mergeChanges) log(ctx context.Context, tx pgx.Tx) error { for _, entry := range []struct { @@ -323,10 +309,6 @@ func (c *mergeChanges) log(ctx context.Context, tx pgx.Tx) error { op syncpkg.Op }{ {syncpkg.EntityTrack, c.tracks, syncpkg.OpDelete}, - {syncpkg.EntityLikeTrack, c.likeDeletes, syncpkg.OpDelete}, - {syncpkg.EntityLikeTrack, c.likeUpserts, syncpkg.OpUpsert}, - {syncpkg.EntityPlaylistTrack, c.playlistDeletes, syncpkg.OpDelete}, - {syncpkg.EntityPlaylistTrack, c.playlistUpserts, syncpkg.OpUpsert}, } { if len(entry.ids) == 0 { continue diff --git a/internal/library/duplicate_resolve.go b/internal/library/duplicate_resolve.go index ed50fb4a..dc04f3b0 100644 --- a/internal/library/duplicate_resolve.go +++ b/internal/library/duplicate_resolve.go @@ -411,17 +411,9 @@ func linkSong(ctx context.Context, pool *pgxpool.Pool, ids []pgtype.UUID) (bool, if link.Moved == 0 { return false, nil } - added, err := tq.ShareSongLikes(ctx, link.SongKey) - if err != nil { + if _, err := tq.ShareSongLikes(ctx, link.SongKey); err != nil { return false, fmt.Errorf("share likes: %w", err) } - likeIDs := make([]string, len(added)) - for i, a := range added { - likeIDs[i] = syncpkg.EncodeLikeID(syncpkg.FormatUUID(a.UserID), syncpkg.FormatUUID(a.TrackID)) - } - if err := syncpkg.LogChanges(ctx, tx, syncpkg.EntityLikeTrack, likeIDs, syncpkg.OpUpsert); err != nil { - return false, fmt.Errorf("log shared likes: %w", err) - } return true, tx.Commit(ctx) } diff --git a/internal/library/scanner.go b/internal/library/scanner.go index b33f2390..c23e0a23 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -799,16 +799,6 @@ func probeDurationMs(ctx context.Context, path string) (int32, error) { return int32(ms), nil } -// ProbeDurationMs is a file's length in milliseconds, read by ffprobe. -func ProbeDurationMs(ctx context.Context, path string) (int32, error) { - return probeDurationMs(ctx, path) -} - -// IsAudioFile reports whether the scanner reads a file with this name. -func IsAudioFile(path string) bool { - return audioExtensions[strings.ToLower(filepath.Ext(path))] -} - // Roots are the folders the scanner reads: the library. func (s *Scanner) Roots() []string { if s == nil { diff --git a/internal/library/song_link_test.go b/internal/library/song_link_test.go index 903c37be..5998e132 100644 --- a/internal/library/song_link_test.go +++ b/internal/library/song_link_test.go @@ -99,15 +99,6 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { if len(liked) != 2 { t.Errorf("liked track ids = %d, want both copies", len(liked)) } - var logged int - if err := pool.QueryRow(ctx, - `SELECT count(*) FROM library_changes WHERE entity_type = 'like_track' AND op = 'upsert'`, - ).Scan(&logged); err != nil { - t.Fatal(err) - } - if logged != 1 { - t.Errorf("logged %d shared likes, want 1 (the album cut)", logged) - } if n, err := q.CountLikedTracks(ctx, f.user.ID); err != nil || n != 1 { t.Errorf("CountLikedTracks = %d (%v), want 1 song", n, err) } diff --git a/internal/playlists/service.go b/internal/playlists/service.go index 531b3d84..bc76956a 100644 --- a/internal/playlists/service.go +++ b/internal/playlists/service.go @@ -170,10 +170,6 @@ func (s *Service) CreateWithID(ctx context.Context, userID, id pgtype.UUID, name 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. @@ -334,10 +330,6 @@ func (s *Service) Update(ctx context.Context, callerID, playlistID pgtype.UUID, if err != nil { return nil, fmt.Errorf("update playlist: %w", err) } - if err := syncpkg.LogChange(ctx, s.pool, syncpkg.EntityPlaylist, - 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 { @@ -361,10 +353,6 @@ func (s *Service) Delete(ctx context.Context, callerID, playlistID pgtype.UUID) if err != nil { return fmt.Errorf("delete playlist: %w", err) } - if err := syncpkg.LogChange(ctx, s.pool, syncpkg.EntityPlaylist, - 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) @@ -415,20 +403,9 @@ func (s *Service) AppendTracks(ctx context.Context, callerID, playlistID pgtype. // exists. func (s *Service) ReplaceTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error { return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error { - rows, err := tx.Query(ctx, - `DELETE FROM playlist_tracks WHERE playlist_id = $1 RETURNING track_id`, playlistID) - if err != nil { + if _, err := tx.Exec(ctx, `DELETE FROM playlist_tracks WHERE playlist_id = $1`, playlistID); err != nil { return fmt.Errorf("clear tracks: %w", err) } - removed, err := pgx.CollectRows(rows, pgx.RowTo[pgtype.UUID]) - if err != nil { - return fmt.Errorf("clear tracks: %w", err) - } - for _, tid := range removed { - if err := logTrackChange(ctx, tx, playlistID, tid, syncpkg.OpDelete); err != nil { - return err - } - } return appendTracks(ctx, tx, playlistID, trackIDs) }) } @@ -464,7 +441,8 @@ func (s *Service) removePositions(ctx context.Context, callerID, playlistID pgty return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error { tq := dbq.New(tx) for _, position := range order { - // The track id names the change for clients that sync. + // Read first: a missing position is ErrNotFound, and expect + // is checked against the row's track. var deletedTrackID pgtype.UUID if err := tx.QueryRow(ctx, `SELECT track_id FROM playlist_tracks WHERE playlist_id = $1 AND position = $2`, @@ -484,9 +462,6 @@ func (s *Service) removePositions(ctx context.Context, callerID, playlistID pgty }); err != nil { return fmt.Errorf("delete track row: %w", err) } - if err := logTrackChange(ctx, tx, playlistID, deletedTrackID, syncpkg.OpDelete); err != nil { - return err - } if err := tq.RenumberPlaylistTracksAfter(ctx, dbq.RenumberPlaylistTracksAfterParams{ PlaylistID: playlistID, Position: position, @@ -543,20 +518,6 @@ func appendTracks(ctx context.Context, tx pgx.Tx, playlistID pgtype.UUID, trackI } return fmt.Errorf("append track: %w", err) } - if err := logTrackChange(ctx, tx, playlistID, tid, syncpkg.OpUpsert); err != nil { - return err - } - } - return nil -} - -// logTrackChange records a playlist entry's change for clients that sync, -// in the transaction that makes it. -func logTrackChange(ctx context.Context, tx pgx.Tx, playlistID, trackID pgtype.UUID, op syncpkg.Op) error { - if err := syncpkg.LogChange(ctx, tx, syncpkg.EntityPlaylistTrack, - syncpkg.EncodePlaylistTrackID(syncpkg.FormatUUID(playlistID), syncpkg.FormatUUID(trackID)), - op); err != nil { - return fmt.Errorf("log change: %w", err) } return nil } diff --git a/internal/sync/changes.go b/internal/sync/changes.go index ec03db41..07e79948 100644 --- a/internal/sync/changes.go +++ b/internal/sync/changes.go @@ -21,9 +21,7 @@ import ( // itself fails after the mutation succeeded, that mutation won't appear in // the change log until the entity is touched again. // -// entityID is the string form of the row's primary key. For composite-key -// entities (likes, playlist_tracks), use EncodeLikeID / EncodePlaylistTrackID -// to produce stable strings. For pgtype.UUID values, use FormatUUID. +// entityID is the row's UUID as a string; use FormatUUID. func LogChange(ctx context.Context, dbtx dbq.DBTX, entityType EntityType, entityID string, op Op) error { q := dbq.New(dbtx) if err := q.InsertLibraryChange(ctx, dbq.InsertLibraryChangeParams{ @@ -83,16 +81,3 @@ func formatUUIDBytes(b [16]byte) string { } return string(out) } - -// EncodeLikeID joins a user UUID and an entity UUID into the stable -// composite identifier used for like_* rows in library_changes. Both -// sides are UUID strings so no escaping is needed. -func EncodeLikeID(userID, entityID string) string { - return userID + ":" + entityID -} - -// EncodePlaylistTrackID joins a playlist UUID and a track UUID into the -// stable composite identifier used for playlist_track rows. -func EncodePlaylistTrackID(playlistID, trackID string) string { - return playlistID + ":" + trackID -} diff --git a/internal/sync/changes_test.go b/internal/sync/changes_test.go index 553a1629..8b5af8b1 100644 --- a/internal/sync/changes_test.go +++ b/internal/sync/changes_test.go @@ -49,12 +49,3 @@ func TestLogChange_RollbackDoesNotPersist(t *testing.T) { require.NoError(t, err) require.Equal(t, cursorBefore, cursorAfter, "rollback must not advance cursor") } - -// Pure unit tests — run even with -short. -func TestEncodeLikeID(t *testing.T) { - require.Equal(t, "u1:t2", sync.EncodeLikeID("u1", "t2")) -} - -func TestEncodePlaylistTrackID(t *testing.T) { - require.Equal(t, "p1:t2", sync.EncodePlaylistTrackID("p1", "t2")) -} diff --git a/internal/sync/types.go b/internal/sync/types.go index 4f507768..c5b40da4 100644 --- a/internal/sync/types.go +++ b/internal/sync/types.go @@ -8,19 +8,16 @@ package sync // EntityType enumerates the entity kinds whose mutations are tracked -// by the library_changes log. Values must stay in sync with the CHECK -// constraint on library_changes.entity_type. +// by the library_changes log: the shared library, the same for every +// listener. The CHECK constraint on library_changes.entity_type also admits +// like_* and playlist* values, which older servers wrote and an older backup +// may still carry; nothing writes or reads them. type EntityType string const ( - EntityArtist EntityType = "artist" - EntityAlbum EntityType = "album" - EntityTrack EntityType = "track" - EntityLikeTrack EntityType = "like_track" - EntityLikeAlbum EntityType = "like_album" - EntityLikeArtist EntityType = "like_artist" - EntityPlaylist EntityType = "playlist" - EntityPlaylistTrack EntityType = "playlist_track" + EntityArtist EntityType = "artist" + EntityAlbum EntityType = "album" + EntityTrack EntityType = "track" ) // Op is upsert or delete. Matches the CHECK constraint on library_changes.op.