From debbeae2cb646d706a61491f24c7f619dbbf5550 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Wed, 25 Nov 2026 11:13:32 +0100 Subject: [PATCH 1/5] feat(search): retry extractions tika could not answer during a walk --- services/search/README.md | 2 +- services/search/pkg/search/export_test.go | 11 ++ services/search/pkg/search/service.go | 101 +++++++++++--- services/search/pkg/search/service_test.go | 146 +++++++++++++++++++++ 4 files changed, 244 insertions(+), 16 deletions(-) create mode 100644 services/search/pkg/search/export_test.go diff --git a/services/search/README.md b/services/search/README.md index 8b2bdecc30..0ed75829c4 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -163,7 +163,7 @@ Additionally, the following optional settings can be set: #### 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. +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 space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. To list the files the service gave up on, search for: diff --git a/services/search/pkg/search/export_test.go b/services/search/pkg/search/export_test.go new file mode 100644 index 0000000000..bc1b10a353 --- /dev/null +++ b/services/search/pkg/search/export_test.go @@ -0,0 +1,11 @@ +package search + +import "time" + +// SetUnreachableRetryDelay shortens the wait between extraction retries, a walk +// test would otherwise sleep a second per retry +func SetUnreachableRetryDelay(d time.Duration) (restore func()) { + previous := unreachableRetryDelay + unreachableRetryDelay = d + return func() { unreachableRetryDelay = previous } +} diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index bbbabdf0c5..226c5e4d4f 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -93,6 +93,17 @@ var errSkipSpace error // burst of uploads instead of spending every attempt inside it var extractionRetryDelays = []time.Duration{time.Hour, 24 * time.Hour} +// a restarting tika answers again within seconds, so a space walk retries an +// extraction that could not reach tika or the file before indexing it by name +var ( + unreachableRetries = 5 + unreachableRetryDelay = time.Second +) + +// this many files in a row out of reach after their retries means tika is down, +// not that one file is gone +const unreachableStreakLimit = 5 + // 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 @@ -549,6 +560,7 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool) }() w := walker.NewWalker(s.gatewaySelector) + unreachable := &unreachableExtractions{} batch, err := s.engine.NewBatch(s.batchSize) if err != nil { return err @@ -583,7 +595,7 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool) s.logger.Debug().Str("path", ref.Path).Msg("Walking tree") if forceRescan { - s.doUpsertItem(session.Ctx(), ref, batch) + s.doUpsertItem(session.Ctx(), ref, batch, unreachable) return nil } @@ -594,11 +606,15 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId, forceRescan bool) return nil } - s.doUpsertItem(session.Ctx(), ref, batch) + s.doUpsertItem(session.Ctx(), ref, batch, unreachable) return nil }) + if err != nil { + return err + } + err = unreachable.err() if err != nil { return err } @@ -706,21 +722,12 @@ func (s *Service) UpdateMetadata(ref *provider.Reference) { }) switch { case errors.Is(err, ErrResourceNotFound): - s.upsertResource(ctx, ref, stat, path, nil) + s.upsertResource(ctx, ref, stat, path, nil, 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) - if stat == nil || path == "" { - return - } - s.upsertResource(ctx, ref, stat, path, batch) -} - // SanitizeHighlights keeps the tags and escapes everything else. func SanitizeHighlights(highlights string) string { var b strings.Builder @@ -830,8 +837,18 @@ 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) { +// doUpsertItem indexes or stores Resource data fields. +func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, batch BatchOperator, unreachable *unreachableExtractions) { + stat, path := s.resInfo(ctx, ref) + if stat == nil || path == "" { + return + } + s.upsertResource(ctx, ref, stat, path, batch, unreachable) +} + +// upsertResource extracts and indexes the resource stat describes, a space walk +// passes unreachable to retry extractions that could not reach tika or the file +func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, stat *provider.StatResponse, path string, batch BatchOperator, unreachable *unreachableExtractions) { if utils.IsProcessing(stat.GetInfo()) { s.logger.Debug().Str("path", path).Msg("resource is still being processed. Skipping.") return @@ -839,7 +856,7 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s // 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()) + doc, err := s.extract(ctx, stat.GetInfo(), unreachable) extractionFailed := err != nil if err != nil { s.logger.Error().Err(err).Str("path", path).Msg("failed to extract resource content") @@ -945,6 +962,36 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s } } +// extract runs the content extraction and retries it while tika or the file is +// out of reach, unless unreachable is nil or says tika is down +func (s *Service) extract(ctx context.Context, info *provider.ResourceInfo, unreachable *unreachableExtractions) (content.Document, error) { + doc, err := s.extractor.Extract(ctx, info) + if unreachable == nil { + return doc, err + } + for retry := 0; retry < unreachableRetries && !unreachable.down && isUnreachable(err); retry++ { + select { + case <-ctx.Done(): + return doc, err + case <-time.After(unreachableRetryDelay): + } + doc, err = s.extractor.Extract(ctx, info) + } + if !isUnreachable(err) { + unreachable.streak, unreachable.down = 0, false + return doc, err + } + + unreachable.streak++ + unreachable.files++ + unreachable.last = err + if unreachable.streak == unreachableStreakLimit { + unreachable.down, unreachable.tripped = true, true + s.logger.Warn().Err(err).Int("files", unreachable.streak).Msg("tika or the files stay out of reach, the remaining files are indexed by name without retries until an extraction succeeds") + } + return doc, err +} + // 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())) @@ -1058,3 +1105,27 @@ func tokenExpiry(ctx context.Context) (time.Time, error) { } return claims.ExpiresAt.Time, nil } + +// unreachableExtractions follows the extractions of one space walk that could +// not reach tika or the file. The walk does not stop when tika is down: the +// files are indexed by name, and IndexSpace reports the outage at the end. +type unreachableExtractions struct { + streak int + down bool + tripped bool + files int + last error +} + +func (u *unreachableExtractions) err() error { + if !u.tripped { + return nil + } + return fmt.Errorf("tika or the files were out of reach, %d files indexed by name only: %w", u.files, u.last) +} + +// isUnreachable tells a failure worth retrying from a file tika cannot parse, +// which fails the same way on the next attempt +func isUnreachable(err error) bool { + return err != nil && !errors.Is(err, content.ErrUnparsable) +} diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 27724b5176..68ea6ea6c0 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -227,6 +227,152 @@ var _ = Describe("Searchprovider", func() { "storageid$spaceid!failed-unreachable", )) }) + + Context("when tika or the files are out of reach", func() { + var ( + files []string + extract func(name string, attempt int) (content.Document, error) + attempts map[string]int + upserted map[string]search.Resource + unreached = errors.New("connection refused") + ) + + BeforeEach(func() { + DeferCleanup(search.SetUnreachableRetryDelay(time.Millisecond)) + attempts = map[string]int{} + upserted = map[string]search.Resource{} + + root := &sprovider.ResourceInfo{ + Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"}, + Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER, + Path: ".", + Mtime: &typesv1beta1.Timestamp{Seconds: 4000}, + } + children := func() []*sprovider.ResourceInfo { + infos := make([]*sprovider.ResourceInfo, 0, len(files)) + for _, name := range files { + infos = append(infos, &sprovider.ResourceInfo{ + Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: name}, + ParentId: root.GetId(), + Type: sprovider.ResourceType_RESOURCE_TYPE_FILE, + Path: name, + Mtime: &typesv1beta1.Timestamp{Seconds: 4000}, + }) + } + return infos + } + + 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( + func(context.Context, *sprovider.ListContainerRequest, ...grpc.CallOption) (*sprovider.ListContainerResponse, error) { + return &sprovider.ListContainerResponse{Status: status.NewOK(context.Background()), Infos: children()}, nil + }) + indexClient.On("Get", mock.Anything, mock.Anything).Return(nil, search.ErrResourceNotFound) + extractor.On("Extract", mock.Anything, mock.Anything).Return( + func(_ context.Context, info *sprovider.ResourceInfo) (content.Document, error) { + if info.GetType() == sprovider.ResourceType_RESOURCE_TYPE_CONTAINER { + return content.Document{}, nil + } + attempts[info.GetPath()]++ + return extract(info.GetPath(), attempts[info.GetPath()]) + }) + + batch := &engineMocks.BatchOperator{} + batch.EXPECT().Push().Return(nil) + batch.On("Upsert", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { + upserted[args.String(0)] = args.Get(1).(search.Resource) + }).Return(nil) + indexClient.On("NewBatch", mock.Anything).Return(batch, nil) + }) + + It("retries the extraction and indexes the content once tika answers again", func() { + files = []string{"report.pdf"} + extract = func(_ string, attempt int) (content.Document, error) { + if attempt < 3 { + return content.Document{Name: "report.pdf"}, unreached + } + return content.Document{Name: "report.pdf", Content: "quarterly numbers"}, nil + } + + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed()) + Expect(attempts).To(Equal(map[string]int{"report.pdf": 3})) + r := upserted["storageid$spaceid!report.pdf"] + Expect(r.Content).To(Equal("quarterly numbers")) + Expect(r.ExtractionFailure).To(BeNil()) + }) + + It("indexes a file still out of reach by name without failing the walk", func() { + files = []string{"gone.pdf", "report.pdf"} + extract = func(name string, _ int) (content.Document, error) { + if name == "gone.pdf" { + return content.Document{Name: name}, unreached + } + return content.Document{Name: name}, nil + } + + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed()) + Expect(attempts).To(Equal(map[string]int{"gone.pdf": 6, "report.pdf": 1})) + Expect(upserted["storageid$spaceid!gone.pdf"].ExtractionFailure).To(Equal(&search.ExtractionFailure{})) + }) + + It("does not retry a file tika cannot parse", func() { + files = []string{"scan.png"} + extract = func(name string, _ int) (content.Document, error) { + return content.Document{Name: name}, fmt.Errorf("%w %q", content.ErrUnparsable, name) + } + + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed()) + Expect(attempts).To(Equal(map[string]int{"scan.png": 1})) + }) + + It("stops retrying once tika stays down, indexes the remaining files by name and reports it", func() { + files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "f.pdf", "g.pdf"} + extract = func(name string, _ int) (content.Document, error) { + return content.Document{Name: name}, unreached + } + + err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false) + Expect(err).To(MatchError(unreached)) + Expect(err).To(MatchError(ContainSubstring("7 files indexed by name only"))) + Expect(attempts).To(Equal(map[string]int{ + "a.pdf": 6, "b.pdf": 6, "c.pdf": 6, "d.pdf": 6, "e.pdf": 6, + "f.pdf": 1, "g.pdf": 1, + })) + for _, name := range files { + Expect(upserted).To(HaveKey("storageid$spaceid!" + name)) + } + }) + + It("retries again once an extraction succeeds after tika was down", func() { + files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "back.pdf", "z.pdf"} + extract = func(name string, attempt int) (content.Document, error) { + switch { + case name == "back.pdf": + return content.Document{Name: name}, nil + case name == "z.pdf" && attempt > 1: + return content.Document{Name: name}, nil + } + return content.Document{Name: name}, unreached + } + + // tika was down during the walk, which is still reported + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(MatchError(unreached)) + Expect(attempts).To(HaveKeyWithValue("back.pdf", 1)) + Expect(attempts).To(HaveKeyWithValue("z.pdf", 2)) + }) + }) }) Describe("indexing a resource in full", func() { From 12e7b86344a68cb1642add4a2e1b431c587c5508 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Wed, 25 Nov 2026 12:22:55 +0100 Subject: [PATCH 2/5] fix(search): retry only unreachable extractions and bound each attempt --- services/search/README.md | 3 +- services/search/pkg/config/content.go | 7 +- .../pkg/config/defaults/defaultconfig.go | 2 + services/search/pkg/content/cs3.go | 20 ++-- services/search/pkg/content/cs3_test.go | 92 +++++++++++++++++++ services/search/pkg/content/extractor.go | 26 ++++++ services/search/pkg/content/tika.go | 12 ++- services/search/pkg/content/tika_test.go | 43 +++++++++ services/search/pkg/search/service.go | 24 ++--- services/search/pkg/search/service_test.go | 15 ++- 10 files changed, 220 insertions(+), 24 deletions(-) create mode 100644 services/search/pkg/content/cs3_test.go diff --git a/services/search/README.md b/services/search/README.md index 0ed75829c4..0651a5fc28 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -160,10 +160,11 @@ The following settings must be set: 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. +* `SEARCH_EXTRACTOR_TIKA_TIMEOUT=5m` (default: `5m`): the time one extraction may take, from downloading the file to the answer of Tika. A longer one counts as Tika being unreachable, see below. Raise it if OCR of large files takes longer, `0` disables the limit. #### 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 space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. +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 same goes for a file the storage refuses to hand out, for example one deleted meanwhile. The content is tried again on the first reindex of its space at least one hour after the failure, and on the first one at least 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 failed connection, a timeout or a server error), a space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. To list the files the service gave up on, search for: diff --git a/services/search/pkg/config/content.go b/services/search/pkg/config/content.go index 515db03b63..645dc88a6e 100644 --- a/services/search/pkg/config/content.go +++ b/services/search/pkg/config/content.go @@ -1,5 +1,7 @@ package config +import "time" + // Extractor defines which extractor to use 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:"1.0.0"` @@ -9,6 +11,7 @@ type Extractor struct { // ExtractorTika configures the Tika extractor type ExtractorTika struct { - TikaURL string `yaml:"tika_url" env:"SEARCH_EXTRACTOR_TIKA_TIKA_URL" desc:"URL of the tika server." introductionVersion:"1.0.0"` - CleanStopWords bool `yaml:"clean_stop_words" env:"SEARCH_EXTRACTOR_TIKA_CLEAN_STOP_WORDS" desc:"Defines if stop words should be cleaned or not. See the documentation for more details." introductionVersion:"1.0.0"` + TikaURL string `yaml:"tika_url" env:"SEARCH_EXTRACTOR_TIKA_TIKA_URL" desc:"URL of the tika server." introductionVersion:"1.0.0"` + CleanStopWords bool `yaml:"clean_stop_words" env:"SEARCH_EXTRACTOR_TIKA_CLEAN_STOP_WORDS" desc:"Defines if stop words should be cleaned or not. See the documentation for more details." introductionVersion:"1.0.0"` + Timeout time.Duration `yaml:"timeout" env:"SEARCH_EXTRACTOR_TIKA_TIMEOUT" desc:"The time one content extraction may take, from downloading the file to the answer of Tika. An extraction that takes longer counts as Tika being unreachable and is retried. 0 disables the limit. See the documentation for more details." introductionVersion:"%%NEXT%%"` } diff --git a/services/search/pkg/config/defaults/defaultconfig.go b/services/search/pkg/config/defaults/defaultconfig.go index fdab375318..4d7ab3c77e 100644 --- a/services/search/pkg/config/defaults/defaultconfig.go +++ b/services/search/pkg/config/defaults/defaultconfig.go @@ -51,6 +51,8 @@ func DefaultConfig() *config.Config { Tika: config.ExtractorTika{ TikaURL: "http://127.0.0.1:9998", CleanStopWords: false, + // the task timeout of tika server 3, tika 4 allows up to an hour per file + Timeout: 5 * time.Minute, }, }, Events: config.Events{ diff --git a/services/search/pkg/content/cs3.go b/services/search/pkg/content/cs3.go index 3c7a9e7738..9087f84608 100644 --- a/services/search/pkg/content/cs3.go +++ b/services/search/pkg/content/cs3.go @@ -44,14 +44,18 @@ func (s cs3) Retrieve(ctx context.Context, rID *provider.ResourceId) (io.ReadClo gatewayClient, err := s.gatewaySelector.Next() if err != nil { s.logger.Error().Err(err).Msg("could not get reva gatewayClient") - return nil, err + return nil, unreachable(err) } res, err := gatewayClient.InitiateFileDownload(ctx, &provider.InitiateFileDownloadRequest{Ref: &provider.Reference{ResourceId: rID, Path: "."}}) if err != nil { - return nil, err + return nil, unreachable(err) } - if res.Status.Code != rpc.Code_CODE_OK { + switch res.GetStatus().GetCode() { + case rpc.Code_CODE_OK: + case rpc.Code_CODE_UNAVAILABLE: + return nil, fmt.Errorf("%w: could not load resoure: %s", ErrUnreachable, res.GetStatus().GetMessage()) + default: return nil, fmt.Errorf("could not load resoure: %s", res.Status.Message) } @@ -66,7 +70,7 @@ func (s cs3) Retrieve(ctx context.Context, rID *provider.ResourceId) (io.ReadClo ep, tt = res.Protocols[0].DownloadEndpoint, res.Protocols[0].Token } - req, err := http.NewRequest(http.MethodGet, ep, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, ep, nil) if err != nil { return nil, err } @@ -76,11 +80,15 @@ func (s cs3) Retrieve(ctx context.Context, rID *provider.ResourceId) (io.ReadClo cres, err := s.httpClient.Do(req) if err != nil { - return nil, err + return nil, unreachable(err) } if cres.StatusCode != http.StatusOK { - return nil, fmt.Errorf("could not download resource. Request returned with statuscode %d ", cres.StatusCode) + err := fmt.Errorf("could not download resource. Request returned with statuscode %d ", cres.StatusCode) + if cres.StatusCode >= http.StatusInternalServerError { + err = fmt.Errorf("%w: %w", ErrUnreachable, err) + } + return nil, err } return cres.Body, nil diff --git a/services/search/pkg/content/cs3_test.go b/services/search/pkg/content/cs3_test.go new file mode 100644 index 0000000000..8ee04f0dce --- /dev/null +++ b/services/search/pkg/content/cs3_test.go @@ -0,0 +1,92 @@ +package content_test + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + revactx "github.com/opencloud-eu/reva/v3/pkg/ctx" + "github.com/opencloud-eu/reva/v3/pkg/rgrpc/todo/pool" + cs3mocks "github.com/opencloud-eu/reva/v3/tests/cs3mocks/mocks" + "github.com/stretchr/testify/mock" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + + "github.com/opencloud-eu/opencloud/pkg/log" + conf "github.com/opencloud-eu/opencloud/services/search/pkg/config/defaults" + "github.com/opencloud-eu/opencloud/services/search/pkg/content" +) + +var _ = Describe("cs3 retriever", func() { + var ( + gatewayClient *cs3mocks.GatewayAPIClient + tika *content.Tika + tikaSrv *httptest.Server + downloadSrv *httptest.Server + downloadStatus int + ctx = metadata.AppendToOutgoingContext(context.Background(), revactx.TokenHeader, "token") + ) + + BeforeEach(func() { + downloadStatus = http.StatusOK + tikaSrv = httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + downloadSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(downloadStatus) + })) + + pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway") + gatewayClient = &cs3mocks.GatewayAPIClient{} + gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient]( + "GatewaySelector", + "eu.opencloud.api.gateway", + func(grpc.ClientConnInterface) gateway.GatewayAPIClient { + return gatewayClient + }, + ) + + cfg := conf.DefaultConfig() + cfg.Extractor.Tika.TikaURL = tikaSrv.URL + var err error + tika, err = content.NewTikaExtractor(gatewaySelector, log.NewLogger(), cfg) + Expect(err).ToNot(HaveOccurred()) + }) + + AfterEach(func() { + tikaSrv.Close() + downloadSrv.Close() + }) + + download := func(code rpc.Code) { + gatewayClient.On("InitiateFileDownload", mock.Anything, mock.Anything).Return(&gateway.InitiateFileDownloadResponse{ + Status: &rpc.Status{Code: code}, + Protocols: []*gateway.FileDownloadProtocol{{Protocol: "spaces", DownloadEndpoint: downloadSrv.URL, Token: "transfer"}}, + }, nil) + } + + DescribeTable("tells a file out of reach from a download the storage refuses", + func(setup func(), unreachable bool) { + setup() + + _, err := tika.Retrieve(ctx, &provider.ResourceId{OpaqueId: "file"}) + Expect(err).To(HaveOccurred()) + Expect(errors.Is(err, content.ErrUnreachable)).To(Equal(unreachable)) + }, + Entry("gateway unavailable", func() { + gatewayClient.On("InitiateFileDownload", mock.Anything, mock.Anything).Return(nil, status.Error(codes.Unavailable, "connection refused")) + }, true), + Entry("storage unavailable", func() { download(rpc.Code_CODE_UNAVAILABLE) }, true), + Entry("data server error", func() { download(rpc.Code_CODE_OK); downloadStatus = http.StatusBadGateway }, true), + Entry("data server down", func() { download(rpc.Code_CODE_OK); downloadSrv.Close() }, true), + Entry("file not found", func() { download(rpc.Code_CODE_NOT_FOUND) }, false), + Entry("permission denied", func() { download(rpc.Code_CODE_PERMISSION_DENIED) }, false), + Entry("download not found", func() { download(rpc.Code_CODE_OK); downloadStatus = http.StatusNotFound }, false), + ) +}) diff --git a/services/search/pkg/content/extractor.go b/services/search/pkg/content/extractor.go index a76548ffe3..263298bb35 100644 --- a/services/search/pkg/content/extractor.go +++ b/services/search/pkg/content/extractor.go @@ -2,16 +2,42 @@ package content import ( "context" + "errors" "fmt" + "net/http" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/google/go-tika/tika" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) +// ErrUnreachable marks a failure to reach tika or the file, a failed connection, +// a timeout or a server error, the next attempt may well get through +var ErrUnreachable = errors.New("tika or the file is unreachable") + // Extractor is responsible to extract content and meta information from documents. type Extractor interface { Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, error) } +// unreachable wraps the error of a failed call in ErrUnreachable, unless the +// other side answered that the request itself is wrong (not found, a 4xx) +func unreachable(err error) error { + var tikaErr tika.ClientError + if errors.As(err, &tikaErr) && tikaErr.StatusCode < http.StatusInternalServerError { + return err + } + if s, ok := status.FromError(err); ok { + switch s.Code() { + case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled: + default: + return err + } + } + return fmt.Errorf("%w: %w", ErrUnreachable, err) +} + // getFirstValue returns the first metadata value present among keys, trying them // in order. It errors when the map is nil or none of the keys holds a value. func getFirstValue(m map[string][]string, keys ...string) (string, error) { diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index 733ff02517..bcc9ccab77 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -8,6 +8,7 @@ import ( "net/http" "slices" "strings" + "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -31,6 +32,7 @@ type Tika struct { tikaURL string ContentExtractionSizeLimit uint64 CleanStopWords bool + Timeout time.Duration } // NewTikaExtractor creates a new Tika instance. @@ -54,6 +56,7 @@ func NewTikaExtractor(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], tikaURL: cfg.Extractor.Tika.TikaURL, ContentExtractionSizeLimit: cfg.ContentExtractionSizeLimit, CleanStopWords: cfg.Extractor.Tika.CleanStopWords, + Timeout: cfg.Extractor.Tika.Timeout, }, nil } @@ -77,6 +80,13 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, return doc, nil } + // a tika that hangs instead of refusing connections would block the walk + if t.Timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, t.Timeout) + defer cancel() + } + data, err := t.Retrieve(ctx, ri.Id) if err != nil { return doc, err @@ -85,7 +95,7 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, metas, err := t.tika.MetaRecursive(ctx, data) if err != nil { - return doc, err + return doc, unreachable(err) } // a file with content always yields metadata, none means tika failed on it if len(metas) == 0 { diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index ab6605cbf9..357ad8ad04 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -2,11 +2,13 @@ package content_test import ( "context" + "errors" "fmt" "io" "net/http" "net/http/httptest" "strings" + "time" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" . "github.com/onsi/ginkgo/v2" @@ -28,6 +30,8 @@ var _ = Describe("Tika", func() { language string tika4Language bool version string + rmetaStatus int + rmetaHangs bool srv *httptest.Server tika *content.Tika ) @@ -38,6 +42,8 @@ var _ = Describe("Tika", func() { tika4Language = false version = "" fullResponse = "" + rmetaStatus = 0 + rmetaHangs = false srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { out := "" switch req.URL.Path { @@ -53,6 +59,16 @@ var _ = Describe("Tika", func() { case "/language/string": out = language case "/rmeta/text": + if rmetaHangs { + // the server notices the client leaving only once the body is read + _, _ = io.Copy(io.Discard, req.Body) + <-req.Context().Done() + return + } + if rmetaStatus != 0 { + w.WriteHeader(rmetaStatus) + return + } if fullResponse != "" { out = fullResponse } else { @@ -129,6 +145,33 @@ var _ = Describe("Tika", func() { 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"}]`), ) + DescribeTable("tells an unreachable tika from a request it rejects", + func(status int, unreachable bool) { + rmetaStatus = status + + _, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Size: 1, + }) + Expect(err).To(HaveOccurred()) + Expect(errors.Is(err, content.ErrUnreachable)).To(Equal(unreachable)) + }, + Entry("server error", http.StatusServiceUnavailable, true), + Entry("unprocessable file", http.StatusUnprocessableEntity, false), + ) + + It("gives up on a tika that does not answer in time", func() { + rmetaHangs = true + tika.Timeout = 10 * time.Millisecond + + _, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Size: 1, + }) + Expect(err).To(MatchError(content.ErrUnreachable)) + Expect(err).To(MatchError(context.DeadlineExceeded)) + }) + It("adds the title", func() { fullResponse = `[{"dc:title": "quarterly report", "X-TIKA:content": "some data"}]` diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 226c5e4d4f..039d6bad8d 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -876,7 +876,7 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s 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)) + r.ExtractionFailure, write = s.nextExtractionFailure(ctx, r.ID, stat.GetInfo(), path, !isUnreachable(err)) if !write { return } @@ -1009,19 +1009,19 @@ func (s *Service) isIndexed(ctx context.Context, info *provider.ResourceInfo) bo 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) { +// nextExtractionFailure counts a failure on top of the ones the indexed entry +// holds for the same version, a new version starts over. A failure to reach tika +// or the file (not counted) says nothing about the file: it 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, counted 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 { + if !counted { // without knowing the entry, a name-only document could replace extracted content return nil, false } @@ -1029,7 +1029,7 @@ func (s *Service) nextExtractionFailure(ctx context.Context, id string, info *pr previous = r } - if !unparsable { + if !counted { if previous != nil && !previous.Deleted { return nil, false } @@ -1124,8 +1124,8 @@ func (u *unreachableExtractions) err() error { return fmt.Errorf("tika or the files were out of reach, %d files indexed by name only: %w", u.files, u.last) } -// isUnreachable tells a failure worth retrying from a file tika cannot parse, -// which fails the same way on the next attempt +// isUnreachable tells a failure worth retrying from one the next attempt runs +// into as well, a file tika cannot parse or a download the storage refuses func isUnreachable(err error) bool { - return err != nil && !errors.Is(err, content.ErrUnparsable) + return errors.Is(err, content.ErrUnreachable) } diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 68ea6ea6c0..3899248be0 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -234,7 +234,7 @@ var _ = Describe("Searchprovider", func() { extract func(name string, attempt int) (content.Document, error) attempts map[string]int upserted map[string]search.Resource - unreached = errors.New("connection refused") + unreached = fmt.Errorf("%w: connection refused", content.ErrUnreachable) ) BeforeEach(func() { @@ -337,6 +337,17 @@ var _ = Describe("Searchprovider", func() { Expect(attempts).To(Equal(map[string]int{"scan.png": 1})) }) + It("does not retry a download the storage refuses and counts it as a failure", func() { + files = []string{"gone.pdf"} + extract = func(name string, _ int) (content.Document, error) { + return content.Document{Name: name}, errors.New("could not load resoure: not found") + } + + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(Succeed()) + Expect(attempts).To(Equal(map[string]int{"gone.pdf": 1})) + Expect(upserted["storageid$spaceid!gone.pdf"].ExtractionFailure.Count).To(Equal(1)) + }) + It("stops retrying once tika stays down, indexes the remaining files by name and reports it", func() { files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "f.pdf", "g.pdf"} extract = func(name string, _ int) (content.Document, error) { @@ -465,7 +476,7 @@ var _ = Describe("Searchprovider", func() { 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")) + extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "scan.png"}, fmt.Errorf("%w: connection refused", content.ErrUnreachable)) indexClient.On("Get", mock.Anything, mock.Anything).Return(previous, getErr) var indexed []search.Resource From 960ff63db3c42837659bf42607d41fd07a99bcf5 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Wed, 25 Nov 2026 13:19:42 +0100 Subject: [PATCH 3/5] fix(search): count extraction timeouts against the file, retry on 429 --- services/search/README.md | 4 ++-- services/search/pkg/config/content.go | 2 +- .../pkg/config/defaults/defaultconfig.go | 6 +++-- services/search/pkg/content/cs3.go | 2 +- services/search/pkg/content/cs3_test.go | 1 + services/search/pkg/content/extractor.go | 12 +++++++--- services/search/pkg/content/tika.go | 23 ++++++++++++++----- services/search/pkg/content/tika_test.go | 5 ++-- 8 files changed, 38 insertions(+), 17 deletions(-) diff --git a/services/search/README.md b/services/search/README.md index 0651a5fc28..f071445dfc 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -160,11 +160,11 @@ The following settings must be set: 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. -* `SEARCH_EXTRACTOR_TIKA_TIMEOUT=5m` (default: `5m`): the time one extraction may take, from downloading the file to the answer of Tika. A longer one counts as Tika being unreachable, see below. Raise it if OCR of large files takes longer, `0` disables the limit. +* `SEARCH_EXTRACTOR_TIKA_TIMEOUT=5m` (default: `5m`): the time one extraction may take, from downloading the file to the answer of Tika. A longer one counts as a failure of the file, see below. Raise it if OCR of large files takes longer, `0` disables the limit. #### 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 same goes for a file the storage refuses to hand out, for example one deleted meanwhile. The content is tried again on the first reindex of its space at least one hour after the failure, and on the first one at least 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 failed connection, a timeout or a server error), a space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. +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 same goes for a file the storage refuses to hand out, for example one deleted meanwhile, and for a file whose extraction takes longer than `SEARCH_EXTRACTOR_TIKA_TIMEOUT`. The content is tried again on the first reindex of its space at least one hour after the failure, and on the first one at least 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 failed connection, a server error or too many requests), a space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. To list the files the service gave up on, search for: diff --git a/services/search/pkg/config/content.go b/services/search/pkg/config/content.go index 645dc88a6e..d6904f4d87 100644 --- a/services/search/pkg/config/content.go +++ b/services/search/pkg/config/content.go @@ -13,5 +13,5 @@ type Extractor struct { type ExtractorTika struct { TikaURL string `yaml:"tika_url" env:"SEARCH_EXTRACTOR_TIKA_TIKA_URL" desc:"URL of the tika server." introductionVersion:"1.0.0"` CleanStopWords bool `yaml:"clean_stop_words" env:"SEARCH_EXTRACTOR_TIKA_CLEAN_STOP_WORDS" desc:"Defines if stop words should be cleaned or not. See the documentation for more details." introductionVersion:"1.0.0"` - Timeout time.Duration `yaml:"timeout" env:"SEARCH_EXTRACTOR_TIKA_TIMEOUT" desc:"The time one content extraction may take, from downloading the file to the answer of Tika. An extraction that takes longer counts as Tika being unreachable and is retried. 0 disables the limit. See the documentation for more details." introductionVersion:"%%NEXT%%"` + Timeout time.Duration `yaml:"timeout" env:"SEARCH_EXTRACTOR_TIKA_TIMEOUT" desc:"The time one content extraction may take, from downloading the file to the answer of Tika. An extraction that takes longer counts as a failure of the file. 0 disables the limit. See the documentation for more details." introductionVersion:"%%NEXT%%"` } diff --git a/services/search/pkg/config/defaults/defaultconfig.go b/services/search/pkg/config/defaults/defaultconfig.go index 4d7ab3c77e..00c4025f25 100644 --- a/services/search/pkg/config/defaults/defaultconfig.go +++ b/services/search/pkg/config/defaults/defaultconfig.go @@ -10,6 +10,9 @@ import ( "github.com/opencloud-eu/opencloud/services/search/pkg/config" ) +// the task timeout of tika server 3, tika 4 allows up to an hour per file +const defaultTikaTimeout = 5 * time.Minute + // FullDefaultConfig returns a fully initialized default configuration func FullDefaultConfig() *config.Config { cfg := DefaultConfig() @@ -51,8 +54,7 @@ func DefaultConfig() *config.Config { Tika: config.ExtractorTika{ TikaURL: "http://127.0.0.1:9998", CleanStopWords: false, - // the task timeout of tika server 3, tika 4 allows up to an hour per file - Timeout: 5 * time.Minute, + Timeout: defaultTikaTimeout, }, }, Events: config.Events{ diff --git a/services/search/pkg/content/cs3.go b/services/search/pkg/content/cs3.go index 9087f84608..8b63df480e 100644 --- a/services/search/pkg/content/cs3.go +++ b/services/search/pkg/content/cs3.go @@ -85,7 +85,7 @@ func (s cs3) Retrieve(ctx context.Context, rID *provider.ResourceId) (io.ReadClo if cres.StatusCode != http.StatusOK { err := fmt.Errorf("could not download resource. Request returned with statuscode %d ", cres.StatusCode) - if cres.StatusCode >= http.StatusInternalServerError { + if transientStatus(cres.StatusCode) { err = fmt.Errorf("%w: %w", ErrUnreachable, err) } return nil, err diff --git a/services/search/pkg/content/cs3_test.go b/services/search/pkg/content/cs3_test.go index 8ee04f0dce..3dc6614f89 100644 --- a/services/search/pkg/content/cs3_test.go +++ b/services/search/pkg/content/cs3_test.go @@ -84,6 +84,7 @@ var _ = Describe("cs3 retriever", func() { }, true), Entry("storage unavailable", func() { download(rpc.Code_CODE_UNAVAILABLE) }, true), Entry("data server error", func() { download(rpc.Code_CODE_OK); downloadStatus = http.StatusBadGateway }, true), + Entry("data server busy", func() { download(rpc.Code_CODE_OK); downloadStatus = http.StatusTooManyRequests }, true), Entry("data server down", func() { download(rpc.Code_CODE_OK); downloadSrv.Close() }, true), Entry("file not found", func() { download(rpc.Code_CODE_NOT_FOUND) }, false), Entry("permission denied", func() { download(rpc.Code_CODE_PERMISSION_DENIED) }, false), diff --git a/services/search/pkg/content/extractor.go b/services/search/pkg/content/extractor.go index 263298bb35..518ae5bf4b 100644 --- a/services/search/pkg/content/extractor.go +++ b/services/search/pkg/content/extractor.go @@ -12,8 +12,8 @@ import ( "google.golang.org/grpc/status" ) -// ErrUnreachable marks a failure to reach tika or the file, a failed connection, -// a timeout or a server error, the next attempt may well get through +// ErrUnreachable marks a failure to reach tika or the file, a failed connection +// or a server error, the next attempt may well get through var ErrUnreachable = errors.New("tika or the file is unreachable") // Extractor is responsible to extract content and meta information from documents. @@ -25,7 +25,7 @@ type Extractor interface { // other side answered that the request itself is wrong (not found, a 4xx) func unreachable(err error) error { var tikaErr tika.ClientError - if errors.As(err, &tikaErr) && tikaErr.StatusCode < http.StatusInternalServerError { + if errors.As(err, &tikaErr) && !transientStatus(tikaErr.StatusCode) { return err } if s, ok := status.FromError(err); ok { @@ -38,6 +38,12 @@ func unreachable(err error) error { return fmt.Errorf("%w: %w", ErrUnreachable, err) } +// transientStatus tells an http status the next attempt may get past, a server +// error or too many requests, from an answer about the request itself +func transientStatus(code int) bool { + return code >= http.StatusInternalServerError || code == http.StatusTooManyRequests +} + // getFirstValue returns the first metadata value present among keys, trying them // in order. It errors when the map is nil or none of the keys holds a value. func getFirstValue(m map[string][]string, keys ...string) (string, error) { diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index bcc9ccab77..c3f529f20d 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -81,21 +81,22 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, } // a tika that hangs instead of refusing connections would block the walk + attemptCtx := ctx if t.Timeout > 0 { var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, t.Timeout) + attemptCtx, cancel = context.WithTimeout(ctx, t.Timeout) defer cancel() } - data, err := t.Retrieve(ctx, ri.Id) + data, err := t.Retrieve(attemptCtx, ri.GetId()) if err != nil { - return doc, err + return doc, t.attemptError(ctx, attemptCtx, ri, err) } defer data.Close() - metas, err := t.tika.MetaRecursive(ctx, data) + metas, err := t.tika.MetaRecursive(attemptCtx, data) if err != nil { - return doc, unreachable(err) + return doc, t.attemptError(ctx, attemptCtx, ri, unreachable(err)) } // a file with content always yields metadata, none means tika failed on it if len(metas) == 0 { @@ -145,13 +146,23 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, doc.MotionPhoto = t.getMotionPhoto(m0, metas[i+1]) } - if langCode := t.detectLanguage(ctx, doc.Content); langCode != "" && t.CleanStopWords { + if langCode := t.detectLanguage(attemptCtx, doc.Content); langCode != "" && t.CleanStopWords { doc.Content = CleanString(doc.Content, langCode) } return doc, nil } +// attemptError turns an attempt that ran out of time into a failure of the file: +// tika accepted the request, so a retry would most likely run as long again and +// stack more work on a tika that may still be parsing +func (t Tika) attemptError(ctx, attemptCtx context.Context, ri *provider.ResourceInfo, err error) error { + if ctx.Err() == nil && errors.Is(attemptCtx.Err(), context.DeadlineExceeded) { + return fmt.Errorf("extracting %q took longer than %s: %w", ri.GetName(), t.Timeout, context.DeadlineExceeded) + } + return err +} + // detectLanguage asks tika for the language of content. Tika 4 moved the // endpoint from /language/string to /language, so try the new path first and // fall back for an older tika. diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index 357ad8ad04..a2f4224ad0 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -157,10 +157,11 @@ var _ = Describe("Tika", func() { Expect(errors.Is(err, content.ErrUnreachable)).To(Equal(unreachable)) }, Entry("server error", http.StatusServiceUnavailable, true), + Entry("too many requests", http.StatusTooManyRequests, true), Entry("unprocessable file", http.StatusUnprocessableEntity, false), ) - It("gives up on a tika that does not answer in time", func() { + It("counts a tika that does not answer in time as a failure of the file", func() { rmetaHangs = true tika.Timeout = 10 * time.Millisecond @@ -168,8 +169,8 @@ var _ = Describe("Tika", func() { Type: provider.ResourceType_RESOURCE_TYPE_FILE, Size: 1, }) - Expect(err).To(MatchError(content.ErrUnreachable)) Expect(err).To(MatchError(context.DeadlineExceeded)) + Expect(errors.Is(err, content.ErrUnreachable)).To(BeFalse()) }) It("adds the title", func() { From b7a169671d2e4062532062c26e3b8efc8e67e3e3 Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Wed, 25 Nov 2026 13:34:16 +0100 Subject: [PATCH 4/5] fix(search): probe tika version to tell a hanging tika from a slow file --- services/search/README.md | 2 +- services/search/pkg/content/export_test.go | 11 +++++++ services/search/pkg/content/extractor.go | 6 ++++ services/search/pkg/content/tika.go | 27 +++++++++++++++-- services/search/pkg/content/tika_test.go | 30 +++++++++++++++++++ services/search/pkg/search/service.go | 25 ++++++++++++++-- services/search/pkg/search/service_test.go | 35 ++++++++++++++++++++++ 7 files changed, 129 insertions(+), 7 deletions(-) create mode 100644 services/search/pkg/content/export_test.go diff --git a/services/search/README.md b/services/search/README.md index f071445dfc..fa73395ff9 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -164,7 +164,7 @@ Additionally, the following optional settings can be set: #### 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 same goes for a file the storage refuses to hand out, for example one deleted meanwhile, and for a file whose extraction takes longer than `SEARCH_EXTRACTOR_TIKA_TIMEOUT`. The content is tried again on the first reindex of its space at least one hour after the failure, and on the first one at least 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 failed connection, a server error or too many requests), a space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. +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 same goes for a file the storage refuses to hand out, for example one deleted meanwhile, and for a file whose extraction takes longer than `SEARCH_EXTRACTOR_TIKA_TIMEOUT` while Tika still answers a request for its version. The content is tried again on the first reindex of its space at least one hour after the failure, and on the first one at least 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 failed connection, a server error, too many requests or a Tika that does not answer its version within five seconds), a space reindex retries the extraction up to five times, one second apart, so a restarting Tika does not leave gaps. Once Tika was unreachable, the reindex asks Tika for its version before each extraction and skips the extraction while it gets no answer. A file still unreachable after that is indexed by name as well, this does not count as a failure and every later reindex tries again. After five such files in a row the reindex assumes Tika is down: it indexes the remaining files by name without retries until an extraction succeeds again, and reports an error naming the number of files indexed by name only once the space is done. To list the files the service gave up on, search for: diff --git a/services/search/pkg/content/export_test.go b/services/search/pkg/content/export_test.go new file mode 100644 index 0000000000..cdcc3b224a --- /dev/null +++ b/services/search/pkg/content/export_test.go @@ -0,0 +1,11 @@ +package content + +import "time" + +// SetProbeTimeout shortens the version check, a test of a hanging tika would +// otherwise wait seconds per probe +func SetProbeTimeout(d time.Duration) (restore func()) { + previous := probeTimeout + probeTimeout = d + return func() { probeTimeout = previous } +} diff --git a/services/search/pkg/content/extractor.go b/services/search/pkg/content/extractor.go index 518ae5bf4b..d4c0e7faba 100644 --- a/services/search/pkg/content/extractor.go +++ b/services/search/pkg/content/extractor.go @@ -21,6 +21,12 @@ type Extractor interface { Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, error) } +// Prober is an Extractor that can tell cheaply whether its backend answers, +// without the cost of a full extraction +type Prober interface { + Probe(ctx context.Context) error +} + // unreachable wraps the error of a failed call in ErrUnreachable, unless the // other side answered that the request itself is wrong (not found, a 4xx) func unreachable(err error) error { diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index c3f529f20d..d6d00a0886 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -23,6 +23,9 @@ import ( // unreachable tika it fails the same way on the next attempt more often than not var ErrUnparsable = errors.New("tika failed to parse") +// tika answers its version without parsing anything, even while busy with a file +var probeTimeout = 5 * time.Second + // Tika is used to extract content from a resource, // it uses apache tika to retrieve all the data. type Tika struct { @@ -153,12 +156,30 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, return doc, nil } +// Probe asks tika for its version, which tells a tika that is down or hangs +// from one busy with a hard file +func (t Tika) Probe(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, probeTimeout) + defer cancel() + _, err := t.tika.Version(ctx) + if err != nil { + return fmt.Errorf("%w: %w", ErrUnreachable, err) + } + return nil +} + // attemptError turns an attempt that ran out of time into a failure of the file: // tika accepted the request, so a retry would most likely run as long again and -// stack more work on a tika that may still be parsing +// stack more work on a tika that may still be parsing. Unless tika does not even +// answer its version, then it hangs and is unreachable. func (t Tika) attemptError(ctx, attemptCtx context.Context, ri *provider.ResourceInfo, err error) error { - if ctx.Err() == nil && errors.Is(attemptCtx.Err(), context.DeadlineExceeded) { - return fmt.Errorf("extracting %q took longer than %s: %w", ri.GetName(), t.Timeout, context.DeadlineExceeded) + if ctx.Err() != nil || !errors.Is(attemptCtx.Err(), context.DeadlineExceeded) { + return err + } + err = fmt.Errorf("extracting %q took longer than %s: %w", ri.GetName(), t.Timeout, context.DeadlineExceeded) + probeErr := t.Probe(ctx) + if probeErr != nil { + return fmt.Errorf("%w, %w", probeErr, err) } return err } diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index a2f4224ad0..d7fd81d30c 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -32,6 +32,7 @@ var _ = Describe("Tika", func() { version string rmetaStatus int rmetaHangs bool + versionHangs bool srv *httptest.Server tika *content.Tika ) @@ -44,10 +45,15 @@ var _ = Describe("Tika", func() { fullResponse = "" rmetaStatus = 0 rmetaHangs = false + versionHangs = false srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { out := "" switch req.URL.Path { case "/version": + if versionHangs { + <-req.Context().Done() + return + } out = version case "/language": if tika4Language { @@ -173,6 +179,30 @@ var _ = Describe("Tika", func() { Expect(errors.Is(err, content.ErrUnreachable)).To(BeFalse()) }) + It("counts a tika that does not even answer its version as unreachable", func() { + DeferCleanup(content.SetProbeTimeout(10 * time.Millisecond)) + rmetaHangs, versionHangs = true, true + tika.Timeout = 10 * time.Millisecond + + _, err := tika.Extract(context.TODO(), &provider.ResourceInfo{ + Type: provider.ResourceType_RESOURCE_TYPE_FILE, + Size: 1, + }) + Expect(err).To(MatchError(context.DeadlineExceeded)) + Expect(errors.Is(err, content.ErrUnreachable)).To(BeTrue()) + }) + + It("probes a tika that answers its version", func() { + Expect(tika.Probe(context.TODO())).To(Succeed()) + }) + + It("probes a tika that hangs as unreachable", func() { + DeferCleanup(content.SetProbeTimeout(10 * time.Millisecond)) + versionHangs = true + + Expect(tika.Probe(context.TODO())).To(MatchError(content.ErrUnreachable)) + }) + It("adds the title", func() { fullResponse = `[{"dc:title": "quarterly report", "X-TIKA:content": "some data"}]` diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 039d6bad8d..3337b12339 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -965,17 +965,17 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s // extract runs the content extraction and retries it while tika or the file is // out of reach, unless unreachable is nil or says tika is down func (s *Service) extract(ctx context.Context, info *provider.ResourceInfo, unreachable *unreachableExtractions) (content.Document, error) { - doc, err := s.extractor.Extract(ctx, info) if unreachable == nil { - return doc, err + return s.extractor.Extract(ctx, info) } + doc, err := s.extractOnce(ctx, info, unreachable.streak > 0) for retry := 0; retry < unreachableRetries && !unreachable.down && isUnreachable(err); retry++ { select { case <-ctx.Done(): return doc, err case <-time.After(unreachableRetryDelay): } - doc, err = s.extractor.Extract(ctx, info) + doc, err = s.extractOnce(ctx, info, true) } if !isUnreachable(err) { unreachable.streak, unreachable.down = 0, false @@ -992,6 +992,25 @@ func (s *Service) extract(ctx context.Context, info *provider.ResourceInfo, unre return doc, err } +// extractOnce runs one extraction. With probe set, after tika could not be +// reached, it first asks tika cheaply whether it answers again and skips the +// extraction if not, a hanging tika would cost the full timeout per file. +func (s *Service) extractOnce(ctx context.Context, info *provider.ResourceInfo, probe bool) (content.Document, error) { + prober, ok := s.extractor.(content.Prober) + if !probe || !ok { + return s.extractor.Extract(ctx, info) + } + probeErr := prober.Probe(ctx) + if probeErr == nil { + return s.extractor.Extract(ctx, info) + } + doc, err := s.basic.Extract(ctx, info) + if err != nil { + return doc, err + } + return doc, probeErr +} + // 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())) diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 3899248be0..4b9b45201a 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -383,6 +383,31 @@ var _ = Describe("Searchprovider", func() { Expect(attempts).To(HaveKeyWithValue("back.pdf", 1)) Expect(attempts).To(HaveKeyWithValue("z.pdf", 2)) }) + + It("skips the extraction while tika does not answer its version", func() { + files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "f.pdf", "g.pdf"} + extract = func(name string, _ int) (content.Document, error) { + if name == "g.pdf" { + return content.Document{Name: name, Content: "back"}, nil + } + return content.Document{Name: name}, unreached + } + // tika hangs from the first file on and answers again once f.pdf is indexed + probing := probingExtractor{Extractor: extractor, probe: func() error { + if _, back := upserted["storageid$spaceid!f.pdf"]; attempts["a.pdf"] > 0 && !back { + return unreached + } + return nil + }} + s = search.NewService(gatewaySelector, indexClient, probing, nil, logger, &config.Config{}) + + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(MatchError(unreached)) + Expect(attempts).To(Equal(map[string]int{"a.pdf": 1, "g.pdf": 1})) + for _, name := range files { + Expect(upserted).To(HaveKey("storageid$spaceid!" + name)) + } + Expect(upserted["storageid$spaceid!g.pdf"].Content).To(Equal("back")) + }) }) }) @@ -1186,3 +1211,13 @@ var _ = DescribeTable("Parse Scope", func ptr[T any](v T) *T { return &v } + +// probingExtractor adds the cheap reachability check of tika to the extractor mock +type probingExtractor struct { + *contentMocks.Extractor + probe func() error +} + +func (p probingExtractor) Probe(context.Context) error { + return p.probe() +} From b6a3e39f0888b5ff586b666710e4ecdd827356fe Mon Sep 17 00:00:00 2001 From: Florian Schade Date: Wed, 25 Nov 2026 14:02:20 +0100 Subject: [PATCH 5/5] fix(search): count only extractions that reach tika in the walk --- services/search/pkg/content/extractor.go | 9 ++++-- services/search/pkg/content/tika.go | 20 ++++++------ services/search/pkg/content/tika_test.go | 11 +++++++ services/search/pkg/search/service.go | 10 +++--- services/search/pkg/search/service_test.go | 37 ++++++++++++++++++++-- 5 files changed, 67 insertions(+), 20 deletions(-) diff --git a/services/search/pkg/content/extractor.go b/services/search/pkg/content/extractor.go index d4c0e7faba..a477f934ef 100644 --- a/services/search/pkg/content/extractor.go +++ b/services/search/pkg/content/extractor.go @@ -21,10 +21,13 @@ type Extractor interface { Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, error) } -// Prober is an Extractor that can tell cheaply whether its backend answers, -// without the cost of a full extraction -type Prober interface { +// RemoteExtractor is an Extractor that hands the content to a remote service +type RemoteExtractor interface { + // Probe tells cheaply whether the remote answers, without a full extraction Probe(ctx context.Context) error + // Remote tells whether extracting ri goes to the remote at all, a folder or + // a file over the size limit does not and says nothing about its state + Remote(ri *provider.ResourceInfo) bool } // unreachable wraps the error of a failed call in ErrUnreachable, unless the diff --git a/services/search/pkg/content/tika.go b/services/search/pkg/content/tika.go index d6d00a0886..c296a91faf 100644 --- a/services/search/pkg/content/tika.go +++ b/services/search/pkg/content/tika.go @@ -70,16 +70,10 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, return doc, err } - if ri.Size == 0 { - return doc, nil - } - - if ri.Type != provider.ResourceType_RESOURCE_TYPE_FILE { - return doc, nil - } - - if ri.Size > t.ContentExtractionSizeLimit { - t.logger.Info().Interface("ResourceID", ri.Id).Str("Name", ri.Name).Msg("file exceeds content extraction size limit. skipping.") + if !t.Remote(ri) { + if ri.GetType() == provider.ResourceType_RESOURCE_TYPE_FILE && ri.GetSize() > t.ContentExtractionSizeLimit { + t.logger.Info().Interface("ResourceID", ri.GetId()).Str("Name", ri.GetName()).Msg("file exceeds content extraction size limit. skipping.") + } return doc, nil } @@ -156,6 +150,12 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document, return doc, nil } +// Remote tells whether extracting ri goes to tika, only a file with content +// within the size limit does +func (t Tika) Remote(ri *provider.ResourceInfo) bool { + return ri.GetType() == provider.ResourceType_RESOURCE_TYPE_FILE && ri.GetSize() > 0 && ri.GetSize() <= t.ContentExtractionSizeLimit +} + // Probe asks tika for its version, which tells a tika that is down or hangs // from one busy with a hard file func (t Tika) Probe(ctx context.Context) error { diff --git a/services/search/pkg/content/tika_test.go b/services/search/pkg/content/tika_test.go index d7fd81d30c..34b3d85030 100644 --- a/services/search/pkg/content/tika_test.go +++ b/services/search/pkg/content/tika_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "math" "net/http" "net/http/httptest" "strings" @@ -192,6 +193,16 @@ var _ = Describe("Tika", func() { Expect(errors.Is(err, content.ErrUnreachable)).To(BeTrue()) }) + DescribeTable("sends only files with content within the size limit to tika", + func(info *provider.ResourceInfo, remote bool) { + Expect(tika.Remote(info)).To(Equal(remote)) + }, + Entry("file", &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_FILE, Size: 1}, true), + Entry("empty file", &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_FILE}, false), + Entry("file over the limit", &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_FILE, Size: math.MaxInt64}, false), + Entry("folder", &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, Size: 1}, false), + ) + It("probes a tika that answers its version", func() { Expect(tika.Probe(context.TODO())).To(Succeed()) }) diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 3337b12339..a8d409ef31 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -963,9 +963,11 @@ func (s *Service) upsertResource(ctx context.Context, ref *provider.Reference, s } // extract runs the content extraction and retries it while tika or the file is -// out of reach, unless unreachable is nil or says tika is down +// out of reach, unless unreachable is nil or says tika is down. A resource the +// extractor does not send to tika leaves the count alone, it says nothing about tika. func (s *Service) extract(ctx context.Context, info *provider.ResourceInfo, unreachable *unreachableExtractions) (content.Document, error) { - if unreachable == nil { + remote, ok := s.extractor.(content.RemoteExtractor) + if unreachable == nil || (ok && !remote.Remote(info)) { return s.extractor.Extract(ctx, info) } doc, err := s.extractOnce(ctx, info, unreachable.streak > 0) @@ -996,11 +998,11 @@ func (s *Service) extract(ctx context.Context, info *provider.ResourceInfo, unre // reached, it first asks tika cheaply whether it answers again and skips the // extraction if not, a hanging tika would cost the full timeout per file. func (s *Service) extractOnce(ctx context.Context, info *provider.ResourceInfo, probe bool) (content.Document, error) { - prober, ok := s.extractor.(content.Prober) + remote, ok := s.extractor.(content.RemoteExtractor) if !probe || !ok { return s.extractor.Extract(ctx, info) } - probeErr := prober.Probe(ctx) + probeErr := remote.Probe(ctx) if probeErr == nil { return s.extractor.Extract(ctx, info) } diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 4b9b45201a..9b5c3a66eb 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -393,7 +393,7 @@ var _ = Describe("Searchprovider", func() { return content.Document{Name: name}, unreached } // tika hangs from the first file on and answers again once f.pdf is indexed - probing := probingExtractor{Extractor: extractor, probe: func() error { + probing := probingExtractor{Extractor: extractor, remote: remoteFiles, probe: func() error { if _, back := upserted["storageid$spaceid!f.pdf"]; attempts["a.pdf"] > 0 && !back { return unreached } @@ -408,6 +408,28 @@ var _ = Describe("Searchprovider", func() { } Expect(upserted["storageid$spaceid!g.pdf"].Content).To(Equal("back")) }) + + It("keeps tika down across a file the extractor does not send to tika", func() { + files = []string{"a.pdf", "b.pdf", "c.pdf", "d.pdf", "e.pdf", "huge.pdf", "f.pdf"} + extract = func(name string, _ int) (content.Document, error) { + if name == "huge.pdf" { + return content.Document{Name: name}, nil + } + return content.Document{Name: name}, unreached + } + probing := probingExtractor{ + Extractor: extractor, + remote: func(info *sprovider.ResourceInfo) bool { + return remoteFiles(info) && info.GetPath() != "huge.pdf" + }, + probe: func() error { return nil }, + } + s = search.NewService(gatewaySelector, indexClient, probing, nil, logger, &config.Config{}) + + Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(MatchError(unreached)) + Expect(attempts).To(HaveKeyWithValue("huge.pdf", 1)) + Expect(attempts).To(HaveKeyWithValue("f.pdf", 1)) + }) }) }) @@ -1212,12 +1234,21 @@ func ptr[T any](v T) *T { return &v } -// probingExtractor adds the cheap reachability check of tika to the extractor mock +// probingExtractor makes the extractor mock one that hands files to tika type probingExtractor struct { *contentMocks.Extractor - probe func() error + probe func() error + remote func(info *sprovider.ResourceInfo) bool } func (p probingExtractor) Probe(context.Context) error { return p.probe() } + +func (p probingExtractor) Remote(info *sprovider.ResourceInfo) bool { + return p.remote(info) +} + +func remoteFiles(info *sprovider.ResourceInfo) bool { + return info.GetType() == sprovider.ResourceType_RESOURCE_TYPE_FILE +}