fix(search): descend into unchanged folders and skip failed uploads

This commit is contained in:
Florian Schade committed 2026-11-23 15:33:09 +01:00
1 parent 43211c135b
commit 4c25436e4e
12 files changed
+295 -13

No files matched your search

+4
View File
@@ -174,6 +174,10 @@ func (b *Backend) Search(_ context.Context, sir *searchService.SearchIndexReques
}, nil
}
func (b *Backend) Get(_ context.Context, id string) (*search.Resource, error) {
return searchResourceByID(id, b.index)
}
func (b *Backend) DocCount() (uint64, error) {
return b.index.DocCount()
}
+30
View File
@@ -1,7 +1,9 @@
package bleve_test
import (
"context"
"fmt"
"time"
bleveSearch "github.com/blevesearch/bleve/v2"
sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
@@ -108,6 +110,34 @@ var _ = Describe("Bleve", func() {
})
})
Describe("Get", func() {
It("returns the indexed resource with its exact mtime", func() {
mtime := time.Unix(1700000000, 123456789).UTC()
childResource.Mtime = &mtime
Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed())
r, err := eng.Get(context.Background(), childResource.ID)
Expect(err).ToNot(HaveOccurred())
Expect(r.ID).To(Equal(childResource.ID))
Expect(r.Mtime).ToNot(BeNil())
Expect(r.Mtime.Equal(mtime)).To(BeTrue(), "got %s", r.Mtime)
})
It("returns a trashed resource", func() {
childResource.Deleted = true
Expect(eng.Upsert(childResource.ID, childResource)).To(Succeed())
r, err := eng.Get(context.Background(), childResource.ID)
Expect(err).ToNot(HaveOccurred())
Expect(r.Deleted).To(BeTrue())
})
It("fails with ErrResourceNotFound for an unknown id", func() {
_, err := eng.Get(context.Background(), "1$2!unknown")
Expect(err).To(MatchError(search.ErrResourceNotFound))
})
})
Describe("New", func() {
It("returns a new index instance", func() {
b := bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.Logger{})
+1 -1
View File
@@ -256,7 +256,7 @@ func searchResourceByID(id string, index bleve.Index) (*search.Resource, error)
return nil, err
}
if res.Hits.Len() == 0 {
return nil, errors.New("entity not found")
return nil, search.ErrResourceNotFound
}
return matchToResource(res.Hits[0]), nil
@@ -169,6 +169,15 @@ func (b *Backend) Search(ctx context.Context, sir *searchService.SearchIndexRequ
}, nil
}
func (b *Backend) Get(ctx context.Context, id string) (*search.Resource, error) {
resource, err := searchResourceByID(ctx, b.client, b.index, id)
if err != nil {
return nil, err
}
return &resource, nil
}
func (b *Backend) DocCount() (uint64, error) {
req, err := osu.BuildIndicesCountReq(
&opensearchgoAPI.IndicesCountReq{
@@ -3,6 +3,7 @@ package opensearch_test
import (
"context"
"testing"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@@ -12,6 +13,7 @@ import (
"github.com/opencloud-eu/opencloud/pkg/log"
"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"
)
func TestOpenSearchBackend(t *testing.T) {
@@ -80,4 +82,49 @@ var _ = Describe("Backend", func() {
})
})
Describe("Get", func() {
const indexName = "opencloud-test-engine-lookup"
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())
})
It("returns the indexed resource with its exact mtime", func() {
mtime := time.Unix(1700000000, 123456789).UTC()
document := opensearchtest.Testdata.Resources.File
document.Mtime = &mtime
Expect(backend.Upsert(document.ID, document)).To(Succeed())
r, err := backend.Get(context.Background(), document.ID)
Expect(err).ToNot(HaveOccurred())
Expect(r.ID).To(Equal(document.ID))
Expect(r.Mtime).ToNot(BeNil())
Expect(r.Mtime.Equal(mtime)).To(BeTrue(), "got %s", r.Mtime)
})
It("returns a trashed resource", func() {
document := opensearchtest.Testdata.Resources.File
document.Deleted = true
Expect(backend.Upsert(document.ID, document)).To(Succeed())
r, err := backend.Get(context.Background(), document.ID)
Expect(err).ToNot(HaveOccurred())
Expect(r.Deleted).To(BeTrue())
})
It("fails with ErrResourceNotFound for an unknown id", func() {
_, err := backend.Get(context.Background(), "1$2!unknown")
Expect(err).To(MatchError(search.ErrResourceNotFound))
})
})
})
+1 -1
View File
@@ -28,7 +28,7 @@ func searchResourceByID(ctx context.Context, client *opensearchgoAPI.Client, ind
case err != nil:
return search.Resource{}, fmt.Errorf("failed to search for resource: %w", err)
case resp.Hits.Total.Value == 0 || len(resp.Hits.Hits) == 0:
return search.Resource{}, fmt.Errorf("document with id %s not found", id)
return search.Resource{}, fmt.Errorf("document with id %s: %w", id, search.ErrResourceNotFound)
}
resource, err := conversions.To[search.Resource](resp.Hits.Hits[0].Source)
@@ -143,6 +143,74 @@ func (_c *Engine_DocCount_Call) RunAndReturn(run func() (uint64, error)) *Engine
return _c
}
// Get provides a mock function for the type Engine
func (_mock *Engine) Get(ctx context.Context, id string) (*search.Resource, error) {
ret := _mock.Called(ctx, id)
if len(ret) == 0 {
panic("no return value specified for Get")
}
var r0 *search.Resource
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (*search.Resource, error)); ok {
return returnFunc(ctx, id)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) *search.Resource); ok {
r0 = returnFunc(ctx, id)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*search.Resource)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, id)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Engine_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
type Engine_Get_Call struct {
*mock.Call
}
// Get is a helper method to define mock.On call
// - ctx context.Context
// - id string
func (_e *Engine_Expecter) Get(ctx any, id any) *Engine_Get_Call {
return &Engine_Get_Call{Call: _e.mock.On("Get", ctx, id)}
}
func (_c *Engine_Get_Call) Run(run func(ctx context.Context, id string)) *Engine_Get_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)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *Engine_Get_Call) Return(resource *search.Resource, err error) *Engine_Get_Call {
_c.Call.Return(resource, err)
return _c
}
func (_c *Engine_Get_Call) RunAndReturn(run func(ctx context.Context, id string) (*search.Resource, error)) *Engine_Get_Call {
_c.Call.Return(run)
return _c
}
// Move provides a mock function for the type Engine
func (_mock *Engine) Move(id string, parentID string, targetPath string) error {
ret := _mock.Called(id, parentID, targetPath)
+4
View File
@@ -35,6 +35,9 @@ const SchemaVersion = 5
// the scope clause is removed together with the boolean operator that joins it to the rest of the query.
var scopeRegex = regexp.MustCompile(`(?:(?:AND|OR)\s+)?scope:\s*([^" "\n\r]*)(?:\s+(?:AND|OR)\b)?`)
// ErrResourceNotFound is returned when the index holds no document with the requested id
var ErrResourceNotFound = errors.New("resource not found")
// Engine is the interface to the search engine
type Engine interface {
Search(ctx context.Context, req *searchService.SearchIndexRequest) (*searchService.SearchIndexResponse, error)
@@ -46,6 +49,7 @@ type Engine interface {
Restore(id string) error
Purge(id string, onlyDeleted bool) error
PurgeSpace(rootID string) error
Get(ctx context.Context, id string) (*Resource, error)
NewBatch(batchSize int) (BatchOperator, error)
}
+16 -9
View File
@@ -577,15 +577,9 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool)
return nil
}
searchRes, err := s.engine.Search(session.Ctx(), &searchsvc.SearchIndexRequest{
Query: "id:" + storagespace.FormatResourceID(info.Id) + ` mtime>=` + utils.TSToTime(info.Mtime).Format(time.RFC3339Nano),
})
if err == nil && len(searchRes.Matches) >= 1 {
if info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
s.logger.Debug().Str("path", ref.Path).Msg("subtree hasn't changed. Skipping.")
return filepath.SkipDir
}
// an unchanged folder is still descended into: its mtime only follows its direct
// children, so files below it that an interrupted run left unindexed would be skipped forever
if s.isIndexed(session.Ctx(), info) {
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
return nil
}
@@ -901,6 +895,19 @@ func (s *Service) MoveItem(ref *provider.Reference) {
}
}
// 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()))
switch {
case errors.Is(err, ErrResourceNotFound):
return false
case err != nil:
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()))
}
func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (*provider.StatResponse, string) {
statRes, err := statResource(ctx, ref, s.gatewaySelector, s.logger)
if err != nil {
+67 -1
View File
@@ -2,6 +2,7 @@ package search_test
import (
"context"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
@@ -128,7 +129,7 @@ var _ = Describe("Searchprovider", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
indexClient.On("NewBatch", mock.Anything).Return(batch, nil)
batch.On("Upsert", mock.Anything, mock.Anything).Return(nil)
indexClient.On("Search", mock.Anything, mock.Anything).Return(&searchsvc.SearchIndexResponse{}, nil)
indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound)
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: ri,
@@ -137,6 +138,71 @@ var _ = Describe("Searchprovider", func() {
err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)
Expect(err).ShouldNot(HaveOccurred())
})
It("descends into an unchanged folder and indexes only what is missing or outdated below it", func() {
indexedAt := time.Unix(4000, 0)
info := func(id string, t sprovider.ResourceType, seconds uint64) *sprovider.ResourceInfo {
return &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: id},
ParentId: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: t,
Path: id,
Mtime: &typesv1beta1.Timestamp{Seconds: seconds},
}
}
root := info("spaceid", sprovider.ResourceType_RESOURCE_TYPE_CONTAINER, 4000)
root.Path = "."
children := []*sprovider.ResourceInfo{
info("current", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000),
info("outdated", sprovider.ResourceType_RESOURCE_TYPE_FILE, 5000),
info("missing", sprovider.ResourceType_RESOURCE_TYPE_FILE, 4000),
info("trashed", 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},
}
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *sprovider.StatRequest, _ ...grpc.CallOption) (*sprovider.StatResponse, error) {
for _, child := range children {
if req.GetRef().GetPath() == "./"+child.GetPath() {
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: child}, nil
}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: root}, nil
})
gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(&sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: children,
}, nil)
indexClient.On("Get", mock.Anything, mock.Anything).Return(
func(_ context.Context, id string) (*search.Resource, error) {
if r, ok := indexed[id]; ok {
return r, nil
}
return nil, search.ErrResourceNotFound
})
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
var upserted []string
batch := &engineMocks.BatchOperator{}
batch.EXPECT().Push().Return(nil)
batch.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
upserted = append(upserted, args.String(0))
}).Return(nil)
indexClient.On("NewBatch", mock.Anything).Return(batch, nil)
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"))
})
})
Describe("UpsertItem", func() {
+4 -1
View File
@@ -213,7 +213,10 @@ func (s Service) processEvent(e raw.Event) error {
case events.FileUploaded:
debounce(getSpaceID(ev.Ref), false)
case events.UploadReady:
debounce(getSpaceID(ev.FileRef), false)
// a failed upload left nothing new to index
if !ev.Failed {
debounce(getSpaceID(ev.FileRef), false)
}
case events.SpaceRenamed:
debounce(ev.ID, false)
case events.SpaceEnabled:
@@ -2,9 +2,12 @@ package event_test
import (
"context"
"slices"
"sync"
"sync/atomic"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/pkg/log"
@@ -67,3 +70,44 @@ var _ = DescribeTable("event",
Entry("FileUploaded", []string{"IndexSpace"}, events.FileUploaded{}, false),
Entry("UploadReady", []string{"IndexSpace"}, events.UploadReady{ExecutingUser: &userv1beta1.User{}}, true),
)
var _ = It("does not index the space of a failed upload", func() {
var (
s = &searchMocks.Searcher{}
mu sync.Mutex
indexed []string
)
indexedSpaces := func() []string {
mu.Lock()
defer mu.Unlock()
return slices.Clone(indexed)
}
stream := rawMocks.NewStream(GinkgoT())
ch := make(chan raw.Event, 2)
stream.EXPECT().Consume(mock.Anything, mock.Anything).Return((<-chan raw.Event)(ch), nil)
svc, err := event.New(context.Background(), stream, log.NewLogger(), nil, nil, s, search.NewSkippedSpaces(nil), 50, 1, true)
Expect(err).NotTo(HaveOccurred())
go func() {
defer GinkgoRecover()
Expect(svc.Run()).To(Succeed())
}()
defer svc.Close()
s.On("IndexSpace", mock.Anything, mock.Anything).Return(nil).Run(func(args mock.Arguments) {
mu.Lock()
defer mu.Unlock()
indexed = append(indexed, args.Get(0).(*provider.StorageSpaceId).GetOpaqueId())
})
ref := func(spaceID string) *provider.Reference {
return &provider.Reference{ResourceId: &provider.ResourceId{StorageId: "storageid", SpaceId: spaceID}}
}
// the successful upload of another space marks when the failed one would have been indexed
ch <- raw.Event{Event: events.Event{Event: events.UploadReady{ExecutingUser: &userv1beta1.User{}, FileRef: ref("failed"), Failed: true}}}
ch <- raw.Event{Event: events.Event{Event: events.UploadReady{ExecutingUser: &userv1beta1.User{}, FileRef: ref("succeeded")}}}
Eventually(indexedSpaces, "2s").Should(ContainElement("storageid$succeeded"))
Consistently(indexedSpaces, "200ms").Should(Equal([]string{"storageid$succeeded"}))
})