fix(search): retry only unreachable extractions and bound each attempt

This commit is contained in:
Florian Schade committed 2026-11-25 12:29:02 +01:00
1 parent debbeae2cb
commit 12e7b86344
10 files changed
+220 -24

No files matched your search

+2 -1
View File
@@ -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:
+5 -2
View File
@@ -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%%"`
}
@@ -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{
+14 -6
View File
@@ -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
+92
View File
@@ -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),
)
})
+26
View File
@@ -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) {
+11 -1
View File
@@ -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 {
+43
View File
@@ -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"}]`
+12 -12
View File
@@ -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)
}
+13 -2
View File
@@ -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