diff --git a/services/search/README.md b/services/search/README.md index 984a833d50..8b2bdecc30 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -161,6 +161,18 @@ Additionally, the following optional settings can be set: * `SEARCH_EXTRACTOR_TIKA_CLEAN_STOP_WORDS=true` (default: `true`): ignore stop words like `I`, `you`, `the` during content extraction. +#### Files Tika Cannot Parse + +A file Tika cannot parse, such as a broken PDF or an image the OCR fails on, is still indexed by name, path and tags, so it stays findable. The content is tried again on later reindexes, the first retry one hour after the failure, the second one day after that. After the third failure the service logs a warning with the path and stops trying until the file changes. If Tika or the file is unreachable, a new or changed file is indexed by name as well, this does not count as a failure and every later reindex tries again. + +To list the files the service gave up on, search for: + +```text +extractionfailure.count>=3 +``` + +A reindex with `--force-rescan` (see below) tries these files again regardless of the limit, for example after a Tika upgrade. + ## Manually Trigger Re-Indexing a Space The service includes a command-line interface to trigger re-indexing a space: diff --git a/services/search/pkg/bleve/backend.go b/services/search/pkg/bleve/backend.go index 17474bed50..5a42cc4e1d 100644 --- a/services/search/pkg/bleve/backend.go +++ b/services/search/pkg/bleve/backend.go @@ -16,6 +16,7 @@ import ( "github.com/opencloud-eu/opencloud/pkg/kql" "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" "github.com/opencloud-eu/opencloud/services/search/pkg/search" searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0" @@ -28,7 +29,7 @@ const defaultBatchSize = 50 var _ search.Engine = (*Backend)(nil) // ensure Backend implements Engine type Backend struct { - index bleve.Index + index *serialIndex queryCreator searchQuery.Creator[query.Query] log log.Logger } @@ -178,6 +179,32 @@ func (b *Backend) Get(_ context.Context, id string) (*search.Resource, error) { return searchResourceByID(id, b.index) } +// Update holds the batch lock from the read to the write, so a batch pushed in +// between is not overwritten; a batch built before the update and pushed after +// it still writes the tags it read +func (b *Backend) Update(_ context.Context, id string, u search.MetadataUpdate) error { + b.index.batchMu.Lock() + defer b.index.batchMu.Unlock() + + r, err := searchResourceByID(id, b.index) + if err != nil { + return err + } + r.Tags = u.Tags + r.Favorites = u.Favorites + + doc, err := mapping.PrepareForIndex(r, r.SearchFieldOverrides()) + if err != nil { + return err + } + batch := b.index.NewBatch() + err = batch.Index(id, doc) + if err != nil { + return err + } + return b.index.bleveIndex.Batch(batch) +} + func (b *Backend) DocCount() (uint64, error) { return b.index.DocCount() } diff --git a/services/search/pkg/bleve/backend_test.go b/services/search/pkg/bleve/backend_test.go index 270c821183..8cff372e2c 100644 --- a/services/search/pkg/bleve/backend_test.go +++ b/services/search/pkg/bleve/backend_test.go @@ -11,6 +11,7 @@ import ( . "github.com/onsi/gomega" "github.com/opencloud-eu/opencloud/pkg/log" + searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/search/pkg/bleve" "github.com/opencloud-eu/opencloud/services/search/pkg/content" bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve" @@ -138,6 +139,55 @@ var _ = Describe("Bleve", func() { }) }) + Describe("Update", func() { + tagHits := func(tag string) []string { + res, err := eng.Search(context.Background(), &searchService.SearchIndexRequest{Query: `tag:("` + tag + `")`}) + Expect(err).ToNot(HaveOccurred()) + var ids []string + for _, match := range res.GetMatches() { + ids = append(ids, match.GetEntity().GetId().GetOpaqueId()) + } + return ids + } + + It("rewrites tags and favorites and keeps the extracted fields", func() { + childResource.Content = "quarterly report" + childResource.Tags = []string{"alpha"} + Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed()) + + Expect(eng.Update(context.Background(), childResource.ID, search.MetadataUpdate{ + Tags: []string{"Beta"}, + Favorites: []string{"user-1"}, + })).To(Succeed()) + + r, err := eng.Get(context.Background(), childResource.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(Equal([]string{"Beta"})) + Expect(r.Favorites).To(Equal([]string{"user-1"})) + Expect(r.Content).To(Equal("quarterly report")) + + Expect(tagHits("beta")).To(ConsistOf("4"), "the lowercase sibling follows the new tag") + Expect(tagHits("alpha")).To(BeEmpty()) + }) + + It("clears the tags", func() { + childResource.Tags = []string{"alpha"} + Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed()) + + Expect(eng.Update(context.Background(), childResource.ID, search.MetadataUpdate{})).To(Succeed()) + + r, err := eng.Get(context.Background(), childResource.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(BeEmpty()) + Expect(tagHits("alpha")).To(BeEmpty()) + }) + + It("fails with ErrResourceNotFound for an unknown id", func() { + err := eng.Update(context.Background(), "1$2!unknown", search.MetadataUpdate{Tags: []string{"alpha"}}) + Expect(err).To(MatchError(search.ErrResourceNotFound)) + }) + }) + Describe("New", func() { It("returns a new index instance", func() { b := bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.Logger{}) diff --git a/services/search/pkg/bleve/testdata/mapping.golden.json b/services/search/pkg/bleve/testdata/mapping.golden.json index 73f6baa748..47574d908b 100644 --- a/services/search/pkg/bleve/testdata/mapping.golden.json +++ b/services/search/pkg/bleve/testdata/mapping.golden.json @@ -30,6 +30,38 @@ } ] }, + "ExtractionFailure": { + "enabled": true, + "dynamic": true, + "properties": { + "Count": { + "enabled": true, + "dynamic": true, + "fields": [ + { + "type": "number", + "store": true, + "index": true, + "include_in_all": true, + "docvalues": true + } + ] + }, + "RetryAt": { + "enabled": true, + "dynamic": true, + "fields": [ + { + "type": "datetime", + "store": true, + "index": true, + "include_in_all": true, + "docvalues": true + } + ] + } + } + }, "Favorites": { "enabled": true, "dynamic": true, diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index 767f8a0d98..733ff02517 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -2,6 +2,7 @@ package content import ( "context" + "errors" "fmt" "io" "net/http" @@ -17,6 +18,10 @@ import ( "github.com/opencloud-eu/opencloud/services/search/pkg/config" ) +// ErrUnparsable marks a file tika answered for but could not parse, unlike an +// unreachable tika it fails the same way on the next attempt more often than not +var ErrUnparsable = errors.New("tika failed to parse") + // Tika is used to extract content from a resource, // it uses apache tika to retrieve all the data. type Tika struct { @@ -82,8 +87,20 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, if err != nil { return doc, err } + // a file with content always yields metadata, none means tika failed on it if len(metas) == 0 { - return doc, nil + return doc, fmt.Errorf("%w %q: no metadata", ErrUnparsable, ri.GetName()) + } + // tika answers a failed parse (ocr crash, broken pdf) with 200 and empty + // content, only this key tells it apart from a file without text + cause, err := getFirstValue(metas[0], + "tk:exception:container-exception", // tika 4 + "X-TIKA:EXCEPTION:container_exception", // tika 3 legacy + ) + if err == nil { + // the value is a java stack trace, its first line names the cause + cause, _, _ = strings.Cut(cause, "\n") + return doc, fmt.Errorf("%w %q: %s", ErrUnparsable, ri.GetName(), cause) } for _, meta := range metas { diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index f0b1850879..ab6605cbf9 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -99,6 +99,36 @@ var _ = Describe("Tika", func() { Expect(doc.Content).To(Equal(body)) }) + It("fails when tika returns no metadata for a file with content", func() { + fullResponse = "[]" + + _, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Name: "report.pdf", + Size: 1, + }) + Expect(err).To(MatchError(content.ErrUnparsable)) + Expect(err).To(MatchError(ContainSubstring("report.pdf"))) + }) + + DescribeTable("fails when tika could not parse the file", + func(response string) { + fullResponse = response + + doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Name: "scan.png", + Size: 1, + }) + Expect(err).To(MatchError(content.ErrUnparsable)) + Expect(err).To(MatchError(And(ContainSubstring("scan.png"), ContainSubstring("bad exit value 1")))) + Expect(err.Error()).ToNot(ContainSubstring("at org.apache")) + Expect(doc.Name).To(Equal("scan.png")) + }, + Entry("tika 4", `[{"tk:content": "", "tk:exception:container-exception": "org.apache.tika.exception.TikaException: TesseractOCRParser bad exit value 1\n\tat org.apache.tika.parser.ocr.TesseractOCRParser.doOCR"}]`), + Entry("tika 3", `[{"X-TIKA:content": "", "X-TIKA:EXCEPTION:container_exception": "org.apache.tika.exception.TikaException: TesseractOCRParser bad exit value 1\n\tat org.apache.tika.parser.ocr.TesseractOCRParser.doOCR"}]`), + ) + It("adds the title", func() { fullResponse = `[{"dc:title": "quarterly report", "X-TIKA:content": "some data"}]` diff --git a/services/search/pkg/opensearch/backend.go b/services/search/pkg/opensearch/backend.go index d56fd6d731..d5610a4483 100644 --- a/services/search/pkg/opensearch/backend.go +++ b/services/search/pkg/opensearch/backend.go @@ -1,11 +1,16 @@ package opensearch import ( + "bytes" "context" + "encoding/json" + "errors" "fmt" + "reflect" "time" storageProvider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + opensearchgo "github.com/opensearch-project/opensearch-go/v4" opensearchgoAPI "github.com/opensearch-project/opensearch-go/v4/opensearchapi" "github.com/opencloud-eu/reva/v3/pkg/errtypes" @@ -17,6 +22,7 @@ import ( "github.com/opencloud-eu/opencloud/pkg/log" searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0" searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" + "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" "github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/convert" "github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/osu" "github.com/opencloud-eu/opencloud/services/search/pkg/search" @@ -24,6 +30,10 @@ import ( const defaultBatchSize = 50 +// updateRetries lets OpenSearch merge a partial update again onto a document +// another write changed between its read and its write +const updateRetries = 3 + var ( ErrUnhealthyCluster = fmt.Errorf("cluster is not healthy") ) @@ -178,6 +188,54 @@ func (b *Backend) Get(ctx context.Context, id string) (*search.Resource, error) return &resource, nil } +// Update sends a partial document, OpenSearch merges it into the stored one, so +// the extracted fields are never read and written back +func (b *Backend) Update(ctx context.Context, id string, u search.MetadataUpdate) error { + r := search.Resource{} + r.Tags = u.Tags + r.Favorites = u.Favorites + full, err := mapping.PrepareForIndex(r, r.SearchFieldOverrides()) + if err != nil { + return fmt.Errorf("failed to prepare the update: %w", err) + } + + // a field the update empties has no sibling in full, the explicit null clears the stale one + siblings := mapping.SearchSiblings(reflect.TypeFor[search.Resource](), r.SearchFieldOverrides()) + partial := map[string]any{} + for _, field := range []string{"Tags", "Favorites"} { + partial[field] = full[field] + if siblings[field].Lowercase { + partial[field+mapping.LowercaseSuffix] = full[field+mapping.LowercaseSuffix] + } + if siblings[field].Words { + partial[field+mapping.WordsSuffix] = full[field+mapping.WordsSuffix] + } + } + + body, err := json.Marshal(map[string]any{"doc": partial}) + if err != nil { + return fmt.Errorf("failed to marshal the update: %w", err) + } + + _, err = b.client.Update(ctx, opensearchgoAPI.UpdateReq{ + Index: b.index, + DocumentID: id, + Body: bytes.NewReader(body), + Params: opensearchgoAPI.UpdateParams{ + Refresh: "wait_for", + RetryOnConflict: new(updateRetries), + }, + }) + var structErr *opensearchgo.StructError + switch { + case errors.As(err, &structErr) && structErr.Err.Type == "document_missing_exception": + return fmt.Errorf("document with id %s: %w", id, search.ErrResourceNotFound) + case err != nil: + return fmt.Errorf("failed to update the document: %w", err) + } + return nil +} + func (b *Backend) DocCount() (uint64, error) { req, err := osu.BuildIndicesCountReq( &opensearchgoAPI.IndicesCountReq{ diff --git a/services/search/pkg/opensearch/backend_test.go b/services/search/pkg/opensearch/backend_test.go index 2fa0c0b2c6..abd74fd1e5 100644 --- a/services/search/pkg/opensearch/backend_test.go +++ b/services/search/pkg/opensearch/backend_test.go @@ -11,6 +11,7 @@ import ( opensearchgoAPI "github.com/opensearch-project/opensearch-go/v4/opensearchapi" "github.com/opencloud-eu/opencloud/pkg/log" + searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/search/internal/opensearchtest" "github.com/opencloud-eu/opencloud/services/search/pkg/opensearch" "github.com/opencloud-eu/opencloud/services/search/pkg/search" @@ -127,4 +128,67 @@ var _ = Describe("Backend", func() { Expect(err).To(MatchError(search.ErrResourceNotFound)) }) }) + + Describe("Update", func() { + const indexName = "opencloud-test-engine-update" + + var backend *opensearch.Backend + + BeforeEach(func() { + physical := opensearch.VersionedIndexName(indexName) + + tc := opensearchtest.NewDefaultTestClient(GinkgoTB(), defaultConfig.Engine.OpenSearch.Client) + tc.Require.IndicesReset([]string{physical}) + deleteIndexOnCleanup(tc, physical) + + var err error + backend, err = opensearch.NewBackend(context.Background(), indexName, tc.Client(), log.NopLogger()) + Expect(err).ToNot(HaveOccurred()) + }) + + tagHits := func(tag string) int { + res, err := backend.Search(context.Background(), &searchService.SearchIndexRequest{Query: `tag:("` + tag + `")`}) + Expect(err).ToNot(HaveOccurred()) + return len(res.GetMatches()) + } + + It("rewrites tags and favorites and keeps the extracted fields", func() { + document := opensearchtest.Testdata.Resources.File + document.Content = "quarterly report" + document.Tags = []string{"alpha"} + Expect(backend.Upsert(document.ID, document)).To(Succeed()) + + Expect(backend.Update(context.Background(), document.ID, search.MetadataUpdate{ + Tags: []string{"Beta"}, + Favorites: []string{"user-1"}, + })).To(Succeed()) + + r, err := backend.Get(context.Background(), document.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(Equal([]string{"Beta"})) + Expect(r.Favorites).To(Equal([]string{"user-1"})) + Expect(r.Content).To(Equal("quarterly report")) + + Expect(tagHits("beta")).To(Equal(1), "the lowercase sibling follows the new tag") + Expect(tagHits("alpha")).To(BeZero()) + }) + + It("clears the tags and their lowercase sibling", func() { + document := opensearchtest.Testdata.Resources.File + document.Tags = []string{"alpha"} + Expect(backend.Upsert(document.ID, document)).To(Succeed()) + + Expect(backend.Update(context.Background(), document.ID, search.MetadataUpdate{})).To(Succeed()) + + r, err := backend.Get(context.Background(), document.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(r.Tags).To(BeEmpty()) + Expect(tagHits("ALPHA")).To(BeZero()) + }) + + It("fails with ErrResourceNotFound for an unknown id", func() { + err := backend.Update(context.Background(), "1$2!unknown", search.MetadataUpdate{Tags: []string{"alpha"}}) + Expect(err).To(MatchError(search.ErrResourceNotFound)) + }) + }) }) diff --git a/services/search/pkg/opensearch/testdata/resource.golden.json b/services/search/pkg/opensearch/testdata/resource.golden.json index ab343eef11..375cd69254 100644 --- a/services/search/pkg/opensearch/testdata/resource.golden.json +++ b/services/search/pkg/opensearch/testdata/resource.golden.json @@ -9,6 +9,16 @@ "Deleted": { "type": "boolean" }, + "ExtractionFailure": { + "properties": { + "Count": { + "type": "long" + }, + "RetryAt": { + "type": "date" + } + } + }, "Favorites": { "type": "keyword" }, diff --git a/services/search/pkg/parity/README.md b/services/search/pkg/parity/README.md index f73000e16f..69cdde843c 100644 --- a/services/search/pkg/parity/README.md +++ b/services/search/pkg/parity/README.md @@ -461,6 +461,21 @@ Fixtures: | PHOTO-05 | `photo.iso<=100` | bright.jpg | bright.jpg | bright.jpg | ✅ | | PHOTO-06 | `photo.cameraMake>1` | no match | no match | no match | ✅ | +### extraction + +Fixtures: + +- `given-up.pdf` +- `waiting.png` +- `extracted.txt` + +| Case | Query | expected | bleve | OpenSearch | same? | +|---|---|---|---|---|---| +| EXTRACTION-01 | `extractionfailure.count>=3` | given-up.pdf | given-up.pdf | given-up.pdf | ✅ | +| EXTRACTION-02 | `ExtractionFailure.Count>=1` | given-up.pdf, waiting.png | given-up.pdf, waiting.png | given-up.pdf, waiting.png | ✅ | +| EXTRACTION-03 | `extractionfailure.retryat>"2029-01-01T00:00:00Z"` | waiting.png | waiting.png | waiting.png | ✅ | +| EXTRACTION-04 | `extractionfailure.retryat<"2029-01-01T00:00:00Z"` | no match | no match | no match | ✅ | + ### scope Fixtures: diff --git a/services/search/pkg/parity/fixtures_test.go b/services/search/pkg/parity/fixtures_test.go index 9e75f037a1..fcb909d310 100644 --- a/services/search/pkg/parity/fixtures_test.go +++ b/services/search/pkg/parity/fixtures_test.go @@ -58,6 +58,20 @@ func withLocation(location *libregraph.GeoCoordinates) fixtureOption { return func(r *search.Resource) { r.Location = location } } +func withExtractionFailure(count int, retryAt string) fixtureOption { + return func(r *search.Resource) { + f := &search.ExtractionFailure{Count: count} + if retryAt != "" { + t, err := time.Parse(time.RFC3339Nano, retryAt) + if err != nil { + panic(err) + } + f.RetryAt = &t + } + r.ExtractionFailure = f + } +} + func fixtureDoc(name string, opts ...fixtureOption) search.Resource { mtime := fixtureNow r := search.Resource{ diff --git a/services/search/pkg/parity/get_test.go b/services/search/pkg/parity/get_test.go new file mode 100644 index 0000000000..9555673c94 --- /dev/null +++ b/services/search/pkg/parity/get_test.go @@ -0,0 +1,42 @@ +package parity + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/services/search/pkg/search" +) + +// the indexer reads its retry bookkeeping back through Get, a nested object +// with a timestamp has to survive the round trip on every engine +var _ = Describe("Get", Ordered, func() { + failed := fixtureDoc("failed.pdf", withExtractionFailure(2, "2030-01-01T12:30:00Z")) + extracted := fixtureDoc("extracted.txt") + + var engines []testEngine + BeforeAll(func() { + engines = newEngines("opencloud-test-engine-parity-get", []search.Resource{failed, extracted}) + }) + + for _, name := range engineNames { + It("returns the extraction failure as written on "+name, func() { + e := engineNamed(engines, name) + if e.unavailable != "" { + Skip(e.unavailable) + } + + r, err := e.backend.Get(context.Background(), failed.ID) + Expect(err).NotTo(HaveOccurred()) + Expect(r.ExtractionFailure).NotTo(BeNil()) + Expect(r.ExtractionFailure.Count).To(Equal(2)) + Expect(r.ExtractionFailure.RetryAt).NotTo(BeNil()) + Expect(*r.ExtractionFailure.RetryAt).To(BeTemporally("==", *failed.ExtractionFailure.RetryAt)) + + r, err = e.backend.Get(context.Background(), extracted.ID) + Expect(err).NotTo(HaveOccurred()) + Expect(r.ExtractionFailure).To(BeNil()) + }) + } +}) diff --git a/services/search/pkg/parity/parity_test.go b/services/search/pkg/parity/parity_test.go index 55d85078c8..3c82ce043e 100644 --- a/services/search/pkg/parity/parity_test.go +++ b/services/search/pkg/parity/parity_test.go @@ -111,6 +111,7 @@ func queryGroups() []queryGroup { everythingGroup(), rangeGroup(), photoGroup(), + extractionGroup(), scopeGroup(), invalidGroup(), quotingGroup(), diff --git a/services/search/pkg/parity/query_extraction_test.go b/services/search/pkg/parity/query_extraction_test.go new file mode 100644 index 0000000000..998cbe7626 --- /dev/null +++ b/services/search/pkg/parity/query_extraction_test.go @@ -0,0 +1,22 @@ +package parity + +import ( + "github.com/opencloud-eu/opencloud/services/search/pkg/search" +) + +func extractionGroup() queryGroup { + return queryGroup{ + name: "extraction", + fixtures: []search.Resource{ + fixtureDoc("given-up.pdf", withExtractionFailure(3, "")), + fixtureDoc("waiting.png", withExtractionFailure(1, "2030-01-01T00:00:00Z")), + fixtureDoc("extracted.txt"), + }, + cases: []queryCase{ + {id: 1, query: `extractionfailure.count>=3`, want: []string{"given-up.pdf"}}, + {id: 2, query: `ExtractionFailure.Count>=1`, want: []string{"given-up.pdf", "waiting.png"}}, + {id: 3, query: `extractionfailure.retryat>"2029-01-01T00:00:00Z"`, want: []string{"waiting.png"}}, + {id: 4, query: `extractionfailure.retryat<"2029-01-01T00:00:00Z"`}, + }, + } +} diff --git a/services/search/pkg/search/mocks/engine.go b/services/search/pkg/search/mocks/engine.go index 9fdee306ef..6797500fc3 100644 --- a/services/search/pkg/search/mocks/engine.go +++ b/services/search/pkg/search/mocks/engine.go @@ -563,6 +563,69 @@ func (_c *Engine_Search_Call) RunAndReturn(run func(ctx context.Context, req *v0 return _c } +// Update provides a mock function for the type Engine +func (_mock *Engine) Update(ctx context.Context, id string, u search.MetadataUpdate) error { + ret := _mock.Called(ctx, id, u) + + if len(ret) == 0 { + panic("no return value specified for Update") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(context.Context, string, search.MetadataUpdate) error); ok { + r0 = returnFunc(ctx, id, u) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// Engine_Update_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Update' +type Engine_Update_Call struct { + *mock.Call +} + +// Update is a helper method to define mock.On call +// - ctx context.Context +// - id string +// - u search.MetadataUpdate +func (_e *Engine_Expecter) Update(ctx any, id any, u any) *Engine_Update_Call { + return &Engine_Update_Call{Call: _e.mock.On("Update", ctx, id, u)} +} + +func (_c *Engine_Update_Call) Run(run func(ctx context.Context, id string, u search.MetadataUpdate)) *Engine_Update_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 search.MetadataUpdate + if args[2] != nil { + arg2 = args[2].(search.MetadataUpdate) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *Engine_Update_Call) Return(err error) *Engine_Update_Call { + _c.Call.Return(err) + return _c +} + +func (_c *Engine_Update_Call) RunAndReturn(run func(ctx context.Context, id string, u search.MetadataUpdate) error) *Engine_Update_Call { + _c.Call.Return(run) + return _c +} + // Upsert provides a mock function for the type Engine func (_mock *Engine) Upsert(id string, r search.Resource) error { ret := _mock.Called(id, r) diff --git a/services/search/pkg/search/mocks/searcher.go b/services/search/pkg/search/mocks/searcher.go index 563cdfede6..0cf6704769 100644 --- a/services/search/pkg/search/mocks/searcher.go +++ b/services/search/pkg/search/mocks/searcher.go @@ -426,24 +426,24 @@ func (_c *Searcher_TrashItem_Call) RunAndReturn(run func(resourceID *providerv1b return _c } -// UpsertItem provides a mock function for the type Searcher -func (_mock *Searcher) UpsertItem(ref *providerv1beta1.Reference) { +// UpdateMetadata provides a mock function for the type Searcher +func (_mock *Searcher) UpdateMetadata(ref *providerv1beta1.Reference) { _mock.Called(ref) return } -// Searcher_UpsertItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpsertItem' -type Searcher_UpsertItem_Call struct { +// Searcher_UpdateMetadata_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateMetadata' +type Searcher_UpdateMetadata_Call struct { *mock.Call } -// UpsertItem is a helper method to define mock.On call +// UpdateMetadata is a helper method to define mock.On call // - ref *providerv1beta1.Reference -func (_e *Searcher_Expecter) UpsertItem(ref any) *Searcher_UpsertItem_Call { - return &Searcher_UpsertItem_Call{Call: _e.mock.On("UpsertItem", ref)} +func (_e *Searcher_Expecter) UpdateMetadata(ref any) *Searcher_UpdateMetadata_Call { + return &Searcher_UpdateMetadata_Call{Call: _e.mock.On("UpdateMetadata", ref)} } -func (_c *Searcher_UpsertItem_Call) Run(run func(ref *providerv1beta1.Reference)) *Searcher_UpsertItem_Call { +func (_c *Searcher_UpdateMetadata_Call) Run(run func(ref *providerv1beta1.Reference)) *Searcher_UpdateMetadata_Call { _c.Call.Run(func(args mock.Arguments) { var arg0 *providerv1beta1.Reference if args[0] != nil { @@ -456,12 +456,12 @@ func (_c *Searcher_UpsertItem_Call) Run(run func(ref *providerv1beta1.Reference) return _c } -func (_c *Searcher_UpsertItem_Call) Return() *Searcher_UpsertItem_Call { +func (_c *Searcher_UpdateMetadata_Call) Return() *Searcher_UpdateMetadata_Call { _c.Call.Return() return _c } -func (_c *Searcher_UpsertItem_Call) RunAndReturn(run func(ref *providerv1beta1.Reference)) *Searcher_UpsertItem_Call { +func (_c *Searcher_UpdateMetadata_Call) RunAndReturn(run func(ref *providerv1beta1.Reference)) *Searcher_UpdateMetadata_Call { _c.Run(run) return _c } diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index a046cc88d8..90a9ac6d0e 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -7,6 +7,7 @@ import ( "regexp" "strings" "sync" + "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" @@ -50,10 +51,20 @@ type Engine interface { Purge(id string, onlyDeleted bool) error PurgeSpace(rootID string) error Get(ctx context.Context, id string) (*Resource, error) + // Update rewrites the fields u carries on the indexed document and keeps the + // rest, ErrResourceNotFound if the index holds no document with that id + Update(ctx context.Context, id string, u MetadataUpdate) error NewBatch(batchSize int) (BatchOperator, error) } +// MetadataUpdate holds the fields a tag or label change rewrites. Both come from +// the stat, so the extracted content stays and tika is not asked again. +type MetadataUpdate struct { + Tags []string + Favorites []string +} + type BatchOperator interface { Upsert(id string, r Resource) error Move(id string, parentID string, targetPath string) error @@ -75,6 +86,21 @@ type Resource struct { Type uint64 `json:"Type"` Deleted bool `json:"Deleted"` Hidden bool `json:"Hidden"` + // ExtractionFailure is set while the content of this version could not be + // parsed, nil means extracted; entries from before the field count as extracted + ExtractionFailure *ExtractionFailure `json:"ExtractionFailure,omitempty"` +} + +// ExtractionFailure is the indexer's own bookkeeping, not derived from the +// storage: losing it with the index costs retries, never data. Two walks failing +// at once may count one failure, that buys one more attempt. +type ExtractionFailure struct { + // Count is the number of parse failures of the indexed version, 0 when only + // tika or the file was unreachable and every walk retries it + Count int `json:"Count"` + // RetryAt is the earliest next attempt, nil for an immediate retry or once + // the attempts are used up + RetryAt *time.Time `json:"RetryAt,omitempty"` } // resourceFieldOverrides is built once (it never changes) and reused on hot diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 9333398cdb..bbbabdf0c5 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -63,7 +63,7 @@ type Searcher interface { TrashItem(resourceID *provider.ResourceId) PurgeItem(ref *provider.Reference) - UpsertItem(ref *provider.Reference) + UpdateMetadata(ref *provider.Reference) RestoreItem(ref *provider.Reference) MoveItem(ref *provider.Reference) } @@ -75,6 +75,7 @@ type Service struct { gatewaySelector pool.Selectable[gateway.GatewayAPIClient] engine Engine extractor content.Extractor + basic *content.Basic metrics *metrics.Metrics serviceAccountID string @@ -87,13 +88,22 @@ type Service struct { var errSkipSpace error +// a parse failure is retried after these delays, then given up until the file +// changes; ocr and image tools also fail under load, so the spacing outlasts a +// burst of uploads instead of spending every attempt inside it +var extractionRetryDelays = []time.Duration{time.Hour, 24 * time.Hour} + // NewService creates a new Provider instance. func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng Engine, extractor content.Extractor, metrics *metrics.Metrics, logger log.Logger, cfg *config.Config) *Service { + // NewBasicExtractor has no failure path + basic, _ := content.NewBasicExtractor(logger) + var s = &Service{ gatewaySelector: gatewaySelector, engine: eng, logger: logger, extractor: extractor, + basic: basic, metrics: metrics, serviceAccountID: cfg.ServiceAccount.ServiceAccountID, @@ -670,14 +680,36 @@ func (s *Service) PurgeDeleted(spaceID *provider.StorageSpaceId) error { return nil } -// UpsertItem indexes or stores Resource data fields. -func (s *Service) UpsertItem(ref *provider.Reference) { +// UpdateMetadata rewrites the tags and favorites of an indexed resource without +// extracting its content again, a resource not indexed yet is upserted in full. +func (s *Service) UpdateMetadata(ref *provider.Reference) { ctx, err := getAuthContext(s.serviceAccountID, s.gatewaySelector, s.serviceAccountSecret, s.logger) if err != nil { s.logger.Error().Err(err).Msg("failed to get auth context") return } - s.doUpsertItem(ctx, ref, nil) + + stat, path := s.resInfo(ctx, ref) + if stat == nil || path == "" { + return + } + + doc, err := s.basic.Extract(ctx, stat.GetInfo()) + if err != nil { + s.logger.Error().Err(err).Msg("failed to read the resource metadata") + return + } + + err = s.engine.Update(ctx, storagespace.FormatResourceID(stat.GetInfo().GetId()), MetadataUpdate{ + Tags: doc.Tags, + Favorites: doc.Favorites, + }) + switch { + case errors.Is(err, ErrResourceNotFound): + s.upsertResource(ctx, ref, stat, path, nil) + case err != nil: + s.logger.Error().Err(err).Interface("id", stat.GetInfo().GetId()).Msg("failed to update the resource metadata in the index") + } } // doUpsertItem indexes or stores Resource data fields. @@ -686,104 +718,7 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat if stat == nil || path == "" { return } - - if utils.IsProcessing(stat.Info) { - s.logger.Debug().Str("path", path).Msg("resource is still being processed. Skipping.") - return - } - - doc, err := s.extractor.Extract(ctx, stat.Info) - if err != nil { - s.logger.Error().Err(err).Msg("failed to extract resource content") - return - } - - r := Resource{ - ID: storagespace.FormatResourceID(stat.Info.Id), - RootID: storagespace.FormatResourceID(&provider.ResourceId{ - StorageId: stat.Info.Id.StorageId, - OpaqueId: stat.Info.Id.SpaceId, - SpaceId: stat.Info.Id.SpaceId, - }), - Path: utils.MakeRelativePath(path), - Type: uint64(stat.Info.Type), - Document: doc, - } - r.Hidden = IsHidden(r.Path) - - if parentID := stat.GetInfo().GetParentId(); parentID != nil { - r.ParentID = storagespace.FormatResourceID(parentID) - } - - if batch != nil { - err = batch.Upsert(r.ID, r) - } else { - err = s.engine.Upsert(r.ID, r) - } - if err != nil { - s.logger.Error().Err(err).Msg("error adding updating the resource in the index") - } else { - logDocCount(s.engine, s.logger) - } - - // determine if metadata needs to be stored in storage as well - metadata := map[string]string{} - facetToMetadata(metadata, doc.Audio, facetKeyPrefix+"audio.") - facetToMetadata(metadata, doc.Image, facetKeyPrefix+"image.") - facetToMetadata(metadata, doc.Location, facetKeyPrefix+"location.") - facetToMetadata(metadata, doc.Photo, facetKeyPrefix+"photo.") - facetToMetadata(metadata, doc.Video, facetKeyPrefix+"video.") - facetToMetadata(metadata, doc.MotionPhoto, facetKeyPrefix+"motionPhoto.") - facetToMetadata(metadata, doc.LivePhoto, facetKeyPrefix+"livePhoto.") - - // the facet keys are ours, so the ones this extraction did not produce - // describe content the resource no longer has - var stale []string - for k, stored := range stat.GetInfo().GetArbitraryMetadata().GetMetadata() { - value, ok := metadata[k] - switch { - case ok && value == stored: - delete(metadata, k) - case !ok && strings.HasPrefix(k, facetKeyPrefix): - stale = append(stale, k) - } - } - if len(metadata) == 0 && len(stale) == 0 { - return - } - - gatewayClient, err := s.gatewaySelector.Next() - if err != nil { - s.logger.Error().Err(err).Msg("could not retrieve client to store metadata") - return - } - - if len(metadata) > 0 { - s.logger.Trace().Str("name", doc.Name).Interface("metadata", metadata).Msg("Storing metadata") - - resp, err := gatewayClient.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ - Ref: ref, - ArbitraryMetadata: &provider.ArbitraryMetadata{ - Metadata: metadata, - }, - }) - if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { - s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error storing metadata") - return - } - } - - if len(stale) > 0 { - s.logger.Trace().Str("name", doc.Name).Strs("keys", stale).Msg("Removing stale metadata") - - resp, err := gatewayClient.UnsetArbitraryMetadata(ctx, &provider.UnsetArbitraryMetadataRequest{ - Ref: ref, - ArbitraryMetadataKeys: stale, - }) - if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { - s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error removing stale metadata") - } - } + s.upsertResource(ctx, ref, stat, path, batch) } // SanitizeHighlights keeps the tags and escapes everything else. @@ -895,6 +830,121 @@ func (s *Service) MoveItem(ref *provider.Reference) { } } +// upsertResource extracts and indexes the resource stat describes +func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, stat *provider.StatResponse, path string, batch BatchOperator) { + if utils.IsProcessing(stat.GetInfo()) { + s.logger.Debug().Str("path", path).Msg("resource is still being processed. Skipping.") + return + } + + // a failed extraction still yields the name, path and tags, the resource + // stays findable and a later space walk retries it + doc, err := s.extractor.Extract(ctx, stat.GetInfo()) + extractionFailed := err != nil + if err != nil { + s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") + } + + r := Resource{ + ID: storagespace.FormatResourceID(stat.GetInfo().GetId()), + RootID: storagespace.FormatResourceID(&provider.ResourceId{ + StorageId: stat.GetInfo().GetId().GetStorageId(), + OpaqueId: stat.GetInfo().GetId().GetSpaceId(), + SpaceId: stat.GetInfo().GetId().GetSpaceId(), + }), + Path: utils.MakeRelativePath(path), + Type: uint64(stat.GetInfo().GetType()), //nolint:gosec // proto enum values are never negative + Document: doc, + } + r.Hidden = IsHidden(r.Path) + if extractionFailed { + var write bool + r.ExtractionFailure, write = s.nextExtractionFailure(ctx, r.ID, stat.GetInfo(), path, errors.Is(err, content.ErrUnparsable)) + if !write { + return + } + } + + if parentID := stat.GetInfo().GetParentId(); parentID != nil { + r.ParentID = storagespace.FormatResourceID(parentID) + } + + if batch != nil { + err = batch.Upsert(r.ID, r) + } else { + err = s.engine.Upsert(r.ID, r) + } + if err != nil { + s.logger.Error().Err(err).Msg("error adding updating the resource in the index") + } else { + logDocCount(s.engine, s.logger) + } + + // without an extraction the facets are unknown, not gone + if extractionFailed { + return + } + + // determine if metadata needs to be stored in storage as well + metadata := map[string]string{} + facetToMetadata(metadata, doc.Audio, facetKeyPrefix+"audio.") + facetToMetadata(metadata, doc.Image, facetKeyPrefix+"image.") + facetToMetadata(metadata, doc.Location, facetKeyPrefix+"location.") + facetToMetadata(metadata, doc.Photo, facetKeyPrefix+"photo.") + facetToMetadata(metadata, doc.Video, facetKeyPrefix+"video.") + facetToMetadata(metadata, doc.MotionPhoto, facetKeyPrefix+"motionPhoto.") + facetToMetadata(metadata, doc.LivePhoto, facetKeyPrefix+"livePhoto.") + + // the facet keys are ours, so the ones this extraction did not produce + // describe content the resource no longer has + var stale []string + for k, stored := range stat.GetInfo().GetArbitraryMetadata().GetMetadata() { + value, ok := metadata[k] + switch { + case ok && value == stored: + delete(metadata, k) + case !ok && strings.HasPrefix(k, facetKeyPrefix): + stale = append(stale, k) + } + } + if len(metadata) == 0 && len(stale) == 0 { + return + } + + gatewayClient, err := s.gatewaySelector.Next() + if err != nil { + s.logger.Error().Err(err).Msg("could not retrieve client to store metadata") + return + } + + if len(metadata) > 0 { + s.logger.Trace().Str("name", doc.Name).Interface("metadata", metadata).Msg("Storing metadata") + + resp, err := gatewayClient.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{ + Ref: ref, + ArbitraryMetadata: &provider.ArbitraryMetadata{ + Metadata: metadata, + }, + }) + if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { + s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error storing metadata") + return + } + } + + if len(stale) > 0 { + s.logger.Trace().Str("name", doc.Name).Strs("keys", stale).Msg("Removing stale metadata") + + resp, err := gatewayClient.UnsetArbitraryMetadata(ctx, &provider.UnsetArbitraryMetadataRequest{ + Ref: ref, + ArbitraryMetadataKeys: stale, + }) + if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK { + s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error removing stale metadata") + } + } +} + // isIndexed reports whether the index holds a live document for info that is at least as new func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bool { r, err := s.engine.Get(ctx, storagespace.FormatResourceID(info.GetId())) @@ -905,7 +955,53 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo s.logger.Error().Err(err).Interface("id", info.GetId()).Msg("failed to look up the indexed resource, indexing it again") return false } - return !r.Deleted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())) + if r.Deleted || r.Mtime == nil || r.Mtime.Before(utils.TSToTime(info.GetMtime())) { + return false + } + f := r.ExtractionFailure + return f == nil || f.Count > len(extractionRetryDelays) || (f.RetryAt != nil && time.Now().Before(*f.RetryAt)) +} + +// nextExtractionFailure counts a parse failure on top of the ones the indexed +// entry holds for the same version, a new version starts over. Any other failure +// (tika or the file unreachable) says nothing about the file: it is not counted, +// leaves a current entry alone and is retried by every walk. write is false +// when the indexed entry has to stay as it is. +func (s *Service) nextExtractionFailure(ctx context.Context, id string, info *provider.ResourceInfo, path string, unparsable bool) (f *ExtractionFailure, write bool) { + var previous *Resource + r, err := s.engine.Get(ctx, id) + switch { + case errors.Is(err, ErrResourceNotFound): + case err != nil: + s.logger.Error().Err(err).Str("id", id).Msg("failed to look up the previous extraction failures") + if !unparsable { + // without knowing the entry, a name-only document could replace extracted content + return nil, false + } + case r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime())): + previous = r + } + + if !unparsable { + if previous != nil && !previous.Deleted { + return nil, false + } + return &ExtractionFailure{}, true + } + + count := 1 + if previous != nil && previous.ExtractionFailure != nil { + count = previous.ExtractionFailure.Count + 1 + } + + f = &ExtractionFailure{Count: count} + if count > len(extractionRetryDelays) { + s.logger.Warn().Str("path", path).Int("failures", count).Msg("giving up on extracting the resource content until it changes, opencloud search index --force-rescan tries again") + return f, true + } + retryAt := time.Now().Add(extractionRetryDelays[count-1]) + f.RetryAt = &retryAt + return f, true } func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 5ebef078e7..27724b5176 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -2,6 +2,8 @@ package search_test import ( "context" + "errors" + "fmt" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -157,12 +159,27 @@ var _ = Describe("Searchprovider", func() { info("outdated", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), info("missing", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), info("trashed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-due", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-waiting", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-given-up", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), + info("failed-given-up-changed", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000), + info("failed-unreachable", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000), } indexed := map[string]*search.Resource{ "storageid$spaceid!spaceid": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}}, "storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Deleted: true}, + "storageid$spaceid!failed-due": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 1, RetryAt: ptr(time.Now().Add(-time.Minute))}}, + "storageid$spaceid!failed-waiting": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 2, RetryAt: ptr(time.Now().Add(time.Hour))}}, + "storageid$spaceid!failed-given-up": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + "storageid$spaceid!failed-given-up-changed": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + "storageid$spaceid!failed-unreachable": {Document: content.Document{Mtime: &indexedAt}, + ExtractionFailure: &search.ExtractionFailure{}}, } gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{ @@ -201,11 +218,23 @@ var _ = Describe("Searchprovider", func() { err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false) Expect(err).ShouldNot(HaveOccurred()) - Expect(upserted).To(ConsistOf("storageid$spaceid!outdated", "storageid$spaceid!missing", "storageid$spaceid!trashed")) + Expect(upserted).To(ConsistOf( + "storageid$spaceid!outdated", + "storageid$spaceid!missing", + "storageid$spaceid!trashed", + "storageid$spaceid!failed-due", + "storageid$spaceid!failed-given-up-changed", + "storageid$spaceid!failed-unreachable", + )) }) }) - Describe("UpsertItem", func() { + Describe("indexing a resource in full", func() { + BeforeEach(func() { + // a resource the index does not hold yet takes the full path + indexClient.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(search.ErrResourceNotFound) + }) + DescribeTable("marks a resource hidden when a dot starts one of its names", func(path string, hidden bool) { info := &sprovider.ResourceInfo{ @@ -230,7 +259,7 @@ var _ = Describe("Searchprovider", func() { indexed = args.Get(1).(search.Resource) }).Return(nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(indexed.Hidden).To(Equal(hidden)) }, Entry("./documents/notes.txt", "./documents/notes.txt", false), @@ -243,6 +272,86 @@ var _ = Describe("Searchprovider", func() { Entry("/", "/", false), ) + DescribeTable("indexes an unparsable resource by name and counts the failures of its version", + func(previous *search.Resource, count int, retryIn time.Duration) { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, fmt.Errorf("%w %q", content.ErrUnparsable, "scan.png")) + if previous == nil { + indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound) + } else { + indexClient.On("Get", mock.Anything, mock.Anything).Return(previous, nil) + } + + var indexed search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = args.Get(1).(search.Resource) + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) + Expect(indexed.Name).To(Equal("scan.png")) + Expect(indexed.ExtractionFailure).ToNot(BeNil()) + Expect(indexed.ExtractionFailure.Count).To(Equal(count)) + if retryIn == 0 { + Expect(indexed.ExtractionFailure.RetryAt).To(BeNil()) + } else { + Expect(indexed.ExtractionFailure.RetryAt).NotTo(BeNil()) + Expect(*indexed.ExtractionFailure.RetryAt).To(BeTemporally("~", time.Now().Add(retryIn), time.Minute)) + } + }, + Entry("first failure", nil, 1, time.Hour), + Entry("second failure of the same version", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 1}}, + 2, 24*time.Hour), + Entry("third failure of the same version gives up", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 2}}, + 3, time.Duration(0)), + Entry("a new version starts over", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(3000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + 1, time.Hour), + ) + + DescribeTable("indexes a resource by name without counting when tika or the file is unreachable", + func(previous *search.Resource, getErr error, written bool) { + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, errors.New("connection refused")) + indexClient.On("Get", mock.Anything, mock.Anything).Return(previous, getErr) + + var indexed []search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = append(indexed, args.Get(1).(search.Resource)) + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: ri.GetId()}) + if !written { + Expect(indexed).To(BeEmpty()) + return + } + Expect(indexed).To(HaveLen(1)) + Expect(indexed[0].Name).To(Equal("scan.png")) + Expect(indexed[0].ExtractionFailure).To(Equal(&search.ExtractionFailure{})) + }, + Entry("a new resource", nil, search.ErrResourceNotFound, true), + Entry("an outdated entry", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(3000, 0)), Content: "old"}}, + nil, true), + Entry("an outdated entry with parse failures starts over", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(3000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 2}}, + nil, true), + Entry("a current entry keeps its content", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0)), Content: "extracted"}}, + nil, false), + Entry("a current entry keeps its parse failures", + &search.Resource{Document: content.Document{Mtime: ptr(time.Unix(4000, 0))}, ExtractionFailure: &search.ExtractionFailure{Count: 3}}, + nil, false), + Entry("an unknown entry is left alone", nil, errors.New("index unavailable"), false), + ) + Context("with facets stored on the resource", func() { var ( info *sprovider.ResourceInfo @@ -292,7 +401,7 @@ var _ = Describe("Searchprovider", func() { Photo: &libregraph.Photo{CameraMake: libregraph.PtrString("Nikon")}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"set", "unset"})) Expect(set).To(Equal(map[string]string{"libre.graph.photo.cameraMake": "Nikon"})) Expect(unset).To(ConsistOf("libre.graph.photo.iso", "libre.graph.location.altitude")) @@ -301,7 +410,7 @@ var _ = Describe("Searchprovider", func() { It("removes all facets when the extraction produces none", func() { extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"unset"})) Expect(unset).To(ConsistOf("libre.graph.photo.cameraMake", "libre.graph.photo.iso", "libre.graph.location.altitude")) }) @@ -313,7 +422,7 @@ var _ = Describe("Searchprovider", func() { Location: &libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(12)}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"unset"})) Expect(unset).To(ConsistOf("libre.graph.retiredFacet.field")) }) @@ -324,7 +433,7 @@ var _ = Describe("Searchprovider", func() { Location: &libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(12), Latitude: libregraph.PtrFloat64(48.1)}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(Equal([]string{"set"})) Expect(set).To(Equal(map[string]string{ "libre.graph.photo.iso": "200", @@ -338,7 +447,15 @@ var _ = Describe("Searchprovider", func() { Location: &libregraph.GeoCoordinates{Altitude: libregraph.PtrFloat64(12)}, }, nil) - s.UpsertItem(&sprovider.Reference{ResourceId: info.GetId()}) + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + Expect(calls).To(BeEmpty()) + }) + + It("keeps the stored facets when the extraction failed", func() { + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, content.ErrUnparsable) + indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) Expect(calls).To(BeEmpty()) }) }) @@ -384,6 +501,71 @@ var _ = Describe("Searchprovider", func() { Entry("a traversal out of a dot folder", "./.git/../notes.txt", false), ) + Describe("UpdateMetadata", func() { + var info *sprovider.ResourceInfo + + BeforeEach(func() { + info = &sprovider.ResourceInfo{ + Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "tagged-opaqueid"}, + ParentId: &sprovider.ResourceId{StorageId: "storageid", OpaqueId: "parentopaqueid"}, + Path: "./report.pdf", + Size: 12345, + ArbitraryMetadata: &sprovider.ArbitraryMetadata{ + Metadata: map[string]string{"tags": "alpha,beta"}, + }, + Opaque: &typesv1beta1.Opaque{ + Map: map[string]*typesv1beta1.OpaqueEntry{ + "favorites": {Decoder: "json", Value: []byte(`["user-1"]`)}, + }, + }, + } + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: info, + }, nil) + gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool { + return req.GetResourceId().GetOpaqueId() == info.GetId().GetOpaqueId() + })).Return(&sprovider.GetPathResponse{ + Status: status.NewOK(context.Background()), + Path: info.GetPath(), + }, nil) + }) + + It("rewrites the tags and favorites without extracting the content", func() { + indexClient.On("Update", mock.Anything, "storageid$spaceid!tagged-opaqueid", search.MetadataUpdate{ + Tags: []string{"alpha", "beta"}, + Favorites: []string{"user-1"}, + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + indexClient.AssertNumberOfCalls(GinkgoT(), "Update", 1) + extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything) + indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything) + }) + + It("indexes the resource in full when the index does not hold it yet", func() { + indexClient.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(search.ErrResourceNotFound) + extractor.On("Extract", mock.Anything, mock.Anything).Return(content.Document{Tags: []string{"alpha", "beta"}}, nil) + + var indexed search.Resource + indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + indexed = args.Get(1).(search.Resource) + }).Return(nil) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + Expect(indexed.ID).To(Equal("storageid$spaceid!tagged-opaqueid")) + gatewayClient.AssertNumberOfCalls(GinkgoT(), "Stat", 1) + }) + + It("does not extract the content when the update fails for another reason", func() { + indexClient.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(errors.New("cluster unavailable")) + + s.UpdateMetadata(&sprovider.Reference{ResourceId: info.GetId()}) + extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything) + indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything) + }) + }) + Describe("Search", func() { It("fails when an empty query is given", func() { res, err := s.Search(ctx, &searchsvc.SearchRequest{ @@ -843,3 +1025,7 @@ var _ = DescribeTable("Parse Scope", `1234$5678!90`, ), ) + +func ptr[T any](v T) *T { + return &v +} diff --git a/services/search/pkg/service/event/service.go b/services/search/pkg/service/event/service.go index f3becfe0d3..86c277b423 100644 --- a/services/search/pkg/service/event/service.go +++ b/services/search/pkg/service/event/service.go @@ -205,10 +205,10 @@ func (s Service) processEvent(e raw.Event) error { case events.FileVersionRestored: debounce(getSpaceID(ev.Ref), false) case events.TagsAdded: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) debounce(getSpaceID(ev.Ref), false) case events.TagsRemoved: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) debounce(getSpaceID(ev.Ref), false) case events.FileUploaded: debounce(getSpaceID(ev.Ref), false) @@ -240,9 +240,9 @@ func (s Service) processEvent(e raw.Event) error { s.log.Error().Err(err).Interface("spaceID", ev.ID).Msg("failed to remove space from the skipped spaces bucket") } case events.LabelAdded: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) case events.LabelRemoved: - s.index.UpsertItem(ev.Ref) + s.index.UpdateMetadata(ev.Ref) default: s.log.Error().Interface("event", e).Msg("unhandled event type, acknowledged without indexing") } diff --git a/services/search/pkg/service/event/service_test.go b/services/search/pkg/service/event/service_test.go index 4c81f412d0..b54fc76113 100644 --- a/services/search/pkg/service/event/service_test.go +++ b/services/search/pkg/service/event/service_test.go @@ -57,16 +57,16 @@ var _ = DescribeTable("event", Entry("SpaceDeleted", []string{"PurgeSpace"}, events.SpaceDeleted{}, false), Entry("ItemPurged", []string{"PurgeItem"}, events.ItemPurged{}, false), Entry("TrashbinPurged", []string{"PurgeDeleted"}, events.TrashbinPurged{}, false), - Entry("LabelAdded", []string{"UpsertItem"}, events.LabelAdded{}, false), - Entry("LabelRemoved", []string{"UpsertItem"}, events.LabelRemoved{}, false), + Entry("LabelAdded", []string{"UpdateMetadata"}, events.LabelAdded{}, false), + Entry("LabelRemoved", []string{"UpdateMetadata"}, events.LabelRemoved{}, false), Entry("ItemTrashed", []string{"TrashItem", "IndexSpace"}, events.ItemTrashed{}, false), Entry("ItemMoved", []string{"MoveItem", "IndexSpace"}, events.ItemMoved{}, false), Entry("ItemRestored", []string{"RestoreItem", "IndexSpace"}, events.ItemRestored{}, false), Entry("ContainerCreated", []string{"IndexSpace"}, events.ContainerCreated{}, false), Entry("FileTouched", []string{"IndexSpace"}, events.FileTouched{}, false), Entry("FileVersionRestored", []string{"IndexSpace"}, events.FileVersionRestored{}, false), - Entry("TagsAdded", []string{"UpsertItem", "IndexSpace"}, events.TagsAdded{}, false), - Entry("TagsRemoved", []string{"UpsertItem", "IndexSpace"}, events.TagsRemoved{}, false), + Entry("TagsAdded", []string{"UpdateMetadata", "IndexSpace"}, events.TagsAdded{}, false), + Entry("TagsRemoved", []string{"UpdateMetadata", "IndexSpace"}, events.TagsRemoved{}, false), Entry("FileUploaded", []string{"IndexSpace"}, events.FileUploaded{}, false), Entry("UploadReady", []string{"IndexSpace"}, events.UploadReady{ExecutingUser: &userv1beta1.User{}}, true), )