Завершённая загрузка ложно «воскресала» из deleted в orphaned, когда её целевой путь переиспользовала другая загрузка (повторная закачка того же фильма в другом качестве): сверка проверяла лишь существование пути, не проверяя, что файл по нему — наша раскладка. Вводим инвариант «один целевой путь — один владелец»: - при успешной раскладке на освободившийся чужой путь владение переходит к новой загрузке — прежние file_link на этот путь помечаются статусом superseded и перестают считаться целью при сверке; - deleted исключён из desyncStates — терминальное состояние больше не переоценивается (источник к нему не вернётся из-за идемпотентности, цель отбирается переходом владения); - Undo снимает только реально свои разложенные ссылки (superseded пропускает — файл по пути теперь чужой хардлинк); - ошибку перехода владения трактуем как некритичную (WARN-and-continue): файлы уже разложены, рассинхрон чужих задач исправит следующий тик. Без миграции схемы (status — TEXT). Дельта влита в основную спеку, обновлены workflow.md и jellyfin-layout.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
308 lines
9.1 KiB
Go
308 lines
9.1 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"testing"
|
|
)
|
|
|
|
func seedDownload(t *testing.T, st *Store) int64 {
|
|
t.Helper()
|
|
id, err := st.CreateDownload(context.Background(),
|
|
newDownloading("aabbccddeeff00112233445566778899aabbccdd"))
|
|
if err != nil {
|
|
t.Fatalf("seed download: %v", err)
|
|
}
|
|
return id
|
|
}
|
|
|
|
func TestCreateRecognition_AttemptsAndCurrent(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
dl := seedDownload(t, st)
|
|
|
|
id1, err := st.CreateRecognition(ctx, &Recognition{
|
|
DownloadID: dl,
|
|
MediaType: NullString("series"),
|
|
Title: NullString("Show"),
|
|
Year: sql.NullInt64{Int64: 2006, Valid: true},
|
|
Plan: NullString(`{"type":"series"}`),
|
|
}, []string{"нет матча в базе"})
|
|
if err != nil {
|
|
t.Fatalf("create #1: %v", err)
|
|
}
|
|
|
|
id2, err := st.CreateRecognition(ctx, &Recognition{
|
|
DownloadID: dl,
|
|
MediaType: NullString("movie"),
|
|
Title: NullString("Show v2"),
|
|
}, []string{"уточнено"})
|
|
if err != nil {
|
|
t.Fatalf("create #2: %v", err)
|
|
}
|
|
if id2 == id1 {
|
|
t.Fatal("ids must differ")
|
|
}
|
|
|
|
cur, err := st.GetCurrentRecognition(ctx, dl)
|
|
if err != nil {
|
|
t.Fatalf("get current: %v", err)
|
|
}
|
|
if cur.ID != id2 {
|
|
t.Errorf("current id = %d, want %d", cur.ID, id2)
|
|
}
|
|
if cur.AttemptNo != 2 {
|
|
t.Errorf("attempt_no = %d, want 2", cur.AttemptNo)
|
|
}
|
|
if !cur.IsCurrent {
|
|
t.Error("current recognition must have is_current = true")
|
|
}
|
|
if cur.Title.String != "Show v2" {
|
|
t.Errorf("title = %q", cur.Title.String)
|
|
}
|
|
if got := cur.ReasonList(); len(got) != 1 || got[0] != "уточнено" {
|
|
t.Errorf("reasons = %v", got)
|
|
}
|
|
}
|
|
|
|
func TestGetCurrentRecognition_None(t *testing.T) {
|
|
st := newTestStore(t)
|
|
dl := seedDownload(t, st)
|
|
cur, err := st.GetCurrentRecognition(context.Background(), dl)
|
|
if err != nil {
|
|
t.Fatalf("get current: %v", err)
|
|
}
|
|
if cur != nil {
|
|
t.Errorf("want nil, got %+v", cur)
|
|
}
|
|
}
|
|
|
|
func TestHints(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
dl := seedDownload(t, st)
|
|
|
|
for _, h := range []string{"второй сезон", "рус+англ дорожки"} {
|
|
if err := st.AddHint(ctx, dl, h); err != nil {
|
|
t.Fatalf("add hint: %v", err)
|
|
}
|
|
}
|
|
got, err := st.ListHints(ctx, dl)
|
|
if err != nil {
|
|
t.Fatalf("list hints: %v", err)
|
|
}
|
|
if len(got) != 2 || got[0] != "второй сезон" || got[1] != "рус+англ дорожки" {
|
|
t.Errorf("hints = %v", got)
|
|
}
|
|
}
|
|
|
|
func TestOverrides_Upsert(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
dl := seedDownload(t, st)
|
|
|
|
if err := st.SetOverride(ctx, dl, "media_type", "series"); err != nil {
|
|
t.Fatalf("set override: %v", err)
|
|
}
|
|
if err := st.SetOverride(ctx, dl, "media_type", "movie"); err != nil { // перезапись
|
|
t.Fatalf("override upsert: %v", err)
|
|
}
|
|
if err := st.SetOverride(ctx, dl, "ignored_files", `["sample.mkv"]`); err != nil {
|
|
t.Fatalf("set override 2: %v", err)
|
|
}
|
|
|
|
got, err := st.ListOverrides(ctx, dl)
|
|
if err != nil {
|
|
t.Fatalf("list overrides: %v", err)
|
|
}
|
|
if got["media_type"] != "movie" {
|
|
t.Errorf("media_type = %q, want movie (upsert)", got["media_type"])
|
|
}
|
|
if got["ignored_files"] != `["sample.mkv"]` {
|
|
t.Errorf("ignored_files = %q", got["ignored_files"])
|
|
}
|
|
}
|
|
|
|
func TestFileLinks_BatchLifecycle(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
dl := seedDownload(t, st)
|
|
|
|
batch := "batch-1"
|
|
links := []FileLink{
|
|
{DownloadID: dl, ApplyBatchID: batch, SrcPath: "/d/a.mkv", DstPath: "/m/A.mkv", Kind: "video", Status: "linked"},
|
|
{DownloadID: dl, ApplyBatchID: batch, SrcPath: "/d/a.srt", DstPath: "/m/A.ru.srt", Kind: "subtitle", Status: "linked"},
|
|
}
|
|
if err := st.CreateFileLinks(ctx, links); err != nil {
|
|
t.Fatalf("create links: %v", err)
|
|
}
|
|
|
|
latest, err := st.LatestBatchID(ctx, dl)
|
|
if err != nil || latest != batch {
|
|
t.Fatalf("latest batch = %q, %v", latest, err)
|
|
}
|
|
|
|
got, err := st.ListFileLinksByBatch(ctx, batch)
|
|
if err != nil {
|
|
t.Fatalf("list by batch: %v", err)
|
|
}
|
|
if len(got) != 2 || got[0].DstPath != "/m/A.mkv" {
|
|
t.Errorf("links = %+v", got)
|
|
}
|
|
|
|
if err := st.DeleteFileLinksByBatch(ctx, batch); err != nil {
|
|
t.Fatalf("delete batch: %v", err)
|
|
}
|
|
after, _ := st.ListFileLinksByBatch(ctx, batch)
|
|
if len(after) != 0 {
|
|
t.Errorf("links remain after delete: %+v", after)
|
|
}
|
|
}
|
|
|
|
func TestSupersedeForeignLinks(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
owner := seedDownload(t, st)
|
|
foreign, err := st.CreateDownload(ctx,
|
|
newDownloading("bbccddeeff00112233445566778899aabbccddee"))
|
|
if err != nil {
|
|
t.Fatalf("seed foreign: %v", err)
|
|
}
|
|
|
|
shared := "/m/Movie (2024).mkv"
|
|
// foreign разложена по shared (linked) и по своему пути (exists);
|
|
// owner разложен по shared и по третьему пути.
|
|
if err := st.CreateFileLinks(ctx, []FileLink{
|
|
{DownloadID: foreign, ApplyBatchID: "f", SrcPath: "/d/f.mkv", DstPath: shared, Kind: "video", Status: "linked"},
|
|
{DownloadID: foreign, ApplyBatchID: "f", SrcPath: "/d/g.mkv", DstPath: "/m/Other (2024).mkv", Kind: "video", Status: "exists"},
|
|
{DownloadID: owner, ApplyBatchID: "o", SrcPath: "/d/o.mkv", DstPath: shared, Kind: "video", Status: "linked"},
|
|
}); err != nil {
|
|
t.Fatalf("create links: %v", err)
|
|
}
|
|
|
|
if err := st.SupersedeForeignLinks(ctx, owner, []string{shared}); err != nil {
|
|
t.Fatalf("supersede: %v", err)
|
|
}
|
|
|
|
links, _ := st.ListFileLinksByBatch(ctx, "f")
|
|
for _, l := range links {
|
|
switch l.DstPath {
|
|
case shared:
|
|
if l.Status != "superseded" {
|
|
t.Errorf("чужая ссылка на %q = %q, want superseded", shared, l.Status)
|
|
}
|
|
default: // /m/Other — другой путь, не трогаем
|
|
if l.Status != "exists" {
|
|
t.Errorf("ссылка на %q = %q, want exists (не тронута)", l.DstPath, l.Status)
|
|
}
|
|
}
|
|
}
|
|
// Свою ссылку owner не суперсидит (download_id != self).
|
|
own, _ := st.ListFileLinksByBatch(ctx, "o")
|
|
if len(own) != 1 || own[0].Status != "linked" {
|
|
t.Errorf("своя ссылка = %+v, want linked", own)
|
|
}
|
|
|
|
// Пустой список путей — no-op, без ошибки.
|
|
if err := st.SupersedeForeignLinks(ctx, owner, nil); err != nil {
|
|
t.Errorf("пустой dstPaths должен быть no-op: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCandidates_Lifecycle(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
dl := seedDownload(t, st)
|
|
recID, err := st.CreateRecognition(ctx, &Recognition{DownloadID: dl}, nil)
|
|
if err != nil {
|
|
t.Fatalf("create recognition: %v", err)
|
|
}
|
|
|
|
cands := []MetadataCandidate{
|
|
{RecognitionID: recID, Provider: "tvdb", ProviderID: "269613",
|
|
Title: NullString("Fargo"), Year: sql.NullInt64{Int64: 2014, Valid: true}},
|
|
{RecognitionID: recID, Provider: "tmdb", ProviderID: "60622",
|
|
Title: NullString("Fargo")},
|
|
}
|
|
if err := st.CreateCandidates(ctx, cands); err != nil {
|
|
t.Fatalf("create candidates: %v", err)
|
|
}
|
|
|
|
got, err := st.ListCandidatesByRecognition(ctx, recID)
|
|
if err != nil {
|
|
t.Fatalf("list: %v", err)
|
|
}
|
|
if len(got) != 2 || got[0].Provider != "tvdb" || got[0].ProviderID != "269613" {
|
|
t.Fatalf("candidates = %+v", got)
|
|
}
|
|
|
|
chosenID := got[0].ID
|
|
if err := st.SetCandidateChosen(ctx, recID, chosenID); err != nil {
|
|
t.Fatalf("set chosen: %v", err)
|
|
}
|
|
got, _ = st.ListCandidatesByRecognition(ctx, recID)
|
|
for _, c := range got {
|
|
want := c.ID == chosenID
|
|
if c.Chosen != want {
|
|
t.Errorf("candidate %d chosen = %v, want %v", c.ID, c.Chosen, want)
|
|
}
|
|
}
|
|
|
|
// GetCandidate + переотметка.
|
|
single, err := st.GetCandidate(ctx, got[1].ID)
|
|
if err != nil || single == nil || single.Provider != "tmdb" {
|
|
t.Fatalf("get candidate = %+v, %v", single, err)
|
|
}
|
|
if err := st.SetCandidateChosen(ctx, recID, got[1].ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _ = st.ListCandidatesByRecognition(ctx, recID)
|
|
if got[0].Chosen || !got[1].Chosen {
|
|
t.Errorf("re-choose failed: %+v", got)
|
|
}
|
|
}
|
|
|
|
func TestExistsByInfohash(t *testing.T) {
|
|
st := newTestStore(t)
|
|
ctx := context.Background()
|
|
const ih = "aabbccddeeff00112233445566778899aabbccdd"
|
|
|
|
exists, err := st.ExistsByInfohash(ctx, ih)
|
|
if err != nil || exists {
|
|
t.Fatalf("пусто: exists=%v err=%v", exists, err)
|
|
}
|
|
if _, err := st.CreateDownload(ctx, newDownloading(ih)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
exists, err = st.ExistsByInfohash(ctx, ih)
|
|
if err != nil || !exists {
|
|
t.Fatalf("после вставки: exists=%v err=%v", exists, err)
|
|
}
|
|
// Терминальное состояние тоже считается «видели» (не реусыновляем).
|
|
id, _ := st.CreateDownload(ctx, newDownloading("ffffffffffffffffffffffffffffffffffffffff"))
|
|
_ = st.SetDownloadState(ctx, id, StateDone, "", "")
|
|
if ex, _ := st.ExistsByInfohash(ctx, "ffffffffffffffffffffffffffffffffffffffff"); !ex {
|
|
t.Error("done-задача должна считаться существующей")
|
|
}
|
|
}
|
|
|
|
func TestGetCandidate_None(t *testing.T) {
|
|
st := newTestStore(t)
|
|
c, err := st.GetCandidate(context.Background(), 999)
|
|
if err != nil || c != nil {
|
|
t.Errorf("want nil,nil; got %+v, %v", c, err)
|
|
}
|
|
}
|
|
|
|
func TestLatestBatchID_None(t *testing.T) {
|
|
st := newTestStore(t)
|
|
dl := seedDownload(t, st)
|
|
latest, err := st.LatestBatchID(context.Background(), dl)
|
|
if err != nil {
|
|
t.Fatalf("latest batch: %v", err)
|
|
}
|
|
if latest != "" {
|
|
t.Errorf("want empty, got %q", latest)
|
|
}
|
|
}
|