feat(library): removing a bad file keeps its track, waiting for a good copy
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m46s
release / android (push) Successful in 4m47s
release / Build signed APK (push) Successful in 5m38s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 31s
release / Verify release artifacts (tag releases only) (push) Skipped

Reports, Duplicates and Suspect sources now end the same way: the file
goes and the track stays, marked missing with its likes, plays and
playlist places, until a good copy lands in the library and move
adoption or missing-pair folding brings it back.

- library.RemoveFile removes one track's file and marks the track
  missing with the queue it was removed from and who removed it
  (tracks.removed_reason / removed_by, migration 0104). The duplicate
  resolver's wrong-slot removal shares the same marking.
- POST /api/admin/quarantine/{id}/remove-file removes a reported file,
  clears the listeners' reports, marks open playback errors deleted and
  records removed_file in the Reports history. A wrong-file or
  wrong-tags report drops the file's recording MBID.
- POST /api/admin/library/suspect-sources/{id}/remove removes a video
  rip's file and its MBID, and writes a suspect_file_remove audit row.
- The removal reason clears with the missing mark when a file returns.

Grimoire #7743 (milestone 635).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:17:26 -05:00
co-authored by Claude Opus 5.5
parent e5f11647ee
commit 9462052625
21 changed files with 694 additions and 28 deletions
+4 -3
View File
@@ -78,9 +78,10 @@ type DeletedTrack struct {
}
// DeleteTrackFile removes a track's file from disk and then its row, tidying
// away an album or artist the delete leaves empty. It is the ONLY path that
// deletes a track file: the admin remove-track endpoint and quarantine's Delete
// file both come through here.
// away an album or artist the delete leaves empty. It is the only path that
// deletes a track with its file: the admin remove-track endpoint and Reports'
// "Remove from library" both come through here. RemoveFile is the other
// path that deletes a file, and it keeps the track.
//
// Order is the whole contract. The file goes first, and if it cannot go — a
// read-only mount, a permission denial, an I/O error — nothing else happens and
+2 -5
View File
@@ -503,8 +503,8 @@ func removeWrongSlots(
}
err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
tq := dbq.New(tx)
if _, err := tq.MarkTracksMissing(ctx, gone); err != nil {
return fmt.Errorf("mark missing: %w", err)
if err := markRemoved(ctx, tq, gone, RemovedForDuplicate, actorID); err != nil {
return err
}
if err := tq.ClearTrackMbids(ctx, gone); err != nil {
return fmt.Errorf("clear mbids: %w", err)
@@ -512,9 +512,6 @@ func removeWrongSlots(
if err := tq.MarkTracksEmptied(ctx, emptied); err != nil {
return fmt.Errorf("mark emptied: %w", err)
}
if err := logTrackChanges(ctx, tq, gone); err != nil {
return fmt.Errorf("log changes: %w", err)
}
if removeErr != nil {
return nil
}
@@ -82,6 +82,14 @@ func TestSettleWrongSlot_GetItAgainRemovesEveryCopy_Integration(t *testing.T) {
if !emptiedTrack(t, f, id) {
t.Errorf("track %s is not marked missing with its slot emptied", syncpkg.FormatUUID(id))
}
got, err := dbq.New(f.pool).GetTrackByID(ctx, id)
if err != nil {
t.Fatal(err)
}
if got.RemovedReason == nil || *got.RemovedReason != string(RemovedForDuplicate) || got.RemovedBy != op.ID {
t.Errorf("track %s waits with reason %v by %v, want duplicate by the admin",
syncpkg.FormatUUID(id), got.RemovedReason, got.RemovedBy)
}
}
settledByHand(t, f, op)
+104
View File
@@ -0,0 +1,104 @@
package library
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/db/dbq"
)
// RemovedFor is the Collection queue a track's file was removed from. Every
// queue ends the same way: the bad file goes and the track waits, missing,
// for a good copy (tracks.removed_reason).
type RemovedFor string
const (
RemovedForReport RemovedFor = "report"
RemovedForDuplicate RemovedFor = "duplicate"
RemovedForSuspect RemovedFor = "suspect"
)
// RemoveFileParams is one track whose file an admin is removing.
type RemoveFileParams struct {
TrackID pgtype.UUID
// ActorID is the admin removing it.
ActorID pgtype.UUID
Reason RemovedFor
// ForgetMBID drops the track's recording MBID. Set it when the file was
// not the track's song, or its tags are not to be trusted: the MBID came
// from that file, and a good copy carrying the real song's MBID must not
// be kept from folding in by it, nor the slot folded into another song.
ForgetMBID bool
// Within runs on the same transaction as the marking, for what the
// caller's queue records about the removal (a report's history row). An
// error from it undoes the marking, though not the removed file.
Within func(ctx context.Context, tq *dbq.Queries) error
}
// RemoveFile removes a track's file from disk and keeps the track: it is
// marked missing, with its likes, plays and playlist places, and the queue it
// was removed from. A good copy that lands in the library later is adopted
// into it (moved.go) or folded into it (missing_pairs.go), so the track comes
// back with its history.
//
// The file goes first. If it cannot, nothing is marked and a
// *FileRemoveError comes back. A file that is already gone is not a failure.
func RemoveFile(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, p RemoveFileParams) (dbq.Track, error) {
if logger == nil {
logger = slog.Default()
}
q := dbq.New(pool)
track, err := q.GetTrackByID(ctx, p.TrackID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return dbq.Track{}, ErrTrackNotFound
}
return dbq.Track{}, fmt.Errorf("get track: %w", err)
}
if err := removeTrackFileOnDisk(track.FilePath); err != nil {
return dbq.Track{}, err
}
err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
tq := dbq.New(tx)
ids := []pgtype.UUID{p.TrackID}
if err := markRemoved(ctx, tq, ids, p.Reason, p.ActorID); err != nil {
return err
}
if p.ForgetMBID {
if err := tq.ClearTrackMbids(ctx, ids); err != nil {
return fmt.Errorf("clear mbid: %w", err)
}
}
if p.Within != nil {
return p.Within(ctx, tq)
}
return nil
})
if err != nil {
return dbq.Track{}, err
}
logger.Info("library: removed a file and kept its track",
"track_id", track.ID.String(), "file_path", track.FilePath, "reason", string(p.Reason))
return track, nil
}
// markRemoved marks tracks whose files were removed on purpose, and tells
// clients they are no longer playable. actorID is invalid when the
// duplicate resolver removed them on its own.
func markRemoved(ctx context.Context, tq *dbq.Queries, ids []pgtype.UUID, reason RemovedFor, actorID pgtype.UUID) error {
if _, err := tq.MarkTracksRemoved(ctx, dbq.MarkTracksRemovedParams{
Reason: string(reason), RemovedBy: actorID, Ids: ids,
}); err != nil {
return fmt.Errorf("mark removed: %w", err)
}
if err := logTrackChanges(ctx, tq, ids); err != nil {
return fmt.Errorf("log changes: %w", err)
}
return nil
}
+164
View File
@@ -0,0 +1,164 @@
package library
import (
"context"
"errors"
"io"
"log/slog"
"os"
"path/filepath"
"syscall"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
)
// A removed file's track stays, missing, with its likes and plays and the
// reason it waits, and the good copy that lands later takes its history over.
func TestRemoveFile_KeepsTheTrackUntilAGoodCopyLands(t *testing.T) {
pool := newPool(t)
ctx := context.Background()
q := dbq.New(pool)
admin, err := q.CreateUser(ctx, dbq.CreateUserParams{
Username: dbtest.TestUserPrefix + "remover", PasswordHash: "x", ApiTokenHash: "remover", IsAdmin: true,
})
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
bad := filepath.Join(dir, "01 bad.mp3")
if err := os.WriteFile(bad, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
track, album, artist := seedTrack(t, pool, bad)
mbid := "rec-kept"
if _, err := pool.Exec(ctx, `UPDATE tracks SET mbid = $2, mbid_source = 'tag' WHERE id = $1`, track.ID, mbid); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, admin.ID, track.ID); err != nil {
t.Fatal(err)
}
if _, err := RemoveFile(ctx, pool, slog.New(slog.NewTextHandler(io.Discard, nil)), RemoveFileParams{
TrackID: track.ID, ActorID: admin.ID, Reason: RemovedForReport,
}); err != nil {
t.Fatalf("RemoveFile: %v", err)
}
if _, err := os.Stat(bad); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("the file is still there: %v", err)
}
waiting, err := q.GetTrackByID(ctx, track.ID)
if err != nil {
t.Fatalf("the track went with its file: %v", err)
}
if !waiting.MissingSince.Valid || waiting.RemovedReason == nil || *waiting.RemovedReason != "report" ||
waiting.RemovedBy != admin.ID {
t.Fatalf("waiting track = missing %v, reason %v, by %v; want missing, report, the admin",
waiting.MissingSince.Valid, waiting.RemovedReason, waiting.RemovedBy)
}
if waiting.Mbid == nil || *waiting.Mbid != mbid {
t.Fatalf("mbid = %v, want %q kept for a report that does not doubt it", waiting.Mbid, mbid)
}
// A good copy lands on the album under the song's title.
good, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: track.Title, AlbumID: album.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: filepath.Join(dir, "01 good.flac"), FileSize: 100, FileFormat: "flac",
})
if err != nil {
t.Fatal(err)
}
if _, err := PairMissingTracks(ctx, pool, nil); err != nil {
t.Fatalf("PairMissingTracks: %v", err)
}
var likes int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM general_likes WHERE track_id = $1`, good.ID).Scan(&likes); err != nil {
t.Fatal(err)
}
if likes != 1 {
t.Fatalf("the good copy has %d likes, want the removed track's one", likes)
}
}
// ForgetMBID drops the recording MBID that came from a file that was not the
// track's song.
func TestRemoveFile_ForgetsADoubtedMBID(t *testing.T) {
pool := newPool(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "rip.mp3")
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
track, _, _ := seedTrack(t, pool, path)
if _, err := pool.Exec(ctx, `UPDATE tracks SET mbid = 'rec-wrong', mbid_source = 'tag' WHERE id = $1`, track.ID); err != nil {
t.Fatal(err)
}
if _, err := RemoveFile(ctx, pool, nil, RemoveFileParams{
TrackID: track.ID, Reason: RemovedForSuspect, ForgetMBID: true,
}); err != nil {
t.Fatalf("RemoveFile: %v", err)
}
got, err := dbq.New(pool).GetTrackByID(ctx, track.ID)
if err != nil {
t.Fatal(err)
}
if got.Mbid != nil {
t.Fatalf("mbid = %q, want it forgotten", *got.Mbid)
}
}
// A file that cannot be removed leaves the track as it was.
func TestRemoveFile_FailedRemovalMarksNothing(t *testing.T) {
pool := newPool(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "stuck.mp3")
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
track, _, _ := seedTrack(t, pool, path)
stubRemoveFile(t, func(p string) error {
return &os.PathError{Op: "remove", Path: p, Err: syscall.EROFS}
})
_, err := RemoveFile(ctx, pool, nil, RemoveFileParams{TrackID: track.ID, Reason: RemovedForReport})
var fre *FileRemoveError
if !errors.As(err, &fre) {
t.Fatalf("err = %v, want a FileRemoveError", err)
}
got, err := dbq.New(pool).GetTrackByID(ctx, track.ID)
if err != nil {
t.Fatal(err)
}
if got.MissingSince.Valid || got.RemovedReason != nil {
t.Fatalf("a track whose file stayed was marked: missing %v, reason %v", got.MissingSince.Valid, got.RemovedReason)
}
}
// The reason describes one missing spell: a file back at its path clears it
// with the missing mark.
func TestRemoveFile_ReasonGoesWhenTheFileIsBack(t *testing.T) {
pool := newPool(t)
ctx := context.Background()
path := filepath.Join(t.TempDir(), "back.mp3")
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
track, _, _ := seedTrack(t, pool, path)
if _, err := RemoveFile(ctx, pool, nil, RemoveFileParams{TrackID: track.ID, Reason: RemovedForReport}); err != nil {
t.Fatalf("RemoveFile: %v", err)
}
q := dbq.New(pool)
if _, err := q.ClearTracksMissing(ctx, []pgtype.UUID{track.ID}); err != nil {
t.Fatalf("ClearTracksMissing: %v", err)
}
got, err := q.GetTrackByID(ctx, track.ID)
if err != nil {
t.Fatal(err)
}
if got.MissingSince.Valid || got.RemovedReason != nil || got.RemovedBy.Valid {
t.Fatalf("back track = missing %v, reason %v, by %v; want all cleared",
got.MissingSince.Valid, got.RemovedReason, got.RemovedBy.Valid)
}
}