fix(playlists): each daily mix keeps its id across rebuilds (#8081)
The nightly rebuild deleted every system playlist and inserted new rows, so each mix got a new id every day. A Subsonic app caches, pins, downloads and syncs a playlist by id, and saw its mixes deleted and recreated daily: a stored mix answered "not found" and an offline download was orphaned. The rebuild now refills yesterday's row for the same mix in place (keyed by kind, plus the seed artist for "Songs like" and the name for a genre mix), inserts only mixes that are new, and deletes the ones today's build didn't make, along with their collage files. The rollups move updated_at, which is the "changed" time Subsonic apps use to see a mix was refreshed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,15 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const clearPlaylistTracks = `-- name: ClearPlaylistTracks :exec
|
||||||
|
DELETE FROM playlist_tracks WHERE playlist_id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) ClearPlaylistTracks(ctx context.Context, playlistID pgtype.UUID) error {
|
||||||
|
_, err := q.db.Exec(ctx, clearPlaylistTracks, playlistID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
const clearStaleSystemPlaylistInFlight = `-- name: ClearStaleSystemPlaylistInFlight :exec
|
const clearStaleSystemPlaylistInFlight = `-- name: ClearStaleSystemPlaylistInFlight :exec
|
||||||
UPDATE system_playlist_runs SET in_flight = false WHERE in_flight = true
|
UPDATE system_playlist_runs SET in_flight = false WHERE in_flight = true
|
||||||
`
|
`
|
||||||
@@ -75,14 +84,14 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleteSystemPlaylistsForUser = `-- name: DeleteSystemPlaylistsForUser :exec
|
const deletePlaylistsByIDs = `-- name: DeletePlaylistsByIDs :exec
|
||||||
DELETE FROM playlists WHERE user_id = $1 AND kind = 'system'
|
DELETE FROM playlists WHERE id = ANY($1::uuid[])
|
||||||
`
|
`
|
||||||
|
|
||||||
// Atomic-replace step. CASCADE on playlist_tracks.playlist_id handles
|
// Mixes a rebuild no longer makes. CASCADE on playlist_tracks.playlist_id
|
||||||
// the join rows.
|
// handles the join rows.
|
||||||
func (q *Queries) DeleteSystemPlaylistsForUser(ctx context.Context, userID pgtype.UUID) error {
|
func (q *Queries) DeletePlaylistsByIDs(ctx context.Context, ids []pgtype.UUID) error {
|
||||||
_, err := q.db.Exec(ctx, deleteSystemPlaylistsForUser, userID)
|
_, err := q.db.Exec(ctx, deletePlaylistsByIDs, ids)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,6 +312,46 @@ func (q *Queries) ListPlaylistsByUserAndKind(ctx context.Context, arg ListPlayli
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listSystemPlaylistsForRebuild = `-- name: ListSystemPlaylistsForRebuild :many
|
||||||
|
SELECT id, name, system_variant, seed_artist_id
|
||||||
|
FROM playlists
|
||||||
|
WHERE user_id = $1 AND kind = 'system'
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListSystemPlaylistsForRebuildRow struct {
|
||||||
|
ID pgtype.UUID
|
||||||
|
Name string
|
||||||
|
SystemVariant *string
|
||||||
|
SeedArtistID pgtype.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
// The user's current mixes, so a rebuild can refill each in place and keep
|
||||||
|
// its id.
|
||||||
|
func (q *Queries) ListSystemPlaylistsForRebuild(ctx context.Context, userID pgtype.UUID) ([]ListSystemPlaylistsForRebuildRow, error) {
|
||||||
|
rows, err := q.db.Query(ctx, listSystemPlaylistsForRebuild, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []ListSystemPlaylistsForRebuildRow
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListSystemPlaylistsForRebuildRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.Name,
|
||||||
|
&i.SystemVariant,
|
||||||
|
&i.SeedArtistID,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const pickSeedArtists = `-- name: PickSeedArtists :many
|
const pickSeedArtists = `-- name: PickSeedArtists :many
|
||||||
WITH liked AS (
|
WITH liked AS (
|
||||||
SELECT gla.artist_id FROM general_likes_artists gla WHERE gla.user_id = $1
|
SELECT gla.artist_id FROM general_likes_artists gla WHERE gla.user_id = $1
|
||||||
@@ -528,6 +577,31 @@ func (q *Queries) PickTopPlayedTracksForUser(ctx context.Context, userID pgtype.
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const refreshSystemPlaylist = `-- name: RefreshSystemPlaylist :exec
|
||||||
|
UPDATE playlists
|
||||||
|
SET name = $2, description = $3, shelf_rank = $4
|
||||||
|
WHERE id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
type RefreshSystemPlaylistParams struct {
|
||||||
|
ID pgtype.UUID
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
ShelfRank int32
|
||||||
|
}
|
||||||
|
|
||||||
|
// A rebuild refilling an existing mix: its name, description and shelf
|
||||||
|
// place may move with the day's build. updated_at moves with the rollups.
|
||||||
|
func (q *Queries) RefreshSystemPlaylist(ctx context.Context, arg RefreshSystemPlaylistParams) error {
|
||||||
|
_, err := q.db.Exec(ctx, refreshSystemPlaylist,
|
||||||
|
arg.ID,
|
||||||
|
arg.Name,
|
||||||
|
arg.Description,
|
||||||
|
arg.ShelfRank,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
const tryClaimSystemPlaylistRun = `-- name: TryClaimSystemPlaylistRun :one
|
const tryClaimSystemPlaylistRun = `-- name: TryClaimSystemPlaylistRun :one
|
||||||
INSERT INTO system_playlist_runs (user_id, in_flight)
|
INSERT INTO system_playlist_runs (user_id, in_flight)
|
||||||
VALUES ($1, true)
|
VALUES ($1, true)
|
||||||
|
|||||||
@@ -214,10 +214,27 @@ SELECT COALESCE(
|
|||||||
LIMIT 1)
|
LIMIT 1)
|
||||||
)::uuid AS id;
|
)::uuid AS id;
|
||||||
|
|
||||||
-- name: DeleteSystemPlaylistsForUser :exec
|
-- name: ListSystemPlaylistsForRebuild :many
|
||||||
-- Atomic-replace step. CASCADE on playlist_tracks.playlist_id handles
|
-- The user's current mixes, so a rebuild can refill each in place and keep
|
||||||
-- the join rows.
|
-- its id.
|
||||||
DELETE FROM playlists WHERE user_id = $1 AND kind = 'system';
|
SELECT id, name, system_variant, seed_artist_id
|
||||||
|
FROM playlists
|
||||||
|
WHERE user_id = $1 AND kind = 'system';
|
||||||
|
|
||||||
|
-- name: RefreshSystemPlaylist :exec
|
||||||
|
-- A rebuild refilling an existing mix: its name, description and shelf
|
||||||
|
-- place may move with the day's build. updated_at moves with the rollups.
|
||||||
|
UPDATE playlists
|
||||||
|
SET name = $2, description = sqlc.arg(description), shelf_rank = sqlc.arg(shelf_rank)
|
||||||
|
WHERE id = $1;
|
||||||
|
|
||||||
|
-- name: ClearPlaylistTracks :exec
|
||||||
|
DELETE FROM playlist_tracks WHERE playlist_id = $1;
|
||||||
|
|
||||||
|
-- name: DeletePlaylistsByIDs :exec
|
||||||
|
-- Mixes a rebuild no longer makes. CASCADE on playlist_tracks.playlist_id
|
||||||
|
-- handles the join rows.
|
||||||
|
DELETE FROM playlists WHERE id = ANY(sqlc.arg(ids)::uuid[]);
|
||||||
|
|
||||||
-- name: ListPlaylistsByUserAndKind :many
|
-- name: ListPlaylistsByUserAndKind :many
|
||||||
-- Used in integration tests; production filter applied in Go
|
-- Used in integration tests; production filter applied in Go
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ func buildDiscoverCandidates(ctx context.Context, q *dbq.Queries, logger *slog.L
|
|||||||
pools.random[:allocations[3]],
|
pools.random[:allocations[3]],
|
||||||
)
|
)
|
||||||
|
|
||||||
// Convert to rankedCandidate (the type insertSystemPlaylist accepts).
|
// Convert to rankedCandidate (the type materializeSystemPlaylist accepts).
|
||||||
// Score is unused for Discover — the daily-deterministic md5 ordering
|
// Score is unused for Discover — the daily-deterministic md5 ordering
|
||||||
// already gave us the ranking.
|
// already gave us the ranking.
|
||||||
ranked := make([]rankedCandidate, 0, len(out))
|
ranked := make([]rankedCandidate, 0, len(out))
|
||||||
|
|||||||
+101
-30
@@ -14,6 +14,8 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"math"
|
"math"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -859,12 +861,31 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
|
|||||||
defer func() { _ = tx.Rollback(ctx) }()
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
qtx := dbq.New(tx)
|
qtx := dbq.New(tx)
|
||||||
|
|
||||||
if err := qtx.DeleteSystemPlaylistsForUser(ctx, userID); err != nil {
|
// Each mix keeps its id from one day's build to the next: the rebuild
|
||||||
buildErr = fmt.Errorf("delete old system playlists: %w", err)
|
// refills yesterday's row for the same mix rather than making a new one.
|
||||||
|
// A Subsonic app caches, pins, downloads and syncs a playlist by its id,
|
||||||
|
// and would otherwise see every mix deleted and recreated each day.
|
||||||
|
existing, err := qtx.ListSystemPlaylistsForRebuild(ctx, userID)
|
||||||
|
if err != nil {
|
||||||
|
buildErr = fmt.Errorf("list current system playlists: %w", err)
|
||||||
return buildErr
|
return buildErr
|
||||||
}
|
}
|
||||||
|
current := make(map[string]pgtype.UUID, len(existing))
|
||||||
|
var stale []pgtype.UUID
|
||||||
|
for _, e := range existing {
|
||||||
|
variant := ""
|
||||||
|
if e.SystemVariant != nil {
|
||||||
|
variant = *e.SystemVariant
|
||||||
|
}
|
||||||
|
key := systemMixKey(variant, e.SeedArtistID, e.Name)
|
||||||
|
if _, dup := current[key]; dup {
|
||||||
|
stale = append(stale, e.ID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
current[key] = e.ID
|
||||||
|
}
|
||||||
|
|
||||||
// Track the playlist IDs we create so we can generate collage covers
|
// Track the playlist IDs we fill so we can generate collage covers
|
||||||
// for each one after the transaction commits. Collage generation
|
// for each one after the transaction commits. Collage generation
|
||||||
// reads the playlist's tracks via a separate query that won't see
|
// reads the playlist's tracks via a separate query that won't see
|
||||||
// uncommitted rows, so the work happens post-commit.
|
// uncommitted rows, so the work happens post-commit.
|
||||||
@@ -874,14 +895,29 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
|
|||||||
if len(bp.Tracks) == 0 {
|
if len(bp.Tracks) == 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
id, err := insertSystemPlaylist(ctx, qtx, userID, bp)
|
key := systemMixKey(bp.Variant, bp.SeedArtistID, bp.Name)
|
||||||
|
existingID := current[key]
|
||||||
|
delete(current, key)
|
||||||
|
id, err := materializeSystemPlaylist(ctx, qtx, userID, bp, existingID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
buildErr = fmt.Errorf("insert %s (%s): %w", bp.Variant, bp.Name, err)
|
buildErr = fmt.Errorf("fill %s (%s): %w", bp.Variant, bp.Name, err)
|
||||||
return buildErr
|
return buildErr
|
||||||
}
|
}
|
||||||
createdIDs = append(createdIDs, id)
|
createdIDs = append(createdIDs, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Mixes today's build didn't make (a seed artist rotated out, a genre
|
||||||
|
// mix no longer earned, a mix with nothing to hold) are removed.
|
||||||
|
for _, id := range current {
|
||||||
|
stale = append(stale, id)
|
||||||
|
}
|
||||||
|
if len(stale) > 0 {
|
||||||
|
if err := qtx.DeletePlaylistsByIDs(ctx, stale); err != nil {
|
||||||
|
buildErr = fmt.Errorf("delete retired system playlists: %w", err)
|
||||||
|
return buildErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if yml.built {
|
if yml.built {
|
||||||
if err := persistYouMightLike(ctx, qtx, userID, yml); err != nil {
|
if err := persistYouMightLike(ctx, qtx, userID, yml); err != nil {
|
||||||
buildErr = fmt.Errorf("persist you-might-like: %w", err)
|
buildErr = fmt.Errorf("persist you-might-like: %w", err)
|
||||||
@@ -908,10 +944,27 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
|
|||||||
"playlist_id", uuidStringPL(plID), "err", cerr)
|
"playlist_id", uuidStringPL(plID), "err", cerr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for _, plID := range stale {
|
||||||
|
_ = os.Remove(filepath.Join(dataDir, "playlist_covers", uuidToFilename(plID)+".jpg"))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// systemMixKey names a mix across days, so a rebuild can find yesterday's
|
||||||
|
// row for it: the kind, plus the seed artist for a "Songs like" mix (whose
|
||||||
|
// name follows the artist's) and the name for a genre mix (one per genre).
|
||||||
|
// Every other kind is one mix per person.
|
||||||
|
func systemMixKey(variant string, seedArtistID pgtype.UUID, name string) string {
|
||||||
|
switch {
|
||||||
|
case seedArtistID.Valid:
|
||||||
|
return variant + "/" + uuidStringPL(seedArtistID)
|
||||||
|
case variant == "genre_mix":
|
||||||
|
return variant + "/" + name
|
||||||
|
}
|
||||||
|
return variant
|
||||||
|
}
|
||||||
|
|
||||||
// pickTopN sorts candidates by score DESC, applies per-album (<=2) /
|
// pickTopN sorts candidates by score DESC, applies per-album (<=2) /
|
||||||
// per-artist (<=3) diversity caps matching Discover's behavior, then
|
// per-artist (<=3) diversity caps matching Discover's behavior, then
|
||||||
// truncates to n. Used by Songs-like-X (and as the fallback inside
|
// truncates to n. Used by Songs-like-X (and as the fallback inside
|
||||||
@@ -1055,32 +1108,50 @@ func systemMixDescription(variant string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// insertSystemPlaylist inserts a kind='system' playlists row plus its
|
// materializeSystemPlaylist fills a kind='system' playlist with bp's
|
||||||
// playlist_tracks via AppendPlaylistTrack (which
|
// tracks via AppendPlaylistTrack (which does the snapshot lookup from
|
||||||
// does the snapshot lookup from tracks/albums/artists). Then recomputes
|
// tracks/albums/artists), then recomputes rollups. existingID, when valid,
|
||||||
// rollups. Returns the new playlist's ID so the caller can drive
|
// is yesterday's row for the same mix, refilled in place so its id holds;
|
||||||
// post-commit collage generation.
|
// otherwise a new row is inserted. Returns the playlist's ID so the caller
|
||||||
|
// can drive post-commit collage generation.
|
||||||
//
|
//
|
||||||
// Pass seed_artist_id with Valid=false (zero pgtype.UUID) for the For-You
|
// Pass seed_artist_id with Valid=false (zero pgtype.UUID) for the For-You
|
||||||
// variant; the CreateSystemPlaylist query persists NULL.
|
// variant; the CreateSystemPlaylist query persists NULL.
|
||||||
//
|
//
|
||||||
// cover_path is always inserted as NULL — the post-commit collage step
|
// A new row's cover_path is NULL — the post-commit collage step in
|
||||||
// in BuildSystemPlaylists overrides it with a 4-cell composite of the
|
// BuildSystemPlaylists draws a 4-cell composite of the contributing
|
||||||
// contributing tracks' album art.
|
// tracks' album art (to the same file, for a refilled row).
|
||||||
func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.UUID,
|
func materializeSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.UUID,
|
||||||
bp builtPlaylist) (pgtype.UUID, error) {
|
bp builtPlaylist, existingID pgtype.UUID) (pgtype.UUID, error) {
|
||||||
variantStr := bp.Variant
|
var playlistID pgtype.UUID
|
||||||
p, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{
|
if existingID.Valid {
|
||||||
UserID: userID,
|
if err := qtx.RefreshSystemPlaylist(ctx, dbq.RefreshSystemPlaylistParams{
|
||||||
Name: bp.Name,
|
ID: existingID,
|
||||||
Description: systemMixDescription(bp.Variant),
|
Name: bp.Name,
|
||||||
SystemVariant: &variantStr,
|
Description: systemMixDescription(bp.Variant),
|
||||||
SeedArtistID: bp.SeedArtistID,
|
ShelfRank: bp.ShelfRank,
|
||||||
CoverPath: nil,
|
}); err != nil {
|
||||||
ShelfRank: bp.ShelfRank,
|
return pgtype.UUID{}, fmt.Errorf("refresh playlist row: %w", err)
|
||||||
})
|
}
|
||||||
if err != nil {
|
if err := qtx.ClearPlaylistTracks(ctx, existingID); err != nil {
|
||||||
return pgtype.UUID{}, fmt.Errorf("insert playlist row: %w", err)
|
return pgtype.UUID{}, fmt.Errorf("clear playlist tracks: %w", err)
|
||||||
|
}
|
||||||
|
playlistID = existingID
|
||||||
|
} else {
|
||||||
|
variantStr := bp.Variant
|
||||||
|
row, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{
|
||||||
|
UserID: userID,
|
||||||
|
Name: bp.Name,
|
||||||
|
Description: systemMixDescription(bp.Variant),
|
||||||
|
SystemVariant: &variantStr,
|
||||||
|
SeedArtistID: bp.SeedArtistID,
|
||||||
|
CoverPath: nil,
|
||||||
|
ShelfRank: bp.ShelfRank,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return pgtype.UUID{}, fmt.Errorf("insert playlist row: %w", err)
|
||||||
|
}
|
||||||
|
playlistID = row.ID
|
||||||
}
|
}
|
||||||
|
|
||||||
tracks, err := oneCopyPerSong(ctx, qtx, bp.Tracks)
|
tracks, err := oneCopyPerSong(ctx, qtx, bp.Tracks)
|
||||||
@@ -1094,7 +1165,7 @@ func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.U
|
|||||||
pickKind = &k
|
pickKind = &k
|
||||||
}
|
}
|
||||||
if _, err := qtx.AppendPlaylistTrack(ctx, dbq.AppendPlaylistTrackParams{
|
if _, err := qtx.AppendPlaylistTrack(ctx, dbq.AppendPlaylistTrackParams{
|
||||||
PlaylistID: p.ID,
|
PlaylistID: playlistID,
|
||||||
TrackID: t.TrackID,
|
TrackID: t.TrackID,
|
||||||
PickKind: pickKind,
|
PickKind: pickKind,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
@@ -1107,10 +1178,10 @@ func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.U
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := qtx.UpdatePlaylistRollups(ctx, p.ID); err != nil {
|
if err := qtx.UpdatePlaylistRollups(ctx, playlistID); err != nil {
|
||||||
return pgtype.UUID{}, fmt.Errorf("update rollups: %w", err)
|
return pgtype.UUID{}, fmt.Errorf("update rollups: %w", err)
|
||||||
}
|
}
|
||||||
return p.ID, nil
|
return playlistID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// oneCopyPerSong keeps the first of a song's copies on different releases
|
// oneCopyPerSong keeps the first of a song's copies on different releases
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ func TestRotateForDay_UntieredPoolIsWholeRotation(t *testing.T) {
|
|||||||
|
|
||||||
func TestFinishMix_PropagatesPickKind(t *testing.T) {
|
func TestFinishMix_PropagatesPickKind(t *testing.T) {
|
||||||
// Tier stamps ride discoverTrack through diversify/truncate into
|
// Tier stamps ride discoverTrack through diversify/truncate into
|
||||||
// the rankedCandidates that insertSystemPlaylist persists.
|
// the rankedCandidates that materializeSystemPlaylist persists.
|
||||||
pool := []discoverTrack{mixTrack(1, pickKindTier1), mixTrack(2, pickKindTier2)}
|
pool := []discoverTrack{mixTrack(1, pickKindTier1), mixTrack(2, pickKindTier2)}
|
||||||
got := finishMix(pool, false)
|
got := finishMix(pool, false)
|
||||||
if len(got) != 2 {
|
if len(got) != 2 {
|
||||||
|
|||||||
@@ -228,39 +228,48 @@ func TestBuildSystemPlaylists_QuarantineExcluded(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBuildSystemPlaylists_AtomicReplace(t *testing.T) {
|
// A rebuild refills each mix in place: a Subsonic app caches, pins and
|
||||||
|
// downloads a playlist by id, so the same mix keeps its id from one build to
|
||||||
|
// the next, and no mix is left behind twice.
|
||||||
|
func TestBuildSystemPlaylists_ARebuildKeepsEachMixsID(t *testing.T) {
|
||||||
pool := dbtest.Pool(t)
|
pool := dbtest.Pool(t)
|
||||||
logger := discardLogger()
|
logger := discardLogger()
|
||||||
u, _ := seedActiveLibrary(t, pool, "atomic", 3, 3)
|
u, _ := seedActiveLibrary(t, pool, "atomic", 3, 3)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
// First build.
|
list := func() map[string]pgtype.UUID {
|
||||||
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil {
|
t.Helper()
|
||||||
|
rows, err := dbq.New(pool).ListPlaylistsByUserAndKind(ctx, dbq.ListPlaylistsByUserAndKindParams{
|
||||||
|
UserID: u.ID, Column2: "system",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("list: %v", err)
|
||||||
|
}
|
||||||
|
out := map[string]pgtype.UUID{}
|
||||||
|
for _, r := range rows {
|
||||||
|
if _, dup := out[r.Name]; dup {
|
||||||
|
t.Fatalf("mix %q is held twice after a rebuild", r.Name)
|
||||||
|
}
|
||||||
|
out[r.Name] = r.ID
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), dir); err != nil {
|
||||||
t.Fatalf("first build: %v", err)
|
t.Fatalf("first build: %v", err)
|
||||||
}
|
}
|
||||||
var ids1 []pgtype.UUID
|
first := list()
|
||||||
rows1, _ := dbq.New(pool).ListPlaylistsByUserAndKind(ctx, dbq.ListPlaylistsByUserAndKindParams{
|
if len(first) == 0 {
|
||||||
UserID: u.ID, Column2: "system",
|
t.Fatal("no system playlists from the first build")
|
||||||
})
|
|
||||||
for _, r := range rows1 {
|
|
||||||
ids1 = append(ids1, r.ID)
|
|
||||||
}
|
}
|
||||||
if len(ids1) == 0 {
|
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), dir); err != nil {
|
||||||
t.Skip("no system playlists from first build; can't verify replace")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Second build — old rows must be gone, replaced with fresh ones.
|
|
||||||
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil {
|
|
||||||
t.Fatalf("second build: %v", err)
|
t.Fatalf("second build: %v", err)
|
||||||
}
|
}
|
||||||
rows2, _ := dbq.New(pool).ListPlaylistsByUserAndKind(ctx, dbq.ListPlaylistsByUserAndKindParams{
|
second := list()
|
||||||
UserID: u.ID, Column2: "system",
|
for name, id := range first {
|
||||||
})
|
if again, ok := second[name]; ok && again != id {
|
||||||
for _, r := range rows2 {
|
t.Errorf("mix %q got a new id on rebuild: %s then %s", name, uuidString(id), uuidString(again))
|
||||||
for _, oldID := range ids1 {
|
|
||||||
if r.ID.Bytes == oldID.Bytes {
|
|
||||||
t.Errorf("playlist id %s persisted across rebuilds — atomic replace failed", uuidString(oldID))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user