Merge branch 'origin/main' into 'next-release/main'

This commit is contained in:
oauth committed 2026-11-25 13:37:43 +00:00
commit dd4d353b97
12 files changed
+661 -47

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 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 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 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:
+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 a failure of the file. 0 disables the limit. See the documentation for more details." introductionVersion:"%%NEXT%%"`
}
@@ -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,6 +54,7 @@ func DefaultConfig() *config.Config {
Tika: config.ExtractorTika{
TikaURL: "http://127.0.0.1:9998",
CleanStopWords: false,
Timeout: defaultTikaTimeout,
},
},
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 transientStatus(cres.StatusCode) {
err = fmt.Errorf("%w: %w", ErrUnreachable, err)
}
return nil, err
}
return cres.Body, nil
+93
View File
@@ -0,0 +1,93 @@
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 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),
Entry("download not found", func() { download(rpc.Code_CODE_OK); downloadStatus = http.StatusNotFound }, false),
)
})
@@ -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 }
}
+41
View File
@@ -2,16 +2,57 @@ 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
// 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)
}
// 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
// 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) && !transientStatus(tikaErr.StatusCode) {
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)
}
// 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) {
+55 -13
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"
@@ -22,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 {
@@ -31,6 +35,7 @@ type Tika struct {
tikaURL string
ContentExtractionSizeLimit uint64
CleanStopWords bool
Timeout time.Duration
}
// NewTikaExtractor creates a new Tika instance.
@@ -54,6 +59,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
}
@@ -64,28 +70,30 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
return doc, err
}
if ri.Size == 0 {
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
}
if ri.Type != provider.ResourceType_RESOURCE_TYPE_FILE {
return doc, nil
// a tika that hangs instead of refusing connections would block the walk
attemptCtx := ctx
if t.Timeout > 0 {
var cancel context.CancelFunc
attemptCtx, cancel = context.WithTimeout(ctx, t.Timeout)
defer cancel()
}
if ri.Size > t.ContentExtractionSizeLimit {
t.logger.Info().Interface("ResourceID", ri.Id).Str("Name", ri.Name).Msg("file exceeds content extraction size limit. skipping.")
return doc, nil
}
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, 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 {
@@ -135,13 +143,47 @@ 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
}
// 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 {
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. 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 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
}
// 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.
+85
View File
@@ -2,11 +2,14 @@ package content_test
import (
"context"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/http/httptest"
"strings"
"time"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
. "github.com/onsi/ginkgo/v2"
@@ -28,6 +31,9 @@ var _ = Describe("Tika", func() {
language string
tika4Language bool
version string
rmetaStatus int
rmetaHangs bool
versionHangs bool
srv *httptest.Server
tika *content.Tika
)
@@ -38,10 +44,17 @@ var _ = Describe("Tika", func() {
tika4Language = false
version = ""
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 {
@@ -53,6 +66,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 +152,68 @@ 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("too many requests", http.StatusTooManyRequests, true),
Entry("unprocessable file", http.StatusUnprocessableEntity, false),
)
It("counts a tika that does not answer in time as a failure of the file", 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(context.DeadlineExceeded))
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())
})
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())
})
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"}]`
+11
View File
@@ -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 }
}
+116 -24
View File
@@ -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 <mark> 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")
@@ -859,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
}
@@ -945,6 +962,57 @@ 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. 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) {
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)
for retry := 0; retry < unreachableRetries && !unreachable.down && isUnreachable(err); retry++ {
select {
case <-ctx.Done():
return doc, err
case <-time.After(unreachableRetryDelay):
}
doc, err = s.extractOnce(ctx, info, true)
}
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
}
// 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) {
remote, ok := s.extractor.(content.RemoteExtractor)
if !probe || !ok {
return s.extractor.Extract(ctx, info)
}
probeErr := remote.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()))
@@ -962,19 +1030,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
}
@@ -982,7 +1050,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
}
@@ -1058,3 +1126,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 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 errors.Is(err, content.ErrUnreachable)
}
+224 -1
View File
@@ -227,6 +227,210 @@ 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 = fmt.Errorf("%w: connection refused", content.ErrUnreachable)
)
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("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) {
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))
})
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, remote: remoteFiles, 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"))
})
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))
})
})
})
Describe("indexing a resource in full", func() {
@@ -319,7 +523,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
@@ -1029,3 +1233,22 @@ var _ = DescribeTable("Parse Scope",
func ptr[T any](v T) *T {
return &v
}
// probingExtractor makes the extractor mock one that hands files to tika
type probingExtractor struct {
*contentMocks.Extractor
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
}