Files
silo-server/internal/api/handlers/libraries_language_change_test.go
f983c54e87 fix(metadata): re-fetch titles/overviews when a library's metadata language changes (#278)
* fix(metadata): re-fetch titles/overviews when a library's metadata language changes

An item's default_metadata_language was stamped once at first match and
never updated: the canonical-language pin in mergeAndPersist routed any
refresh in a different language into the localization tables, the
upserts' COALESCE kept the old stamp forever, quick-mode library refresh
skipped complete items entirely, and changing the language in
HandleUpdateLibrary triggered nothing. Items stayed in the old language
no matter how often the admin refreshed (#211).

Four coupled changes:
- ProcessRequest.AdoptLanguage: folder-scoped manual refreshes adopt the
  library's language as the item's new canonical language when it
  differs from the stamp, rewriting the base row instead of localizing
  to the side. Only ModeManualRefresh adopts — scheduled refreshes merge
  fill-empty and would restamp without rewriting the text.
- Upsert language pins inverted (media_items, seasons, episodes): prefer
  the incoming non-empty default_metadata_language over the existing
  stamp. All existing callers send the unchanged stamp or empty, so
  behavior is unchanged outside adoption; the restamp is atomic with the
  canonical write.
- Quick-mode refresh lister now includes complete items whose stamp
  differs from the library's configured language.
- HandleUpdateLibrary enqueues a quick library metadata refresh when the
  metadata language changes, mirroring the paths-change rescan trigger.

Fixes #211

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(metadata): gate language adoption on field locks and library agreement

Two hardening fixes for AdoptLanguage from review of #278:

- Locked fields defeat the restamp: title/overview merges honor per-field
  locks, but the restamp was unconditional. An item with both language-
  bearing fields locked kept its old-language text yet got stamped the
  new language, so the quick-refresh mismatch predicate never flagged it
  again. mergeAndPersist now skips adoption when both name and overview
  are locked, falling back to the non-adopting behavior: the stamp stays
  put, isCanonicalWrite goes false, and the fetch routes to the
  localization tables exactly like a non-adopting refresh in that
  language does today. One locked field still adopts — the other is
  actually rewritten.

- Multi-library flip-flop: an item in libraries with different metadata
  languages had its canonical base row rewritten to whichever library
  refreshed last, oscillating forever. Process now requires every
  library containing the item (media_item_libraries) to resolve to the
  adoption target before setting AdoptLanguage, via the existing
  GetDistinctMetadataLanguagesForItem (which applies the same empty→en
  default as resolveFolderLanguage). Disagreement or a lookup failure
  keeps the current stamp — stable beats flip-flopping.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com>
2026-07-02 14:07:21 -04:00

113 lines
3.8 KiB
Go

package handlers
import (
"context"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"sync"
"testing"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Silo-Server/silo-server/internal/adminjob"
"github.com/Silo-Server/silo-server/internal/catalog"
"github.com/Silo-Server/silo-server/internal/models"
)
type fakeAdminJobCreator struct {
mu sync.Mutex
refreshs []adminjob.LibraryRefreshRequest
}
func (f *fakeAdminJobCreator) Create(context.Context, adminjob.CreateJobInput) (*models.AdminJob, error) {
return &models.AdminJob{}, nil
}
func (f *fakeAdminJobCreator) CreateLibraryRefresh(_ context.Context, _ int, req adminjob.LibraryRefreshRequest, _ string) (*models.AdminJob, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.refreshs = append(f.refreshs, req)
return &models.AdminJob{}, nil
}
func (f *fakeAdminJobCreator) libraryRefreshes() []adminjob.LibraryRefreshRequest {
f.mu.Lock()
defer f.mu.Unlock()
return append([]adminjob.LibraryRefreshRequest(nil), f.refreshs...)
}
// TestHandleUpdateLibraryLanguageChangeQueuesRefresh covers the trigger half
// of issue #211: changing a library's metadata language must enqueue a
// library metadata refresh so existing items re-fetch in the new language,
// while an update that does not change the language must not enqueue one.
func TestHandleUpdateLibraryLanguageChangeQueuesRefresh(t *testing.T) {
dsn := os.Getenv("SILO_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("SILO_TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatalf("connect db: %v", err)
}
t.Cleanup(pool.Close)
var folderID int
if err := pool.QueryRow(ctx, `
INSERT INTO media_folders (type, name, enabled, metadata_language)
VALUES ('movies', 'Lang Change Test', true, 'zh')
RETURNING id
`).Scan(&folderID); err != nil {
t.Fatalf("seed folder: %v", err)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM media_folders WHERE id = $1`, folderID)
})
jobs := &fakeAdminJobCreator{}
h := NewLibraryHandler(catalog.NewFolderRepository(pool), nil, nil, pool, nil)
h.JobRepo = jobs
doUpdate := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPut, "/libraries/"+strconv.Itoa(folderID), strings.NewReader(body))
chiCtx := chi.NewRouteContext()
chiCtx.URLParams.Add("id", strconv.Itoa(folderID))
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, chiCtx))
rec := httptest.NewRecorder()
h.HandleUpdateLibrary(rec, req)
return rec
}
// An update that does not touch the language must not enqueue a refresh.
if rec := doUpdate(`{"name":"Lang Change Test Renamed"}`); rec.Code != http.StatusOK {
t.Fatalf("rename update status = %d (body: %s)", rec.Code, rec.Body.String())
}
if got := jobs.libraryRefreshes(); len(got) != 0 {
t.Fatalf("refresh jobs after rename = %d, want 0", len(got))
}
// Changing the metadata language must enqueue a refresh for this library.
if rec := doUpdate(`{"metadata_language":"da"}`); rec.Code != http.StatusOK {
t.Fatalf("language update status = %d (body: %s)", rec.Code, rec.Body.String())
}
refreshes := jobs.libraryRefreshes()
if len(refreshes) != 1 {
t.Fatalf("refresh jobs after language change = %d, want 1", len(refreshes))
}
if refreshes[0].LibraryID != folderID {
t.Errorf("refresh library id = %d, want %d", refreshes[0].LibraryID, folderID)
}
// Re-submitting the same language is a no-op update and must not enqueue.
if rec := doUpdate(`{"metadata_language":"da"}`); rec.Code != http.StatusOK {
t.Fatalf("same-language update status = %d (body: %s)", rec.Code, rec.Body.String())
}
if got := jobs.libraryRefreshes(); len(got) != 1 {
t.Fatalf("refresh jobs after same-language update = %d, want still 1", len(got))
}
}