fix(library): a track delete that cannot remove its file deletes nothing — #3918
test-go / test (push) Failing after 55s
test-web / test (push) Successful in 56s
test-go / integration (push) Failing after 4m50s
android / Build + lint + test (push) Successful in 5m52s
release / Build signed APK (releases and dev) (push) Successful in 6m5s
release / Build + push container image (push) Successful in 1m14s
release / Verify release artifacts (tag releases only) (push) Skipped
test-go / test (push) Failing after 55s
test-web / test (push) Successful in 56s
test-go / integration (push) Failing after 4m50s
android / Build + lint + test (push) Successful in 5m52s
release / Build signed APK (releases and dev) (push) Successful in 6m5s
release / Build + push container image (push) Successful in 1m14s
release / Verify release artifacts (tag releases only) (push) Skipped
Two delete paths had opposite failure policies. tracks.RemoveTrack
logged a failed os.Remove and deleted the row anyway, which CASCADEs
likes, plays, playlist memberships and tags, while the file survived
for the next scan to re-import as a stranger. library.DeleteTrackFile
stopped correctly but reported it as a bare 500 nobody could read.
One path now: library.DeleteTrackFile removes the file first and, on
anything but ErrNotExist, returns *FileRemoveError with nothing
deleted. Only then does it delete the row and tidy an emptied album
and artist in one transaction, log the sync change and clear orphaned
artist art. RemoveTrack calls it, which also fixes RemoveTrack never
logging a sync change. Quarantine Delete file now tidies emptied
albums and artists too.
Both endpoints answer an unwritable library (EROFS, EACCES, EPERM) with
409 library_not_writable. The message names the directory (removal
writes to the parent), the uid:gid the server runs as, and that
nothing was deleted. Other remove errors are 500 file_delete_failed
with the path.
The reachable surface is quarantine Delete file, which failed
silently: no copy for the code on either client, and Android swallowed
the exception so the row just reappeared. Web and Android now have
copy for both codes and append the server message for exactly those
two. Android's quarantine screen shows it in a snackbar.
DELETE /api/admin/tracks/{id} has had no client since f7278f24, which
kept it on purpose for a safer admin surface, so its history loss was
latent. Fixed rather than removed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQ31KQpYbStyK5y58UmPLH
This commit is contained in:
@@ -133,6 +133,13 @@ func (h *handlers) handleDeleteQuarantineFile(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
action, err := h.lidarrQuarantine.DeleteFile(r.Context(), id, admin.ID)
|
||||
if err != nil {
|
||||
// Written in the enveloped shape, not writeAdminJSONErr's bare code: the
|
||||
// message is the part that tells the operator which directory and uid.
|
||||
if apiErr, ok := fileRemoveAPIError(err); ok {
|
||||
logFileRemoveFailure(h.logger, apiErr, "track_id", uuidToString(id))
|
||||
writeErr(w, apiErr)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, lidarrquarantine.ErrTrackNotFound):
|
||||
writeAdminJSONErr(w, http.StatusNotFound, "track_not_found")
|
||||
|
||||
@@ -69,7 +69,7 @@ func installQuarantineClientFn(t *testing.T, h *handlers) {
|
||||
}
|
||||
return lidarr.NewClient(c.BaseURL, c.APIKey)
|
||||
}
|
||||
h.lidarrQuarantine = lidarrquarantine.NewService(h.pool, cfg, clientFn)
|
||||
h.lidarrQuarantine = lidarrquarantine.NewService(h.pool, cfg, clientFn, h.dataDir)
|
||||
}
|
||||
|
||||
// flagDirect bypasses the HTTP handler to seed a quarantine row via the
|
||||
|
||||
@@ -23,15 +23,17 @@ type removeTrackResponse struct {
|
||||
|
||||
// handleRemoveTrack implements DELETE /api/admin/tracks/{id}?unmonitor=true|false.
|
||||
//
|
||||
// Admin-only (gated by auth.RequireAdmin on the /admin route group). Always
|
||||
// deletes the file + DB row and runs the album/artist cascade tidy-up. When
|
||||
// Admin-only (gated by auth.RequireAdmin on the /admin route group). Deletes the
|
||||
// file, then the DB row, and runs the album/artist cascade tidy-up — and deletes
|
||||
// nothing at all when the file cannot be removed (#3918). When
|
||||
// unmonitor=true and the track has an mbid, also calls Lidarr.UnmonitorTrack
|
||||
// — failure there is non-fatal (the destructive part already completed) and
|
||||
// surfaces as `lidarr_unmonitor_failed: true` in the success envelope.
|
||||
//
|
||||
// Per spec §5, Lidarr-side errors during the unmonitor step do NOT map to
|
||||
// wire error codes; the only error codes this handler emits are not_found,
|
||||
// server_error, plus the auth codes the middleware emits upstream.
|
||||
// wire error codes. The codes this handler emits are not_found,
|
||||
// library_not_writable (409) and file_delete_failed when the file could not be
|
||||
// removed, server_error, plus the auth codes the middleware emits upstream.
|
||||
func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := chi.URLParam(r, "id")
|
||||
trackID, ok := parseUUID(idStr)
|
||||
@@ -66,6 +68,11 @@ func (h *handlers) handleRemoveTrack(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: "track not found"})
|
||||
return
|
||||
}
|
||||
if apiErr, ok := fileRemoveAPIError(err); ok {
|
||||
logFileRemoveFailure(h.logger, apiErr, "track_id", idStr)
|
||||
writeErr(w, apiErr)
|
||||
return
|
||||
}
|
||||
h.logger.Error("api: remove track failed", "err", err, "track_id", idStr)
|
||||
writeErr(w, apierror.InternalMsg("remove failed", err))
|
||||
return
|
||||
|
||||
@@ -65,7 +65,7 @@ func testHandlers(t *testing.T) (*handlers, *pgxpool.Pool) {
|
||||
}
|
||||
lidarrCfg := lidarrconfig.New(pool)
|
||||
lidarrReqs := lidarrrequests.NewService(pool, lidarrCfg, nil, nil)
|
||||
lidarrQuar := lidarrquarantine.NewService(pool, lidarrCfg, nil)
|
||||
lidarrQuar := lidarrquarantine.NewService(pool, lidarrCfg, nil, "")
|
||||
// tracks.Service has no Lidarr unmonitorer in tests by default; the
|
||||
// admin-tracks tests below override h.tracks via installTracksLidarrStub
|
||||
// when they need a stubbed Lidarr.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||
)
|
||||
|
||||
// fileRemoveAPIError answers a delete that could not reach the track's file
|
||||
// (#3918). Both delete endpoints use it, so the operator gets the same
|
||||
// explanation from the admin remove-track action and from quarantine's Delete
|
||||
// file.
|
||||
//
|
||||
// The unwritable case is a 409 rather than a 500 because nothing is broken: the
|
||||
// request conflicts with how the library is mounted, and the fix is the
|
||||
// operator's. The message names the directory — removal writes to the parent,
|
||||
// not the file — and the uid/gid the process runs as, which is the half of a
|
||||
// permission problem invisible from the host. Every case says nothing was
|
||||
// deleted, because that is exactly what the operator will be worried about.
|
||||
func fileRemoveAPIError(err error) (*apierror.Error, bool) {
|
||||
var fre *library.FileRemoveError
|
||||
if !errors.As(err, &fre) {
|
||||
return nil, false
|
||||
}
|
||||
if fre.NotWritable() {
|
||||
return &apierror.Error{
|
||||
Status: http.StatusConflict,
|
||||
Code: "library_not_writable",
|
||||
Message: fmt.Sprintf(
|
||||
"Minstrel runs as uid %d, gid %d and cannot delete from %s (%s). "+
|
||||
"The library mount must be writable by that user. Nothing was deleted.",
|
||||
fre.UID, fre.GID, fre.Dir(), fre.Reason()),
|
||||
Cause: err,
|
||||
}, true
|
||||
}
|
||||
return &apierror.Error{
|
||||
Status: http.StatusInternalServerError,
|
||||
Code: "file_delete_failed",
|
||||
Message: fmt.Sprintf("Could not delete %s (%s). Nothing was deleted.", fre.Path, fre.Reason()),
|
||||
Cause: err,
|
||||
}, true
|
||||
}
|
||||
|
||||
// logFileRemoveFailure records a delete that could not reach its file. An
|
||||
// unwritable library is an environment fact the operator can fix, so it is a
|
||||
// Warn; anything else is a real fault.
|
||||
func logFileRemoveFailure(logger *slog.Logger, apiErr *apierror.Error, attrs ...any) {
|
||||
attrs = append(attrs, "code", apiErr.Code, "err", apiErr.Cause)
|
||||
if apiErr.Status == http.StatusConflict {
|
||||
logger.Warn("api: track file could not be deleted", attrs...)
|
||||
return
|
||||
}
|
||||
logger.Error("api: track file could not be deleted", attrs...)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
||||
)
|
||||
|
||||
const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3"
|
||||
|
||||
// removeFailure builds the error a delete service returns when the file would
|
||||
// not go, wrapped the way lidarrquarantine.DeleteFile and tracks.RemoveTrack
|
||||
// wrap it — the mapping has to see through that.
|
||||
func removeFailure(errno syscall.Errno) error {
|
||||
return fmt.Errorf("delete file: %w", &library.FileRemoveError{
|
||||
Path: removeTestPath, UID: 1000, GID: 1000,
|
||||
Err: &fs.PathError{Op: "remove", Path: removeTestPath, Err: errno},
|
||||
})
|
||||
}
|
||||
|
||||
func TestFileRemoveAPIError(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
errno syscall.Errno
|
||||
wantStatus int
|
||||
wantCode string
|
||||
wantIn []string
|
||||
}{
|
||||
{
|
||||
name: "read-only mount", errno: syscall.EROFS,
|
||||
wantStatus: http.StatusConflict, wantCode: "library_not_writable",
|
||||
wantIn: []string{"uid 1000, gid 1000", "/music/Moe Shop/WWW (2020)", "read-only file system", "Nothing was deleted"},
|
||||
},
|
||||
{
|
||||
name: "permission denied", errno: syscall.EACCES,
|
||||
wantStatus: http.StatusConflict, wantCode: "library_not_writable",
|
||||
wantIn: []string{"permission denied", "Nothing was deleted"},
|
||||
},
|
||||
{
|
||||
name: "operation not permitted", errno: syscall.EPERM,
|
||||
wantStatus: http.StatusConflict, wantCode: "library_not_writable",
|
||||
wantIn: []string{"operation not permitted"},
|
||||
},
|
||||
{
|
||||
name: "i/o error", errno: syscall.EIO,
|
||||
wantStatus: http.StatusInternalServerError, wantCode: "file_delete_failed",
|
||||
wantIn: []string{removeTestPath, "input/output error", "Nothing was deleted"},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
apiErr, ok := fileRemoveAPIError(removeFailure(tc.errno))
|
||||
if !ok {
|
||||
t.Fatal("a wrapped *library.FileRemoveError was not recognised")
|
||||
}
|
||||
if apiErr.Status != tc.wantStatus || apiErr.Code != tc.wantCode {
|
||||
t.Fatalf("got %d %s, want %d %s", apiErr.Status, apiErr.Code, tc.wantStatus, tc.wantCode)
|
||||
}
|
||||
for _, want := range tc.wantIn {
|
||||
if !strings.Contains(apiErr.Message, want) {
|
||||
t.Errorf("message %q lacks %q", apiErr.Message, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The unwritable answer must name the DIRECTORY. Removal needs write access to
|
||||
// the parent, so a message naming the file would send the operator to fix the
|
||||
// wrong permissions. The directory is a prefix of the file path, which is why a
|
||||
// plain "contains the directory" check could never catch that regression.
|
||||
func TestFileRemoveAPIError_NotWritableNamesTheDirectoryNotTheFile(t *testing.T) {
|
||||
apiErr, _ := fileRemoveAPIError(removeFailure(syscall.EROFS))
|
||||
if strings.Contains(apiErr.Message, "01 - WWW.mp3") {
|
||||
t.Fatalf("message names the file rather than its directory: %q", apiErr.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileRemoveAPIError_IgnoresOtherErrors(t *testing.T) {
|
||||
for name, err := range map[string]error{
|
||||
"nil": nil,
|
||||
"plain error": errors.New("delete track: connection reset"),
|
||||
"path error": &fs.PathError{Op: "remove", Path: removeTestPath, Err: syscall.EROFS},
|
||||
"not found": library.ErrTrackNotFound,
|
||||
} {
|
||||
if _, ok := fileRemoveAPIError(err); ok {
|
||||
t.Errorf("%s: mapped as a file-remove failure", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user