From a73b6cb4367a20f703176180269ee4525e3fbf60 Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Wed, 11 Nov 2026 09:32:55 +0100 Subject: [PATCH 1/7] Reduce memory usage to avoid OOM kills in memory-constrained systems --- README.md | 2 + internal/index/bleve_textrank_write.go | 79 +++--- internal/index/bleve_textrank_write_test.go | 2 +- internal/index/textrank_count_store.go | 262 ++++++++++++++++++++ internal/index/textrank_count_store_test.go | 172 +++++++++++++ 5 files changed, 473 insertions(+), 44 deletions(-) create mode 100644 internal/index/textrank_count_store.go create mode 100644 internal/index/textrank_count_store_test.go diff --git a/README.md b/README.md index afa1c0c6..4dfc65d3 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,8 @@ Subjects help narrow the results too: when both books have subjects that are unc Recommendations update in the background as your library changes, so new books or edited subjects may not affect them immediately. After an upgrade or a change to `--max-similarity-phrase-frequency`, recommendations may be temporarily unavailable while Coreander updates them. You do not need to force a reindex when changing the three recommendation settings below. +Library-wide keyword clean-up uses temporary disk space to keep memory usage down on large libraries. Ensure the system's temporary directory has free space. If it is RAM-backed or too small, set `TMPDIR` to a directory on a disk with enough space. Temporary counting files are removed when the pass finishes, including when it reports an error; if the process is forcibly killed, its `coreander-textrank-*` temporary directory may remain. + You can fine-tune this behavior with the following flags: |Flag|Environment variable|Description| diff --git a/internal/index/bleve_textrank_write.go b/internal/index/bleve_textrank_write.go index 93be44fa..824c4f3c 100644 --- a/internal/index/bleve_textrank_write.go +++ b/internal/index/bleve_textrank_write.go @@ -3,6 +3,7 @@ package index import ( "fmt" "log" + "math" "path/filepath" "sort" "strconv" @@ -414,12 +415,23 @@ func (b *BleveIndexer) maintainTextRankEntries(batchSize int) error { b.beginPruning(int(docCount) * 2) defer b.endPruning() + var after []string textRankFieldsSearch := func(from int) (*bleve.SearchResult, error) { - req := bleve.NewSearchRequestOptions(bleve.NewMatchAllQuery(), batchSize, from, false) + if from == 0 { + after = nil + } + req := bleve.NewSearchRequestOptions(bleve.NewMatchAllQuery(), batchSize, 0, false) + req.SortBy([]string{"_id"}) + req.SetSearchAfter(after) + req.Score = "none" req.Fields = []string{"TextRankPhrases", "TextRankWords", "SubjectsSlugs"} b.documentsMu.RLock() defer b.documentsMu.RUnlock() - return b.documentsIdx.Search(req) + result, err := b.documentsIdx.Search(req) + if err == nil && len(result.Hits) > 0 { + after = result.Hits[len(result.Hits)-1].Sort + } + return result, err } counts, err := b.countTextRankEntries(docCount, batchSize, textRankFieldsSearch) @@ -444,10 +456,11 @@ type textRankEntryCounts struct { } func (b *BleveIndexer) countTextRankEntries(docCount uint64, batchSize int, search func(int) (*bleve.SearchResult, error)) (*textRankEntryCounts, error) { - phraseDocCount := make(map[string]int) - wordDocCount := make(map[string]int) - similarityCounts := make(map[string]int) - subjectCounts := make(map[string]int) + counts, err := newTextRankCountStore() + if err != nil { + return nil, err + } + defer counts.close() b.documentsMu.RLock() phraseAnalyzer := b.documentsIdx.Mapping().AnalyzerNamed(defaultAnalyzer) b.documentsMu.RUnlock() @@ -465,37 +478,38 @@ func (b *BleveIndexer) countTextRankEntries(docCount uint64, batchSize int, sear } for _, hit := range result.Hits { - for _, subject := range uniqueTextRankEntries(slicer(hit.Fields["SubjectsSlugs"])) { + entries := make(map[textRankCountKey]struct{}) + for _, subject := range slicer(hit.Fields["SubjectsSlugs"]) { if subject != "" { - subjectCounts[subject]++ + entries[textRankCountKey{"subject", subject}] = struct{}{} } } - seenSimilarityPhrases := make(map[string]bool) // hydrateDocument assumes a full Fields "*" fetch (it // type-asserts every Metadata field unconditionally); this pass // requests only keyword and subject fields, so read them // directly via slicer instead. - for _, phrase := range uniqueTextRankEntries(slicer(hit.Fields["TextRankPhrases"])) { - phraseDocCount[phrase]++ + for _, phrase := range slicer(hit.Fields["TextRankPhrases"]) { + entries[textRankCountKey{"phrase", phrase}] = struct{}{} key := similarityPhraseKey(phrase, phraseAnalyzer) - if key != "" && !seenSimilarityPhrases[key] { - similarityCounts[key]++ - seenSimilarityPhrases[key] = true + if key != "" { + entries[textRankCountKey{"similarity", key}] = struct{}{} } } - for _, word := range uniqueTextRankEntries(slicer(hit.Fields["TextRankWords"])) { - wordDocCount[word]++ + for _, word := range slicer(hit.Fields["TextRankWords"]) { + entries[textRankCountKey{"word", word}] = struct{}{} } + if err := counts.add(entries); err != nil { + return nil, err + } + } + if err := counts.flush(); err != nil { + return nil, err } b.recordPruningProgress(len(result.Hits)) } - return &textRankEntryCounts{ - phrases: phraseDocCount, - words: wordDocCount, - similarityPhrases: similarityCounts, - subjects: subjectCounts, - }, nil + threshold := math.Max(b.commonTextRankEntryRatio*float64(docCount), float64(b.minCommonTextRankAbsoluteCount)) + return counts.load(threshold, similarityPhraseThreshold(docCount, b.maxSimilarityPhraseFrequency)) } // pruneCommonTextRankEntries only removes common keywords using collected counts. @@ -614,27 +628,6 @@ func (b *BleveIndexer) rewriteCommonTextRankEntries(docCount uint64, batchSize i return pruned, nil } -// uniqueTextRankEntries de-duplicates a document's TextRankPhrases/ -// TextRankWords before they're counted towards countTextRankEntries' -// per-document-frequency maps, so a document listing the same entry twice -// (which rankDocument's own extraction shouldn't normally produce) can never -// inflate its corpus-wide count by more than one. -func uniqueTextRankEntries(entries []string) []string { - if len(entries) == 0 { - return entries - } - seen := make(map[string]struct{}, len(entries)) - out := make([]string, 0, len(entries)) - for _, entry := range entries { - if _, ok := seen[entry]; ok { - continue - } - seen[entry] = struct{}{} - out = append(out, entry) - } - return out -} - // filterOutCommonTextRankEntries returns entries without any item whose // corpus-wide document count (from docCount, keyed by entry) exceeds // threshold, preserving the original (weight-descending) order. diff --git a/internal/index/bleve_textrank_write_test.go b/internal/index/bleve_textrank_write_test.go index 2b80c856..526a0b39 100644 --- a/internal/index/bleve_textrank_write_test.go +++ b/internal/index/bleve_textrank_write_test.go @@ -128,7 +128,7 @@ func TestPruneCommonTextRankEntriesRewritesCommonEntries(t *testing.T) { MinCommonTextRankAbsoluteCount: 1, }) - const docCount = 10 + const docCount = 23 for i := 0; i < docCount; i++ { id := strconv.Itoa(i) document := Document{ diff --git a/internal/index/textrank_count_store.go b/internal/index/textrank_count_store.go new file mode 100644 index 00000000..3c7f60ef --- /dev/null +++ b/internal/index/textrank_count_store.go @@ -0,0 +1,262 @@ +package index + +import ( + "bufio" + "cmp" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "os" + "path/filepath" + "slices" +) + +type textRankCountKey struct { + kind, entry string +} + +type textRankCountRecord struct { + Kind string + Entry string + Count int +} + +func compareTextRankCounts(a, b textRankCountRecord) int { + if order := cmp.Compare(a.Kind, b.Kind); order != 0 { + return order + } + return cmp.Compare(a.Entry, b.Entry) +} + +// Sorted runs keep counting memory bounded; each merge opens only three files. +type textRankCountStore struct { + dir string + pending map[textRankCountKey]int + bytes int + limit int + runs []string + next int +} + +func newTextRankCountStore() (*textRankCountStore, error) { + dir, err := os.MkdirTemp("", "coreander-textrank-") + if err != nil { + return nil, fmt.Errorf("create TextRank counting directory: %w", err) + } + return &textRankCountStore{ + dir: dir, pending: make(map[textRankCountKey]int), limit: 1024 * 1024, + }, nil +} + +func (s *textRankCountStore) add(entries map[textRankCountKey]struct{}) error { + for key := range entries { + if s.pending[key] == 0 { + s.bytes += len(key.kind) + len(key.entry) + 64 + } + s.pending[key]++ + if s.bytes >= s.limit { + if err := s.flush(); err != nil { + return err + } + } + } + return nil +} + +func (s *textRankCountStore) writeRun(write func(*json.Encoder) error) (path string, err error) { + path = filepath.Join(s.dir, fmt.Sprintf("run-%d", s.next)) + s.next++ + file, err := os.Create(path) + if err != nil { + return "", fmt.Errorf("create TextRank counting run: %w", err) + } + defer func() { err = errors.Join(err, file.Close()) }() + buffer := bufio.NewWriter(file) + if err := write(json.NewEncoder(buffer)); err != nil { + return "", fmt.Errorf("write TextRank counting run: %w", err) + } + if err := buffer.Flush(); err != nil { + return "", fmt.Errorf("flush TextRank counting run: %w", err) + } + return path, nil +} + +func (s *textRankCountStore) flush() error { + if len(s.pending) == 0 { + return nil + } + records := make([]textRankCountRecord, 0, len(s.pending)) + for key, count := range s.pending { + records = append(records, textRankCountRecord{key.kind, key.entry, count}) + } + slices.SortFunc(records, compareTextRankCounts) + path, err := s.writeRun(func(encoder *json.Encoder) error { + for _, record := range records { + if err := encoder.Encode(record); err != nil { + return err + } + } + return nil + }) + if err != nil { + return err + } + s.pending = make(map[textRankCountKey]int) + s.bytes = 0 + // Binary compaction avoids retaining an unbounded list of tiny runs or + // repeatedly merging the entire corpus for every new batch. + for level := 0; ; level++ { + if level == len(s.runs) { + s.runs = append(s.runs, path) + return nil + } + if s.runs[level] == "" { + s.runs[level] = path + return nil + } + merged, err := s.merge(s.runs[level], path) + if err != nil { + return err + } + s.runs[level] = "" + path = merged + } +} + +func (s *textRankCountStore) merge(left, right string) (path string, err error) { + a, err := os.Open(left) + if err != nil { + return "", fmt.Errorf("open TextRank counting run: %w", err) + } + defer func() { err = errors.Join(err, a.Close()) }() + b, err := os.Open(right) + if err != nil { + return "", fmt.Errorf("open TextRank counting run: %w", err) + } + defer func() { err = errors.Join(err, b.Close()) }() + path, err = s.writeRun(func(encoder *json.Encoder) error { + decoders := [2]*json.Decoder{ + json.NewDecoder(bufio.NewReader(a)), json.NewDecoder(bufio.NewReader(b)), + } + var records [2]textRankCountRecord + var done [2]bool + advance := func(i int) error { + err := decoders[i].Decode(&records[i]) + if err == io.EOF { + done[i] = true + return nil + } + return err + } + if err := advance(0); err != nil { + return err + } + if err := advance(1); err != nil { + return err + } + for !done[0] || !done[1] { + i := 0 + if done[0] || (!done[1] && compareTextRankCounts(records[0], records[1]) > 0) { + i = 1 + } + record := records[i] + equal := !done[0] && !done[1] && compareTextRankCounts(records[0], records[1]) == 0 + if equal { + record.Count += records[1-i].Count + } + if err := encoder.Encode(record); err != nil { + return err + } + if err := advance(i); err != nil { + return err + } + if equal { + if err := advance(1 - i); err != nil { + return err + } + } + } + return nil + }) + if err != nil { + return "", err + } + for _, input := range []string{left, right} { + if err := os.Remove(input); err != nil { + return "", fmt.Errorf("remove merged TextRank counting run: %w", err) + } + } + return path, nil +} + +func (s *textRankCountStore) load(pruneThreshold, phraseThreshold float64) (counts *textRankEntryCounts, err error) { + if err := s.flush(); err != nil { + return nil, err + } + path := "" + for _, run := range s.runs { + if run == "" { + continue + } + if path == "" { + path = run + } else { + path, err = s.merge(path, run) + if err != nil { + return nil, err + } + } + } + counts = &textRankEntryCounts{ + phrases: make(map[string]int), words: make(map[string]int), + similarityPhrases: make(map[string]int), subjects: make(map[string]int), + } + if path == "" { + return counts, nil + } + file, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("open final TextRank counts: %w", err) + } + defer func() { err = errors.Join(err, file.Close()) }() + decoder := json.NewDecoder(bufio.NewReader(file)) + for { + var record textRankCountRecord + if err := decoder.Decode(&record); err != nil { + if err == io.EOF { + return counts, nil + } + return nil, fmt.Errorf("decode TextRank counts: %w", err) + } + var destination map[string]int + switch record.Kind { + case "phrase": + if float64(record.Count) > pruneThreshold { + destination = counts.phrases + } + case "word": + if float64(record.Count) > pruneThreshold { + destination = counts.words + } + case "similarity": + if record.Entry != "" && record.Count >= similarityMinPhraseDocumentFrequency && float64(record.Count) <= phraseThreshold { + destination = counts.similarityPhrases + } + case "subject": + destination = counts.subjects + default: + return nil, fmt.Errorf("invalid TextRank count kind %q", record.Kind) + } + if destination != nil { + destination[record.Entry] = record.Count + } + } +} + +func (s *textRankCountStore) close() { + if err := os.RemoveAll(s.dir); err != nil { + log.Printf("Remove temporary TextRank counts: %s", err) + } +} diff --git a/internal/index/textrank_count_store_test.go b/internal/index/textrank_count_store_test.go new file mode 100644 index 00000000..f6c4fe75 --- /dev/null +++ b/internal/index/textrank_count_store_test.go @@ -0,0 +1,172 @@ +package index + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/blevesearch/bleve/v2" + "github.com/blevesearch/bleve/v2/search" +) + +func TestTextRankCountStoreFiltersAndCleansUp(t *testing.T) { + t.Setenv("TMPDIR", t.TempDir()) + store, err := newTextRankCountStore() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.close) + store.limit = 256 + for i := range 25 { + entries := map[textRankCountKey]struct{}{ + {"phrase", "common phrase"}: {}, + {"word", "common"}: {}, + {"subject", "physics"}: {}, + {"similarity", "too common"}: {}, + {"similarity", fmt.Sprintf("unique %d", i)}: {}, + } + if i < 20 { + entries[textRankCountKey{"phrase", "boundary phrase"}] = struct{}{} + entries[textRankCountKey{"similarity", "boundary pair"}] = struct{}{} + } + if i < 2 { + entries[textRankCountKey{"similarity", "atomic bomb"}] = struct{}{} + } + if err := store.add(entries); err != nil { + t.Fatal(err) + } + if i%3 == 0 { + if err := store.flush(); err != nil { + t.Fatal(err) + } + } + } + if err := store.flush(); err != nil { + t.Fatal(err) + } + counts, err := store.load(20, 20) + if err != nil { + t.Fatal(err) + } + if len(counts.phrases) != 1 || counts.phrases["common phrase"] != 25 || + len(counts.words) != 1 || counts.words["common"] != 25 || + len(counts.similarityPhrases) != 2 || counts.similarityPhrases["atomic bomb"] != 2 || + counts.similarityPhrases["boundary pair"] != 20 || counts.subjects["physics"] != 25 { + t.Fatalf("incorrect filtered counts: %+v", counts) + } + store.close() + if _, err := os.Stat(store.dir); !os.IsNotExist(err) { + t.Fatalf("temporary counts were not removed: %v", err) + } +} + +func TestTextRankCountStorePreservesEntriesAcrossMerges(t *testing.T) { + store, err := newTextRankCountStore() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.close) + store.limit = 128 + entries := []string{"", "a\nb", "a\tb", "\"quoted\"", "ámbito físico", strings.Repeat("long", 20000)} + for range 3 { + for _, entry := range entries { + if err := store.add(map[textRankCountKey]struct{}{{"subject", entry}: {}}); err != nil { + t.Fatal(err) + } + } + } + counts, err := store.load(20, 20) + if err != nil { + t.Fatal(err) + } + if len(counts.subjects) != len(entries) { + t.Fatalf("got %d entries, want %d", len(counts.subjects), len(entries)) + } + for _, entry := range entries { + if counts.subjects[entry] != 3 { + t.Fatalf("entry of length %d has count %d, want 3", len(entry), counts.subjects[entry]) + } + } +} + +func TestTextRankCountStoreRejectsCorruptRun(t *testing.T) { + store, err := newTextRankCountStore() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.close) + if err := store.add(map[textRankCountKey]struct{}{{"subject", "physics"}: {}}); err != nil { + t.Fatal(err) + } + if err := store.flush(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(store.runs[0], []byte("{"), 0600); err != nil { + t.Fatal(err) + } + if _, err := store.load(20, 20); err == nil { + t.Fatal("corrupt counting run must return an explicit error") + } +} + +func TestTextRankCountingStorageFailureDoesNotPublish(t *testing.T) { + idx, documents := newTestTextRankIndexer(t, Config{}) + t.Cleanup(func() { _ = idx.Close() }) + doc := evidenceDocument("reference", "atomic bomb") + if err := IndexDocument(documents, doc.ID, doc); err != nil { + t.Fatal(err) + } + t.Setenv("TMPDIR", filepath.Join(t.TempDir(), "missing")) + if err := idx.maintainTextRankEntries(10); err == nil { + t.Fatal("unavailable counting storage must return an error") + } + for _, key := range [][]byte{internalDocCountAtLastPrune, internalSimilarityPhraseStatistics} { + value, err := documents.GetInternal(key) + if err != nil || len(value) != 0 { + t.Fatalf("failed maintenance published %q: %q, %v", key, value, err) + } + } +} + +func BenchmarkTextRankCountingMemory(b *testing.B) { + for _, documents := range []int{100, 1000, 10000} { + b.Run(fmt.Sprint(documents), func(b *testing.B) { + documentsIndex, err := bleve.NewMemOnly(CreateDocumentsMapping()) + if err != nil { + b.Fatal(err) + } + defer documentsIndex.Close() + idx := NewBleve(documentsIndex, nil, nil, "", nil, Config{}) + var peak uint64 + for b.Loop() { + counts, err := idx.countTextRankEntries(uint64(documents), 10, func(from int) (*bleve.SearchResult, error) { + runtime.GC() + var memory runtime.MemStats + runtime.ReadMemStats(&memory) + peak = max(peak, memory.HeapAlloc) + result := &bleve.SearchResult{} + for i := from; i < min(from+10, documents); i++ { + phrases := make([]interface{}, 100) + for j := range phrases { + phrases[j] = fmt.Sprintf("unique%d phrase%d", i, j) + } + result.Hits = append(result.Hits, &search.DocumentMatch{ + Fields: map[string]interface{}{"TextRankPhrases": phrases}, + }) + } + return result, nil + }) + if err != nil { + b.Fatal(err) + } + if len(counts.phrases) != 0 || len(counts.similarityPhrases) != 0 { + b.Fatal("unique phrases must not be retained") + } + } + b.ReportMetric(float64(peak)/1024/1024, "live-heap-MiB") + }) + } +} From 11664983c349e72aaa0cc2ac435f3b5f7d5f1217 Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Sun, 22 Nov 2026 09:41:22 +0100 Subject: [PATCH 2/7] COnsolidated datasourceid --- index_migration_test.go | 21 +++-- internal/biography/service.go | 1 + .../datasource/biblioreads/adapter_test.go | 4 +- internal/datasource/model/author.go | 3 +- internal/datasource/wikidata/author.go | 11 ++- internal/datasource/wikidata/service.go | 7 +- internal/datasource/wikidata/service_test.go | 11 ++- internal/index/author.go | 19 ++-- internal/index/authors_enrich_test.go | 46 +++++++--- internal/index/bleve.go | 3 +- internal/index/bleve_author_migrate.go | 5 +- internal/index/bleve_author_migrate_test.go | 90 +++++++++++++++++-- internal/index/bleve_author_read.go | 14 ++- internal/index/bleve_author_write.go | 6 +- internal/index/document_data_sources_test.go | 6 +- internal/webserver/author_bio_test.go | 19 ++-- internal/webserver/author_summary_test.go | 35 +++++--- .../webserver/controller/author/controller.go | 5 +- .../partials/author-summary-doc-detail.html | 8 +- .../views/partials/author-summary.html | 8 +- .../views/partials/authors-list-item.html | 2 +- 21 files changed, 229 insertions(+), 95 deletions(-) diff --git a/index_migration_test.go b/index_migration_test.go index ac92b868..299c15b2 100644 --- a/index_migration_test.go +++ b/index_migration_test.go @@ -91,8 +91,12 @@ func TestGetIndexesRebuildsOlderDocuments(t *testing.T) { seedDocumentIndex(t, version) authors := index.CreateAuthorsIndex(homeDir + authorsIndexPath) retrieved := time.Now().UTC().Truncate(time.Second) - if err := authors.Index("existing-author", index.Author{ - Slug: "existing-author", Name: "Existing Author", DataSourceID: "Q1", RetrievedOn: retrieved, + if err := authors.Index("existing-author", struct { + index.Author + DataSourceLinks string + }{ + Author: index.Author{Slug: "existing-author", Name: "Existing Author", RetrievedOn: retrieved}, + DataSourceLinks: `{"wikidata":"Q1"}`, }); err != nil { t.Fatal(err) } @@ -150,7 +154,7 @@ func TestGetIndexesRebuildsOlderDocuments(t *testing.T) { t.Fatalf("library must be searchable after rebuilding: %+v, %v", book, err) } author, err := idx.Author("existing-author", "") - if err != nil || author.DataSourceID != "Q1" || !author.RetrievedOn.Equal(retrieved) { + if err != nil || author.DataSourceLinks["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { t.Fatalf("rebuilding must preserve author metadata: %+v, %v", author, err) } if err := idx.Close(); err != nil { @@ -270,13 +274,18 @@ func TestGetIndexesMigratesAuthorsWithoutReindexingDocuments(t *testing.T) { } legacyMapping := index.CreateAuthorsMapping().(*mapping.IndexMappingImpl) delete(legacyMapping.DefaultMapping.Properties, "DataSourceLinks") + legacyMapping.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) authors, err := bleve.New(homeDir+authorsIndexPath, legacyMapping) if err != nil { t.Fatal(err) } retrieved := time.Now().UTC().Truncate(time.Second) - if err := authors.Index("alice-borchardt", index.Author{ - Slug: "alice-borchardt", Name: "Alice Borchardt", DataSourceID: "Q1", RetrievedOn: retrieved, + if err := authors.Index("alice-borchardt", struct { + index.Author + DataSourceID string + }{ + Author: index.Author{Slug: "alice-borchardt", Name: "Alice Borchardt", RetrievedOn: retrieved}, + DataSourceID: "Q1", }); err != nil { t.Fatal(err) } @@ -305,7 +314,7 @@ func TestGetIndexesMigratesAuthorsWithoutReindexingDocuments(t *testing.T) { t.Fatalf("author migration changed document enrichment state: %+v, %v", data, err) } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceID != "Q1" || !author.RetrievedOn.Equal(retrieved) { + if err != nil || author.DataSourceLinks["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { t.Fatalf("expected existing author metadata preserved: %+v, %v", author, err) } if pending, err := idx.AuthorsWithoutInfo(); err != nil || len(pending) != 0 { diff --git a/internal/biography/service.go b/internal/biography/service.go index 79707bf2..579844de 100644 --- a/internal/biography/service.go +++ b/internal/biography/service.go @@ -74,6 +74,7 @@ func (s *Service) forLanguage(language string) *Service { return s } +func (s *Service) LinkKey() string { return s.source.LinkKey() } func (s *Service) ProfileServiceName() string { return s.source.ProfileServiceName() } func (s *Service) ProfileInputName() string { return s.source.ProfileInputName() } func (s *Service) ProfileValue(author index.Author) string { diff --git a/internal/datasource/biblioreads/adapter_test.go b/internal/datasource/biblioreads/adapter_test.go index 075814a4..d7260029 100644 --- a/internal/datasource/biblioreads/adapter_test.go +++ b/internal/datasource/biblioreads/adapter_test.go @@ -256,7 +256,7 @@ func TestEnrichStoresSecondAuthorURLAndPreservesItOnEdits(t *testing.T) { if err != nil || first.DataSourceLinks["goodreads"] != "" { t.Fatalf("first author must not receive coauthor URL, got %+v, %v", first, err) } - stale.DataSourceID = "Q2" + stale.DataSourceLinks["wikidata"] = "Q2" stale.RetrievedOn = time.Now().UTC() stale.DataSourceLinks["goodreads"] = "999.Stale" if err := idx.IndexAuthor(stale); err != nil { @@ -268,7 +268,7 @@ func TestEnrichStoresSecondAuthorURLAndPreservesItOnEdits(t *testing.T) { author, err = idx.Author("second-author", "") if err != nil || author.DataSourceLinks["goodreads"] != "2" || author.DataSourceLinks["other"] != "https://example.org/second-author" || - author.DataSourceID != "Q2" || author.DocumentCount != 1 { + author.DataSourceLinks["wikidata"] != "Q2" || author.DocumentCount != 1 { t.Fatalf("stale author edit lost URL or metadata: %+v, %v", author, err) } if _, err := idx.NewFile("second.pdf", []byte("")); err != nil { diff --git a/internal/datasource/model/author.go b/internal/datasource/model/author.go index e02faffd..d3f31544 100644 --- a/internal/datasource/model/author.go +++ b/internal/datasource/model/author.go @@ -24,11 +24,10 @@ type Author interface { DateOfBirth() precisiondate.PrecisionDate DateOfDeath() precisiondate.PrecisionDate Image() string - // Links returns the current links owned by this datasource, including language-specific keys. + // Links returns source-owned profile IDs and URLs, including language-specific keys. Links() map[string]string // OwnsLink identifies entries replaced by a metadata refresh, even if absent from Links. OwnsLink(key string) bool - SourceID() string RetrievedOn() time.Time Pseudonyms() []string } diff --git a/internal/datasource/wikidata/author.go b/internal/datasource/wikidata/author.go index 19e1c511..cc9cffd1 100644 --- a/internal/datasource/wikidata/author.go +++ b/internal/datasource/wikidata/author.go @@ -83,7 +83,10 @@ func (a Author) DateOfDeath() precisiondate.PrecisionDate { } func (a Author) Links() map[string]string { - links := make(map[string]string, len(a.wikipediaLink)+1) + links := make(map[string]string, len(a.wikipediaLink)+2) + if a.wikidataEntityId != "" { + links["wikidata"] = a.wikidataEntityId + } if a.website != "" { links["website"] = a.website } @@ -96,7 +99,7 @@ func (a Author) Links() map[string]string { } func (a Author) OwnsLink(key string) bool { - return key == "website" || strings.HasPrefix(key, "wikipedia:") + return key == "wikidata" || key == "website" || strings.HasPrefix(key, "wikipedia:") } func (a Author) Image() string { @@ -111,10 +114,6 @@ func (a Author) Gender() float64 { return a.gender } -func (a Author) SourceID() string { - return a.wikidataEntityId -} - func (a Author) RetrievedOn() time.Time { return a.retrievedOn } diff --git a/internal/datasource/wikidata/service.go b/internal/datasource/wikidata/service.go index 81592e72..03d70780 100644 --- a/internal/datasource/wikidata/service.go +++ b/internal/datasource/wikidata/service.go @@ -44,6 +44,8 @@ type WikidataSource struct { wikidata wikidata } +func (WikidataSource) LinkKey() string { return "wikidata" } + func (WikidataSource) OwnsLink(key string) bool { return (Author{}).OwnsLink(key) } @@ -53,10 +55,11 @@ func (WikidataSource) ProfileServiceName() string { } func (WikidataSource) ProfileValue(author index.Author) string { - if author.DataSourceID == "" { + id := author.DataSourceLinks["wikidata"] + if id == "" { return "" } - return "https://www.wikidata.org/wiki/" + author.DataSourceID + return "https://www.wikidata.org/wiki/" + id } // NormalizeAuthorID accepts a Wikidata author ID or profile URL. diff --git a/internal/datasource/wikidata/service_test.go b/internal/datasource/wikidata/service_test.go index 8af7eaed..664beaec 100644 --- a/internal/datasource/wikidata/service_test.go +++ b/internal/datasource/wikidata/service_test.go @@ -50,7 +50,8 @@ func TestNormalizeAuthorID(t *testing.T) { func TestAuthorLinks(t *testing.T) { author := Author{ - website: "https://author.example", + wikidataEntityId: "Q1234", + website: "https://author.example", wikipediaLink: map[string]string{ "en": "https://en.wikipedia.org/wiki/Example", "es": "https://es.wikipedia.org/wiki/Ejemplo", @@ -58,6 +59,7 @@ func TestAuthorLinks(t *testing.T) { }, } want := map[string]string{ + "wikidata": "Q1234", "website": "https://author.example", "wikipedia:en": "https://en.wikipedia.org/wiki/Example", "wikipedia:es": "https://es.wikipedia.org/wiki/Ejemplo", @@ -66,12 +68,13 @@ func TestAuthorLinks(t *testing.T) { t.Fatalf("unexpected author links: %+v", got) } links := author.Links() + links["wikidata"] = "Q1" links["website"] = "https://changed.example" links["wikipedia:en"] = "https://changed.example/en" if got := author.Links(); !reflect.DeepEqual(got, want) { t.Fatalf("caller mutated author links: %+v", got) } - for _, key := range []string{"website", "wikipedia:en", "wikipedia:de"} { + for _, key := range []string{"wikidata", "website", "wikipedia:en", "wikipedia:de"} { if !author.OwnsLink(key) { t.Errorf("Wikidata should own %q, including missing language links", key) } @@ -186,7 +189,7 @@ func TestRetrieveAuthorsBatch(t *testing.T) { if len(authors) != 1 { t.Fatalf("expected 1 author from batch retrieve, got %d", len(authors)) } - if authors["miguel"].SourceID() != "Q1234" { - t.Fatalf("expected Q1234, got %q", authors["miguel"].SourceID()) + if authors["miguel"].Links()["wikidata"] != "Q1234" { + t.Fatalf("expected Q1234, got %q", authors["miguel"].Links()["wikidata"]) } } diff --git a/internal/index/author.go b/internal/index/author.go index b69d46c0..ab5ac425 100644 --- a/internal/index/author.go +++ b/internal/index/author.go @@ -11,16 +11,15 @@ import ( ) type Author struct { - Slug string - Name string - BirthName string - DataSourceID string - RetrievedOn time.Time - InstanceOf float64 - Description map[string]string - DateOfBirth precisiondate.PrecisionDate - DateOfDeath precisiondate.PrecisionDate - // DataSourceLinks contains references owned by external data sources. + Slug string + Name string + BirthName string + RetrievedOn time.Time + InstanceOf float64 + Description map[string]string + DateOfBirth precisiondate.PrecisionDate + DateOfDeath precisiondate.PrecisionDate + // DataSourceLinks contains source-owned profile IDs and URLs. DataSourceLinks map[string]string DataSourceImage string Gender float64 diff --git a/internal/index/authors_enrich_test.go b/internal/index/authors_enrich_test.go index 51244e02..f8fde203 100644 --- a/internal/index/authors_enrich_test.go +++ b/internal/index/authors_enrich_test.go @@ -18,6 +18,7 @@ type mockAuthorDataSource struct { byName map[string]datasourcemodel.Author bySlug map[string]datasourcemodel.Author entityIDs map[string][]string + candidates map[string][]string calls int searchCalls int retrieveCalls int @@ -25,6 +26,8 @@ type mockAuthorDataSource struct { errName string } +func (*mockAuthorDataSource) LinkKey() string { return "example" } + func (m *mockAuthorDataSource) SearchAuthor(name string, _ []string) (datasourcemodel.Author, error) { m.calls++ m.searchCalls++ @@ -54,7 +57,7 @@ func (m *mockAuthorDataSource) SearchEntityIDs(name string) ([]string, error) { } } if author, ok := m.byName[name]; ok && author != nil { - return []string{author.SourceID()}, nil + return []string{author.Links()["example"]}, nil } return nil, nil } @@ -68,6 +71,7 @@ func (m *mockAuthorDataSource) RetrieveAuthor(_ []string, _ []string) (datasourc func (m *mockAuthorDataSource) RetrieveAuthors(candidates map[string][]string, _ []string, _ time.Duration, onResult func(string, datasourcemodel.Author) error) error { m.calls++ m.retrieveCalls++ + m.candidates = maps.Clone(candidates) for slug := range candidates { author := m.bySlug[slug] if err := onResult(slug, author); err != nil { @@ -90,11 +94,19 @@ func (a stubAuthor) Gender() float64 { return 0 } func (a stubAuthor) DateOfBirth() precisiondate.PrecisionDate { return precisiondate.PrecisionDate{} } func (a stubAuthor) DateOfDeath() precisiondate.PrecisionDate { return precisiondate.PrecisionDate{} } func (a stubAuthor) Image() string { return "" } -func (a stubAuthor) Links() map[string]string { return maps.Clone(a.links) } +func (a stubAuthor) Links() map[string]string { + links := maps.Clone(a.links) + if a.sourceID != "" { + if links == nil { + links = make(map[string]string) + } + links["example"] = a.sourceID + } + return links +} func (a stubAuthor) OwnsLink(key string) bool { - return a.linkPrefix != "" && strings.HasPrefix(key, a.linkPrefix) + return key == "example" || (a.linkPrefix != "" && strings.HasPrefix(key, a.linkPrefix)) } -func (a stubAuthor) SourceID() string { return a.sourceID } func (a stubAuthor) RetrievedOn() time.Time { return time.Now().UTC() } func (a stubAuthor) Pseudonyms() []string { return nil } @@ -167,8 +179,9 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { defer authors.Close() idx := index.NewBleve(nil, authors, nil, "", nil, index.Config{}) author := index.Author{ - Slug: "writer", Name: "Writer", DataSourceID: "Q1", DocumentCount: 3, + Slug: "writer", Name: "Writer", DocumentCount: 3, DataSourceLinks: map[string]string{ + "example": "Q1", "example:website": "https://old.example", "example:en": "https://en.example/Old", "catalog": "https://catalog.example/writer", }, @@ -196,7 +209,7 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { t.Fatal(err) } if stored.DataSourceLinks["example:website"] != "" || stored.DataSourceLinks["example:en"] != "" || - stored.DataSourceID != "" || stored.RetrievedOn.IsZero() { + stored.DataSourceLinks["example"] != "" || stored.RetrievedOn.IsZero() { t.Fatalf("reset must remove metadata association and owned links: %+v", stored) } if stored.DataSourceLinks["catalog"] != "https://catalog.example/writer" || @@ -268,10 +281,16 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if err := idx.IndexAuthor(index.Author{Slug: "done", Name: "Done Author", RetrievedOn: time.Now().UTC()}); err != nil { t.Fatal(err) } + if err := idx.IndexAuthor(index.Author{ + Slug: "known", Name: "Known Author", DataSourceLinks: map[string]string{"example": "Q2", "other": "unrelated"}, + }); err != nil { + t.Fatal(err) + } dataSource := &mockAuthorDataSource{ bySlug: map[string]datasourcemodel.Author{ "found": stubAuthor{sourceID: "Q1"}, + "known": stubAuthor{sourceID: "Q2"}, }, entityIDs: map[string][]string{ "Found Author": {"Q1"}, @@ -290,6 +309,9 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if dataSource.retrieveCalls != 1 { t.Fatalf("expected 1 batched Wikidata entity fetch, got %d", dataSource.retrieveCalls) } + if ids := dataSource.candidates["known"]; len(ids) != 1 || ids[0] != "Q2" { + t.Fatalf("expected the known source reference reused without a name search, got %v", ids) + } if elapsed < 50*time.Millisecond { t.Fatalf("expected throttling between lookups, took %s", elapsed) } @@ -298,8 +320,12 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if err != nil { t.Fatal(err) } - if found.DataSourceID != "Q1" { - t.Fatalf("expected enriched author Q1, got %q", found.DataSourceID) + if found.DataSourceLinks["example"] != "Q1" { + t.Fatalf("expected enriched author Q1, got %q", found.DataSourceLinks["example"]) + } + known, err := idx.Author("known", "en") + if err != nil || known.DataSourceLinks["example"] != "Q2" || known.DataSourceLinks["other"] != "unrelated" { + t.Fatalf("enrichment lost existing source references: %+v, %v", known, err) } missing, err := idx.Author("missing", "en") @@ -309,8 +335,8 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if missing.RetrievedOn.IsZero() { t.Fatal("expected missing author to be marked as processed") } - if missing.DataSourceID != "" { - t.Fatalf("expected missing author to have no data source id, got %q", missing.DataSourceID) + if missing.DataSourceLinks["example"] != "" { + t.Fatalf("expected missing author to have no data source id, got %q", missing.DataSourceLinks["example"]) } remaining, err := idx.AuthorsWithoutInfo() diff --git a/internal/index/bleve.go b/internal/index/bleve.go index 6e0d43b5..f5f16fa7 100644 --- a/internal/index/bleve.go +++ b/internal/index/bleve.go @@ -35,7 +35,7 @@ const DocumentVersion = "v14" // AuthorVersion identifies the mapping used for indexing authors. Any changes in the mapping requires an increase // of version, to signal that a new index needs to be created. -const AuthorVersion = "3" +const AuthorVersion = "4" // Metadata fields var ( @@ -578,7 +578,6 @@ func CreateAuthorsMapping() mapping.IndexMapping { indexMapping.DefaultMapping.AddFieldMappingsAt("Name", simpleTextFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("BirthName", simpleTextFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("RetrievedOn", dateTimeFieldMapping) - indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceID", keywordFieldMappingNotIndexable) indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceImage", keywordFieldMappingNotIndexable) indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceLinks", storedOnlyFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfBirth.Date", numericFieldMapping) diff --git a/internal/index/bleve_author_migrate.go b/internal/index/bleve_author_migrate.go index 4fdc6900..ac784e75 100644 --- a/internal/index/bleve_author_migrate.go +++ b/internal/index/bleve_author_migrate.go @@ -11,7 +11,7 @@ import ( "github.com/blevesearch/bleve/v2" ) -// OpenAuthorsIndex upgrades version 2 without discarding stored author metadata. +// OpenAuthorsIndex upgrades versions 2 and 3 without discarding stored author metadata. // The previous index is kept only until the migrated index opens successfully. func OpenAuthorsIndex(path string, batchSize int) (bleve.Index, error) { authors, err := bleve.Open(path) @@ -34,7 +34,7 @@ func OpenAuthorsIndex(path string, batchSize int) (bleve.Index, error) { if err != nil { return nil, errors.Join(err, authors.Close()) } - if string(version) == "2" { + if string(version) == "2" || string(version) == "3" { upgraded, err := migrateAuthorsIndex(authors, path, batchSize) if err != nil { return nil, errors.Join(err, authors.Close()) @@ -54,6 +54,7 @@ func migrateAuthorsIndex(authors bleve.Index, path string, batchSize int) (bleve if batchSize <= 0 { return nil, fmt.Errorf("authors migration batch size must be positive") } + // Retain the historical path for recovery of interrupted version 2 upgrades. backup := path + ".v2-backup" if _, err := os.Stat(backup); err == nil { return nil, fmt.Errorf("authors migration backup already exists: %s", backup) diff --git a/internal/index/bleve_author_migrate_test.go b/internal/index/bleve_author_migrate_test.go index 7e964cbf..7a384512 100644 --- a/internal/index/bleve_author_migrate_test.go +++ b/internal/index/bleve_author_migrate_test.go @@ -1,6 +1,7 @@ package index import ( + "encoding/json" "os" "path/filepath" "reflect" @@ -18,6 +19,7 @@ func legacyAuthorsIndex(t *testing.T, path string) bleve.Index { t.Helper() m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) delete(m.DefaultMapping.Properties, "DataSourceLinks") + m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) idx, err := bleve.New(path, m) if err != nil { t.Fatal(err) @@ -34,8 +36,9 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { retrieved := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) want := Author{ Slug: "alice-borchardt", Name: "Alice Borchardt", BirthName: "Alice O'Brien", - DataSourceID: "Q1", RetrievedOn: retrieved, + RetrievedOn: retrieved, DataSourceLinks: map[string]string{ + "wikidata": "Q1", "wikipedia:en": "https://en.wikipedia.org/wiki/Alice_Borchardt", "wikipedia:es": "https://es.wikipedia.org/wiki/Alice_Borchardt", "website": "https://example.org", @@ -49,9 +52,10 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { for _, author := range []Author{want, {Slug: "other", Name: "Other", RetrievedOn: retrieved}, {Slug: "third", Name: "Third", RetrievedOn: retrieved}} { if err := legacy.Index(author.Slug, struct { Author + DataSourceID string Website string WikipediaLink map[string]string - }{author, author.DataSourceLinks["website"], map[string]string{ + }{author, author.DataSourceLinks["wikidata"], author.DataSourceLinks["website"], map[string]string{ "en": author.DataSourceLinks["wikipedia:en"], "es": author.DataSourceLinks["wikipedia:es"], }}); err != nil { t.Fatal(err) @@ -117,7 +121,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { func TestOpenAuthorsIndexRecoversInterruptedSwap(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") legacy := legacyAuthorsIndex(t, path+".v2-backup") - if err := legacy.Index("saved", Author{Slug: "saved", Name: "Saved Author", DataSourceID: "Q1"}); err != nil { + if err := legacy.Index("saved", map[string]string{"Slug": "saved", "Name": "Saved Author", "DataSourceID": "Q1"}); err != nil { t.Fatal(err) } if err := legacy.Close(); err != nil { @@ -133,6 +137,79 @@ func TestOpenAuthorsIndexRecoversInterruptedSwap(t *testing.T) { } } +func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { + for _, referenceID := range []string{"", "Q2"} { + t.Run("reference="+referenceID, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "authors_index") + m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) + m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) + legacy, err := bleve.New(path, m) + if err != nil { + t.Fatal(err) + } + want := Author{ + Slug: "writer", Name: "Writer", RetrievedOn: time.Now().UTC().Truncate(time.Second), + Description: map[string]string{"en": "Writer", "es": "Escritora"}, DocumentCount: 7, + Pseudonyms: []string{"Writer Alias"}, + DataSourceLinks: map[string]string{ + "goodreads": "1.Writer", "wikipedia:es": "https://es.wikipedia.org/wiki/Writer", + }, + Bio: AuthorBio{Source: "https://es.wikipedia.org/wiki/Writer", Language: "es", + Text: map[string]string{"es": "Biografia", "en": "Biography"}}, + } + if referenceID != "" { + want.DataSourceLinks["wikidata"] = referenceID + } + links, err := json.Marshal(want.DataSourceLinks) + if err != nil { + t.Fatal(err) + } + stored := want + stored.DataSourceLinks = nil + if err := legacy.Index(want.Slug, struct { + Author + DataSourceID string + DataSourceLinks string + }{stored, "Q1", string(links)}); err != nil { + t.Fatal(err) + } + if err := legacy.SetInternal(internalVersion, []byte("3")); err != nil { + t.Fatal(err) + } + if err := legacy.Close(); err != nil { + t.Fatal(err) + } + upgraded, err := OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + if err := upgraded.Close(); err != nil { + t.Fatal(err) + } + reopened, err := OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + req := bleve.NewSearchRequest(bleve.NewDocIDQuery([]string{want.Slug})) + req.Fields = []string{"*"} + result, err := reopened.Search(req) + if err != nil || len(result.Hits) != 1 { + t.Fatalf("reading migrated author: %v", err) + } + if _, found := result.Hits[0].Fields["DataSourceID"]; found { + t.Fatal("migration retained the standalone source ID") + } + if referenceID == "" { + want.DataSourceLinks["wikidata"] = "Q1" + } + if got := hydrateAuthor(result.Hits[0]); !reflect.DeepEqual(got, want) { + t.Fatalf("migration changed author metadata or references:\ngot: %#v\nwant: %#v", got, want) + } + }) + } +} + func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") backup := legacyAuthorsIndex(t, path+".v2-backup") @@ -140,7 +217,7 @@ func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { t.Fatal(err) } current := CreateAuthorsIndex(path) - if err := current.Index("saved", Author{Slug: "saved", Name: "Saved Author", DataSourceID: "Q1"}); err != nil { + if err := indexAuthor(current, "saved", Author{Slug: "saved", Name: "Saved Author", DataSourceLinks: map[string]string{"wikidata": "Q1"}}); err != nil { t.Fatal(err) } if err := current.Close(); err != nil { @@ -162,7 +239,7 @@ func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { func TestOpenAuthorsIndexMigrationFailurePreservesOriginal(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") legacy := legacyAuthorsIndex(t, path) - if err := legacy.Index("saved", Author{Slug: "saved", Name: "Saved Author", DataSourceID: "Q1"}); err != nil { + if err := legacy.Index("saved", map[string]string{"Slug": "saved", "Name": "Saved Author", "DataSourceID": "Q1"}); err != nil { t.Fatal(err) } @@ -189,6 +266,7 @@ func TestOpenAuthorsIndexMigratesLegacyAuthorLinks(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) delete(m.DefaultMapping.Properties, "DataSourceLinks") + m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) legacyURL := bleve.NewKeywordFieldMapping() legacyURL.Index = false legacyURL.IncludeInAll = false @@ -222,7 +300,7 @@ func TestOpenAuthorsIndexMigratesLegacyAuthorLinks(t *testing.T) { } idx := NewBleve(nil, upgraded, nil, "", nil, Config{}) author, err := idx.Author("alice", "") - if err != nil || author.DataSourceID != "Q1" || author.DocumentCount != 7 || + if err != nil || author.DataSourceLinks["wikidata"] != "Q1" || author.DocumentCount != 7 || author.DataSourceLinks["website"] != "https://example.org" || author.DataSourceLinks["wikipedia:en"] != "https://en.wikipedia.org/wiki/Alice" || author.DataSourceLinks["wikipedia:es"] != "https://es.wikipedia.org/wiki/Alice" { diff --git a/internal/index/bleve_author_read.go b/internal/index/bleve_author_read.go index 7eb82733..20fe976f 100644 --- a/internal/index/bleve_author_read.go +++ b/internal/index/bleve_author_read.go @@ -108,13 +108,6 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { } } - dataSourceID := "" - if val, ok := fields["DataSourceID"]; ok && val != nil { - if str, ok := val.(string); ok { - dataSourceID = str - } - } - dataSourceImage := "" if val, ok := fields["DataSourceImage"]; ok && val != nil { if str, ok := val.(string); ok { @@ -147,7 +140,6 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { Name: name, BirthName: birthName, Slug: slug, - DataSourceID: dataSourceID, RetrievedOn: retrievedOn, InstanceOf: instanceOf, Description: make(map[string]string), @@ -163,6 +155,12 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { log.Printf("Error reading data source links for author %s: %s", docID, err) } } + if legacyID, ok := fields["DataSourceID"].(string); ok && legacyID != "" && author.DataSourceLinks["wikidata"] == "" { + if author.DataSourceLinks == nil { + author.DataSourceLinks = make(map[string]string) + } + author.DataSourceLinks["wikidata"] = legacyID + } author.Bio.Source, _ = fields["Bio.Source"].(string) author.Bio.Language, _ = fields["Bio.Language"].(string) // Extract descriptions and biographies for all languages. diff --git a/internal/index/bleve_author_write.go b/internal/index/bleve_author_write.go index 8e6f0c75..ed6b2d0a 100644 --- a/internal/index/bleve_author_write.go +++ b/internal/index/bleve_author_write.go @@ -290,6 +290,7 @@ const ( // AuthorDataSource retrieves author metadata from an external source. type AuthorDataSource interface { + LinkKey() string SearchAuthor(name string, languages []string) (datasourcemodel.Author, error) SearchEntityIDs(name string) ([]string, error) RetrieveAuthor(ids []string, languages []string) (datasourcemodel.Author, error) @@ -298,7 +299,6 @@ type AuthorDataSource interface { // CombineWithDataSource merges external author metadata into an indexed author. func CombineWithDataSource(author *Author, authorDataSource datasourcemodel.Author, supportedLanguages []string) { - author.DataSourceID = authorDataSource.SourceID() author.BirthName = authorDataSource.BirthName() author.RetrievedOn = authorDataSource.RetrievedOn() author.DataSourceLinks = maps.Clone(author.DataSourceLinks) @@ -364,8 +364,8 @@ func (b *BleveIndexer) EnrichAuthorsFromDataSource(dataSource AuthorDataSource, searchIndex := 0 for _, author := range authors { authorsBySlug[author.Slug] = author - if author.DataSourceID != "" { - candidates[author.Slug] = []string{author.DataSourceID} + if id := author.DataSourceLinks[dataSource.LinkKey()]; id != "" { + candidates[author.Slug] = []string{id} b.recordAuthorEnrichmentProgress() continue } diff --git a/internal/index/document_data_sources_test.go b/internal/index/document_data_sources_test.go index 3c79047d..e6492780 100644 --- a/internal/index/document_data_sources_test.go +++ b/internal/index/document_data_sources_test.go @@ -296,8 +296,8 @@ func TestUpdateDocumentStoresAuthorLinksFirstWins(t *testing.T) { } if existing { if err := idx.IndexAuthor(Author{ - Name: "Existing Writer", Slug: "writer", DocumentCount: 42, DataSourceID: "external-id", - DataSourceLinks: map[string]string{"other": "other-reference"}, + Name: "Existing Writer", Slug: "writer", DocumentCount: 42, + DataSourceLinks: map[string]string{"wikidata": "external-id", "other": "other-reference"}, }); err != nil { t.Fatal(err) } @@ -317,7 +317,7 @@ func TestUpdateDocumentStoresAuthorLinksFirstWins(t *testing.T) { } if existing { if author.Name != "Existing Writer" || author.DocumentCount != 42 || - author.DataSourceID != "external-id" || author.DataSourceLinks["other"] != "other-reference" { + author.DataSourceLinks["wikidata"] != "external-id" || author.DataSourceLinks["other"] != "other-reference" { t.Fatalf("existing author metadata changed: %+v", author) } } else if author.Name != "Writer" || author.DocumentCount != 3 { diff --git a/internal/webserver/author_bio_test.go b/internal/webserver/author_bio_test.go index 19d6e376..1c8628af 100644 --- a/internal/webserver/author_bio_test.go +++ b/internal/webserver/author_bio_test.go @@ -177,12 +177,12 @@ func TestAuthorDetailCardLayoutAndSanitization(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceID = "Q1234" author.Description = map[string]string{"en": "American novelist"} author.RetrievedOn = time.Now() author.DateOfBirth = precisiondate.NewPrecisionDate("+1920-01-02T00:00:00Z", precisiondate.PrecisionDay) author.DateOfDeath = precisiondate.NewPrecisionDate("+1992-04-06T00:00:00Z", precisiondate.PrecisionDay) author.DataSourceLinks = map[string]string{ + "wikidata": "Q1234", "goodreads": "1.John_Doe", "website": "https://example.com", } @@ -356,19 +356,22 @@ func (*bioMetadataSource) NormalizeAuthorID(value string) (string, error) { func (s *bioMetadataSource) RetrieveAuthor(ids []string, _ []string) (datasourcemodel.Author, error) { return bioMetadata{sourceID: ids[0], link: s.link}, nil } -func (*bioMetadataSource) OwnsLink(key string) bool { return strings.HasPrefix(key, "catalog:") } +func (*bioMetadataSource) OwnsLink(key string) bool { + return key == "example" || strings.HasPrefix(key, "catalog:") +} type bioMetadata struct { alternativeAuthorMetadata sourceID, link string } -func (m bioMetadata) SourceID() string { return m.sourceID } func (m bioMetadata) Links() map[string]string { + links := map[string]string{"example": m.sourceID} if m.link == "" { - return nil + return links } - return map[string]string{"catalog:es": m.link} + links["catalog:es"] = m.link + return links } func (bioMetadata) OwnsLink(key string) bool { return (&bioMetadataSource{}).OwnsLink(key) @@ -424,8 +427,8 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceID = "old-author" author.DataSourceLinks = map[string]string{ + "example": "old-author", "catalog:es": "old-profile", "independent": "other-profile", } @@ -455,7 +458,7 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceID != "new-author" || stored.Bio.Source != source.link || stored.Bio.Text["es"] != result.text || + if stored.DataSourceLinks["example"] != "new-author" || stored.Bio.Source != source.link || stored.Bio.Text["es"] != result.text || stored.DataSourceLinks["independent"] != "other-profile" { t.Fatalf("metadata update must refresh and persist its biography while preserving independent links: %+v", stored) } @@ -500,7 +503,7 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceID != sourceID || + if response.StatusCode != http.StatusOK || stored.DataSourceLinks["example"] != sourceID || stored.Bio.Source != "" || len(stored.Bio.Text) != 0 || stored.DataSourceLinks["catalog:es"] != "" || len(result.calls) != beforeCalls { t.Fatalf("missing or cleared metadata links must clear the biography without requests: %+v", stored) diff --git a/internal/webserver/author_summary_test.go b/internal/webserver/author_summary_test.go index a4a828a3..09504a12 100644 --- a/internal/webserver/author_summary_test.go +++ b/internal/webserver/author_summary_test.go @@ -31,8 +31,10 @@ type alternativeAuthorSource struct { } func (*alternativeAuthorSource) ProfileServiceName() string { return "Example catalog" } +func (*alternativeAuthorSource) LinkKey() string { return "example" } +func (*alternativeAuthorSource) OwnsLink(key string) bool { return key == "example" } func (*alternativeAuthorSource) ProfileValue(author index.Author) string { - return "https://example.org/authors/" + author.DataSourceID + return "https://example.org/authors/" + author.DataSourceLinks["example"] } func (*alternativeAuthorSource) AuthorLink(index.Author, string) datasourcemodel.DataSourceLink { return datasourcemodel.DataSourceLink{} @@ -62,10 +64,11 @@ func (alternativeAuthorMetadata) DateOfBirth() precisiondate.PrecisionDate { func (alternativeAuthorMetadata) DateOfDeath() precisiondate.PrecisionDate { return precisiondate.PrecisionDate{} } -func (alternativeAuthorMetadata) Image() string { return "" } -func (alternativeAuthorMetadata) Links() map[string]string { return nil } -func (alternativeAuthorMetadata) OwnsLink(string) bool { return false } -func (alternativeAuthorMetadata) SourceID() string { return "alice" } +func (alternativeAuthorMetadata) Image() string { return "" } +func (alternativeAuthorMetadata) Links() map[string]string { + return map[string]string{"example": "alice"} +} +func (alternativeAuthorMetadata) OwnsLink(key string) bool { return key == "example" } func (alternativeAuthorMetadata) RetrievedOn() time.Time { return time.Unix(1, 0).UTC() } func (alternativeAuthorMetadata) Pseudonyms() []string { return nil } @@ -83,8 +86,7 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceID = "old-profile" - author.DataSourceLinks = map[string]string{"independent": "https://other.example/author"} + author.DataSourceLinks = map[string]string{"example": "old-profile", "independent": "https://other.example/author"} if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) } @@ -145,11 +147,17 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { if value := page.Find(`input[name="sourceID"]`).AttrOr("value", ""); value != "https://example.org/authors/alice" { t.Fatalf("expected the provider profile URL in the form, got %q", value) } + if description := strings.TrimSpace(page.Find("p.capitalize.lead").Text()); description != "Updated author metadata" { + t.Fatalf("expected metadata rendered from the provider's reference, got %q", description) + } + if imageURL := page.Find(`img[src^="/authors/"]`).AttrOr("src", ""); imageURL != "/authors/john-doe_alice.webp" { + t.Fatalf("expected image URL to use the provider's reference, got %q", imageURL) + } stored, err := idx.Author("john-doe", "en") if err != nil { t.Fatal(err) } - if stored.DataSourceID != "alice" || stored.BirthName != "Alice Example" || + if stored.DataSourceLinks["example"] != "alice" || stored.BirthName != "Alice Example" || stored.Description["en"] != "Updated author metadata" || stored.DataSourceLinks["independent"] != before.DataSourceLinks["independent"] || !reflect.DeepEqual(source.retrievedIDs, []string{"alice"}) { @@ -275,7 +283,7 @@ func TestClearAuthorRemovesImage(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceID != "" || stored.DataSourceImage != "" || + if stored.DataSourceLinks["wikidata"] != "" || stored.DataSourceImage != "" || stored.DataSourceLinks["website"] != "" || stored.DataSourceLinks["wikipedia:en"] != "" || stored.DataSourceLinks["wikipedia:es"] != "" { t.Fatalf("metadata reset restored stale metadata: %+v", stored) @@ -292,7 +300,7 @@ func TestClearAuthorRemovesImage(t *testing.T) { type summaryDataSourceLinks struct{} func (summaryDataSourceLinks) AuthorLink(author index.Author, _ string) datasourcemodel.DataSourceLink { - if author.DataSourceID == "" { + if author.DataSourceLinks["wikidata"] == "" { return datasourcemodel.DataSourceLink{} } return datasourcemodel.DataSourceLink{ @@ -320,8 +328,8 @@ func TestAuthorSummaryDataSourceLinks(t *testing.T) { } { author := index.Author{ Slug: tc.name, Name: "Alice Borchardt", - DataSourceID: tc.dataSourceID, RetrievedOn: time.Now().UTC(), - DataSourceLinks: map[string]string{"website": "https://author.example/" + tc.name}, + RetrievedOn: time.Now().UTC(), + DataSourceLinks: map[string]string{"wikidata": tc.dataSourceID, "website": "https://author.example/" + tc.name}, } if tc.wikipedia { for _, lang := range locales { @@ -406,12 +414,13 @@ func (editableAlternativeLinks) AuthorLink(author index.Author, _ string) dataso } func (editableAlternativeLinks) ProfileServiceName() string { return "Example catalog" } +func (editableAlternativeLinks) LinkKey() string { return "example" } func (editableAlternativeLinks) ProfileValue(index.Author) string { return "catalog-profile" } func TestDocumentAuthorProfileUsesMetadataSource(t *testing.T) { app, idx := newDataSourceProvidersTestApp(t, nil, nil, editableAlternativeLinks{}) if err := idx.IndexAuthor(index.Author{ - Slug: "jane-doe", Name: "Jane Doe", DataSourceID: "Q1234", RetrievedOn: time.Now().UTC(), + Slug: "jane-doe", Name: "Jane Doe", DataSourceLinks: map[string]string{"wikidata": "Q1234"}, RetrievedOn: time.Now().UTC(), }); err != nil { t.Fatal(err) } diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index 4aebf4fb..d6e729b7 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -19,6 +19,7 @@ type DataSourceLinkProvider interface { } type ProfileInputProvider interface { + LinkKey() string ProfileServiceName() string ProfileValue(author index.Author) string } @@ -27,6 +28,7 @@ type ProfileInput struct { Name string ServiceName string Value string + Reference string Method string Action string FormID string @@ -40,7 +42,8 @@ type ProfileInput struct { func NewProfileInput(provider ProfileInputProvider, author index.Author, name, method, action string) ProfileInput { return ProfileInput{ Name: name, ServiceName: provider.ProfileServiceName(), Value: provider.ProfileValue(author), - Method: method, Action: action, + Reference: author.DataSourceLinks[provider.LinkKey()], + Method: method, Action: action, } } diff --git a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html index a0f35509..6320328a 100644 --- a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html +++ b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html @@ -1,3 +1,5 @@ +{{$metadataID := index .Author.DataSourceLinks "wikidata"}} +{{range .ProfileInputs}}{{if eq .Name "sourceID"}}{{$metadataID = .Reference}}{{end}}{{end}}
@@ -7,7 +9,7 @@

{{.Author.Name}}

{{.Author.BirthName}}

{{end}}
- {{if eq .Author.DataSourceID ""}} + {{if eq $metadataID ""}}

{{t .Lang "Sorry, we don't have information about this author at the moment"}}

{{else if index .Author.Description .Lang}}

{{index .Author.Description .Lang}}

@@ -18,7 +20,7 @@

{{.Author.Name}}

{{end}} - {{if ne .Author.DataSourceID ""}} + {{if ne $metadataID ""}}
{{if ne .Author.DateOfBirth.Date 0}}
{{t .Lang "Date of birth"}}
@@ -86,7 +88,7 @@

{{.Author.Name}}

- {{.Author.Name}} + {{.Author.Name}}
diff --git a/internal/webserver/embedded/views/partials/author-summary.html b/internal/webserver/embedded/views/partials/author-summary.html index a40f234a..407df519 100644 --- a/internal/webserver/embedded/views/partials/author-summary.html +++ b/internal/webserver/embedded/views/partials/author-summary.html @@ -1,3 +1,5 @@ +{{$metadataID := index .Author.DataSourceLinks "wikidata"}} +{{range .ProfileInputs}}{{if eq .Name "sourceID"}}{{$metadataID = .Reference}}{{end}}{{end}}
@@ -7,14 +9,14 @@

{{.Author.Name}}

{{.Author.BirthName}}

{{end}}
- {{if eq .Author.DataSourceID ""}} + {{if eq $metadataID ""}} {{if not (or .BioParagraphs .BioPending)}}

{{t .Lang "Sorry, we don't have information about this author at the moment"}}

{{end}} {{else if index .Author.Description .Lang}}

{{index .Author.Description .Lang}}

{{end}} - {{if ne .Author.DataSourceID ""}} + {{if ne $metadataID ""}}
{{if ne .Author.DateOfBirth.Date 0}}
{{t .Lang "Date of birth"}}
@@ -86,7 +88,7 @@

{{.Author.Name}}

- {{.Author.Name}} + {{.Author.Name}}
{{if or (index .Author.DataSourceLinks "website") .DataSourceLinks}}
diff --git a/internal/webserver/embedded/views/partials/authors-list-item.html b/internal/webserver/embedded/views/partials/authors-list-item.html index 487f19ca..aa60dd7f 100644 --- a/internal/webserver/embedded/views/partials/authors-list-item.html +++ b/internal/webserver/embedded/views/partials/authors-list-item.html @@ -2,7 +2,7 @@ From 119e0a589da7c9ecc9c779d57bcfce35897902e1 Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Sun, 22 Nov 2026 19:21:43 +0100 Subject: [PATCH 3/7] COnsolidated datasourceid --- index_migration_test.go | 4 +- internal/biography/service.go | 14 ++-- internal/biography/service_test.go | 8 +- .../datasource/biblioreads/adapter_test.go | 34 ++++---- internal/datasource/biblioreads/bio.go | 2 +- internal/datasource/biblioreads/reviews.go | 2 +- .../datasource/biblioreads/reviews_test.go | 4 +- internal/datasource/wikidata/bio.go | 2 +- internal/datasource/wikidata/bio_test.go | 6 +- internal/datasource/wikidata/service.go | 4 +- internal/datasource/wikidata/service_test.go | 2 +- internal/index/author.go | 16 ++-- internal/index/author_bio_test.go | 6 +- internal/index/authors_enrich_test.go | 52 ++++++------ internal/index/bleve_author_migrate.go | 8 +- internal/index/bleve_author_migrate_test.go | 84 +++++++++++++++---- internal/index/bleve_author_read.go | 14 ++-- internal/index/bleve_author_write.go | 40 ++++----- internal/index/bleve_document_data_sources.go | 8 +- internal/index/data_source_fields_test.go | 6 +- internal/index/document_data_sources_test.go | 6 +- internal/index/rebuild_authors_test.go | 6 +- internal/webserver/author_bio_test.go | 30 +++---- internal/webserver/author_summary_test.go | 30 +++---- .../webserver/controller/author/controller.go | 2 +- .../webserver/document_biblioreads_test.go | 2 +- .../partials/author-summary-doc-detail.html | 6 +- .../views/partials/author-summary.html | 6 +- .../views/partials/authors-list-item.html | 2 +- 29 files changed, 229 insertions(+), 177 deletions(-) diff --git a/index_migration_test.go b/index_migration_test.go index 299c15b2..e1746463 100644 --- a/index_migration_test.go +++ b/index_migration_test.go @@ -154,7 +154,7 @@ func TestGetIndexesRebuildsOlderDocuments(t *testing.T) { t.Fatalf("library must be searchable after rebuilding: %+v, %v", book, err) } author, err := idx.Author("existing-author", "") - if err != nil || author.DataSourceLinks["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { t.Fatalf("rebuilding must preserve author metadata: %+v, %v", author, err) } if err := idx.Close(); err != nil { @@ -314,7 +314,7 @@ func TestGetIndexesMigratesAuthorsWithoutReindexingDocuments(t *testing.T) { t.Fatalf("author migration changed document enrichment state: %+v, %v", data, err) } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceLinks["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { t.Fatalf("expected existing author metadata preserved: %+v, %v", author, err) } if pending, err := idx.AuthorsWithoutInfo(); err != nil || len(pending) != 0 { diff --git a/internal/biography/service.go b/internal/biography/service.go index 579844de..868eb5fb 100644 --- a/internal/biography/service.go +++ b/internal/biography/service.go @@ -109,7 +109,7 @@ func (s *Service) RefreshMetadataBio(ctx context.Context, author index.Author, l } func (s *Service) authorLink(author index.Author) (string, bool) { - value := author.DataSourceLinks[s.source.LinkKey()] + value := author.DataSourceReferences[s.source.LinkKey()] id, err := s.source.NormalizeAuthorID(value) return value, err == nil && id != "" && id == value } @@ -179,7 +179,7 @@ type storeFunc func(slug string, bio index.AuthorBio) error func (s *Service) bioStore(author index.Author, merge bool) storeFunc { linkKey := s.source.LinkKey() - previousLink := author.DataSourceLinks[linkKey] + previousLink := author.DataSourceReferences[linkKey] return func(slug string, bio index.AuthorBio) error { if bio.Source != previousLink { return s.index.StoreCanonicalAuthorBio(slug, linkKey, previousLink, bio) @@ -194,7 +194,7 @@ func (s *Service) UpdateBio(ctx context.Context, author index.Author, id, langua s = s.forLanguage(language) linkKey := s.source.LinkKey() if id == "" { - if err := s.index.StoreCanonicalAuthorBio(author.Slug, linkKey, author.DataSourceLinks[linkKey], index.AuthorBio{}); err != nil { + if err := s.index.StoreCanonicalAuthorBio(author.Slug, linkKey, author.DataSourceReferences[linkKey], index.AuthorBio{}); err != nil { return "", "", fmt.Errorf("clearing %s author link: %w", s.ProfileServiceName(), err) } return "", "", nil @@ -207,11 +207,11 @@ func (s *Service) UpdateBio(ctx context.Context, author index.Author, id, langua return "", "", fmt.Errorf("invalid %s author ID %q", s.ProfileServiceName(), id) } save := s.bioStore(author, false) - author.DataSourceLinks = maps.Clone(author.DataSourceLinks) - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + author.DataSourceReferences = maps.Clone(author.DataSourceReferences) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - author.DataSourceLinks[linkKey] = id + author.DataSourceReferences[linkKey] = id author.Bio = index.AuthorBio{} ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), requestTimeout) defer cancel() diff --git a/internal/biography/service_test.go b/internal/biography/service_test.go index 312ac967..28e899b9 100644 --- a/internal/biography/service_test.go +++ b/internal/biography/service_test.go @@ -32,7 +32,7 @@ func (*fakeSource) LinkKey() string { return "catalog" } func (*fakeSource) ProfileServiceName() string { return "Example catalog" } func (*fakeSource) ProfileInputName() string { return "catalogID" } func (*fakeSource) ProfileValue(author index.Author) string { - return author.DataSourceLinks["catalog"] + return author.DataSourceReferences["catalog"] } func (*fakeSource) NormalizeAuthorID(value string) (string, error) { if value == "invalid" { @@ -114,7 +114,7 @@ func (f *fakeBioIndex) StoreAuthorBioForLink(_ string, linkKey, previousSource s func catalogAuthor(bio index.AuthorBio) index.Author { return index.Author{ Slug: "alice", Name: "Alice Example", - DataSourceLinks: map[string]string{"catalog": "alice"}, Bio: bio, + DataSourceReferences: map[string]string{"catalog": "alice"}, Bio: bio, } } @@ -423,7 +423,7 @@ func TestUpdateBio(t *testing.T) { source := &fakeSource{desc: englishBio, canonical: "primary"} idx := &fakeBioIndex{} provider := biography.NewService(source, &fakeTranslator{}, idx) - author := index.Author{Slug: "alice", DataSourceLinks: map[string]string{"catalog": previous}} + author := index.Author{Slug: "alice", DataSourceReferences: map[string]string{"catalog": previous}} text, _, err := provider.UpdateBio(context.Background(), author, "variant", "es") if err != nil || text != "[es] "+englishBio || idx.linkKey != "catalog" || idx.previousSource != previous || len(idx.replaced) != 1 || idx.replaced[0].Source != "primary" { @@ -432,7 +432,7 @@ func TestUpdateBio(t *testing.T) { if !slices.Equal(source.calls, []string{"variant"}) || !slices.Equal(source.refreshes, []bool{true}) { t.Fatalf("profile edits must bypass source caches, got %q, refresh=%v", source.calls, source.refreshes) } - if author.DataSourceLinks["catalog"] != previous { + if author.DataSourceReferences["catalog"] != previous { t.Fatal("updating must not mutate the caller's author") } }) diff --git a/internal/datasource/biblioreads/adapter_test.go b/internal/datasource/biblioreads/adapter_test.go index d7260029..e6879a49 100644 --- a/internal/datasource/biblioreads/adapter_test.go +++ b/internal/datasource/biblioreads/adapter_test.go @@ -167,11 +167,11 @@ func TestEnrichStoresMatchingResult(t *testing.T) { t.Error("expected document to be marked as BiblioReads-enriched") } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceLinks["goodreads"] != wantAuthorURL { + if err != nil || author.DataSourceReferences["goodreads"] != wantAuthorURL { t.Fatalf("expected matching author URL stored, got %+v, %v", author, err) } other, err := idx.Author("second-author", "") - if err != nil || other.DataSourceLinks["goodreads"] != "" { + if err != nil || other.DataSourceReferences["goodreads"] != "" { t.Fatalf("unmatched coauthor must not receive the URL, got %+v, %v", other, err) } if want := []string{"La Reina Dragon Alice Borchardt", "La Reina Dragon"}; !slices.Equal(source.Queries(), want) { @@ -240,7 +240,7 @@ func TestEnrichStoresSecondAuthorURLAndPreservesItOnEdits(t *testing.T) { if err != nil { t.Fatal(err) } - stale.DataSourceLinks = map[string]string{"other": "https://example.org/second-author"} + stale.DataSourceReferences = map[string]string{"other": "https://example.org/second-author"} if err := idx.IndexAuthor(stale); err != nil { t.Fatal(err) } @@ -248,34 +248,34 @@ func TestEnrichStoresSecondAuthorURLAndPreservesItOnEdits(t *testing.T) { t.Fatal(err) } author, err := idx.Author("second-author", "") - if err != nil || author.DataSourceLinks["goodreads"] != "2" || - author.DataSourceLinks["other"] != "https://example.org/second-author" { + if err != nil || author.DataSourceReferences["goodreads"] != "2" || + author.DataSourceReferences["other"] != "https://example.org/second-author" { t.Fatalf("expected second author URL stored, got %+v, %v", author, err) } first, err := idx.Author("alice-borchardt", "") - if err != nil || first.DataSourceLinks["goodreads"] != "" { + if err != nil || first.DataSourceReferences["goodreads"] != "" { t.Fatalf("first author must not receive coauthor URL, got %+v, %v", first, err) } - stale.DataSourceLinks["wikidata"] = "Q2" + stale.DataSourceReferences["wikidata"] = "Q2" stale.RetrievedOn = time.Now().UTC() - stale.DataSourceLinks["goodreads"] = "999.Stale" + stale.DataSourceReferences["goodreads"] = "999.Stale" if err := idx.IndexAuthor(stale); err != nil { t.Fatal(err) } - if stale.DataSourceLinks["goodreads"] != "999.Stale" { + if stale.DataSourceReferences["goodreads"] != "999.Stale" { t.Fatal("indexing an author mutated the caller's links") } author, err = idx.Author("second-author", "") - if err != nil || author.DataSourceLinks["goodreads"] != "2" || - author.DataSourceLinks["other"] != "https://example.org/second-author" || - author.DataSourceLinks["wikidata"] != "Q2" || author.DocumentCount != 1 { + if err != nil || author.DataSourceReferences["goodreads"] != "2" || + author.DataSourceReferences["other"] != "https://example.org/second-author" || + author.DataSourceReferences["wikidata"] != "Q2" || author.DocumentCount != 1 { t.Fatalf("stale author edit lost URL or metadata: %+v, %v", author, err) } if _, err := idx.NewFile("second.pdf", []byte("")); err != nil { t.Fatal(err) } author, err = idx.Author("second-author", "") - if err != nil || author.DataSourceLinks["goodreads"] != "2" || author.DocumentCount != 2 { + if err != nil || author.DataSourceReferences["goodreads"] != "2" || author.DocumentCount != 2 { t.Fatalf("incrementing document count lost author URL: %+v, %v", author, err) } } @@ -292,7 +292,7 @@ func TestEnrichRejectsInvalidAuthorURL(t *testing.T) { t.Fatal(err) } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceLinks["goodreads"] != "" { + if err != nil || author.DataSourceReferences["goodreads"] != "" { t.Fatalf("invalid author paths must not be stored as author IDs: %+v, %v", author, err) } doc, err := idx.DocumentByID(testID) @@ -700,11 +700,11 @@ func TestBookMatchesKennedyMiddleName(t *testing.T) { t.Fatalf("expected persisted book match and rating, got %+v, %v", stored, err) } author, err := idx.Author("paul-kennedy", "") - if err != nil || author.DataSourceLinks["goodreads"] != "8390124.Paul_M_Kennedy" || author.Name != "Paul Kennedy" { + if err != nil || author.DataSourceReferences["goodreads"] != "8390124.Paul_M_Kennedy" || author.Name != "Paul Kennedy" { t.Fatalf("expected author URL with original name preserved, got %+v, %v", author, err) } other, err := idx.Author("another-writer", "") - if err != nil || other.DataSourceLinks["goodreads"] != "" { + if err != nil || other.DataSourceReferences["goodreads"] != "" { t.Fatalf("unmatched coauthor must not receive the URL, got %+v, %v", other, err) } if want := []string{title + " Paul Kennedy", title}; !slices.Equal(source.Queries(), want) { @@ -1228,7 +1228,7 @@ func TestMatchesTolkienOmnibusSearchResults(t *testing.T) { t.Fatalf("expected persisted omnibus match, got %+v", stored) } author, err := idx.Author("j-r-r-tolkien", "") - if err != nil || author.DataSourceLinks["goodreads"] != "656983.J_R_R_Tolkien" { + if err != nil || author.DataSourceReferences["goodreads"] != "656983.J_R_R_Tolkien" { t.Fatalf("expected author URL on author record, got %+v, %v", author, err) } if want := []string{title + " J. R. R. Tolkien", title}; !slices.Equal(source.Queries(), want) { diff --git a/internal/datasource/biblioreads/bio.go b/internal/datasource/biblioreads/bio.go index 7c68344f..abbe0726 100644 --- a/internal/datasource/biblioreads/bio.go +++ b/internal/datasource/biblioreads/bio.go @@ -47,7 +47,7 @@ func (*BioSource) ProfileInputName() string { } func (*BioSource) ProfileValue(author index.Author) string { - if id := author.DataSourceLinks[Source]; id != "" { + if id := author.DataSourceReferences[Source]; id != "" { return goodreadsBaseURL + goodreadsAuthorPrefix + id } return "" diff --git a/internal/datasource/biblioreads/reviews.go b/internal/datasource/biblioreads/reviews.go index b682ce9a..0319e2dd 100644 --- a/internal/datasource/biblioreads/reviews.go +++ b/internal/datasource/biblioreads/reviews.go @@ -43,7 +43,7 @@ func (b *ReviewProvider) Name() string { // AuthorLink returns the indexed author link without making a network request. func (b *ReviewProvider) AuthorLink(author index.Author, _ string) datasourcemodel.DataSourceLink { - id := author.DataSourceLinks[Source] + id := author.DataSourceReferences[Source] if !authorIDPattern.MatchString(id) { return goodreadsDataSourceLink("", goodreadsAuthorPrefix) } diff --git a/internal/datasource/biblioreads/reviews_test.go b/internal/datasource/biblioreads/reviews_test.go index fe19c404..6341e45b 100644 --- a/internal/datasource/biblioreads/reviews_test.go +++ b/internal/datasource/biblioreads/reviews_test.go @@ -21,7 +21,7 @@ func withBiblioReadsData(t *testing.T, document index.Document, data biblioreads func TestBiblioReadsDataSourceLinks(t *testing.T) { provider := biblioreads.NewReviewProvider(nil, nil) author := provider.AuthorLink(index.Author{ - DataSourceLinks: map[string]string{"goodreads": "123.Jane_Doe"}, + DataSourceReferences: map[string]string{"goodreads": "123.Jane_Doe"}, }, "en") if author.URL != "https://www.goodreads.com/author/show/123.Jane_Doe" || author.Source != "Goodreads" || author.Icon != "/images/goodreads.svg" || !author.IconInvertible { @@ -42,7 +42,7 @@ func TestBiblioReadsDataSourceLinks(t *testing.T) { {"goodreads": "123.Jane_Doe/"}, {"goodreads": "123?x=y"}, } { - if link := provider.AuthorLink(index.Author{DataSourceLinks: links}, "en"); link.URL != "" { + if link := provider.AuthorLink(index.Author{DataSourceReferences: links}, "en"); link.URL != "" { t.Errorf("unexpected Goodreads link for %v: %+v", links, link) } } diff --git a/internal/datasource/wikidata/bio.go b/internal/datasource/wikidata/bio.go index 67f6e60b..83dd5ba0 100644 --- a/internal/datasource/wikidata/bio.go +++ b/internal/datasource/wikidata/bio.go @@ -39,7 +39,7 @@ func (*BioSource) ProfileInputName() string { return "wikipediaURL" } func (*BioSource) MetadataServiceName() string { return "Wikidata" } func (s *BioSource) ProfileValue(author index.Author) string { - return author.DataSourceLinks[s.LinkKey()] + return author.DataSourceReferences[s.LinkKey()] } // NormalizeAuthorID accepts article URLs, retaining their language and encoded title. diff --git a/internal/datasource/wikidata/bio_test.go b/internal/datasource/wikidata/bio_test.go index afad23f5..471c364a 100644 --- a/internal/datasource/wikidata/bio_test.go +++ b/internal/datasource/wikidata/bio_test.go @@ -43,7 +43,7 @@ func TestBioUsesKnownLinkInCurrentLanguage(t *testing.T) { idx := authorIndex(t) author := index.Author{ Slug: "example", Name: "Example", - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "wikipedia:en": "https://en.wikipedia.org/wiki/Example", "wikipedia:es": "https://es.wikipedia.org/wiki/Autor_%C3%B1", }, @@ -78,7 +78,7 @@ func TestBioUsesKnownLinkInCurrentLanguage(t *testing.T) { }}, nil }) provider := biography.NewService(NewBioSource(), nil, idx) - if value := provider.ProfileValueForLanguage(author, "es"); value != author.DataSourceLinks["wikipedia:es"] { + if value := provider.ProfileValueForLanguage(author, "es"); value != author.DataSourceReferences["wikipedia:es"] { t.Fatalf("profile input must show the current language's link: %q", value) } if _, _, pending := provider.StoredBio(author, "fr"); pending { @@ -96,7 +96,7 @@ func TestBioUsesKnownLinkInCurrentLanguage(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.Bio.Source != author.DataSourceLinks["wikipedia:es"] || + if stored.Bio.Source != author.DataSourceReferences["wikipedia:es"] || stored.Bio.Language != "es" || stored.Bio.Text["es"] != want { t.Fatalf("must persist safe emphasis and paragraph breaks with the known language: %+v", stored.Bio) } diff --git a/internal/datasource/wikidata/service.go b/internal/datasource/wikidata/service.go index 03d70780..eb302dab 100644 --- a/internal/datasource/wikidata/service.go +++ b/internal/datasource/wikidata/service.go @@ -55,7 +55,7 @@ func (WikidataSource) ProfileServiceName() string { } func (WikidataSource) ProfileValue(author index.Author) string { - id := author.DataSourceLinks["wikidata"] + id := author.DataSourceReferences["wikidata"] if id == "" { return "" } @@ -93,7 +93,7 @@ func (WikidataSource) NormalizeAuthorID(value string) (string, error) { } func (WikidataSource) AuthorLink(author index.Author, language string) model.DataSourceLink { - url := author.DataSourceLinks["wikipedia:"+language] + url := author.DataSourceReferences["wikipedia:"+language] if url == "" { return model.DataSourceLink{} } diff --git a/internal/datasource/wikidata/service_test.go b/internal/datasource/wikidata/service_test.go index 664beaec..7fa6ecbd 100644 --- a/internal/datasource/wikidata/service_test.go +++ b/internal/datasource/wikidata/service_test.go @@ -92,7 +92,7 @@ func TestAuthorLinks(t *testing.T) { func TestWikipediaDataSourceLink(t *testing.T) { source := NewWikidataSource(Gowikidata{}) link := source.AuthorLink(index.Author{ - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "wikipedia:en": "https://en.wikipedia.org/wiki/Example", "wikipedia:es": "https://es.wikipedia.org/wiki/Ejemplo", }, diff --git a/internal/index/author.go b/internal/index/author.go index ab5ac425..8d829057 100644 --- a/internal/index/author.go +++ b/internal/index/author.go @@ -19,12 +19,12 @@ type Author struct { Description map[string]string DateOfBirth precisiondate.PrecisionDate DateOfDeath precisiondate.PrecisionDate - // DataSourceLinks contains source-owned profile IDs and URLs. - DataSourceLinks map[string]string - DataSourceImage string - Gender float64 - Pseudonyms []string - DocumentCount uint64 + // DataSourceReferences contains source-owned profile IDs and URLs. + DataSourceReferences map[string]string + DataSourceImage string + Gender float64 + Pseudonyms []string + DocumentCount uint64 // Bio is managed by StoreAuthorBio; IndexAuthor keeps the stored value. Bio AuthorBio // ownsRefreshedLink marks links replaced by a metadata refresh or explicit reset. @@ -43,7 +43,7 @@ type AuthorBio struct { } func (a Author) ClearMetadata(ownsLink func(string) bool) Author { - links := maps.Clone(a.DataSourceLinks) + links := maps.Clone(a.DataSourceReferences) for source := range links { if ownsLink(source) { delete(links, source) @@ -51,7 +51,7 @@ func (a Author) ClearMetadata(ownsLink func(string) bool) Author { } return Author{ Slug: a.Slug, Name: a.Name, DocumentCount: a.DocumentCount, - RetrievedOn: time.Now().UTC(), DataSourceLinks: links, Bio: a.Bio, + RetrievedOn: time.Now().UTC(), DataSourceReferences: links, Bio: a.Bio, ownsRefreshedLink: ownsLink, } } diff --git a/internal/index/author_bio_test.go b/internal/index/author_bio_test.go index 5bf4b0c3..060a7517 100644 --- a/internal/index/author_bio_test.go +++ b/internal/index/author_bio_test.go @@ -125,7 +125,7 @@ func TestStoreCanonicalAuthorBio(t *testing.T) { idx := newAuthorsTestIndex(t) const variant = "18647721.Plat_n" const linkKey = "external-profile" - author := index.Author{Slug: "platon", Name: "Platón", DataSourceLinks: map[string]string{ + author := index.Author{Slug: "platon", Name: "Platón", DataSourceReferences: map[string]string{ linkKey: variant, "website": "https://example.com", }} if err := idx.IndexAuthor(author); err != nil { @@ -139,7 +139,7 @@ func TestStoreCanonicalAuthorBio(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks[linkKey] != bio.Source || stored.Bio.Source != bio.Source || !maps.Equal(stored.Bio.Text, bio.Text) || stored.DataSourceLinks["website"] != "https://example.com" || stored.Name != author.Name { + if stored.DataSourceReferences[linkKey] != bio.Source || stored.Bio.Source != bio.Source || !maps.Equal(stored.Bio.Text, bio.Text) || stored.DataSourceReferences["website"] != "https://example.com" || stored.Name != author.Name { t.Fatalf("canonical resolution must update only the profile link and bio: %+v", stored) } if err := idx.StoreCanonicalAuthorBio(author.Slug, linkKey, variant, index.AuthorBio{Source: "999"}); err == nil { @@ -152,7 +152,7 @@ func TestStoreCanonicalAuthorBio(t *testing.T) { t.Fatal("a stale biography must not restore a cleared source") } stored, err = idx.Author(author.Slug, "en") - if err != nil || stored.DataSourceLinks[linkKey] != "" || stored.DataSourceLinks["website"] != "https://example.com" || stored.Bio.Source != "" { + if err != nil || stored.DataSourceReferences[linkKey] != "" || stored.DataSourceReferences["website"] != "https://example.com" || stored.Bio.Source != "" { t.Fatalf("clearing the profile link must preserve other author data: %+v, %v", stored, err) } } diff --git a/internal/index/authors_enrich_test.go b/internal/index/authors_enrich_test.go index f8fde203..fb9a7de8 100644 --- a/internal/index/authors_enrich_test.go +++ b/internal/index/authors_enrich_test.go @@ -119,7 +119,7 @@ func TestAuthorMetadataRefreshUpdatesLinks(t *testing.T) { idx := index.NewBleve(nil, authors, nil, "", nil, index.Config{}) author := index.Author{ Slug: "writer", Name: "Writer", - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "example:website": "https://old.example", "example:en": "https://en.example/Old", "example:es": "https://es.example/Old", @@ -141,7 +141,7 @@ func TestAuthorMetadataRefreshUpdatesLinks(t *testing.T) { if err != nil { t.Fatal(err) } - current.DataSourceLinks["another-provider"] = "https://another.example/writer" + current.DataSourceReferences["another-provider"] = "https://another.example/writer" if err := idx.IndexAuthor(current); err != nil { t.Fatal(err) } @@ -152,18 +152,18 @@ func TestAuthorMetadataRefreshUpdatesLinks(t *testing.T) { if err != nil { t.Fatal(err) } - if got.DataSourceLinks["example:website"] != source.links["example:website"] || - got.DataSourceLinks["example:en"] != source.links["example:en"] || - got.DataSourceLinks["example:es"] != "" { - t.Fatalf("metadata links were not refreshed: %+v", got.DataSourceLinks) + if got.DataSourceReferences["example:website"] != source.links["example:website"] || + got.DataSourceReferences["example:en"] != source.links["example:en"] || + got.DataSourceReferences["example:es"] != "" { + t.Fatalf("metadata links were not refreshed: %+v", got.DataSourceReferences) } - if got.DataSourceLinks["goodreads"] != "1.Writer" || - got.DataSourceLinks["catalog"] != "https://catalog.example/writer" || - got.DataSourceLinks["another-provider"] != "https://another.example/writer" { - t.Fatalf("metadata refresh lost independent provider links: %+v", got.DataSourceLinks) + if got.DataSourceReferences["goodreads"] != "1.Writer" || + got.DataSourceReferences["catalog"] != "https://catalog.example/writer" || + got.DataSourceReferences["another-provider"] != "https://another.example/writer" { + t.Fatalf("metadata refresh lost independent provider links: %+v", got.DataSourceReferences) } if source.links != nil { - author.DataSourceLinks["example:website"] = "https://caller.example" + author.DataSourceReferences["example:website"] = "https://caller.example" if source.links["example:website"] != "https://new.example" { t.Fatal("combining metadata retained a mutable datasource map") } @@ -180,7 +180,7 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { idx := index.NewBleve(nil, authors, nil, "", nil, index.Config{}) author := index.Author{ Slug: "writer", Name: "Writer", DocumentCount: 3, - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "example": "Q1", "example:website": "https://old.example", "example:en": "https://en.example/Old", "catalog": "https://catalog.example/writer", @@ -190,14 +190,14 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { t.Fatal(err) } reset := author.ClearMetadata((stubAuthor{linkPrefix: "example:"}).OwnsLink) - if author.DataSourceLinks["example:website"] == "" { + if author.DataSourceReferences["example:website"] == "" { t.Fatal("reset must not mutate the caller's links") } current, err := idx.Author("writer", "en") if err != nil { t.Fatal(err) } - current.DataSourceLinks["goodreads"] = "1.Writer" + current.DataSourceReferences["goodreads"] = "1.Writer" if err := idx.IndexAuthor(current); err != nil { t.Fatal(err) } @@ -208,12 +208,12 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks["example:website"] != "" || stored.DataSourceLinks["example:en"] != "" || - stored.DataSourceLinks["example"] != "" || stored.RetrievedOn.IsZero() { + if stored.DataSourceReferences["example:website"] != "" || stored.DataSourceReferences["example:en"] != "" || + stored.DataSourceReferences["example"] != "" || stored.RetrievedOn.IsZero() { t.Fatalf("reset must remove metadata association and owned links: %+v", stored) } - if stored.DataSourceLinks["catalog"] != "https://catalog.example/writer" || - stored.DataSourceLinks["goodreads"] != "1.Writer" || stored.DocumentCount != 3 { + if stored.DataSourceReferences["catalog"] != "https://catalog.example/writer" || + stored.DataSourceReferences["goodreads"] != "1.Writer" || stored.DocumentCount != 3 { t.Fatalf("reset must retain independent and concurrent author data: %+v", stored) } stale := index.Author{Slug: "writer", Name: "Writer"} @@ -224,8 +224,8 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { if err != nil { t.Fatal(err) } - if len(stored.DataSourceLinks) != 2 { - t.Fatalf("ordinary stale writes must preserve independent links: %+v", stored.DataSourceLinks) + if len(stored.DataSourceReferences) != 2 { + t.Fatalf("ordinary stale writes must preserve independent links: %+v", stored.DataSourceReferences) } } @@ -282,7 +282,7 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { t.Fatal(err) } if err := idx.IndexAuthor(index.Author{ - Slug: "known", Name: "Known Author", DataSourceLinks: map[string]string{"example": "Q2", "other": "unrelated"}, + Slug: "known", Name: "Known Author", DataSourceReferences: map[string]string{"example": "Q2", "other": "unrelated"}, }); err != nil { t.Fatal(err) } @@ -320,11 +320,11 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if err != nil { t.Fatal(err) } - if found.DataSourceLinks["example"] != "Q1" { - t.Fatalf("expected enriched author Q1, got %q", found.DataSourceLinks["example"]) + if found.DataSourceReferences["example"] != "Q1" { + t.Fatalf("expected enriched author Q1, got %q", found.DataSourceReferences["example"]) } known, err := idx.Author("known", "en") - if err != nil || known.DataSourceLinks["example"] != "Q2" || known.DataSourceLinks["other"] != "unrelated" { + if err != nil || known.DataSourceReferences["example"] != "Q2" || known.DataSourceReferences["other"] != "unrelated" { t.Fatalf("enrichment lost existing source references: %+v, %v", known, err) } @@ -335,8 +335,8 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if missing.RetrievedOn.IsZero() { t.Fatal("expected missing author to be marked as processed") } - if missing.DataSourceLinks["example"] != "" { - t.Fatalf("expected missing author to have no data source id, got %q", missing.DataSourceLinks["example"]) + if missing.DataSourceReferences["example"] != "" { + t.Fatalf("expected missing author to have no data source id, got %q", missing.DataSourceReferences["example"]) } remaining, err := idx.AuthorsWithoutInfo() diff --git a/internal/index/bleve_author_migrate.go b/internal/index/bleve_author_migrate.go index ac784e75..011356f3 100644 --- a/internal/index/bleve_author_migrate.go +++ b/internal/index/bleve_author_migrate.go @@ -117,11 +117,11 @@ func copyAuthors(source, destination bleve.Index, batchSize int) error { source = "wikipedia:" + strings.TrimPrefix(field, "WikipediaLink.") } if link, ok := value.(string); source != "" && ok && link != "" { - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - if author.DataSourceLinks[source] == "" { - author.DataSourceLinks[source] = link + if author.DataSourceReferences[source] == "" { + author.DataSourceReferences[source] = link } } } diff --git a/internal/index/bleve_author_migrate_test.go b/internal/index/bleve_author_migrate_test.go index 7a384512..b808f3c5 100644 --- a/internal/index/bleve_author_migrate_test.go +++ b/internal/index/bleve_author_migrate_test.go @@ -37,7 +37,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { want := Author{ Slug: "alice-borchardt", Name: "Alice Borchardt", BirthName: "Alice O'Brien", RetrievedOn: retrieved, - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "wikidata": "Q1", "wikipedia:en": "https://en.wikipedia.org/wiki/Alice_Borchardt", "wikipedia:es": "https://es.wikipedia.org/wiki/Alice_Borchardt", @@ -55,8 +55,8 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { DataSourceID string Website string WikipediaLink map[string]string - }{author, author.DataSourceLinks["wikidata"], author.DataSourceLinks["website"], map[string]string{ - "en": author.DataSourceLinks["wikipedia:en"], "es": author.DataSourceLinks["wikipedia:es"], + }{author, author.DataSourceReferences["wikidata"], author.DataSourceReferences["website"], map[string]string{ + "en": author.DataSourceReferences["wikipedia:en"], "es": author.DataSourceReferences["wikipedia:es"], }}); err != nil { t.Fatal(err) } @@ -94,7 +94,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { t.Fatalf("expected original index removed after successful migration, got %v", err) } - got.DataSourceLinks["goodreads"] = "1.Writer" + got.DataSourceReferences["goodreads"] = "1.Writer" if err := idx.IndexAuthor(got); err != nil { t.Fatal(err) } @@ -112,7 +112,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { if err != nil || len(result.Hits) != 1 { t.Fatalf("reading reopened author: %v", err) } - want.DataSourceLinks["goodreads"] = "1.Writer" + want.DataSourceReferences["goodreads"] = "1.Writer" if got := hydrateAuthor(result.Hits[0]); !reflect.DeepEqual(got, want) { t.Fatalf("migrated mapping or URL did not survive reopening: %#v", got) } @@ -151,21 +151,21 @@ func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { Slug: "writer", Name: "Writer", RetrievedOn: time.Now().UTC().Truncate(time.Second), Description: map[string]string{"en": "Writer", "es": "Escritora"}, DocumentCount: 7, Pseudonyms: []string{"Writer Alias"}, - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "goodreads": "1.Writer", "wikipedia:es": "https://es.wikipedia.org/wiki/Writer", }, Bio: AuthorBio{Source: "https://es.wikipedia.org/wiki/Writer", Language: "es", Text: map[string]string{"es": "Biografia", "en": "Biography"}}, } if referenceID != "" { - want.DataSourceLinks["wikidata"] = referenceID + want.DataSourceReferences["wikidata"] = referenceID } - links, err := json.Marshal(want.DataSourceLinks) + links, err := json.Marshal(want.DataSourceReferences) if err != nil { t.Fatal(err) } stored := want - stored.DataSourceLinks = nil + stored.DataSourceReferences = nil if err := legacy.Index(want.Slug, struct { Author DataSourceID string @@ -201,7 +201,7 @@ func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { t.Fatal("migration retained the standalone source ID") } if referenceID == "" { - want.DataSourceLinks["wikidata"] = "Q1" + want.DataSourceReferences["wikidata"] = "Q1" } if got := hydrateAuthor(result.Hits[0]); !reflect.DeepEqual(got, want) { t.Fatalf("migration changed author metadata or references:\ngot: %#v\nwant: %#v", got, want) @@ -210,6 +210,58 @@ func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { } } +func TestAuthorReferencesRemainCompatibleWithCurrentIndex(t *testing.T) { + path := filepath.Join(t.TempDir(), "authors_index") + authors := CreateAuthorsIndex(path) + if err := authors.Index("writer", struct { + Author + DataSourceLinks string + }{ + Author: Author{Slug: "writer", Name: "Writer"}, + DataSourceLinks: `{"wikidata":"Q1","website":"https://example.org"}`, + }); err != nil { + t.Fatal(err) + } + if err := authors.Close(); err != nil { + t.Fatal(err) + } + authors, err := OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + idx := NewBleve(nil, authors, nil, "", nil, Config{}) + author, err := idx.Author("writer", "") + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || author.DataSourceReferences["website"] != "https://example.org" { + t.Fatalf("existing references lost: %+v, %v", author, err) + } + author.DataSourceReferences["goodreads"] = "1.Writer" + if err := idx.IndexAuthor(author); err != nil { + t.Fatal(err) + } + if err := authors.Close(); err != nil { + t.Fatal(err) + } + authors, err = OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + defer authors.Close() + req := bleve.NewSearchRequest(bleve.NewDocIDQuery([]string{"writer"})) + req.Fields = []string{"*"} + result, err := authors.Search(req) + if err != nil || len(result.Hits) != 1 { + t.Fatalf("reading saved author: %v", err) + } + fields := result.Hits[0].Fields + if _, ok := fields["DataSourceLinks"].(string); !ok { + t.Fatal("references must retain the existing stored field name") + } + got := hydrateAuthor(result.Hits[0]) + if !reflect.DeepEqual(got.DataSourceReferences, author.DataSourceReferences) { + t.Fatalf("references did not survive reopening: %+v", got.DataSourceReferences) + } +} + func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") backup := legacyAuthorsIndex(t, path+".v2-backup") @@ -217,7 +269,7 @@ func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { t.Fatal(err) } current := CreateAuthorsIndex(path) - if err := indexAuthor(current, "saved", Author{Slug: "saved", Name: "Saved Author", DataSourceLinks: map[string]string{"wikidata": "Q1"}}); err != nil { + if err := indexAuthor(current, "saved", Author{Slug: "saved", Name: "Saved Author", DataSourceReferences: map[string]string{"wikidata": "Q1"}}); err != nil { t.Fatal(err) } if err := current.Close(); err != nil { @@ -300,13 +352,13 @@ func TestOpenAuthorsIndexMigratesLegacyAuthorLinks(t *testing.T) { } idx := NewBleve(nil, upgraded, nil, "", nil, Config{}) author, err := idx.Author("alice", "") - if err != nil || author.DataSourceLinks["wikidata"] != "Q1" || author.DocumentCount != 7 || - author.DataSourceLinks["website"] != "https://example.org" || - author.DataSourceLinks["wikipedia:en"] != "https://en.wikipedia.org/wiki/Alice" || - author.DataSourceLinks["wikipedia:es"] != "https://es.wikipedia.org/wiki/Alice" { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || author.DocumentCount != 7 || + author.DataSourceReferences["website"] != "https://example.org" || + author.DataSourceReferences["wikipedia:en"] != "https://en.wikipedia.org/wiki/Alice" || + author.DataSourceReferences["wikipedia:es"] != "https://es.wikipedia.org/wiki/Alice" { t.Fatalf("migration lost legacy links or metadata: %+v, %v", author, err) } - author.DataSourceLinks["other"] = "https://example.org/alice" + author.DataSourceReferences["other"] = "https://example.org/alice" if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) } diff --git a/internal/index/bleve_author_read.go b/internal/index/bleve_author_read.go index 20fe976f..94f0b18c 100644 --- a/internal/index/bleve_author_read.go +++ b/internal/index/bleve_author_read.go @@ -150,16 +150,16 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { Pseudonyms: slicer(fields["Pseudonyms"]), DocumentCount: documentCount, } - if links, ok := fields["DataSourceLinks"].(string); ok { - if err := json.Unmarshal([]byte(links), &author.DataSourceLinks); err != nil { - log.Printf("Error reading data source links for author %s: %s", docID, err) + if references, ok := fields["DataSourceLinks"].(string); ok { + if err := json.Unmarshal([]byte(references), &author.DataSourceReferences); err != nil { + log.Printf("Error reading data source references for author %s: %s", docID, err) } } - if legacyID, ok := fields["DataSourceID"].(string); ok && legacyID != "" && author.DataSourceLinks["wikidata"] == "" { - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if legacyID, ok := fields["DataSourceID"].(string); ok && legacyID != "" && author.DataSourceReferences["wikidata"] == "" { + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - author.DataSourceLinks["wikidata"] = legacyID + author.DataSourceReferences["wikidata"] = legacyID } author.Bio.Source, _ = fields["Bio.Source"].(string) author.Bio.Language, _ = fields["Bio.Language"].(string) diff --git a/internal/index/bleve_author_write.go b/internal/index/bleve_author_write.go index ed6b2d0a..a4a9bf0e 100644 --- a/internal/index/bleve_author_write.go +++ b/internal/index/bleve_author_write.go @@ -11,13 +11,13 @@ import ( datasourcemodel "github.com/svera/coreander/v5/internal/datasource/model" ) -// indexAuthor stores links as one stored-only field so new sources need no mapping changes. +// indexAuthor retains the stored field name for compatibility with existing indexes. func indexAuthor(destination interface{ Index(string, any) error }, id string, author Author) error { - links, err := json.Marshal(author.DataSourceLinks) + links, err := json.Marshal(author.DataSourceReferences) if err != nil { return err } - author.DataSourceLinks = nil + author.DataSourceReferences = nil return destination.Index(id, struct { Author DataSourceLinks string @@ -173,18 +173,18 @@ func (b *BleveIndexer) IndexAuthor(author Author) error { return err } // Link enrichment runs independently of metadata enrichment and UI edits. - links := maps.Clone(author.DataSourceLinks) - if len(current.DataSourceLinks) > 0 { + links := maps.Clone(author.DataSourceReferences) + if len(current.DataSourceReferences) > 0 { if links == nil { links = make(map[string]string) } - for source, link := range current.DataSourceLinks { + for source, link := range current.DataSourceReferences { if author.ownsRefreshedLink == nil || !author.ownsRefreshedLink(source) { links[source] = link } } } - author.DataSourceLinks = links + author.DataSourceReferences = links if current.Slug != "" { author.Bio = current.Bio } @@ -215,16 +215,16 @@ func (b *BleveIndexer) StoreCanonicalAuthorBio(slug, linkKey, previousLink strin if err != nil || author.Slug == "" { return err } - if author.DataSourceLinks[linkKey] != previousLink { + if author.DataSourceReferences[linkKey] != previousLink { return fmt.Errorf("data source link changed while resolving primary profile for %s", slug) } - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } if bio.Source == "" { - delete(author.DataSourceLinks, linkKey) + delete(author.DataSourceReferences, linkKey) } else { - author.DataSourceLinks[linkKey] = bio.Source + author.DataSourceReferences[linkKey] = bio.Source } author.Bio = bio return indexAuthor(b.authorsIdx, slug, author) @@ -246,7 +246,7 @@ func (b *BleveIndexer) storeAuthorBioChecked(slug, linkKey string, bio AuthorBio if err != nil || author.Slug == "" { return err } - if expectedLink != nil && author.DataSourceLinks[linkKey] != *expectedLink { + if expectedLink != nil && author.DataSourceReferences[linkKey] != *expectedLink { return fmt.Errorf("data source link changed while retrieving biography for %s", slug) } if merge && author.Bio.Source == bio.Source && author.Bio.Language == bio.Language { @@ -301,14 +301,14 @@ type AuthorDataSource interface { func CombineWithDataSource(author *Author, authorDataSource datasourcemodel.Author, supportedLanguages []string) { author.BirthName = authorDataSource.BirthName() author.RetrievedOn = authorDataSource.RetrievedOn() - author.DataSourceLinks = maps.Clone(author.DataSourceLinks) + author.DataSourceReferences = maps.Clone(author.DataSourceReferences) author.ownsRefreshedLink = authorDataSource.OwnsLink - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - for source := range author.DataSourceLinks { + for source := range author.DataSourceReferences { if authorDataSource.OwnsLink(source) { - delete(author.DataSourceLinks, source) + delete(author.DataSourceReferences, source) } } author.InstanceOf = authorDataSource.InstanceOf() @@ -317,7 +317,7 @@ func CombineWithDataSource(author *Author, authorDataSource datasourcemodel.Auth author.DateOfDeath = authorDataSource.DateOfDeath() for key, link := range authorDataSource.Links() { if link != "" { - author.DataSourceLinks[key] = link + author.DataSourceReferences[key] = link } } author.DataSourceImage = authorDataSource.Image() @@ -364,7 +364,7 @@ func (b *BleveIndexer) EnrichAuthorsFromDataSource(dataSource AuthorDataSource, searchIndex := 0 for _, author := range authors { authorsBySlug[author.Slug] = author - if id := author.DataSourceLinks[dataSource.LinkKey()]; id != "" { + if id := author.DataSourceReferences[dataSource.LinkKey()]; id != "" { candidates[author.Slug] = []string{id} b.recordAuthorEnrichmentProgress() continue diff --git a/internal/index/bleve_document_data_sources.go b/internal/index/bleve_document_data_sources.go index 4912b048..0a3d4982 100644 --- a/internal/index/bleve_document_data_sources.go +++ b/internal/index/bleve_document_data_sources.go @@ -77,13 +77,13 @@ func (b *BleveIndexer) storeAuthorLinkLocked(link AuthorLink) error { author.DocumentCount += result.Total } } - if author.DataSourceLinks[link.Source] != "" { + if author.DataSourceReferences[link.Source] != "" { return nil } - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - author.DataSourceLinks[link.Source] = link.Value + author.DataSourceReferences[link.Source] = link.Value return indexAuthor(b.authorsIdx, link.Slug, author) } diff --git a/internal/index/data_source_fields_test.go b/internal/index/data_source_fields_test.go index 07dd7083..2360ce0f 100644 --- a/internal/index/data_source_fields_test.go +++ b/internal/index/data_source_fields_test.go @@ -287,15 +287,15 @@ func TestAuthorDataSourceLinksAreStoredButNotSearchable(t *testing.T) { "dummy": authorURL, "other": "https://example.org/Zyxwv_Author", } - if err := idx.IndexAuthor(index.Author{Slug: "alice", Name: "Example Writer", DataSourceLinks: links}); err != nil { + if err := idx.IndexAuthor(index.Author{Slug: "alice", Name: "Example Writer", DataSourceReferences: links}); err != nil { t.Fatal(err) } author, err := idx.Author("alice", "") if err != nil { t.Fatal(err) } - if !maps.Equal(author.DataSourceLinks, links) { - t.Fatalf("expected stored author links, got %+v", author.DataSourceLinks) + if !maps.Equal(author.DataSourceReferences, links) { + t.Fatalf("expected stored author links, got %+v", author.DataSourceReferences) } for _, q := range []query.Query{ fieldTermQuery("DataSourceLinks", authorURL), diff --git a/internal/index/document_data_sources_test.go b/internal/index/document_data_sources_test.go index e6492780..2ef73111 100644 --- a/internal/index/document_data_sources_test.go +++ b/internal/index/document_data_sources_test.go @@ -297,7 +297,7 @@ func TestUpdateDocumentStoresAuthorLinksFirstWins(t *testing.T) { if existing { if err := idx.IndexAuthor(Author{ Name: "Existing Writer", Slug: "writer", DocumentCount: 42, - DataSourceLinks: map[string]string{"wikidata": "external-id", "other": "other-reference"}, + DataSourceReferences: map[string]string{"wikidata": "external-id", "other": "other-reference"}, }); err != nil { t.Fatal(err) } @@ -312,12 +312,12 @@ func TestUpdateDocumentStoresAuthorLinksFirstWins(t *testing.T) { } } author, err := idx.Author("writer", "") - if err != nil || author.DataSourceLinks["dummy"] != "first-reference" { + if err != nil || author.DataSourceReferences["dummy"] != "first-reference" { t.Fatalf("first author link lost: %+v, %v", author, err) } if existing { if author.Name != "Existing Writer" || author.DocumentCount != 42 || - author.DataSourceLinks["wikidata"] != "external-id" || author.DataSourceLinks["other"] != "other-reference" { + author.DataSourceReferences["wikidata"] != "external-id" || author.DataSourceReferences["other"] != "other-reference" { t.Fatalf("existing author metadata changed: %+v", author) } } else if author.Name != "Writer" || author.DocumentCount != 3 { diff --git a/internal/index/rebuild_authors_test.go b/internal/index/rebuild_authors_test.go index 76a8c08b..901464b8 100644 --- a/internal/index/rebuild_authors_test.go +++ b/internal/index/rebuild_authors_test.go @@ -63,7 +63,7 @@ func TestRebuildAuthorsFromDocuments(t *testing.T) { if author.DocumentCount != 1 { t.Fatalf("expected DocumentCount=1 for George Orwell, got %d", author.DocumentCount) } - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ "goodreads": "3706.George_Orwell", "other": "https://example.org/authors/orwell", } @@ -74,8 +74,8 @@ func TestRebuildAuthorsFromDocuments(t *testing.T) { t.Fatal(err) } author, err = idx.Author("george-orwell", "en") - if err != nil || author.DataSourceLinks["goodreads"] != "3706.George_Orwell" || - author.DataSourceLinks["other"] != "https://example.org/authors/orwell" { + if err != nil || author.DataSourceReferences["goodreads"] != "3706.George_Orwell" || + author.DataSourceReferences["other"] != "https://example.org/authors/orwell" { t.Fatalf("expected existing author URL preserved during rebuild, got %+v, %v", author, err) } diff --git a/internal/webserver/author_bio_test.go b/internal/webserver/author_bio_test.go index 1c8628af..f6d10385 100644 --- a/internal/webserver/author_bio_test.go +++ b/internal/webserver/author_bio_test.go @@ -94,7 +94,7 @@ func seedBioTestAuthor(t *testing.T, idx *index.BleveIndexer, links map[string]s if err != nil { t.Fatal(err) } - author.DataSourceLinks = links + author.DataSourceReferences = links author.RetrievedOn = time.Now() if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) @@ -181,7 +181,7 @@ func TestAuthorDetailCardLayoutAndSanitization(t *testing.T) { author.RetrievedOn = time.Now() author.DateOfBirth = precisiondate.NewPrecisionDate("+1920-01-02T00:00:00Z", precisiondate.PrecisionDay) author.DateOfDeath = precisiondate.NewPrecisionDate("+1992-04-06T00:00:00Z", precisiondate.PrecisionDay) - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ "wikidata": "Q1234", "goodreads": "1.John_Doe", "website": "https://example.com", @@ -190,7 +190,7 @@ func TestAuthorDetailCardLayoutAndSanitization(t *testing.T) { t.Fatal(err) } if err := idx.StoreAuthorBio(author.Slug, index.AuthorBio{ - Source: author.DataSourceLinks["goodreads"], Language: "en", + Source: author.DataSourceReferences["goodreads"], Language: "en", Text: map[string]string{"en": `John Doe wrote many books.`}, }); err != nil { t.Fatal(err) @@ -334,7 +334,7 @@ func (*localizedBioSource) ProfileServiceName() string { return "Example biogra func (*localizedBioSource) MetadataServiceName() string { return "Example catalog" } func (*localizedBioSource) ProfileInputName() string { return "catalogBioID" } func (s *localizedBioSource) ProfileValue(author index.Author) string { - return author.DataSourceLinks[s.LinkKey()] + return author.DataSourceReferences[s.LinkKey()] } func (*localizedBioSource) NormalizeAuthorID(value string) (string, error) { return strings.TrimSpace(value), nil @@ -397,8 +397,8 @@ func TestLocalizedAuthorBioUsesCurrentLanguageOnAuthorPage(t *testing.T) { if page.Find(`[hx-get="/authors/john-doe/bio"]`).Length() != 1 || len(result.calls) != 0 { t.Fatal("a known profile must enable lazy biography retrieval without requesting the source") } - if err := idx.StoreAuthorBioForLink(author.Slug, "catalog:es", author.DataSourceLinks["catalog:es"], index.AuthorBio{ - Source: author.DataSourceLinks["catalog:es"], Language: "es", Text: map[string]string{"es": "Stored Spanish biography."}, + if err := idx.StoreAuthorBioForLink(author.Slug, "catalog:es", author.DataSourceReferences["catalog:es"], index.AuthorBio{ + Source: author.DataSourceReferences["catalog:es"], Language: "es", Text: map[string]string{"es": "Stored Spanish biography."}, }, true); err != nil { t.Fatal(err) } @@ -427,7 +427,7 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ "example": "old-author", "catalog:es": "old-profile", "independent": "other-profile", @@ -436,7 +436,7 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { t.Fatal(err) } if err := idx.StoreAuthorBio(author.Slug, index.AuthorBio{ - Source: author.DataSourceLinks["catalog:es"], Language: "es", Text: map[string]string{"es": "Stale biography."}, + Source: author.DataSourceReferences["catalog:es"], Language: "es", Text: map[string]string{"es": "Stale biography."}, }); err != nil { t.Fatal(err) } @@ -458,8 +458,8 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks["example"] != "new-author" || stored.Bio.Source != source.link || stored.Bio.Text["es"] != result.text || - stored.DataSourceLinks["independent"] != "other-profile" { + if stored.DataSourceReferences["example"] != "new-author" || stored.Bio.Source != source.link || stored.Bio.Text["es"] != result.text || + stored.DataSourceReferences["independent"] != "other-profile" { t.Fatalf("metadata update must refresh and persist its biography while preserving independent links: %+v", stored) } if style == "" && strings.TrimSpace(page.Find("#author-bio-text").Text()) != result.text { @@ -503,9 +503,9 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceLinks["example"] != sourceID || + if response.StatusCode != http.StatusOK || stored.DataSourceReferences["example"] != sourceID || stored.Bio.Source != "" || len(stored.Bio.Text) != 0 || - stored.DataSourceLinks["catalog:es"] != "" || len(result.calls) != beforeCalls { + stored.DataSourceReferences["catalog:es"] != "" || len(result.calls) != beforeCalls { t.Fatalf("missing or cleared metadata links must clear the biography without requests: %+v", stored) } } @@ -526,7 +526,7 @@ func testAuthorBioRefreshResults(t *testing.T) { client := &bioAuthorClient{} app, idx := newAuthorBioTestApp(t, client, &bioTranslator{}) author := seedBioTestAuthor(t, idx, map[string]string{"goodreads": "1.John_Doe"}) - cached := index.AuthorBio{Source: author.DataSourceLinks["goodreads"], Language: "en"} + cached := index.AuthorBio{Source: author.DataSourceReferences["goodreads"], Language: "en"} if state == "populated" { cached.Text = map[string]string{"en": "Old biography", "es": "Old translation", "fr": "Stale translation"} } @@ -691,7 +691,7 @@ func testAuthorBioProfileEditing(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceLinks["goodreads"] != "879.Plato" || stored.Bio.Source != "879.Plato" || + if response.StatusCode != http.StatusOK || stored.DataSourceReferences["goodreads"] != "879.Plato" || stored.Bio.Source != "879.Plato" || page.Find("#author-john-doe").Length() != 1 || page.Find(`a[href="https://www.goodreads.com/author/show/879.Plato"]`).Length() != 1 || page.Find(`input[name="goodreadsID"]`).AttrOr("value", "") != "https://www.goodreads.com/author/show/879.Plato" { t.Fatalf("updating the Goodreads ID must refresh the whole card and persist the new source, got %+v", stored.Bio) @@ -721,7 +721,7 @@ func testAuthorBioProfileEditing(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceLinks["goodreads"] != "" || stored.Bio.Source != "" || + if response.StatusCode != http.StatusOK || stored.DataSourceReferences["goodreads"] != "" || stored.Bio.Source != "" || len(stored.Bio.Text) != 0 || client.calls != 2 || page.Find(`a[href*="goodreads.com/author/"]`).Length() != 0 || page.Find(`input[name="goodreadsID"]`).AttrOr("value", "") != "" { t.Fatalf("blank Goodreads ID must clear link and biography without lookup: status=%d author=%+v calls=%d", response.StatusCode, stored, client.calls) diff --git a/internal/webserver/author_summary_test.go b/internal/webserver/author_summary_test.go index 09504a12..373cddec 100644 --- a/internal/webserver/author_summary_test.go +++ b/internal/webserver/author_summary_test.go @@ -34,7 +34,7 @@ func (*alternativeAuthorSource) ProfileServiceName() string { return "Example ca func (*alternativeAuthorSource) LinkKey() string { return "example" } func (*alternativeAuthorSource) OwnsLink(key string) bool { return key == "example" } func (*alternativeAuthorSource) ProfileValue(author index.Author) string { - return "https://example.org/authors/" + author.DataSourceLinks["example"] + return "https://example.org/authors/" + author.DataSourceReferences["example"] } func (*alternativeAuthorSource) AuthorLink(index.Author, string) datasourcemodel.DataSourceLink { return datasourcemodel.DataSourceLink{} @@ -86,7 +86,7 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceLinks = map[string]string{"example": "old-profile", "independent": "https://other.example/author"} + author.DataSourceReferences = map[string]string{"example": "old-profile", "independent": "https://other.example/author"} if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) } @@ -157,9 +157,9 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks["example"] != "alice" || stored.BirthName != "Alice Example" || + if stored.DataSourceReferences["example"] != "alice" || stored.BirthName != "Alice Example" || stored.Description["en"] != "Updated author metadata" || - stored.DataSourceLinks["independent"] != before.DataSourceLinks["independent"] || + stored.DataSourceReferences["independent"] != before.DataSourceReferences["independent"] || !reflect.DeepEqual(source.retrievedIDs, []string{"alice"}) { t.Fatalf("expected normalized ID retrieval and persisted metadata while preserving independent links: %+v", stored) } @@ -210,7 +210,7 @@ func TestClearAuthorRemovesImage(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ "website": "https://old.example", "wikipedia:en": "https://en.wikipedia.org/wiki/Old", "wikipedia:es": "https://es.wikipedia.org/wiki/Old", "goodreads": "1.Writer", "catalog": "https://catalog.example/writer", @@ -283,13 +283,13 @@ func TestClearAuthorRemovesImage(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks["wikidata"] != "" || stored.DataSourceImage != "" || - stored.DataSourceLinks["website"] != "" || stored.DataSourceLinks["wikipedia:en"] != "" || - stored.DataSourceLinks["wikipedia:es"] != "" { + if stored.DataSourceReferences["wikidata"] != "" || stored.DataSourceImage != "" || + stored.DataSourceReferences["website"] != "" || stored.DataSourceReferences["wikipedia:en"] != "" || + stored.DataSourceReferences["wikipedia:es"] != "" { t.Fatalf("metadata reset restored stale metadata: %+v", stored) } - if stored.DataSourceLinks["goodreads"] != "1.Writer" || - stored.DataSourceLinks["catalog"] != "https://catalog.example/writer" || + if stored.DataSourceReferences["goodreads"] != "1.Writer" || + stored.DataSourceReferences["catalog"] != "https://catalog.example/writer" || stored.DocumentCount != documentCount { t.Fatalf("metadata reset lost independent author data: %+v", stored) } @@ -300,7 +300,7 @@ func TestClearAuthorRemovesImage(t *testing.T) { type summaryDataSourceLinks struct{} func (summaryDataSourceLinks) AuthorLink(author index.Author, _ string) datasourcemodel.DataSourceLink { - if author.DataSourceLinks["wikidata"] == "" { + if author.DataSourceReferences["wikidata"] == "" { return datasourcemodel.DataSourceLink{} } return datasourcemodel.DataSourceLink{ @@ -328,12 +328,12 @@ func TestAuthorSummaryDataSourceLinks(t *testing.T) { } { author := index.Author{ Slug: tc.name, Name: "Alice Borchardt", - RetrievedOn: time.Now().UTC(), - DataSourceLinks: map[string]string{"wikidata": tc.dataSourceID, "website": "https://author.example/" + tc.name}, + RetrievedOn: time.Now().UTC(), + DataSourceReferences: map[string]string{"wikidata": tc.dataSourceID, "website": "https://author.example/" + tc.name}, } if tc.wikipedia { for _, lang := range locales { - author.DataSourceLinks["wikipedia:"+lang] = strings.Replace(wikipediaURL, "en.wikipedia.org", lang+".wikipedia.org", 1) + author.DataSourceReferences["wikipedia:"+lang] = strings.Replace(wikipediaURL, "en.wikipedia.org", lang+".wikipedia.org", 1) } } if err := idx.IndexAuthor(author); err != nil { @@ -420,7 +420,7 @@ func (editableAlternativeLinks) ProfileValue(index.Author) string { return "cata func TestDocumentAuthorProfileUsesMetadataSource(t *testing.T) { app, idx := newDataSourceProvidersTestApp(t, nil, nil, editableAlternativeLinks{}) if err := idx.IndexAuthor(index.Author{ - Slug: "jane-doe", Name: "Jane Doe", DataSourceLinks: map[string]string{"wikidata": "Q1234"}, RetrievedOn: time.Now().UTC(), + Slug: "jane-doe", Name: "Jane Doe", DataSourceReferences: map[string]string{"wikidata": "Q1234"}, RetrievedOn: time.Now().UTC(), }); err != nil { t.Fatal(err) } diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index d6e729b7..85d01a8d 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -42,7 +42,7 @@ type ProfileInput struct { func NewProfileInput(provider ProfileInputProvider, author index.Author, name, method, action string) ProfileInput { return ProfileInput{ Name: name, ServiceName: provider.ProfileServiceName(), Value: provider.ProfileValue(author), - Reference: author.DataSourceLinks[provider.LinkKey()], + Reference: author.DataSourceReferences[provider.LinkKey()], Method: method, Action: action, } } diff --git a/internal/webserver/document_biblioreads_test.go b/internal/webserver/document_biblioreads_test.go index f541fee9..ebfdddc9 100644 --- a/internal/webserver/document_biblioreads_test.go +++ b/internal/webserver/document_biblioreads_test.go @@ -550,7 +550,7 @@ func TestDocumentDetailBiblioReadsSearchesUnlinkedDocuments(t *testing.T) { t.Errorf("expected the found link to be stored, got %+v", stored) } author, err := idx.Author("jane-doe", "") - if err != nil || author.DataSourceLinks["goodreads"] != "1.Jane_Doe" || author.DocumentCount != 1 { + if err != nil || author.DataSourceReferences["goodreads"] != "1.Jane_Doe" || author.DocumentCount != 1 { t.Fatalf("expected missing author entry created with URL and document count, got %+v, %v", author, err) } if mustBiblioReadsData(t, stored).ResourceID != "" || mustBiblioReadsData(t, stored).LegacyBookID != 0 { diff --git a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html index 6320328a..ea83c37d 100644 --- a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html +++ b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html @@ -1,4 +1,4 @@ -{{$metadataID := index .Author.DataSourceLinks "wikidata"}} +{{$metadataID := index .Author.DataSourceReferences "wikidata"}} {{range .ProfileInputs}}{{if eq .Name "sourceID"}}{{$metadataID = .Reference}}{{end}}{{end}}
@@ -73,9 +73,9 @@

{{.Author.Name}}

{{end}} {{end}} - {{if or (index .Author.DataSourceLinks "website") .DataSourceLinks}} + {{if or (index .Author.DataSourceReferences "website") .DataSourceLinks}}
    - {{with index .Author.DataSourceLinks "website"}} + {{with index .Author.DataSourceReferences "website"}}
  • {{t $.Lang "Website"}} diff --git a/internal/webserver/embedded/views/partials/author-summary.html b/internal/webserver/embedded/views/partials/author-summary.html index 407df519..0380a626 100644 --- a/internal/webserver/embedded/views/partials/author-summary.html +++ b/internal/webserver/embedded/views/partials/author-summary.html @@ -1,4 +1,4 @@ -{{$metadataID := index .Author.DataSourceLinks "wikidata"}} +{{$metadataID := index .Author.DataSourceReferences "wikidata"}} {{range .ProfileInputs}}{{if eq .Name "sourceID"}}{{$metadataID = .Reference}}{{end}}{{end}}
    @@ -90,10 +90,10 @@

    {{.Author.Name}}

    {{.Author.Name}}
    - {{if or (index .Author.DataSourceLinks "website") .DataSourceLinks}} + {{if or (index .Author.DataSourceReferences "website") .DataSourceLinks}}
      - {{with index .Author.DataSourceLinks "website"}} + {{with index .Author.DataSourceReferences "website"}}
    • {{t $.Lang "Website"}} diff --git a/internal/webserver/embedded/views/partials/authors-list-item.html b/internal/webserver/embedded/views/partials/authors-list-item.html index aa60dd7f..19547a36 100644 --- a/internal/webserver/embedded/views/partials/authors-list-item.html +++ b/internal/webserver/embedded/views/partials/authors-list-item.html @@ -2,7 +2,7 @@ From 6ffff674eeafa00d256c6ad65819b2506ddd7bfb Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Sun, 22 Nov 2026 20:30:44 +0100 Subject: [PATCH 4/7] COnsolidated datasourceid --- index_migration_test.go | 8 +-- internal/biography/service.go | 10 ++-- internal/biography/service_test.go | 2 +- internal/datasource/biblioreads/bio.go | 2 +- internal/datasource/wikidata/bio.go | 6 +-- internal/datasource/wikidata/service.go | 2 +- internal/index/authors_enrich_test.go | 2 +- internal/index/bleve.go | 2 +- internal/index/bleve_author_migrate.go | 24 ++++++++- internal/index/bleve_author_migrate_test.go | 50 ++++++++++++++----- internal/index/bleve_author_read.go | 8 +-- internal/index/bleve_author_write.go | 8 +-- internal/index/data_source_fields_test.go | 12 ++--- internal/webserver/author_bio_test.go | 4 +- internal/webserver/author_summary_test.go | 4 +- .../webserver/controller/author/controller.go | 4 +- 16 files changed, 94 insertions(+), 54 deletions(-) diff --git a/index_migration_test.go b/index_migration_test.go index e1746463..2e01c01a 100644 --- a/index_migration_test.go +++ b/index_migration_test.go @@ -93,10 +93,10 @@ func TestGetIndexesRebuildsOlderDocuments(t *testing.T) { retrieved := time.Now().UTC().Truncate(time.Second) if err := authors.Index("existing-author", struct { index.Author - DataSourceLinks string + DataSourceReferences string }{ - Author: index.Author{Slug: "existing-author", Name: "Existing Author", RetrievedOn: retrieved}, - DataSourceLinks: `{"wikidata":"Q1"}`, + Author: index.Author{Slug: "existing-author", Name: "Existing Author", RetrievedOn: retrieved}, + DataSourceReferences: `{"wikidata":"Q1"}`, }); err != nil { t.Fatal(err) } @@ -273,7 +273,7 @@ func TestGetIndexesMigratesAuthorsWithoutReindexingDocuments(t *testing.T) { t.Fatal(err) } legacyMapping := index.CreateAuthorsMapping().(*mapping.IndexMappingImpl) - delete(legacyMapping.DefaultMapping.Properties, "DataSourceLinks") + delete(legacyMapping.DefaultMapping.Properties, "DataSourceReferences") legacyMapping.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) authors, err := bleve.New(homeDir+authorsIndexPath, legacyMapping) if err != nil { diff --git a/internal/biography/service.go b/internal/biography/service.go index 868eb5fb..b3f9c011 100644 --- a/internal/biography/service.go +++ b/internal/biography/service.go @@ -34,7 +34,7 @@ var spaceBeforePunctuation = regexp.MustCompile(` +([,.;:!?)\]])`) // Source supplies cleaned biography HTML (b, strong, i and em, with newline-separated // paragraphs) and identifies the profile it belongs to. type Source interface { - LinkKey() string + ReferenceKey() string ProfileServiceName() string ProfileInputName() string ProfileValue(author index.Author) string @@ -74,7 +74,7 @@ func (s *Service) forLanguage(language string) *Service { return s } -func (s *Service) LinkKey() string { return s.source.LinkKey() } +func (s *Service) ReferenceKey() string { return s.source.ReferenceKey() } func (s *Service) ProfileServiceName() string { return s.source.ProfileServiceName() } func (s *Service) ProfileInputName() string { return s.source.ProfileInputName() } func (s *Service) ProfileValue(author index.Author) string { @@ -109,7 +109,7 @@ func (s *Service) RefreshMetadataBio(ctx context.Context, author index.Author, l } func (s *Service) authorLink(author index.Author) (string, bool) { - value := author.DataSourceReferences[s.source.LinkKey()] + value := author.DataSourceReferences[s.source.ReferenceKey()] id, err := s.source.NormalizeAuthorID(value) return value, err == nil && id != "" && id == value } @@ -178,7 +178,7 @@ func (s *Service) RefreshBio(ctx context.Context, author index.Author, language type storeFunc func(slug string, bio index.AuthorBio) error func (s *Service) bioStore(author index.Author, merge bool) storeFunc { - linkKey := s.source.LinkKey() + linkKey := s.source.ReferenceKey() previousLink := author.DataSourceReferences[linkKey] return func(slug string, bio index.AuthorBio) error { if bio.Source != previousLink { @@ -192,7 +192,7 @@ func (s *Service) bioStore(author index.Author, merge bool) storeFunc { // An empty ID removes the profile and biography. func (s *Service) UpdateBio(ctx context.Context, author index.Author, id, language string) (string, string, error) { s = s.forLanguage(language) - linkKey := s.source.LinkKey() + linkKey := s.source.ReferenceKey() if id == "" { if err := s.index.StoreCanonicalAuthorBio(author.Slug, linkKey, author.DataSourceReferences[linkKey], index.AuthorBio{}); err != nil { return "", "", fmt.Errorf("clearing %s author link: %w", s.ProfileServiceName(), err) diff --git a/internal/biography/service_test.go b/internal/biography/service_test.go index 28e899b9..eb3fe9cf 100644 --- a/internal/biography/service_test.go +++ b/internal/biography/service_test.go @@ -28,7 +28,7 @@ type fakeSource struct { refreshes []bool } -func (*fakeSource) LinkKey() string { return "catalog" } +func (*fakeSource) ReferenceKey() string { return "catalog" } func (*fakeSource) ProfileServiceName() string { return "Example catalog" } func (*fakeSource) ProfileInputName() string { return "catalogID" } func (*fakeSource) ProfileValue(author index.Author) string { diff --git a/internal/datasource/biblioreads/bio.go b/internal/datasource/biblioreads/bio.go index abbe0726..0d533852 100644 --- a/internal/datasource/biblioreads/bio.go +++ b/internal/datasource/biblioreads/bio.go @@ -36,7 +36,7 @@ func NewBioSource(client AuthorClient) *BioSource { return &BioSource{client: client} } -func (*BioSource) LinkKey() string { return Source } +func (*BioSource) ReferenceKey() string { return Source } func (*BioSource) ProfileServiceName() string { return "Goodreads" diff --git a/internal/datasource/wikidata/bio.go b/internal/datasource/wikidata/bio.go index 83dd5ba0..793b2db5 100644 --- a/internal/datasource/wikidata/bio.go +++ b/internal/datasource/wikidata/bio.go @@ -31,15 +31,15 @@ func (*BioSource) ForLanguage(language string) biography.Source { return &BioSource{language: language} } -func (s *BioSource) Language() string { return s.language } -func (s *BioSource) LinkKey() string { return "wikipedia:" + s.language } +func (s *BioSource) Language() string { return s.language } +func (s *BioSource) ReferenceKey() string { return "wikipedia:" + s.language } func (*BioSource) ProfileServiceName() string { return "Wikipedia" } func (*BioSource) ProfileInputName() string { return "wikipediaURL" } func (*BioSource) MetadataServiceName() string { return "Wikidata" } func (s *BioSource) ProfileValue(author index.Author) string { - return author.DataSourceReferences[s.LinkKey()] + return author.DataSourceReferences[s.ReferenceKey()] } // NormalizeAuthorID accepts article URLs, retaining their language and encoded title. diff --git a/internal/datasource/wikidata/service.go b/internal/datasource/wikidata/service.go index eb302dab..ec3b910f 100644 --- a/internal/datasource/wikidata/service.go +++ b/internal/datasource/wikidata/service.go @@ -44,7 +44,7 @@ type WikidataSource struct { wikidata wikidata } -func (WikidataSource) LinkKey() string { return "wikidata" } +func (WikidataSource) ReferenceKey() string { return "wikidata" } func (WikidataSource) OwnsLink(key string) bool { return (Author{}).OwnsLink(key) diff --git a/internal/index/authors_enrich_test.go b/internal/index/authors_enrich_test.go index fb9a7de8..16696890 100644 --- a/internal/index/authors_enrich_test.go +++ b/internal/index/authors_enrich_test.go @@ -26,7 +26,7 @@ type mockAuthorDataSource struct { errName string } -func (*mockAuthorDataSource) LinkKey() string { return "example" } +func (*mockAuthorDataSource) ReferenceKey() string { return "example" } func (m *mockAuthorDataSource) SearchAuthor(name string, _ []string) (datasourcemodel.Author, error) { m.calls++ diff --git a/internal/index/bleve.go b/internal/index/bleve.go index f5f16fa7..f917f80f 100644 --- a/internal/index/bleve.go +++ b/internal/index/bleve.go @@ -579,7 +579,7 @@ func CreateAuthorsMapping() mapping.IndexMapping { indexMapping.DefaultMapping.AddFieldMappingsAt("BirthName", simpleTextFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("RetrievedOn", dateTimeFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceImage", keywordFieldMappingNotIndexable) - indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceLinks", storedOnlyFieldMapping) + indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceReferences", storedOnlyFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfBirth.Date", numericFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfBirth.Precision", numericFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfDeath.Date", numericFieldMapping) diff --git a/internal/index/bleve_author_migrate.go b/internal/index/bleve_author_migrate.go index 011356f3..6a6ddf00 100644 --- a/internal/index/bleve_author_migrate.go +++ b/internal/index/bleve_author_migrate.go @@ -9,9 +9,10 @@ import ( "strings" "github.com/blevesearch/bleve/v2" + "github.com/blevesearch/bleve/v2/mapping" ) -// OpenAuthorsIndex upgrades versions 2 and 3 without discarding stored author metadata. +// OpenAuthorsIndex upgrades older author mappings without discarding stored metadata. // The previous index is kept only until the migrated index opens successfully. func OpenAuthorsIndex(path string, batchSize int) (bleve.Index, error) { authors, err := bleve.Open(path) @@ -34,7 +35,15 @@ func OpenAuthorsIndex(path string, batchSize int) (bleve.Index, error) { if err != nil { return nil, errors.Join(err, authors.Close()) } - if string(version) == "2" || string(version) == "3" { + legacyMapping := false + if string(version) == AuthorVersion { + m, ok := authors.Mapping().(*mapping.IndexMappingImpl) + if !ok || m.DefaultMapping == nil { + return nil, errors.Join(fmt.Errorf("unsupported authors index mapping"), authors.Close()) + } + _, legacyMapping = m.DefaultMapping.Properties["DataSourceLinks"] + } + if string(version) == "2" || string(version) == "3" || legacyMapping { upgraded, err := migrateAuthorsIndex(authors, path, batchSize) if err != nil { return nil, errors.Join(err, authors.Close()) @@ -107,7 +116,18 @@ func copyAuthors(source, destination bleve.Index, batchSize int) error { } batch := destination.NewBatch() for _, hit := range result.Hits { + if _, exists := hit.Fields["DataSourceReferences"]; !exists { + if legacyLinks, ok := hit.Fields["DataSourceLinks"]; ok { + hit.Fields["DataSourceReferences"] = legacyLinks + } + } author := hydrateAuthor(hit) + if legacyID, ok := hit.Fields["DataSourceID"].(string); ok && legacyID != "" && author.DataSourceReferences["wikidata"] == "" { + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) + } + author.DataSourceReferences["wikidata"] = legacyID + } for field, value := range hit.Fields { source := "" switch { diff --git a/internal/index/bleve_author_migrate_test.go b/internal/index/bleve_author_migrate_test.go index b808f3c5..769d0987 100644 --- a/internal/index/bleve_author_migrate_test.go +++ b/internal/index/bleve_author_migrate_test.go @@ -18,7 +18,7 @@ import ( func legacyAuthorsIndex(t *testing.T, path string) bleve.Index { t.Helper() m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) - delete(m.DefaultMapping.Properties, "DataSourceLinks") + delete(m.DefaultMapping.Properties, "DataSourceReferences") m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) idx, err := bleve.New(path, m) if err != nil { @@ -50,12 +50,14 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { Pseudonyms: []string{"Alice", "A. Borchardt"}, DocumentCount: 7, } for _, author := range []Author{want, {Slug: "other", Name: "Other", RetrievedOn: retrieved}, {Slug: "third", Name: "Third", RetrievedOn: retrieved}} { + stored := author + stored.DataSourceReferences = nil if err := legacy.Index(author.Slug, struct { Author DataSourceID string Website string WikipediaLink map[string]string - }{author, author.DataSourceReferences["wikidata"], author.DataSourceReferences["website"], map[string]string{ + }{stored, author.DataSourceReferences["wikidata"], author.DataSourceReferences["website"], map[string]string{ "en": author.DataSourceReferences["wikipedia:en"], "es": author.DataSourceReferences["wikipedia:es"], }}); err != nil { t.Fatal(err) @@ -141,7 +143,7 @@ func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { for _, referenceID := range []string{"", "Q2"} { t.Run("reference="+referenceID, func(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") - m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) + m := oldReferenceAuthorsMapping() m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) legacy, err := bleve.New(path, m) if err != nil { @@ -200,6 +202,12 @@ func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { if _, found := result.Hits[0].Fields["DataSourceID"]; found { t.Fatal("migration retained the standalone source ID") } + if _, found := result.Hits[0].Fields["DataSourceLinks"]; found { + t.Fatal("migration retained the old reference field") + } + if _, found := result.Hits[0].Fields["DataSourceReferences"]; !found { + t.Fatal("migration did not store the renamed reference field") + } if referenceID == "" { want.DataSourceReferences["wikidata"] = "Q1" } @@ -210,14 +218,28 @@ func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { } } -func TestAuthorReferencesRemainCompatibleWithCurrentIndex(t *testing.T) { +func oldReferenceAuthorsMapping() *mapping.IndexMappingImpl { + m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) + m.DefaultMapping.Properties["DataSourceLinks"] = m.DefaultMapping.Properties["DataSourceReferences"] + delete(m.DefaultMapping.Properties, "DataSourceReferences") + return m +} + +func TestOpenAuthorsIndexMigratesDevelopmentVersion4(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") - authors := CreateAuthorsIndex(path) + authors, err := bleve.New(path, oldReferenceAuthorsMapping()) + if err != nil { + t.Fatal(err) + } + if err := authors.SetInternal(internalVersion, []byte(AuthorVersion)); err != nil { + t.Fatal(err) + } if err := authors.Index("writer", struct { Author DataSourceLinks string }{ - Author: Author{Slug: "writer", Name: "Writer"}, + Author: Author{Slug: "writer", Name: "Writer", DocumentCount: 3, + Bio: AuthorBio{Source: "1.Writer", Language: "en", Text: map[string]string{"en": "Biography"}}}, DataSourceLinks: `{"wikidata":"Q1","website":"https://example.org"}`, }); err != nil { t.Fatal(err) @@ -225,13 +247,14 @@ func TestAuthorReferencesRemainCompatibleWithCurrentIndex(t *testing.T) { if err := authors.Close(); err != nil { t.Fatal(err) } - authors, err := OpenAuthorsIndex(path, 1) + authors, err = OpenAuthorsIndex(path, 1) if err != nil { t.Fatal(err) } idx := NewBleve(nil, authors, nil, "", nil, Config{}) author, err := idx.Author("writer", "") - if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || author.DataSourceReferences["website"] != "https://example.org" { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || author.DataSourceReferences["website"] != "https://example.org" || + author.DocumentCount != 3 || author.Bio.Text["en"] != "Biography" { t.Fatalf("existing references lost: %+v, %v", author, err) } author.DataSourceReferences["goodreads"] = "1.Writer" @@ -241,7 +264,7 @@ func TestAuthorReferencesRemainCompatibleWithCurrentIndex(t *testing.T) { if err := authors.Close(); err != nil { t.Fatal(err) } - authors, err = OpenAuthorsIndex(path, 1) + authors, err = OpenAuthorsIndex(path, 0) if err != nil { t.Fatal(err) } @@ -253,8 +276,11 @@ func TestAuthorReferencesRemainCompatibleWithCurrentIndex(t *testing.T) { t.Fatalf("reading saved author: %v", err) } fields := result.Hits[0].Fields - if _, ok := fields["DataSourceLinks"].(string); !ok { - t.Fatal("references must retain the existing stored field name") + if _, ok := fields["DataSourceReferences"].(string); !ok { + t.Fatal("references must use the renamed stored field") + } + if _, ok := fields["DataSourceLinks"]; ok { + t.Fatal("migration retained the old reference field") } got := hydrateAuthor(result.Hits[0]) if !reflect.DeepEqual(got.DataSourceReferences, author.DataSourceReferences) { @@ -317,7 +343,7 @@ func TestOpenAuthorsIndexMigrationFailurePreservesOriginal(t *testing.T) { func TestOpenAuthorsIndexMigratesLegacyAuthorLinks(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) - delete(m.DefaultMapping.Properties, "DataSourceLinks") + delete(m.DefaultMapping.Properties, "DataSourceReferences") m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) legacyURL := bleve.NewKeywordFieldMapping() legacyURL.Index = false diff --git a/internal/index/bleve_author_read.go b/internal/index/bleve_author_read.go index 94f0b18c..ac788756 100644 --- a/internal/index/bleve_author_read.go +++ b/internal/index/bleve_author_read.go @@ -150,17 +150,11 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { Pseudonyms: slicer(fields["Pseudonyms"]), DocumentCount: documentCount, } - if references, ok := fields["DataSourceLinks"].(string); ok { + if references, ok := fields["DataSourceReferences"].(string); ok { if err := json.Unmarshal([]byte(references), &author.DataSourceReferences); err != nil { log.Printf("Error reading data source references for author %s: %s", docID, err) } } - if legacyID, ok := fields["DataSourceID"].(string); ok && legacyID != "" && author.DataSourceReferences["wikidata"] == "" { - if author.DataSourceReferences == nil { - author.DataSourceReferences = make(map[string]string) - } - author.DataSourceReferences["wikidata"] = legacyID - } author.Bio.Source, _ = fields["Bio.Source"].(string) author.Bio.Language, _ = fields["Bio.Language"].(string) // Extract descriptions and biographies for all languages. diff --git a/internal/index/bleve_author_write.go b/internal/index/bleve_author_write.go index a4a9bf0e..b7733045 100644 --- a/internal/index/bleve_author_write.go +++ b/internal/index/bleve_author_write.go @@ -11,7 +11,7 @@ import ( datasourcemodel "github.com/svera/coreander/v5/internal/datasource/model" ) -// indexAuthor retains the stored field name for compatibility with existing indexes. +// indexAuthor stores references as one stored-only field so new sources need no mapping changes. func indexAuthor(destination interface{ Index(string, any) error }, id string, author Author) error { links, err := json.Marshal(author.DataSourceReferences) if err != nil { @@ -20,7 +20,7 @@ func indexAuthor(destination interface{ Index(string, any) error }, id string, a author.DataSourceReferences = nil return destination.Index(id, struct { Author - DataSourceLinks string + DataSourceReferences string }{author, string(links)}) } @@ -290,7 +290,7 @@ const ( // AuthorDataSource retrieves author metadata from an external source. type AuthorDataSource interface { - LinkKey() string + ReferenceKey() string SearchAuthor(name string, languages []string) (datasourcemodel.Author, error) SearchEntityIDs(name string) ([]string, error) RetrieveAuthor(ids []string, languages []string) (datasourcemodel.Author, error) @@ -364,7 +364,7 @@ func (b *BleveIndexer) EnrichAuthorsFromDataSource(dataSource AuthorDataSource, searchIndex := 0 for _, author := range authors { authorsBySlug[author.Slug] = author - if id := author.DataSourceReferences[dataSource.LinkKey()]; id != "" { + if id := author.DataSourceReferences[dataSource.ReferenceKey()]; id != "" { candidates[author.Slug] = []string{id} b.recordAuthorEnrichmentProgress() continue diff --git a/internal/index/data_source_fields_test.go b/internal/index/data_source_fields_test.go index 2360ce0f..f0fc0479 100644 --- a/internal/index/data_source_fields_test.go +++ b/internal/index/data_source_fields_test.go @@ -198,7 +198,7 @@ func TestDataSourceFieldsAreStoredButNotSearchable(t *testing.T) { queries := map[string]bleve.SearchRequest{ "provider data field term": *bleve.NewSearchRequest(fieldTermQuery("DataSources", bookURL)), "provider URL field term": *bleve.NewSearchRequest(fieldTermQuery("DataSources.dummy.url", bookURL)), - "author URL field term": *bleve.NewSearchRequest(fieldTermQuery("DataSourceLinks.dummy", authorURL)), + "author URL field term": *bleve.NewSearchRequest(fieldTermQuery("DataSourceReferences.dummy", authorURL)), "resource ID field term": *bleve.NewSearchRequest(fieldTermQuery("DataSources.dummy.referenceId", referenceID)), "legacy ID numeric field": *bleve.NewSearchRequest(providerRecordIDQuery(recordID)), "_all match": *bleve.NewSearchRequest(bleve.NewMatchQuery("zyxwvbook")), @@ -275,7 +275,7 @@ func providerRecordIDQuery(id int) *query.NumericRangeQuery { return q } -func TestAuthorDataSourceLinksAreStoredButNotSearchable(t *testing.T) { +func TestAuthorDataSourceReferencesAreStoredButNotSearchable(t *testing.T) { authors, err := bleve.NewMemOnly(index.CreateAuthorsMapping()) if err != nil { t.Fatal(err) @@ -298,12 +298,12 @@ func TestAuthorDataSourceLinksAreStoredButNotSearchable(t *testing.T) { t.Fatalf("expected stored author links, got %+v", author.DataSourceReferences) } for _, q := range []query.Query{ - fieldTermQuery("DataSourceLinks", authorURL), - fieldTermQuery("DataSourceLinks.dummy", authorURL), - fieldTermQuery("DataSourceLinks.other", links["other"]), + fieldTermQuery("DataSourceReferences", authorURL), + fieldTermQuery("DataSourceReferences.dummy", authorURL), + fieldTermQuery("DataSourceReferences.other", links["other"]), bleve.NewTermQuery(authorURL), bleve.NewMatchQuery("Zyxwv_Author"), - bleve.NewQueryStringQuery(`DataSourceLinks:"` + authorURL + `"`), + bleve.NewQueryStringQuery(`DataSourceReferences:"` + authorURL + `"`), } { result, err := authors.Search(bleve.NewSearchRequest(q)) if err != nil { diff --git a/internal/webserver/author_bio_test.go b/internal/webserver/author_bio_test.go index f6d10385..65272ed5 100644 --- a/internal/webserver/author_bio_test.go +++ b/internal/webserver/author_bio_test.go @@ -329,12 +329,12 @@ func (s *localizedBioSource) ForLanguage(language string) biography.Source { return &localizedBioSource{language: language, result: s.result} } func (s *localizedBioSource) Language() string { return s.language } -func (s *localizedBioSource) LinkKey() string { return "catalog:" + s.language } +func (s *localizedBioSource) ReferenceKey() string { return "catalog:" + s.language } func (*localizedBioSource) ProfileServiceName() string { return "Example biographies" } func (*localizedBioSource) MetadataServiceName() string { return "Example catalog" } func (*localizedBioSource) ProfileInputName() string { return "catalogBioID" } func (s *localizedBioSource) ProfileValue(author index.Author) string { - return author.DataSourceReferences[s.LinkKey()] + return author.DataSourceReferences[s.ReferenceKey()] } func (*localizedBioSource) NormalizeAuthorID(value string) (string, error) { return strings.TrimSpace(value), nil diff --git a/internal/webserver/author_summary_test.go b/internal/webserver/author_summary_test.go index 373cddec..882bc5c4 100644 --- a/internal/webserver/author_summary_test.go +++ b/internal/webserver/author_summary_test.go @@ -31,7 +31,7 @@ type alternativeAuthorSource struct { } func (*alternativeAuthorSource) ProfileServiceName() string { return "Example catalog" } -func (*alternativeAuthorSource) LinkKey() string { return "example" } +func (*alternativeAuthorSource) ReferenceKey() string { return "example" } func (*alternativeAuthorSource) OwnsLink(key string) bool { return key == "example" } func (*alternativeAuthorSource) ProfileValue(author index.Author) string { return "https://example.org/authors/" + author.DataSourceReferences["example"] @@ -414,7 +414,7 @@ func (editableAlternativeLinks) AuthorLink(author index.Author, _ string) dataso } func (editableAlternativeLinks) ProfileServiceName() string { return "Example catalog" } -func (editableAlternativeLinks) LinkKey() string { return "example" } +func (editableAlternativeLinks) ReferenceKey() string { return "example" } func (editableAlternativeLinks) ProfileValue(index.Author) string { return "catalog-profile" } func TestDocumentAuthorProfileUsesMetadataSource(t *testing.T) { diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index 85d01a8d..d80384ef 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -19,7 +19,7 @@ type DataSourceLinkProvider interface { } type ProfileInputProvider interface { - LinkKey() string + ReferenceKey() string ProfileServiceName() string ProfileValue(author index.Author) string } @@ -42,7 +42,7 @@ type ProfileInput struct { func NewProfileInput(provider ProfileInputProvider, author index.Author, name, method, action string) ProfileInput { return ProfileInput{ Name: name, ServiceName: provider.ProfileServiceName(), Value: provider.ProfileValue(author), - Reference: author.DataSourceReferences[provider.LinkKey()], + Reference: author.DataSourceReferences[provider.ReferenceKey()], Method: method, Action: action, } } From 679d7000bfa2767f01e5d157c7f4336a933feecf Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Mon, 23 Nov 2026 07:54:51 +0100 Subject: [PATCH 5/7] COnsolidated datasourceid --- internal/biography/service.go | 1 - internal/webserver/author_summary_test.go | 17 +++++++++++++++++ internal/webserver/controller/author/bio.go | 9 +++++---- .../webserver/controller/author/controller.go | 18 ++++++++++++++---- .../webserver/controller/author/datasource.go | 2 +- .../webserver/controller/author/documents.go | 1 + .../webserver/controller/author/summary.go | 18 ++++++++++-------- internal/webserver/controller/author/update.go | 13 +++++++------ .../controller/document/controller.go | 4 ++-- .../webserver/controller/document/detail.go | 12 +++++++----- .../webserver/embedded/views/author/list.html | 2 +- .../embedded/views/document/detail.html | 4 ++-- .../partials/author-summary-doc-detail.html | 3 +-- .../views/partials/author-summary.html | 3 +-- 14 files changed, 69 insertions(+), 38 deletions(-) diff --git a/internal/biography/service.go b/internal/biography/service.go index b3f9c011..bdc5f6f4 100644 --- a/internal/biography/service.go +++ b/internal/biography/service.go @@ -74,7 +74,6 @@ func (s *Service) forLanguage(language string) *Service { return s } -func (s *Service) ReferenceKey() string { return s.source.ReferenceKey() } func (s *Service) ProfileServiceName() string { return s.source.ProfileServiceName() } func (s *Service) ProfileInputName() string { return s.source.ProfileInputName() } func (s *Service) ProfileValue(author index.Author) string { diff --git a/internal/webserver/author_summary_test.go b/internal/webserver/author_summary_test.go index 882bc5c4..4973b291 100644 --- a/internal/webserver/author_summary_test.go +++ b/internal/webserver/author_summary_test.go @@ -165,6 +165,23 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { } }) } + for _, path := range []string{ + "/authors/john-doe", "/authors/john-doe/summary", "/authors/john-doe/summary?style=clear", + "/documents/john-doe-test-epub", + } { + t.Run(path, func(t *testing.T) { + for _, cookie := range []*http.Cookie{admin, {Name: "anonymous"}} { + page := getPageWithCookie(t, app, cookie, path) + card := page.Find("#author-john-doe") + if got := strings.TrimSpace(card.Find("p.capitalize.lead").Text()); got != "Updated author metadata" { + t.Fatalf("%s: expected metadata for the configured source, got %q", path, got) + } + if got := card.Find(`img[src^="/authors/"]`).AttrOr("src", ""); got != "/authors/john-doe_alice.webp" { + t.Fatalf("%s: expected image URL with the configured source reference, got %q", path, got) + } + } + }) + } } func TestClearAuthorRemovesImage(t *testing.T) { diff --git a/internal/webserver/controller/author/bio.go b/internal/webserver/controller/author/bio.go index 65342856..7c2051de 100644 --- a/internal/webserver/controller/author/bio.go +++ b/internal/webserver/controller/author/bio.go @@ -93,10 +93,11 @@ func (a *Controller) renderAuthorSummary(c fiber.Ctx, author index.Author, lang, session, _ := c.Locals("Session").(model.Session) vars := fiber.Map{ "Author": author, "Lang": lang, "Session": session, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": a.getImageVersion(author.Slug), - "ProfileInputs": a.profileInputs(author, lang, "", invalidProfile, c.FormValue(invalidProfile)), - "InvalidProfile": invalidProfile != "", + "MetadataReference": MetadataReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": a.getImageVersion(author.Slug), + "ProfileInputs": a.profileInputs(author, lang, "", invalidProfile, c.FormValue(invalidProfile)), + "InvalidProfile": invalidProfile != "", } a.addBioVars(vars, "partials/author-summary", author, lang) if err := c.Render("partials/author-summary", vars); err != nil { diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index d80384ef..2176abce 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -19,16 +19,19 @@ type DataSourceLinkProvider interface { } type ProfileInputProvider interface { - ReferenceKey() string ProfileServiceName() string ProfileValue(author index.Author) string } +type MetadataProfileProvider interface { + ProfileInputProvider + ReferenceKey() string +} + type ProfileInput struct { Name string ServiceName string Value string - Reference string Method string Action string FormID string @@ -42,9 +45,16 @@ type ProfileInput struct { func NewProfileInput(provider ProfileInputProvider, author index.Author, name, method, action string) ProfileInput { return ProfileInput{ Name: name, ServiceName: provider.ProfileServiceName(), Value: provider.ProfileValue(author), - Reference: author.DataSourceReferences[provider.ReferenceKey()], - Method: method, Action: action, + Method: method, Action: action, + } +} + +func MetadataReference(author index.Author, provider MetadataProfileProvider) string { + key := "wikidata" + if provider != nil { + key = provider.ReferenceKey() } + return author.DataSourceReferences[key] } func NewMetadataProfileInput(provider ProfileInputProvider, author index.Author, style string) ProfileInput { diff --git a/internal/webserver/controller/author/datasource.go b/internal/webserver/controller/author/datasource.go index af3ee8cb..0fa05146 100644 --- a/internal/webserver/controller/author/datasource.go +++ b/internal/webserver/controller/author/datasource.go @@ -3,7 +3,7 @@ package author import "github.com/svera/coreander/v5/internal/datasource/model" type DataSource interface { - ProfileInputProvider + MetadataProfileProvider OwnsLink(key string) bool NormalizeAuthorID(value string) (string, error) SearchAuthor(name string, languages []string) (model.Author, error) diff --git a/internal/webserver/controller/author/documents.go b/internal/webserver/controller/author/documents.go index 5167675f..d60a0ee2 100644 --- a/internal/webserver/controller/author/documents.go +++ b/internal/webserver/controller/author/documents.go @@ -67,6 +67,7 @@ func (a *Controller) Documents(c fiber.Ctx) error { templateVars := fiber.Map{ "Author": author, + "MetadataReference": MetadataReference(author, a.dataSource), "BioParagraphs": bioParagraphs, "BioPending": bioPending, "BioTranslatedFrom": bioTranslatedFrom, diff --git a/internal/webserver/controller/author/summary.go b/internal/webserver/controller/author/summary.go index c8168322..02dd1003 100644 --- a/internal/webserver/controller/author/summary.go +++ b/internal/webserver/controller/author/summary.go @@ -47,10 +47,11 @@ func (a *Controller) Summary(c fiber.Ctx) error { if !author.RetrievedOn.IsZero() { templateVars := fiber.Map{ - "Author": author, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": imageVersion, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "MetadataReference": MetadataReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": imageVersion, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) @@ -76,10 +77,11 @@ func (a *Controller) Summary(c fiber.Ctx) error { } templateVars := fiber.Map{ - "Author": author, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": imageVersion, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "MetadataReference": MetadataReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": imageVersion, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) diff --git a/internal/webserver/controller/author/update.go b/internal/webserver/controller/author/update.go index fa0d2511..0e1be373 100644 --- a/internal/webserver/controller/author/update.go +++ b/internal/webserver/controller/author/update.go @@ -83,12 +83,13 @@ func (a *Controller) Update(c fiber.Ctx) error { } templateVars := fiber.Map{ - "Author": author, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": a.getImageVersion(author.Slug), - "Lang": lang, - "Session": session, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "MetadataReference": MetadataReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": a.getImageVersion(author.Slug), + "Lang": lang, + "Session": session, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) diff --git a/internal/webserver/controller/document/controller.go b/internal/webserver/controller/document/controller.go index 813883e7..642602a8 100644 --- a/internal/webserver/controller/document/controller.go +++ b/internal/webserver/controller/document/controller.go @@ -103,12 +103,12 @@ type Controller struct { appFs afero.Fs translator i18n.Translator reviewProvider ReviewProvider - authorDataSource authorcontroller.ProfileInputProvider + authorDataSource authorcontroller.MetadataProfileProvider linkProviders []authorcontroller.DataSourceLinkProvider } // NewController creates a document controller. A nil reviewProvider disables scores and reviews. -func NewController(hlRepository highlightsRepository, usersRepository usersRepository, readingRepository readingRepository, annotationsRepository annotationsRepository, sender Sender, idx IdxReaderWriter, appFs afero.Fs, cfg Config, translator i18n.Translator, reviewProvider ReviewProvider, authorDataSource authorcontroller.ProfileInputProvider, linkProviders ...authorcontroller.DataSourceLinkProvider) *Controller { +func NewController(hlRepository highlightsRepository, usersRepository usersRepository, readingRepository readingRepository, annotationsRepository annotationsRepository, sender Sender, idx IdxReaderWriter, appFs afero.Fs, cfg Config, translator i18n.Translator, reviewProvider ReviewProvider, authorDataSource authorcontroller.MetadataProfileProvider, linkProviders ...authorcontroller.DataSourceLinkProvider) *Controller { return &Controller{ hlRepository: hlRepository, usersRepository: usersRepository, diff --git a/internal/webserver/controller/document/detail.go b/internal/webserver/controller/document/detail.go index 0ac443c4..5ba39e4d 100644 --- a/internal/webserver/controller/document/detail.go +++ b/internal/webserver/controller/document/detail.go @@ -17,10 +17,11 @@ import ( // render eagerly (i.e. without the async /summary htmx round-trip), so it can // only fall back to that round-trip when the author hasn't been enriched yet. type authorSummary struct { - Author index.Author - ImageVersion string - DataSourceLinks []datasourcemodel.DataSourceLink - ProfileInputs []authorcontroller.ProfileInput + Author index.Author + MetadataReference string + ImageVersion string + DataSourceLinks []datasourcemodel.DataSourceLink + ProfileInputs []authorcontroller.ProfileInput } func (d *Controller) Detail(c fiber.Ctx) error { @@ -152,7 +153,8 @@ func (d *Controller) authorSummaryFor(authorSlug, lang string) authorSummary { } return authorSummary{ Author: author, ImageVersion: fsutil.AuthorImageVersion(d.appFs, d.config.CacheDir, author.Slug), - DataSourceLinks: links, ProfileInputs: profileInputs, + MetadataReference: authorcontroller.MetadataReference(author, d.authorDataSource), + DataSourceLinks: links, ProfileInputs: profileInputs, } } diff --git a/internal/webserver/embedded/views/author/list.html b/internal/webserver/embedded/views/author/list.html index d87f704a..21075774 100644 --- a/internal/webserver/embedded/views/author/list.html +++ b/internal/webserver/embedded/views/author/list.html @@ -1,6 +1,6 @@ {{if ne .Author.Name ""}} {{if not .Author.RetrievedOn.IsZero}} - {{template "partials/author-summary" dict "Lang" .Lang "Author" .Author "Session" .Session "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "BioParagraphs" .BioParagraphs "BioPending" .BioPending "BioTranslatedFrom" .BioTranslatedFrom "BioRefreshAvailable" .BioRefreshAvailable "ProfileInputs" .ProfileInputs}} + {{template "partials/author-summary" dict "Lang" .Lang "Author" .Author "Session" .Session "MetadataReference" .MetadataReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "BioParagraphs" .BioParagraphs "BioPending" .BioPending "BioTranslatedFrom" .BioTranslatedFrom "BioRefreshAvailable" .BioRefreshAvailable "ProfileInputs" .ProfileInputs}} {{else}}
      diff --git a/internal/webserver/embedded/views/document/detail.html b/internal/webserver/embedded/views/document/detail.html index 1c543081..f326cf94 100644 --- a/internal/webserver/embedded/views/document/detail.html +++ b/internal/webserver/embedded/views/document/detail.html @@ -60,7 +60,7 @@

      {{.Document.Title}}


      {{range .AuthorSummaries}} {{if not .Author.RetrievedOn.IsZero}} - {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" .Author "Session" $.Session "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "ProfileInputs" .ProfileInputs}} + {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" .Author "Session" $.Session "MetadataReference" .MetadataReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "ProfileInputs" .ProfileInputs}} {{else}} {{template "partials/author-summary-doc-detail-placeholder" dict "AuthorSlug" .Author.Slug "Lang" $.Lang}} {{end}} @@ -71,7 +71,7 @@

      {{.Document.Title}}

      {{range $i, $entry := .IllustratorSummaries}} {{if eq $i 0}}
      {{end}} {{if not $entry.Author.RetrievedOn.IsZero}} - {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" $entry.Author "Session" $.Session "ImageVersion" $entry.ImageVersion "DataSourceLinks" $entry.DataSourceLinks "ProfileInputs" $entry.ProfileInputs}} + {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" $entry.Author "Session" $.Session "MetadataReference" $entry.MetadataReference "ImageVersion" $entry.ImageVersion "DataSourceLinks" $entry.DataSourceLinks "ProfileInputs" $entry.ProfileInputs}} {{else}} {{template "partials/author-summary-doc-detail-placeholder" dict "AuthorSlug" $entry.Author.Slug "Lang" $.Lang}} {{end}} diff --git a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html index ea83c37d..bc8128da 100644 --- a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html +++ b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html @@ -1,5 +1,4 @@ -{{$metadataID := index .Author.DataSourceReferences "wikidata"}} -{{range .ProfileInputs}}{{if eq .Name "sourceID"}}{{$metadataID = .Reference}}{{end}}{{end}} +{{$metadataID := .MetadataReference}}
      diff --git a/internal/webserver/embedded/views/partials/author-summary.html b/internal/webserver/embedded/views/partials/author-summary.html index 0380a626..390f9d01 100644 --- a/internal/webserver/embedded/views/partials/author-summary.html +++ b/internal/webserver/embedded/views/partials/author-summary.html @@ -1,5 +1,4 @@ -{{$metadataID := index .Author.DataSourceReferences "wikidata"}} -{{range .ProfileInputs}}{{if eq .Name "sourceID"}}{{$metadataID = .Reference}}{{end}}{{end}} +{{$metadataID := .MetadataReference}}
      From 1c129fc5426aa0e3840b824ad923d07ee8b05e1b Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Mon, 23 Nov 2026 19:25:25 +0100 Subject: [PATCH 6/7] COnsolidated datasourceid --- internal/webserver/controller/author/bio.go | 10 ++--- .../webserver/controller/author/controller.go | 2 +- .../webserver/controller/author/documents.go | 40 +++++++++---------- .../webserver/controller/author/summary.go | 20 +++++----- .../webserver/controller/author/update.go | 14 +++---- .../webserver/controller/document/detail.go | 14 +++---- .../webserver/embedded/views/author/list.html | 2 +- .../embedded/views/document/detail.html | 4 +- .../partials/author-summary-doc-detail.html | 8 ++-- .../views/partials/author-summary.html | 8 ++-- 10 files changed, 61 insertions(+), 61 deletions(-) diff --git a/internal/webserver/controller/author/bio.go b/internal/webserver/controller/author/bio.go index 7c2051de..d1960489 100644 --- a/internal/webserver/controller/author/bio.go +++ b/internal/webserver/controller/author/bio.go @@ -93,11 +93,11 @@ func (a *Controller) renderAuthorSummary(c fiber.Ctx, author index.Author, lang, session, _ := c.Locals("Session").(model.Session) vars := fiber.Map{ "Author": author, "Lang": lang, "Session": session, - "MetadataReference": MetadataReference(author, a.dataSource), - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": a.getImageVersion(author.Slug), - "ProfileInputs": a.profileInputs(author, lang, "", invalidProfile, c.FormValue(invalidProfile)), - "InvalidProfile": invalidProfile != "", + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": a.getImageVersion(author.Slug), + "ProfileInputs": a.profileInputs(author, lang, "", invalidProfile, c.FormValue(invalidProfile)), + "InvalidProfile": invalidProfile != "", } a.addBioVars(vars, "partials/author-summary", author, lang) if err := c.Render("partials/author-summary", vars); err != nil { diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index 2176abce..c555a718 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -49,7 +49,7 @@ func NewProfileInput(provider ProfileInputProvider, author index.Author, name, m } } -func MetadataReference(author index.Author, provider MetadataProfileProvider) string { +func AuthorDataSourceReference(author index.Author, provider MetadataProfileProvider) string { key := "wikidata" if provider != nil { key = provider.ReferenceKey() diff --git a/internal/webserver/controller/author/documents.go b/internal/webserver/controller/author/documents.go index d60a0ee2..591d58cc 100644 --- a/internal/webserver/controller/author/documents.go +++ b/internal/webserver/controller/author/documents.go @@ -66,26 +66,26 @@ func (a *Controller) Documents(c fiber.Ctx) error { bioParagraphs, bioTranslatedFrom, bioPending := a.storedBio(author, lang) templateVars := fiber.Map{ - "Author": author, - "MetadataReference": MetadataReference(author, a.dataSource), - "BioParagraphs": bioParagraphs, - "BioPending": bioPending, - "BioTranslatedFrom": bioTranslatedFrom, - "BioRefreshAvailable": a.bioRefreshAvailable(author), - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ProfileInputs": a.profileInputs(author, lang, "", "", ""), - "ImageVersion": a.getImageVersion(author.Slug), - "DocumentSearchFields": searchFields, - "DocumentsOnly": true, - "Results": searchResults, - "Paginator": view.Pagination(model.MaxPagesNavigator, searchResults, c.Queries()), - "Title": author.Name, - "EmailFrom": a.sender.From(), - "WordsPerMinute": a.config.WordsPerMinute, - "URL": view.URL(c), - "SortURL": view.BaseURLWithout(c, "sort-by", "page"), - "SortBy": c.Query("sort-by"), - "AdditionalSortOptions": authorDocumentSortOptions(a.config.ReviewSourceConfigured), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "BioParagraphs": bioParagraphs, + "BioPending": bioPending, + "BioTranslatedFrom": bioTranslatedFrom, + "BioRefreshAvailable": a.bioRefreshAvailable(author), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ProfileInputs": a.profileInputs(author, lang, "", "", ""), + "ImageVersion": a.getImageVersion(author.Slug), + "DocumentSearchFields": searchFields, + "DocumentsOnly": true, + "Results": searchResults, + "Paginator": view.Pagination(model.MaxPagesNavigator, searchResults, c.Queries()), + "Title": author.Name, + "EmailFrom": a.sender.From(), + "WordsPerMinute": a.config.WordsPerMinute, + "URL": view.URL(c), + "SortURL": view.BaseURLWithout(c, "sort-by", "page"), + "SortBy": c.Query("sort-by"), + "AdditionalSortOptions": authorDocumentSortOptions(a.config.ReviewSourceConfigured), } if c.Get("hx-request") == "true" { diff --git a/internal/webserver/controller/author/summary.go b/internal/webserver/controller/author/summary.go index 02dd1003..1f6db798 100644 --- a/internal/webserver/controller/author/summary.go +++ b/internal/webserver/controller/author/summary.go @@ -47,11 +47,11 @@ func (a *Controller) Summary(c fiber.Ctx) error { if !author.RetrievedOn.IsZero() { templateVars := fiber.Map{ - "Author": author, - "MetadataReference": MetadataReference(author, a.dataSource), - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": imageVersion, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": imageVersion, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) @@ -77,11 +77,11 @@ func (a *Controller) Summary(c fiber.Ctx) error { } templateVars := fiber.Map{ - "Author": author, - "MetadataReference": MetadataReference(author, a.dataSource), - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": imageVersion, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": imageVersion, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) diff --git a/internal/webserver/controller/author/update.go b/internal/webserver/controller/author/update.go index 0e1be373..d5aa9934 100644 --- a/internal/webserver/controller/author/update.go +++ b/internal/webserver/controller/author/update.go @@ -83,13 +83,13 @@ func (a *Controller) Update(c fiber.Ctx) error { } templateVars := fiber.Map{ - "Author": author, - "MetadataReference": MetadataReference(author, a.dataSource), - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": a.getImageVersion(author.Slug), - "Lang": lang, - "Session": session, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": a.getImageVersion(author.Slug), + "Lang": lang, + "Session": session, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) diff --git a/internal/webserver/controller/document/detail.go b/internal/webserver/controller/document/detail.go index 5ba39e4d..103ba694 100644 --- a/internal/webserver/controller/document/detail.go +++ b/internal/webserver/controller/document/detail.go @@ -17,11 +17,11 @@ import ( // render eagerly (i.e. without the async /summary htmx round-trip), so it can // only fall back to that round-trip when the author hasn't been enriched yet. type authorSummary struct { - Author index.Author - MetadataReference string - ImageVersion string - DataSourceLinks []datasourcemodel.DataSourceLink - ProfileInputs []authorcontroller.ProfileInput + Author index.Author + AuthorDataSourceReference string + ImageVersion string + DataSourceLinks []datasourcemodel.DataSourceLink + ProfileInputs []authorcontroller.ProfileInput } func (d *Controller) Detail(c fiber.Ctx) error { @@ -153,8 +153,8 @@ func (d *Controller) authorSummaryFor(authorSlug, lang string) authorSummary { } return authorSummary{ Author: author, ImageVersion: fsutil.AuthorImageVersion(d.appFs, d.config.CacheDir, author.Slug), - MetadataReference: authorcontroller.MetadataReference(author, d.authorDataSource), - DataSourceLinks: links, ProfileInputs: profileInputs, + AuthorDataSourceReference: authorcontroller.AuthorDataSourceReference(author, d.authorDataSource), + DataSourceLinks: links, ProfileInputs: profileInputs, } } diff --git a/internal/webserver/embedded/views/author/list.html b/internal/webserver/embedded/views/author/list.html index 21075774..60b36f51 100644 --- a/internal/webserver/embedded/views/author/list.html +++ b/internal/webserver/embedded/views/author/list.html @@ -1,6 +1,6 @@ {{if ne .Author.Name ""}} {{if not .Author.RetrievedOn.IsZero}} - {{template "partials/author-summary" dict "Lang" .Lang "Author" .Author "Session" .Session "MetadataReference" .MetadataReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "BioParagraphs" .BioParagraphs "BioPending" .BioPending "BioTranslatedFrom" .BioTranslatedFrom "BioRefreshAvailable" .BioRefreshAvailable "ProfileInputs" .ProfileInputs}} + {{template "partials/author-summary" dict "Lang" .Lang "Author" .Author "Session" .Session "AuthorDataSourceReference" .AuthorDataSourceReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "BioParagraphs" .BioParagraphs "BioPending" .BioPending "BioTranslatedFrom" .BioTranslatedFrom "BioRefreshAvailable" .BioRefreshAvailable "ProfileInputs" .ProfileInputs}} {{else}}
      diff --git a/internal/webserver/embedded/views/document/detail.html b/internal/webserver/embedded/views/document/detail.html index f326cf94..3eebbfaf 100644 --- a/internal/webserver/embedded/views/document/detail.html +++ b/internal/webserver/embedded/views/document/detail.html @@ -60,7 +60,7 @@

      {{.Document.Title}}


      {{range .AuthorSummaries}} {{if not .Author.RetrievedOn.IsZero}} - {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" .Author "Session" $.Session "MetadataReference" .MetadataReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "ProfileInputs" .ProfileInputs}} + {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" .Author "Session" $.Session "AuthorDataSourceReference" .AuthorDataSourceReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "ProfileInputs" .ProfileInputs}} {{else}} {{template "partials/author-summary-doc-detail-placeholder" dict "AuthorSlug" .Author.Slug "Lang" $.Lang}} {{end}} @@ -71,7 +71,7 @@

      {{.Document.Title}}

      {{range $i, $entry := .IllustratorSummaries}} {{if eq $i 0}}
      {{end}} {{if not $entry.Author.RetrievedOn.IsZero}} - {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" $entry.Author "Session" $.Session "MetadataReference" $entry.MetadataReference "ImageVersion" $entry.ImageVersion "DataSourceLinks" $entry.DataSourceLinks "ProfileInputs" $entry.ProfileInputs}} + {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" $entry.Author "Session" $.Session "AuthorDataSourceReference" $entry.AuthorDataSourceReference "ImageVersion" $entry.ImageVersion "DataSourceLinks" $entry.DataSourceLinks "ProfileInputs" $entry.ProfileInputs}} {{else}} {{template "partials/author-summary-doc-detail-placeholder" dict "AuthorSlug" $entry.Author.Slug "Lang" $.Lang}} {{end}} diff --git a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html index bc8128da..ea4776c7 100644 --- a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html +++ b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html @@ -1,4 +1,4 @@ -{{$metadataID := .MetadataReference}} +{{$authorDataSourceReference := .AuthorDataSourceReference}}
      @@ -8,7 +8,7 @@

      {{.Author.Name}}

      {{.Author.BirthName}}

      {{end}}
      - {{if eq $metadataID ""}} + {{if eq $authorDataSourceReference ""}}

      {{t .Lang "Sorry, we don't have information about this author at the moment"}}

      {{else if index .Author.Description .Lang}}

      {{index .Author.Description .Lang}}

      @@ -19,7 +19,7 @@

      {{.Author.Name}}

      {{end}} - {{if ne $metadataID ""}} + {{if ne $authorDataSourceReference ""}}
      {{if ne .Author.DateOfBirth.Date 0}}
      {{t .Lang "Date of birth"}}
      @@ -87,7 +87,7 @@

      {{.Author.Name}}

      - {{.Author.Name}} + {{.Author.Name}}
      diff --git a/internal/webserver/embedded/views/partials/author-summary.html b/internal/webserver/embedded/views/partials/author-summary.html index 390f9d01..e5fc60b2 100644 --- a/internal/webserver/embedded/views/partials/author-summary.html +++ b/internal/webserver/embedded/views/partials/author-summary.html @@ -1,4 +1,4 @@ -{{$metadataID := .MetadataReference}} +{{$authorDataSourceReference := .AuthorDataSourceReference}}
      @@ -8,14 +8,14 @@

      {{.Author.Name}}

      {{.Author.BirthName}}

      {{end}}
      - {{if eq $metadataID ""}} + {{if eq $authorDataSourceReference ""}} {{if not (or .BioParagraphs .BioPending)}}

      {{t .Lang "Sorry, we don't have information about this author at the moment"}}

      {{end}} {{else if index .Author.Description .Lang}}

      {{index .Author.Description .Lang}}

      {{end}} - {{if ne $metadataID ""}} + {{if ne $authorDataSourceReference ""}}
      {{if ne .Author.DateOfBirth.Date 0}}
      {{t .Lang "Date of birth"}}
      @@ -87,7 +87,7 @@

      {{.Author.Name}}

      - {{.Author.Name}} + {{.Author.Name}}
      {{if or (index .Author.DataSourceReferences "website") .DataSourceLinks}}
      From d4e26b11a9e46a2bc9f3a5219ad8cc8f0d7816b0 Mon Sep 17 00:00:00 2001 From: Sergio Vera Date: Mon, 23 Nov 2026 19:38:25 +0100 Subject: [PATCH 7/7] COnsolidated datasourceid --- internal/webserver/controller/author/controller.go | 4 ++-- internal/webserver/controller/author/datasource.go | 2 +- internal/webserver/controller/document/controller.go | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index c555a718..57cac331 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -23,7 +23,7 @@ type ProfileInputProvider interface { ProfileValue(author index.Author) string } -type MetadataProfileProvider interface { +type AuthorDataSourceProfileProvider interface { ProfileInputProvider ReferenceKey() string } @@ -49,7 +49,7 @@ func NewProfileInput(provider ProfileInputProvider, author index.Author, name, m } } -func AuthorDataSourceReference(author index.Author, provider MetadataProfileProvider) string { +func AuthorDataSourceReference(author index.Author, provider AuthorDataSourceProfileProvider) string { key := "wikidata" if provider != nil { key = provider.ReferenceKey() diff --git a/internal/webserver/controller/author/datasource.go b/internal/webserver/controller/author/datasource.go index 0fa05146..dbd93029 100644 --- a/internal/webserver/controller/author/datasource.go +++ b/internal/webserver/controller/author/datasource.go @@ -3,7 +3,7 @@ package author import "github.com/svera/coreander/v5/internal/datasource/model" type DataSource interface { - MetadataProfileProvider + AuthorDataSourceProfileProvider OwnsLink(key string) bool NormalizeAuthorID(value string) (string, error) SearchAuthor(name string, languages []string) (model.Author, error) diff --git a/internal/webserver/controller/document/controller.go b/internal/webserver/controller/document/controller.go index 642602a8..bd54e6dc 100644 --- a/internal/webserver/controller/document/controller.go +++ b/internal/webserver/controller/document/controller.go @@ -103,12 +103,12 @@ type Controller struct { appFs afero.Fs translator i18n.Translator reviewProvider ReviewProvider - authorDataSource authorcontroller.MetadataProfileProvider + authorDataSource authorcontroller.AuthorDataSourceProfileProvider linkProviders []authorcontroller.DataSourceLinkProvider } // NewController creates a document controller. A nil reviewProvider disables scores and reviews. -func NewController(hlRepository highlightsRepository, usersRepository usersRepository, readingRepository readingRepository, annotationsRepository annotationsRepository, sender Sender, idx IdxReaderWriter, appFs afero.Fs, cfg Config, translator i18n.Translator, reviewProvider ReviewProvider, authorDataSource authorcontroller.MetadataProfileProvider, linkProviders ...authorcontroller.DataSourceLinkProvider) *Controller { +func NewController(hlRepository highlightsRepository, usersRepository usersRepository, readingRepository readingRepository, annotationsRepository annotationsRepository, sender Sender, idx IdxReaderWriter, appFs afero.Fs, cfg Config, translator i18n.Translator, reviewProvider ReviewProvider, authorDataSource authorcontroller.AuthorDataSourceProfileProvider, linkProviders ...authorcontroller.DataSourceLinkProvider) *Controller { return &Controller{ hlRepository: hlRepository, usersRepository: usersRepository,