fix(stable-9.0-PR13034): don't abort a reindex on unresolvable files; make the abort threshold configurable

Backport of PR #13034
This commit is contained in:
Paul Faure authored and Martin Mattel committed 2026-10-31 15:39:14 +01:00
1 parent 143dc02b93
commit b4a6238bdd
9 files changed
+587 -41

No files matched your search

@@ -0,0 +1,31 @@
Bugfix: Reindex no longer aborts on unresolvable files; threshold configurable
`IndexSpace` aborted the walk after 5 consecutive files failed, on the assumption
that the content extractor was down. Two things made that fire on healthy
systems:
1. A file the walker listed but that could not be stat'ed by its path (a node
whose stored name no longer matched its directory entry) counted as an
extraction failure. The extractor was never involved.
2. The counter only ever saw files that actually needed work. On a space that
was already almost fully indexed, five problem files scattered anywhere in
walk order looked "consecutive", the walk aborted at the same point every
time, and nothing after that point was indexed until the files were fixed
by hand.
The walk still resolves each file by its path. When Stat by path does not find
a file, the walk tries again with the ID it listed, so such a node is indexed.
A healthy file costs no extra GetPath call. A file that Stat or GetPath does not find (CODE_NOT_FOUND, deleted
since it was listed) is skipped without counting; auth, gateway, transport and
deadline failures still count. Because the gateway also answers NOT_FOUND when
it cannot reach a storage provider, a walk in which at least 5 files, and more
than half of the files that needed work, were not found ends with an error
instead of reporting the space as indexed. Already-indexed, unchanged files
reset the counter, a cancelled or timed-out walk (including its retry waits)
stops with an error, and each walk logs a summary of indexed, unchanged, failed
and not-found files. The threshold became configurable with
`SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES` (default 5, unchanged; 0 never
aborts and logs a warning at startup; negative values are rejected).
https://github.com/owncloud/ocis/pull/13034
https://github.com/owncloud/ocis/issues/13033
+2
View File
@@ -5,6 +5,8 @@ type Extractor struct {
Type string `yaml:"type" env:"SEARCH_EXTRACTOR_TYPE" desc:"Defines the content extraction engine. Defaults to 'basic'. Supported values are: 'basic' and 'tika'." introductionVersion:"pre5.0"`
CS3AllowInsecure bool `yaml:"cs3_allow_insecure" env:"OCIS_INSECURE;SEARCH_EXTRACTOR_CS3SOURCE_INSECURE" desc:"Ignore untrusted SSL certificates when connecting to the CS3 source." introductionVersion:"pre5.0"`
Tika ExtractorTika `yaml:"tika"`
MaxConsecutiveFailures int `yaml:"max_consecutive_failures" env:"SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES" desc:"Abort a space (re)index walk after this many files in a row fail content extraction, which usually means the extraction service is down. Files that cannot be resolved at all are logged and skipped without counting towards this limit. Set to 0 to never abort." introductionVersion:"9.0.0"`
}
// ExtractorTika configures the Tika extractor
@@ -9,6 +9,10 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/config"
)
// defaultMaxConsecutiveFailures is the number of consecutive extraction
// failures after which a space (re)index walk gives up on the extractor.
const defaultMaxConsecutiveFailures = 5
// FullDefaultConfig returns a fully initialized default configuration
func FullDefaultConfig() *config.Config {
cfg := DefaultConfig()
@@ -46,6 +50,7 @@ func DefaultConfig() *config.Config {
TikaURL: "http://127.0.0.1:9998",
CleanStopWords: true,
},
MaxConsecutiveFailures: defaultMaxConsecutiveFailures,
},
Events: config.Events{
Endpoint: "127.0.0.1:9233",
@@ -2,6 +2,7 @@ package parser
import (
"errors"
"fmt"
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
@@ -44,6 +45,10 @@ func Validate(cfg *config.Config) error {
if cfg.ServiceAccount.ServiceAccountSecret == "" {
return shared.MissingServiceAccountSecret(cfg.Service.Name)
}
if cfg.Extractor.MaxConsecutiveFailures < 0 {
return fmt.Errorf("%s: SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES must be 0 (never abort) or greater, got %d",
cfg.Service.Name, cfg.Extractor.MaxConsecutiveFailures)
}
return nil
}
@@ -0,0 +1,44 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/search/pkg/config"
"github.com/owncloud/ocis/v2/services/search/pkg/config/defaults"
)
func validConfig() *config.Config {
cfg := defaults.DefaultConfig()
cfg.TokenManager = &config.TokenManager{JWTSecret: "secret"}
cfg.ServiceAccount = config.ServiceAccount{ServiceAccountID: "id", ServiceAccountSecret: "secret"}
return cfg
}
func TestDefaultMaxConsecutiveFailures(t *testing.T) {
assert.Equal(t, 5, defaults.DefaultConfig().Extractor.MaxConsecutiveFailures)
}
func TestValidateMaxConsecutiveFailures(t *testing.T) {
for _, tc := range []struct {
name string
value int
wantErr bool
}{
{name: "default", value: 5},
{name: "never abort", value: 0},
{name: "negative", value: -1, wantErr: true},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := validConfig()
cfg.Extractor.MaxConsecutiveFailures = tc.value
err := Validate(cfg)
if tc.wantErr {
assert.ErrorContains(t, err, "SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES")
return
}
assert.NoError(t, err)
})
}
}
@@ -0,0 +1,9 @@
package search
import "time"
// SetExtractionRetryDelay shortens the delay between extraction retries for a
// test.
func (s *Service) SetExtractionRetryDelay(d time.Duration) {
s.extractionRetryDelay = d
}
+25 -9
View File
@@ -23,6 +23,17 @@ import (
var scopeRegex = regexp.MustCompile(`scope:\s*([^" "\n\r]*)`)
var vaultRegex = regexp.MustCompile(`vault:\s*(\S+)`)
// errResourceNotFound is returned by statResource when Stat answers
// CODE_NOT_FOUND: the resource was deleted or moved since it was listed. The
// gateway also answers NOT_FOUND when it cannot reach the storage provider, so
// a run of them can mean an outage (see IndexSpace).
var errResourceNotFound = errors.New("resource not found")
// errPathNotResolved is returned by ResolveReference when GetPath answers with
// a non-OK status. When the status is CODE_NOT_FOUND, the error also matches
// errResourceNotFound.
var errPathNotResolved = errors.New("could not resolve the resource's path")
// ResolveReference makes sure the path is relative to the space root
func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider.ResourceInfo, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.Reference, error) {
if ref.GetResourceId().GetOpaqueId() == ref.GetResourceId().GetSpaceId() {
@@ -37,9 +48,16 @@ func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider
gpRes, err := gatewayClient.GetPath(ctx, &provider.GetPathRequest{
ResourceId: ri.GetId(),
})
if err != nil || gpRes.GetStatus().GetCode() != rpc.Code_CODE_OK {
if err != nil {
return nil, err
}
if code := gpRes.GetStatus().GetCode(); code != rpc.Code_CODE_OK {
if code == rpc.Code_CODE_NOT_FOUND {
// Deleted since the Stat, like a Stat that answers NOT_FOUND.
return nil, fmt.Errorf("%w: %w: %s", errPathNotResolved, errResourceNotFound, gpRes.GetStatus().GetMessage())
}
return nil, fmt.Errorf("%w: %s %s", errPathNotResolved, code, gpRes.GetStatus().GetMessage())
}
return &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: ref.GetResourceId().GetStorageId(),
@@ -80,7 +98,7 @@ func getAuthContext(ctx context.Context, serviceAccountID string, gatewaySelecto
return utils.GetServiceUserContextWithContext(ctx, gatewayClient, serviceAccountID, secret)
}
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], logger log.Logger) (*provider.StatResponse, error) {
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.StatResponse, error) {
gatewayClient, err := gatewaySelector.Next()
if err != nil {
return nil, err
@@ -88,19 +106,17 @@ func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector
res, err := gatewayClient.Stat(ctx, &provider.StatRequest{Ref: ref})
if err != nil {
logger.Error().Err(err).Msg("failed to stat the moved resource")
return nil, err
}
switch res.GetStatus().GetCode() {
switch code := res.GetStatus().GetCode(); code {
case rpc.Code_CODE_OK:
return res, nil
case rpc.Code_CODE_NOT_FOUND:
// Resource was moved or deleted in the meantime. ignore.
return nil, err
// Moved or deleted in the meantime, or a backend the gateway could
// not reach: the gateway answers NOT_FOUND for both.
return nil, errResourceNotFound
default:
err := errors.New("failed to stat the moved resource")
logger.Error().Interface("res", res).Msg(err.Error())
return nil, err
return nil, fmt.Errorf("stat failed: %s %s", code, res.GetStatus().GetMessage())
}
}
+145 -27
View File
@@ -24,6 +24,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/tags"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/fieldmaskpb"
@@ -75,6 +76,12 @@ type Service struct {
serviceAccountID string
serviceAccountSecret string
// maxConsecutiveFailures aborts an IndexSpace walk after this many
// consecutive extraction failures. 0 disables the abort.
maxConsecutiveFailures int
// extractionRetryDelay is the pause between extraction retries in IndexSpace.
extractionRetryDelay time.Duration
}
var errSkipSpace error
@@ -89,6 +96,13 @@ func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng e
serviceAccountID: cfg.ServiceAccount.ServiceAccountID,
serviceAccountSecret: cfg.ServiceAccount.ServiceAccountSecret,
maxConsecutiveFailures: cfg.Extractor.MaxConsecutiveFailures,
extractionRetryDelay: _extractionRetryDelay,
}
if s.maxConsecutiveFailures == 0 {
s.logger.Warn().Msg("SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES is 0: a space reindex never aborts, even when the content extractor is down")
}
return s
@@ -455,11 +469,15 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
return res, nil
}
// Retry constants for IndexSpace extraction failure handling.
// Retry and outage constants for IndexSpace.
const (
_extractionRetries = 5 // max retry attempts per file
_extractionRetryDelay = 1 * time.Second // delay between retries
_consecutiveAbort = 5 // abort walk after this many consecutive file failures
_extractionRetryDelay = 1 * time.Second // default delay between retries
// A walk in which at least _missingMinCount files were not found, and they
// are more than half of the files that needed work, fails at the end: the
// gateway answers NOT_FOUND when it cannot reach the storage provider, and
// that must not report the space as indexed.
_missingMinCount = 5
)
// IndexSpace (re)indexes all resources of a given space.
@@ -480,7 +498,14 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
}
rootID.OpaqueId = rootID.SpaceId
failures := 0
// failures counts extraction failures in a row. A file that was indexed or
// was already indexed and unchanged resets it; a file that is not found
// (deleted since it was listed) neither counts nor resets it.
var (
failures int
indexedCount, unchangedCount, failedCount int
missingCount int
)
w := walker.NewWalker(s.gatewaySelector)
err = w.Walk(ownerCtx, &rootID, func(wd string, info *provider.ResourceInfo, err error) error {
@@ -493,17 +518,22 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
return nil
}
// A cancelled or timed-out walk must stop with an error, not carry on
// with failing lookups.
if err := ownerCtx.Err(); err != nil {
return fmt.Errorf("index walk stopped: %w", err)
}
relPath := utils.MakeRelativePath(filepath.Join(wd, info.Path))
if slices.Contains(_skipPathDirs, relPath) {
s.logger.Info().Str("path", relPath).Msg("skipping directory from being indexed")
return filepath.SkipDir
}
ref := &provider.Reference{
Path: relPath,
ResourceId: &rootID,
if slices.Contains(_skipPathNames, relPath) {
return nil // the space root itself is never indexed
}
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
s.logger.Debug().Str("path", relPath).Msg("Walking tree")
// Skip nodes still in postprocessing — their blob isn't in the
// blobstore yet. Their own UploadReady will re-trigger IndexSpace.
if utils.ReadPlainFromOpaque(info.Opaque, "status") == "processing" {
@@ -523,32 +553,72 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
// With O(1) DocID lookups the cost is negligible.
return nil
}
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
s.logger.Debug().Str("path", relPath).Msg("element hasn't changed. Skipping.")
unchangedCount++
failures = 0
return nil
}
}
if err := s.upsertItem(ownerCtx, ref, _extractionRetries); err != nil {
// Resolve the node by its path. A stale node fails a Stat by path but
// the ID the walker listed still finds it. So retry by ID only after
// a not-found: a healthy file costs no extra GetPath call.
ref := &provider.Reference{Path: relPath, ResourceId: &rootID}
err = s.upsertItem(ownerCtx, ref, _extractionRetries)
if errors.Is(err, errResourceNotFound) && info.GetId() != nil {
s.logger.Debug().Str("path", relPath).Msg("resource not found by path, retrying by ID")
err = s.upsertItem(ownerCtx, &provider.Reference{ResourceId: info.GetId()}, _extractionRetries)
}
if err != nil {
if errors.Is(err, errResourceNotFound) {
missingCount++
s.logger.Debug().Err(err).Str("path", relPath).Msg("skipping resource that no longer exists")
return nil
}
failures++
failedCount++
s.logger.Warn().Err(err).
Int("failures", failures).
Str("path", ref.Path).
Str("path", relPath).
Msg("extraction failed after retries")
if failures >= _consecutiveAbort {
if s.maxConsecutiveFailures > 0 && failures >= s.maxConsecutiveFailures {
return fmt.Errorf("aborting index walk: %d consecutive extraction failures, last error: %w", failures, err)
}
return nil
}
indexedCount++
failures = 0
return nil
})
// The context check comes first: a walk cut short reports that, whatever
// the last file's error was.
if ctxErr := ownerCtx.Err(); ctxErr != nil {
return fmt.Errorf("index walk stopped: %w", ctxErr)
}
level := zerolog.InfoLevel
if failedCount > 0 || missingCount > 0 {
level = zerolog.WarnLevel
}
s.logger.WithLevel(level).Str("space", spaceID.GetOpaqueId()).
Int("indexed", indexedCount).
Int("unchanged", unchangedCount).
Int("failed", failedCount).
Int("not_found", missingCount).
Msg("index walk finished")
if err != nil {
return err
}
if attempted := indexedCount + failedCount + missingCount; missingCount >= _missingMinCount && missingCount*2 > attempted {
return fmt.Errorf("index walk incomplete: %d of %d files were not found, which suggests the storage provider was unreachable", missingCount, attempted)
}
logDocCount(s.engine, s.logger)
return nil
@@ -564,7 +634,12 @@ func (s *Service) TrashItem(_ context.Context, rID *provider.ResourceId) {
// UpsertItem indexes or stores Resource data fields.
func (s *Service) UpsertItem(ctx context.Context, ref *provider.Reference) {
if err := s.upsertItem(ctx, ref, 0); err != nil {
err := s.upsertItem(ctx, ref, 0)
switch {
case err == nil:
case errors.Is(err, errResourceNotFound):
s.logger.Debug().Err(err).Msg("resource to upsert no longer exists")
default:
s.logger.Error().Err(err).Msg("failed to upsert resource")
}
}
@@ -572,9 +647,9 @@ func (s *Service) UpsertItem(ctx context.Context, ref *provider.Reference) {
// upsertItem is the core extraction-and-index method. When retries > 0,
// a failed extraction is retried up to that many times with a fixed delay.
func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retries int) error {
ctx2, stat, path := s.resInfo(ctx, ref)
if ctx2 == nil || stat == nil || path == "" {
return fmt.Errorf("could not resolve resource info for %s", ref.GetPath())
ctx2, stat, path, err := s.resolve(ctx, ref)
if err != nil {
return fmt.Errorf("could not resolve resource info for %s: %w", refString(ref), err)
}
if slices.Contains(_skipPathNames, path) || slices.Contains(_skipPathDirs, path) {
@@ -592,7 +667,6 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
resourceID := storagespace.FormatResourceID(stat.Info.Id)
var doc content.Document
var err error
for attempt := range retries + 1 {
doc, err = s.extractor.Extract(ctx2, stat.Info)
if err == nil {
@@ -601,13 +675,19 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
if attempt < retries {
s.logger.Debug().Err(err).
Int("attempt", attempt+1).
Str("path", ref.Path).
Str("path", path).
Msg("extraction attempt failed, retrying")
time.Sleep(_extractionRetryDelay)
t := time.NewTimer(s.extractionRetryDelay)
select {
case <-ctx.Done():
t.Stop()
return fmt.Errorf("extraction for %s stopped: %w", path, ctx.Err())
case <-t.C:
}
}
}
if err != nil {
return fmt.Errorf("extraction failed for %s: %w", ref.Path, err)
return fmt.Errorf("extraction failed for %s: %w", path, err)
}
r := engine.Resource{
@@ -629,7 +709,7 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
}
if err = s.engine.Upsert(r.ID, r); err != nil {
return fmt.Errorf("index upsert for %s: %w", ref.Path, err)
return fmt.Errorf("index upsert for %s: %w", path, err)
}
logDocCount(s.engine, s.logger)
@@ -795,21 +875,59 @@ func (s *Service) MoveItem(ctx context.Context, ref *provider.Reference) {
}
}
// resInfo is resolve for the event handlers (UpdateTags, RestoreItem, MoveItem).
// It logs a failure once and returns nils, except when only the path could not
// be resolved: then it still returns the Stat result with an empty path, as
// before, so UpdateTags (which needs only the Stat result) still works.
func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (context.Context, *provider.StatResponse, string) {
ctx2, stat, path, err := s.resolve(ctx, ref)
switch {
case err == nil:
return ctx2, stat, path
case errors.Is(err, errPathNotResolved):
s.logger.Debug().Err(err).Str("ref", refString(ref)).Msg("could not resolve the resource's path")
return ctx2, stat, ""
case errors.Is(err, errResourceNotFound):
s.logger.Debug().Err(err).Str("ref", refString(ref)).Msg("resource no longer exists")
default:
s.logger.Warn().Err(err).Str("ref", refString(ref)).Msg("could not resolve resource info")
}
return nil, nil, ""
}
// resolve returns the auth context, Stat response and space-relative path of
// ref. Stat CODE_NOT_FOUND is errResourceNotFound and a non-OK GetPath is
// errPathNotResolved (with the Stat result still returned); every other
// failure (auth, gateway, transport, deadline) is returned as its own error.
func (s *Service) resolve(ctx context.Context, ref *provider.Reference) (context.Context, *provider.StatResponse, string, error) {
ownerCtx, err := getAuthContext(ctx, s.serviceAccountID, s.gatewaySelector, s.serviceAccountSecret, s.logger)
if err != nil {
return nil, nil, ""
return nil, nil, "", fmt.Errorf("auth context: %w", err)
}
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector, s.logger)
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector)
if err != nil {
return nil, nil, ""
return nil, nil, "", err
}
r, err := ResolveReference(ownerCtx, ref, statRes.GetInfo(), s.gatewaySelector)
if err != nil {
return nil, nil, ""
if errors.Is(err, errPathNotResolved) {
return ownerCtx, statRes, "", err
}
return nil, nil, "", fmt.Errorf("get path: %w", err)
}
if r.GetPath() == "" {
return ownerCtx, statRes, "", errPathNotResolved
}
return ownerCtx, statRes, r.GetPath()
return ownerCtx, statRes, r.GetPath(), nil
}
// refString describes ref for logs and errors: its path, or its resource ID.
func refString(ref *provider.Reference) string {
if p := ref.GetPath(); p != "" {
return p
}
return storagespace.FormatResourceID(ref.GetResourceId())
}
+321 -5
View File
@@ -9,6 +9,7 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
collaborationv1beta1 "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
@@ -26,6 +27,7 @@ import (
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
@@ -171,7 +173,7 @@ var _ = Describe("Searchprovider", func() {
indexClient.On("Lookup", mock.Anything).Return(nil, engine.ErrResourceNotFound)
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(sreq *sprovider.StatRequest) bool {
return sreq.Ref.ResourceId.StorageId == "storageid" &&
sreq.Ref.ResourceId.OpaqueId == "spaceid" &&
(sreq.Ref.ResourceId.OpaqueId == "spaceid" || sreq.Ref.ResourceId.OpaqueId == ri.Id.OpaqueId) &&
sreq.Ref.ResourceId.SpaceId == "spaceid"
})).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
@@ -179,6 +181,7 @@ var _ = Describe("Searchprovider", func() {
}, nil)
err := s.IndexSpace(context.Background(), &sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"})
Expect(err).ShouldNot(HaveOccurred())
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", 1)
})
It("walks the space skipping .space directory", func() {
@@ -256,11 +259,21 @@ var _ = Describe("Searchprovider", func() {
}
}
// Build path-to-fileInfo map for O(1) Stat dispatch.
fileInfoByPath := make(map[string]*sprovider.ResourceInfo, numDirs)
// Build ID-to-fileInfo and ID-to-path maps for O(1) Stat and GetPath dispatch.
fileInfoByID := make(map[string]*sprovider.ResourceInfo, numDirs)
filePathByID := make(map[string]string, numDirs)
for dirID, fi := range fileInfoByDir {
fileInfoByPath["./"+dirID+"/"+fi.Path] = fi
fileInfoByID[fi.Id.OpaqueId] = fi
filePathByID[fi.Id.OpaqueId] = "/" + dirID + "/" + fi.Path
}
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return fileInfoByID[req.GetResourceId().GetOpaqueId()] != nil
})).Return(
func(_ context.Context, req *sprovider.GetPathRequest, _ ...grpc.CallOption) *sprovider.GetPathResponse {
return &sprovider.GetPathResponse{Status: status.NewOK(context.Background()), Path: filePathByID[req.GetResourceId().GetOpaqueId()]}
},
func(_ context.Context, _ *sprovider.GetPathRequest, _ ...grpc.CallOption) error { return nil },
)
// Single Stat mock dispatching via map — avoids 10k separate matchers.
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
@@ -271,7 +284,7 @@ var _ = Describe("Searchprovider", func() {
Info: rootInfo,
}
}
if fi, ok := fileInfoByPath[sreq.Ref.Path]; ok {
if fi, ok := fileInfoByID[sreq.Ref.GetResourceId().GetOpaqueId()]; ok {
return &sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: fi,
@@ -382,6 +395,280 @@ var _ = Describe("Searchprovider", func() {
})
})
Describe("IndexSpace abort threshold", func() {
// A root container listing numFiles files. Stat by ID answers per the
// missing/statBroken sets, Stat by path per staleByPath; Lookup finds only
// the files in indexed, so every other file is attempted.
const numFiles = 6
var (
rootInfo *sprovider.ResourceInfo
fileInfos []*sprovider.ResourceInfo
missing map[string]bool // Stat answers NOT_FOUND
statBroken map[string]bool // Stat answers with an internal error
staleByPath map[string]bool // Stat by path answers NOT_FOUND, Stat by ID works
pathMissing map[string]bool // GetPath answers NOT_FOUND
pathBroken map[string]bool // GetPath answers with an internal error
indexed map[string]bool // already indexed and unchanged
newService = func(maxConsecutiveFailures int) *search.Service {
cfg := &config.Config{}
cfg.Extractor.MaxConsecutiveFailures = maxConsecutiveFailures
s := search.NewService(gatewaySelector, indexClient, extractor, logger, cfg)
s.SetExtractionRetryDelay(time.Millisecond)
return s
}
spaceID = &sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}
)
BeforeEach(func() {
missing = map[string]bool{}
statBroken = map[string]bool{}
staleByPath = map[string]bool{}
pathMissing = map[string]bool{}
pathBroken = map[string]bool{}
indexed = map[string]bool{}
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
rootInfo = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: ".",
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
fileInfos = make([]*sprovider.ResourceInfo, numFiles)
byID := map[string]*sprovider.ResourceInfo{}
for i := range fileInfos {
fileInfos[i] = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: fmt.Sprintf("file-%d", i)},
ParentId: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
Path: fmt.Sprintf("file-%d.pdf", i),
Size: 1024,
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
byID[fileInfos[i].Id.OpaqueId] = fileInfos[i]
}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, sreq *sprovider.StatRequest, _ ...grpc.CallOption) *sprovider.StatResponse {
id := sreq.GetRef().GetResourceId().GetOpaqueId()
if p := sreq.GetRef().GetPath(); p != "" && p != "." {
// By path, relative to the space root.
for _, fi := range fileInfos {
if "./"+fi.Path == p && !staleByPath[fi.Id.OpaqueId] {
id = fi.Id.OpaqueId
break
}
id = ""
}
}
switch {
case id == "spaceid":
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: rootInfo}
case statBroken[id]:
return &sprovider.StatResponse{Status: status.NewInternal(context.Background(), "storage unavailable")}
case missing[id] || byID[id] == nil:
return &sprovider.StatResponse{Status: status.NewNotFound(context.Background(), id)}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: byID[id]}
},
func(_ context.Context, _ *sprovider.StatRequest, _ ...grpc.CallOption) error { return nil },
)
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return byID[req.GetResourceId().GetOpaqueId()] != nil
})).Return(
func(_ context.Context, req *sprovider.GetPathRequest, _ ...grpc.CallOption) *sprovider.GetPathResponse {
id := req.GetResourceId().GetOpaqueId()
switch {
case pathMissing[id]:
return &sprovider.GetPathResponse{Status: status.NewNotFound(context.Background(), id)}
case pathBroken[id]:
return &sprovider.GetPathResponse{Status: status.NewInternal(context.Background(), "storage unavailable")}
}
return &sprovider.GetPathResponse{Status: status.NewOK(context.Background()), Path: "/" + byID[id].Path}
},
func(_ context.Context, _ *sprovider.GetPathRequest, _ ...grpc.CallOption) error { return nil },
)
gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(&sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: fileInfos,
}, nil)
indexClient.On("Lookup", mock.Anything).Return(
func(id string) *engine.Resource {
if indexed[id] {
return &engine.Resource{ID: id, Extracted: true, Document: content.Document{Mtime: time.Unix(6000, 0).UTC().Format(time.RFC3339Nano)}}
}
return nil
},
func(id string) error {
if indexed[id] {
return nil
}
return engine.ErrResourceNotFound
},
)
indexClient.On("Upsert", mock.Anything, mock.Anything).Return(nil)
})
It("does not count a file that no longer exists towards the abort threshold", func() {
missing["file-0"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "a file deleted since it was listed is skipped, never counted")
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles-1)
})
It("keeps the failure count across a file that no longer exists", func() {
// Only file-0 and file-2 fail extraction. file-1 is gone between them.
// It neither counts nor resets the counter, so a threshold of 2
// aborts at file-2, before the healthy file-3 could reset it.
missing["file-1"] = true
extractor.On("Extract", mock.Anything, mock.MatchedBy(func(ri *sprovider.ResourceInfo) bool {
return ri.GetId().GetOpaqueId() == "file-0" || ri.GetId().GetOpaqueId() == "file-2"
}), mock.Anything).Return(content.Document{}, errors.New("extractor down"))
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
})
It("fails the walk when most files are not found, as in a storage provider outage", func() {
// The gateway answers NOT_FOUND when it cannot reach the provider.
for _, fi := range fileInfos {
missing[fi.Id.OpaqueId] = true
}
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "an outage must not report the space as indexed")
Expect(err.Error()).To(ContainSubstring(fmt.Sprintf("index walk incomplete: %d of %d files were not found", numFiles, numFiles)))
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("indexes a stale node that Stat cannot find by its path but can by its ID", func() {
staleByPath["file-1"] = true
var extracted []string
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
extracted = append(extracted, args.Get(1).(*sprovider.ResourceInfo).GetId().GetOpaqueId())
}).Return(content.Document{}, nil)
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred())
Expect(extracted).To(ConsistOf("file-0", "file-1", "file-2", "file-3", "file-4", "file-5"))
gatewayClient.AssertNumberOfCalls(GinkgoT(), "GetPath", 1) // only the stale node needs the ID fallback
})
It("does not count a file that is gone between the Stat and the GetPath", func() {
staleByPath["file-1"] = true // forces the lookup by ID, which calls GetPath
pathMissing["file-1"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "a vanished file is not an extraction failure")
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles-1)
})
It("counts a GetPath failure other than not-found", func() {
staleByPath["file-1"] = true
pathBroken["file-1"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "a storage failure must not look like a deleted file")
Expect(err.Error()).To(ContainSubstring("aborting index walk: 1 consecutive extraction failures"))
})
It("resolves healthy files by path, without a GetPath call", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred())
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles)
gatewayClient.AssertNotCalled(GinkgoT(), "GetPath", mock.Anything, mock.Anything)
})
It("aborts after the configured number of consecutive extraction failures", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("extractor down"))
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything)
})
It("never aborts when the threshold is 0", func() {
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
}).Return(content.Document{}, errors.New("extractor down"))
err := newService(0).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "with the abort disabled the walk finishes despite failures")
Expect(int(extractCalls.Load())).To(Equal(numFiles*6), "every file was attempted, each with all retries")
})
It("counts a Stat failure other than not-found towards the abort threshold", func() {
for _, fi := range fileInfos {
statBroken[fi.Id.OpaqueId] = true
}
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "a storage or auth error must not look like a deleted file")
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("stops with an error when the walk's context ends, instead of skipping the rest", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
cancel() // e.g. the index command's request timeout fires during the walk
}).Return(content.Document{}, nil)
err := newService(0).IndexSpace(ctx, spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("index walk stopped"))
Expect(int(extractCalls.Load())).To(Equal(1), "no file after the cancellation was attempted")
})
It("stops retrying a failed extraction as soon as the context ends", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
cancel()
}).Return(content.Document{}, errors.New("extractor down"))
s := newService(0)
s.SetExtractionRetryDelay(time.Hour)
done := make(chan error, 1)
go func() { done <- s.IndexSpace(ctx, spaceID) }()
var err error
Eventually(done, 5*time.Second).Should(Receive(&err), "the retry wait must end with the context, not after an hour")
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("index walk stopped"))
Expect(int(extractCalls.Load())).To(Equal(1))
})
It("resets the counter on an already indexed, unchanged file", func() {
// Failing files 0, 2 and 4 are each followed by an indexed one.
for i := 1; i < numFiles; i += 2 {
indexed[storagespace.FormatResourceID(fileInfos[i].Id)] = true
}
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("cannot extract"))
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "failures separated by a healthy file are not consecutive")
})
})
Describe("UpdateTags", func() {
BeforeEach(func() {
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
@@ -430,6 +717,35 @@ var _ = Describe("Searchprovider", func() {
})
})
Describe("UpdateTags when GetPath fails", func() {
for name, getPathStatus := range map[string]func() *rpcv1beta1.Status{
"with an internal error": func() *rpcv1beta1.Status { return status.NewInternal(context.Background(), "no path") },
"with not found": func() *rpcv1beta1.Status { return status.NewNotFound(context.Background(), "no path") },
} {
It("still updates the tags from the Stat result, GetPath answering "+name, func() {
noPathID := &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "nopath"}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: &sprovider.ResourceInfo{
Id: noPathID,
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
ArbitraryMetadata: &sprovider.ArbitraryMetadata{
Metadata: map[string]string{"tags": "important"},
},
},
}, nil)
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return req.GetResourceId().GetOpaqueId() == "nopath"
})).Return(&sprovider.GetPathResponse{Status: getPathStatus()}, nil)
indexClient.On("Update", "storageid$spaceid!nopath", mock.Anything).Return(nil)
s.UpdateTags(context.Background(), &sprovider.Reference{ResourceId: noPathID})
indexClient.AssertCalled(GinkgoT(), "Update", "storageid$spaceid!nopath", mock.Anything)
})
}
})
Describe("Search", func() {
It("fails when an empty query is given", func() {
res, err := s.Search(ctx, &searchsvc.SearchRequest{