mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-11-26 18:16:47 -05:00
fix(search): keep tika out of tag updates and retry incomplete extractions
This commit is contained in:
1 parent
0b73e9ecf8
commit
4e3d952c13
15 files changed
+486
-17
No files matched your search
@@ -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,31 @@ 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 cannot be overwritten with the document as it was before
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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,57 @@ 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"}
|
||||
childResource.Extracted = true
|
||||
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(r.Extracted).To(BeTrue())
|
||||
|
||||
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{})
|
||||
|
||||
@@ -30,6 +30,19 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"Extracted": {
|
||||
"enabled": true,
|
||||
"dynamic": true,
|
||||
"fields": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"store": true,
|
||||
"index": true,
|
||||
"include_in_all": true,
|
||||
"docvalues": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"Favorites": {
|
||||
"enabled": true,
|
||||
"dynamic": true,
|
||||
|
||||
@@ -82,8 +82,9 @@ 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("tika returned no metadata for %q", ri.GetName())
|
||||
}
|
||||
|
||||
for _, meta := range metas {
|
||||
|
||||
@@ -99,6 +99,17 @@ 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(ContainSubstring("report.pdf")))
|
||||
})
|
||||
|
||||
It("adds the title", func() {
|
||||
fullResponse = `[{"dc:title": "quarterly report", "X-TIKA:content": "some data"}]`
|
||||
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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,69 @@ 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"}
|
||||
document.Extracted = true
|
||||
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(r.Extracted).To(BeTrue())
|
||||
|
||||
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))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,9 @@
|
||||
"Deleted": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"Extracted": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"Favorites": {
|
||||
"type": "keyword"
|
||||
},
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -426,6 +426,46 @@ func (_c *Searcher_TrashItem_Call) RunAndReturn(run func(resourceID *providerv1b
|
||||
return _c
|
||||
}
|
||||
|
||||
// UpdateMetadata provides a mock function for the type Searcher
|
||||
func (_mock *Searcher) UpdateMetadata(ref *providerv1beta1.Reference) {
|
||||
_mock.Called(ref)
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// UpdateMetadata is a helper method to define mock.On call
|
||||
// - ref *providerv1beta1.Reference
|
||||
func (_e *Searcher_Expecter) UpdateMetadata(ref any) *Searcher_UpdateMetadata_Call {
|
||||
return &Searcher_UpdateMetadata_Call{Call: _e.mock.On("UpdateMetadata", ref)}
|
||||
}
|
||||
|
||||
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 {
|
||||
arg0 = args[0].(*providerv1beta1.Reference)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *Searcher_UpdateMetadata_Call) Return() *Searcher_UpdateMetadata_Call {
|
||||
_c.Call.Return()
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *Searcher_UpdateMetadata_Call) RunAndReturn(run func(ref *providerv1beta1.Reference)) *Searcher_UpdateMetadata_Call {
|
||||
_c.Run(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// UpsertItem provides a mock function for the type Searcher
|
||||
func (_mock *Searcher) UpsertItem(ref *providerv1beta1.Reference) {
|
||||
_mock.Called(ref)
|
||||
|
||||
@@ -50,10 +50,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 +85,9 @@ type Resource struct {
|
||||
Type uint64 `json:"Type"`
|
||||
Deleted bool `json:"Deleted"`
|
||||
Hidden bool `json:"Hidden"`
|
||||
// Extracted is set once the content extraction succeeded, a document
|
||||
// without it is extracted again on the next reindex
|
||||
Extracted bool `json:"Extracted"`
|
||||
}
|
||||
|
||||
// resourceFieldOverrides is built once (it never changes) and reused on hot
|
||||
|
||||
@@ -64,6 +64,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)
|
||||
}
|
||||
@@ -680,6 +681,43 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
|
||||
s.doUpsertItem(ctx, ref, nil)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
stat, _ := s.resInfo(ctx, ref)
|
||||
if stat == nil {
|
||||
return
|
||||
}
|
||||
|
||||
basic, err := content.NewBasicExtractor(s.logger)
|
||||
if err != nil {
|
||||
s.logger.Error().Err(err).Msg("failed to create the basic extractor")
|
||||
return
|
||||
}
|
||||
doc, err := 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.doUpsertItem(ctx, ref, 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.
|
||||
func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, batch BatchOperator) {
|
||||
stat, path := s.resInfo(ctx, ref)
|
||||
@@ -710,6 +748,7 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat
|
||||
Document: doc,
|
||||
}
|
||||
r.Hidden = IsHidden(r.Path)
|
||||
r.Extracted = true
|
||||
|
||||
if parentID := stat.GetInfo().GetParentId(); parentID != nil {
|
||||
r.ParentID = storagespace.FormatResourceID(parentID)
|
||||
@@ -895,7 +934,7 @@ func (s *Service) MoveItem(ref *provider.Reference) {
|
||||
}
|
||||
}
|
||||
|
||||
// isIndexed reports whether the index holds a live document for info that is at least as new
|
||||
// isIndexed reports whether the index holds a live, fully extracted 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()))
|
||||
switch {
|
||||
@@ -905,7 +944,7 @@ 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()))
|
||||
return !r.Deleted && r.Extracted && r.Mtime != nil && !r.Mtime.Before(utils.TSToTime(info.GetMtime()))
|
||||
}
|
||||
|
||||
func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package search_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
@@ -157,12 +158,14 @@ 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("unextracted", 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!spaceid": {Document: content.Document{Mtime: &indexedAt}, Extracted: true},
|
||||
"storageid$spaceid!current": {Document: content.Document{Mtime: &indexedAt}, Extracted: true},
|
||||
"storageid$spaceid!outdated": {Document: content.Document{Mtime: &indexedAt}, Extracted: true},
|
||||
"storageid$spaceid!trashed": {Document: content.Document{Mtime: &indexedAt}, Extracted: true, Deleted: true},
|
||||
"storageid$spaceid!unextracted": {Document: content.Document{Mtime: &indexedAt}},
|
||||
}
|
||||
|
||||
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
|
||||
@@ -201,7 +204,7 @@ 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!unextracted"))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -243,6 +246,22 @@ var _ = Describe("Searchprovider", func() {
|
||||
Entry("/", "/", false),
|
||||
)
|
||||
|
||||
It("marks the resource as extracted", func() {
|
||||
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{}, 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.UpsertItem(&sprovider.Reference{ResourceId: ri.GetId()})
|
||||
Expect(indexed.Extracted).To(BeTrue())
|
||||
})
|
||||
|
||||
Context("with facets stored on the resource", func() {
|
||||
var (
|
||||
info *sprovider.ResourceInfo
|
||||
@@ -384,6 +403,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"))
|
||||
Expect(indexed.Extracted).To(BeTrue())
|
||||
})
|
||||
|
||||
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{
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user