feat(library): Missing files says why each track waits, and can forget or export it
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m26s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m29s
release / android (push) Successful in 4m43s
release / Build signed APK (push) Successful in 5m1s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped

- The missing list carries each track's disc and track number, its
  recording and release-group MBIDs, the Collection queue its file was
  removed from, and the admin who removed it.
- POST /api/admin/library/missing/forget deletes waiting tracks for good,
  tidying away an album or artist they leave empty, and writes a
  track_forget audit row naming each. It is all or nothing: a track that
  has its file again is refused with 409 track_has_file.
- GET /api/admin/library/missing.csv exports every waiting track (artist,
  album, disc, track, title, MBIDs, why, since) to hand to whatever finds
  music.
- DELETE /api/admin/tracks/{id} is retired. No client called it; its
  service becomes tracks.Service.ForgetTracks.

Grimoire #7744 (milestone 635).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:34:01 -05:00
co-authored by Claude Opus 5.5
parent 9462052625
commit 492eb2fb9a
16 changed files with 621 additions and 558 deletions
+20 -56
View File
@@ -1,25 +1,17 @@
// Package tracks owns the track-level admin actions behind DELETE
// /api/admin/tracks/{id} and the duplicate merge. RemoveTrack's destructive
// part goes through library.DeleteTrackFile — the one path that deletes a
// track file.
//
// No client calls the endpoint today; it is kept for an admin surface to
// rebind.
// Package tracks owns the track-level admin actions that are written to the
// audit log: forgetting tracks that wait for a file, and the duplicate merge.
package tracks
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
)
@@ -30,7 +22,7 @@ import (
// same pointer.
var ErrNotFound = apierror.ErrNotFound
// Service owns RemoveTrack and MergeDuplicates.
// Service owns ForgetTracks and MergeDuplicates.
type Service struct {
pool *pgxpool.Pool
logger *slog.Logger
@@ -47,55 +39,27 @@ func NewService(pool *pgxpool.Pool, logger *slog.Logger, dataDir string) *Servic
return &Service{pool: pool, logger: logger, dataDir: dataDir}
}
// RemoveTrack deletes the track's file and then its row, and tidies away an
// album or artist the delete empties.
//
// Returns:
// - deletedAlbumID: non-nil when removing the track left the album
// empty and the album row was deleted.
// - deletedArtistID: non-nil when both album AND artist were left
// empty (only set if deletedAlbumID is also set).
// - err: ErrNotFound, or a failure before anything was deleted. When the
// file cannot be removed it is a *library.FileRemoveError and NOTHING was
// deleted — see library.DeleteTrackFile for why that order is the contract.
//
// A removal is written to the audit log with adminID as the actor. The
// track's names are read before the delete, since the row, and perhaps its
// album and artist, are gone after it.
func (s *Service) RemoveTrack(
ctx context.Context, trackID, adminID pgtype.UUID,
) (deletedAlbumID *pgtype.UUID, deletedArtistID *pgtype.UUID, err error) {
q := dbq.New(s.pool)
track, err := q.GetTrackByID(ctx, trackID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil, ErrNotFound
}
return nil, nil, fmt.Errorf("get track: %w", err)
}
meta := map[string]any{
"track_id": syncpkg.FormatUUID(track.ID),
"title": track.Title,
"file_path": track.FilePath,
}
if artist, err := q.GetArtistByID(ctx, track.ArtistID); err == nil {
meta["artist"] = artist.Name
}
if album, err := q.GetAlbumByID(ctx, track.AlbumID); err == nil {
meta["album"] = album.Title
}
deleted, err := library.DeleteTrackFile(ctx, s.pool, s.logger, s.dataDir, trackID)
// ForgetTracks removes tracks waiting for a file that an admin has given up
// on (library.ForgetMissingTracks), and writes the forget to the audit log
// with adminID as the actor, naming each track and the file it had. It is all
// or nothing: a track that has its file again is library.ErrTrackPresent, and
// an unknown one is ErrNotFound.
func (s *Service) ForgetTracks(ctx context.Context, ids []pgtype.UUID, adminID pgtype.UUID) ([]library.ForgottenTrack, error) {
gone, err := library.ForgetMissingTracks(ctx, s.pool, s.logger, s.dataDir, ids)
if err != nil {
if errors.Is(err, library.ErrTrackNotFound) {
return nil, nil, ErrNotFound
return nil, ErrNotFound
}
return nil, nil, fmt.Errorf("delete track: %w", err)
return nil, err
}
meta["album_deleted"] = deleted.AlbumID != nil
meta["artist_deleted"] = deleted.ArtistID != nil
audit.WriteOrLog(ctx, s.pool, s.logger, adminID, pgtype.UUID{}, audit.ActionTrackRemove, meta)
return deleted.AlbumID, deleted.ArtistID, nil
named := make([]map[string]string, 0, len(gone))
for _, t := range gone {
named = append(named, map[string]string{
"track_id": syncpkg.FormatUUID(t.ID), "title": t.Title, "file_path": t.FilePath,
})
}
audit.WriteOrLog(ctx, s.pool, s.logger, adminID, pgtype.UUID{}, audit.ActionTrackForget, map[string]any{"tracks": named})
return gone, nil
}
// MergeDuplicates merges a duplicate group into the copy to keep
+70 -159
View File
@@ -15,6 +15,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
)
// --- test seed helpers (inlined; mirrors quarantine patterns) -----------
@@ -97,200 +98,110 @@ func seedArtistAlbumTrack(t *testing.T, pool *pgxpool.Pool, prefix, mbid, filePa
// --- tests --------------------------------------------------------------
func TestRemoveTrack_NotFound(t *testing.T) {
// markMissing marks tracks as waiting for a file, as a scan that could not
// find them would.
func markMissing(t *testing.T, pool *pgxpool.Pool, ids ...pgtype.UUID) {
t.Helper()
if _, err := dbq.New(pool).MarkTracksMissing(context.Background(), ids); err != nil {
t.Fatalf("mark missing: %v", err)
}
}
func TestForgetTracks_NotFound(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
var bogus pgtype.UUID
bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
bogus.Valid = true
svc := NewService(pool, nil, "")
_, _, err := svc.RemoveTrack(context.Background(), bogus, admin.ID)
_, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{bogus}, admin.ID)
if !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound", err)
}
}
func TestRemoveTrack_LocalFile_HappyPath(t *testing.T) {
// A track that has its file plays, and is not forgotten; nor is the waiting
// track asked about with it.
func TestForgetTracks_RefusesATrackThatHasItsFile(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
dir := t.TempDir()
path := filepath.Join(dir, "track.mp3")
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
_, _, track := seedArtistAlbumTrack(t, pool, "Solo", "", path)
_, _, present := seedArtistAlbumTrack(t, pool, "Present", "", filepath.Join(dir, "p.mp3"))
_, _, waiting := seedArtistAlbumTrack(t, pool, "Waiting", "", filepath.Join(dir, "w.mp3"))
markMissing(t, pool, waiting.ID)
svc := NewService(pool, nil, "")
_, _, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID)
if err != nil {
t.Fatalf("RemoveTrack: %v", err)
}
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Errorf("file still present: %v", err)
_, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{waiting.ID, present.ID}, admin.ID)
if !errors.Is(err, library.ErrTrackPresent) {
t.Fatalf("err = %v, want library.ErrTrackPresent", err)
}
q := dbq.New(pool)
if _, err := q.GetTrackByID(context.Background(), track.ID); err == nil {
t.Errorf("track row still exists")
for _, id := range []pgtype.UUID{present.ID, waiting.ID} {
if _, err := q.GetTrackByID(context.Background(), id); err != nil {
t.Errorf("track %v was forgotten by a refused forget: %v", id, err)
}
}
}
func TestRemoveTrack_WritesAuditRow(t *testing.T) {
// Forget deletes the waiting tracks, tidies away the album and artist they
// leave empty, and names each in the audit log.
func TestForgetTracks_DeletesWaitingTracksAndAudits(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil {
t.Fatalf("reset audit_log: %v", err)
}
path := filepath.Join(t.TempDir(), "lone.mp3")
artist, album, track := seedArtistAlbumTrack(t, pool, "Lone", "", path)
markMissing(t, pool, track.ID)
dir := t.TempDir()
path := filepath.Join(dir, "track.mp3")
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
_, _, track := seedArtistAlbumTrack(t, pool, "Audited", "", path)
svc := NewService(pool, nil, "")
if _, _, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID); err != nil {
t.Fatalf("RemoveTrack: %v", err)
}
var actor pgtype.UUID
var title, artist, album, filePath string
var albumDeleted bool
err := pool.QueryRow(context.Background(), `
SELECT actor_id, metadata->>'title', metadata->>'artist', metadata->>'album',
metadata->>'file_path', (metadata->>'album_deleted')::boolean
FROM audit_log WHERE action = 'track_remove'`).
Scan(&actor, &title, &artist, &album, &filePath, &albumDeleted)
gone, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{track.ID}, admin.ID)
if err != nil {
t.Fatalf("read audit row: %v", err)
t.Fatalf("ForgetTracks: %v", err)
}
if actor != admin.ID {
t.Errorf("actor = %v, want the admin %v", actor, admin.ID)
}
if title != "Audited Track" || artist != "Audited Artist" || album != "Audited Album" || filePath != path {
t.Errorf("metadata = %q / %q / %q / %q", title, artist, album, filePath)
}
if !albumDeleted {
t.Errorf("album_deleted = false, want true: the track was its album's only one")
}
}
func TestRemoveTrack_FileAlreadyMissing(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
// Path doesn't exist on disk; service must tolerate and clean up DB.
missing := filepath.Join(t.TempDir(), "does-not-exist.mp3")
_, _, track := seedArtistAlbumTrack(t, pool, "Ghost", "", missing)
svc := NewService(pool, nil, "")
_, _, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID)
if err != nil {
t.Fatalf("RemoveTrack: %v", err)
if len(gone) != 1 || gone[0].ID != track.ID {
t.Fatalf("forgotten = %+v, want the one track", gone)
}
q := dbq.New(pool)
if _, err := q.GetTrackByID(context.Background(), track.ID); err == nil {
t.Errorf("track row still exists")
}
}
func TestRemoveTrack_Cascade_AlbumEmpty(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
q := dbq.New(pool)
// Two-album artist: removing the sole track of album A leaves A
// orphaned, but the artist still has album B (so the artist cascade
// must NOT fire).
artist, err := q.UpsertArtist(context.Background(), dbq.UpsertArtistParams{
Name: "Cascade Artist", SortName: "Cascade Artist",
})
if err != nil {
t.Fatalf("artist: %v", err)
}
albumA, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{
Title: "Album A", SortTitle: "Album A", ArtistID: artist.ID,
})
if err != nil {
t.Fatalf("albumA: %v", err)
}
albumB, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{
Title: "Album B", SortTitle: "Album B", ArtistID: artist.ID,
})
if err != nil {
t.Fatalf("albumB: %v", err)
}
dir := t.TempDir()
pathA := filepath.Join(dir, "a.mp3")
pathB := filepath.Join(dir, "b.mp3")
_ = os.WriteFile(pathA, []byte("x"), 0o644)
_ = os.WriteFile(pathB, []byte("x"), 0o644)
trackA, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
Title: "TA", AlbumID: albumA.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: pathA, FileSize: 1, FileFormat: "mp3",
})
if err != nil {
t.Fatalf("trackA: %v", err)
}
if _, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
Title: "TB", AlbumID: albumB.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: pathB, FileSize: 1, FileFormat: "mp3",
}); err != nil {
t.Fatalf("trackB: %v", err)
}
svc := NewService(pool, nil, "")
delAlbum, delArtist, err := svc.RemoveTrack(context.Background(), trackA.ID, admin.ID)
if err != nil {
t.Fatalf("RemoveTrack: %v", err)
}
if delAlbum == nil || *delAlbum != albumA.ID {
t.Errorf("deletedAlbumID = %v, want %v", delAlbum, albumA.ID)
}
if delArtist != nil {
t.Errorf("deletedArtistID = %v, want nil (artist still has album B)", delArtist)
}
if _, err := q.GetAlbumByID(context.Background(), albumA.ID); err == nil {
t.Errorf("album A still exists after cascade")
}
if _, err := q.GetAlbumByID(context.Background(), albumB.ID); err != nil {
t.Errorf("album B unexpectedly removed: %v", err)
}
if _, err := q.GetArtistByID(context.Background(), artist.ID); err != nil {
t.Errorf("artist unexpectedly removed: %v", err)
}
}
func TestRemoveTrack_Cascade_ArtistEmpty(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
dir := t.TempDir()
path := filepath.Join(dir, "lone.mp3")
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
artist, album, track := seedArtistAlbumTrack(t, pool, "Lone", "", path)
svc := NewService(pool, nil, "")
delAlbum, delArtist, err := svc.RemoveTrack(context.Background(), track.ID, admin.ID)
if err != nil {
t.Fatalf("RemoveTrack: %v", err)
}
if delAlbum == nil || *delAlbum != album.ID {
t.Errorf("deletedAlbumID = %v, want %v", delAlbum, album.ID)
}
if delArtist == nil || *delArtist != artist.ID {
t.Errorf("deletedArtistID = %v, want %v", delArtist, artist.ID)
}
q := dbq.New(pool)
if _, err := q.GetAlbumByID(context.Background(), album.ID); err == nil {
t.Errorf("album still exists after cascade")
t.Errorf("album left empty still exists")
}
if _, err := q.GetArtistByID(context.Background(), artist.ID); err == nil {
t.Errorf("artist still exists after cascade")
t.Errorf("artist left empty still exists")
}
var actor pgtype.UUID
var title, filePath string
if err := pool.QueryRow(context.Background(), `
SELECT actor_id, metadata->'tracks'->0->>'title', metadata->'tracks'->0->>'file_path'
FROM audit_log WHERE action = 'track_forget'`).Scan(&actor, &title, &filePath); err != nil {
t.Fatalf("read audit row: %v", err)
}
if actor != admin.ID || title != "Lone Track" || filePath != path {
t.Errorf("audit = actor %v, %q, %q", actor, title, filePath)
}
}
// An album that keeps another track is left alone.
func TestForgetTracks_KeepsAnAlbumThatStillHasTracks(t *testing.T) {
pool := newPool(t)
admin := seedAdmin(t, pool, "alice")
q := dbq.New(pool)
ctx := context.Background()
_, album, first := seedArtistAlbumTrack(t, pool, "Shared", "", filepath.Join(t.TempDir(), "a.mp3"))
if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Second", AlbumID: album.ID, ArtistID: first.ArtistID,
DurationMs: 1000, FilePath: filepath.Join(t.TempDir(), "b.mp3"), FileSize: 1, FileFormat: "mp3",
}); err != nil {
t.Fatal(err)
}
markMissing(t, pool, first.ID)
if _, err := NewService(pool, nil, "").ForgetTracks(ctx, []pgtype.UUID{first.ID}, admin.ID); err != nil {
t.Fatalf("ForgetTracks: %v", err)
}
if _, err := q.GetAlbumByID(ctx, album.ID); err != nil {
t.Errorf("album with a track left was removed: %v", err)
}
}