Merge pull request #4133 from fschade/search-oversized-metadata

fix(search): extract the metadata of files over the size limit
This commit is contained in:
Florian Schade authored and GitHub committed 2026-11-26 13:46:59 +01:00
commit 335e482a96
5 files changed
+103 -27

No files matched your search

+1
View File
@@ -160,6 +160,7 @@ 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_CONTENT_EXTRACTION_SIZE_LIMIT=20971520` (default: 20 MiB): files up to this size get their content extracted. Of a larger file only the metadata is extracted, such as EXIF or the image size, from its first bytes up to this size.
* `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
+1 -1
View File
@@ -27,7 +27,7 @@ type Config struct {
Events Events `yaml:"events"`
Engine Engine `yaml:"engine"`
Extractor Extractor `yaml:"extractor"`
ContentExtractionSizeLimit uint64 `yaml:"content_extraction_size_limit" env:"SEARCH_CONTENT_EXTRACTION_SIZE_LIMIT" desc:"Maximum file size in bytes that is allowed for content extraction." introductionVersion:"1.0.0"`
ContentExtractionSizeLimit uint64 `yaml:"content_extraction_size_limit" env:"SEARCH_CONTENT_EXTRACTION_SIZE_LIMIT" desc:"Maximum file size in bytes that is allowed for content extraction. Of a larger file only the metadata is extracted, from its first bytes up to this size." introductionVersion:"1.0.0"`
BatchSize int `yaml:"batch_size" env:"SEARCH_BATCH_SIZE" desc:"The number of documents to process in a single batch. Defaults to 500." introductionVersion:"1.0.0"`
ReindexMaxConcurrency int `yaml:"reindex_concurrency" env:"SEARCH_REINDEX_MAX_CONCURRENCY" desc:"The maximum number of spaces that are reindexed concurrently when reindexing all spaces." introductionVersion:"7.4.0"`
QueryTemplate string `yaml:"query_template" env:"SEARCH_QUERY_TEMPLATE" desc:"A KQL template every search runs through, see the search service documentation for the available placeholders." introductionVersion:"9.0.0"`
+1 -1
View File
@@ -26,7 +26,7 @@ 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
// an empty file does not and says nothing about its state
Remote(ri *provider.ResourceInfo) bool
}
+46 -22
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"math"
"net/http"
"slices"
"strings"
@@ -71,11 +72,11 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
}
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
}
// the head of a file over the limit still holds its metadata (exif, image
// size), its content is left out and tika may fail on the cut
oversized := ri.GetSize() > t.ContentExtractionSizeLimit
// a tika that hangs instead of refusing connections would block the walk
attemptCtx := ctx
@@ -91,9 +92,25 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
}
defer data.Close()
metas, err := t.tika.MetaRecursive(attemptCtx, data)
var input io.Reader = data
handler := "text"
if oversized {
input = io.LimitReader(data, int64(min(t.ContentExtractionSizeLimit, math.MaxInt64)))
handler = "ignore"
}
metas, err := t.tika.MetaRecursiveType(attemptCtx, input, handler)
if err != nil {
return doc, t.attemptError(ctx, attemptCtx, ri, unreachable(err))
err = t.attemptError(ctx, attemptCtx, ri, unreachable(err))
if oversized && !errors.Is(err, ErrUnreachable) {
// a failure on the cut says nothing about the file, a retry would fail the same way
t.logger.Info().Err(err).Interface("ResourceID", ri.GetId()).Str("Name", ri.GetName()).Msg("no metadata from the head of a file over the content extraction size limit")
return doc, nil
}
return doc, err
}
if oversized {
t.addFacets(&doc, metas)
return doc, nil
}
// a file with content always yields metadata, none means tika failed on it
if len(metas) == 0 {
@@ -128,20 +145,7 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
}
}
// facets describe the file itself, not its embedded parts (cover art, clips)
m0 := metas[0]
doc.Location = t.getLocation(m0)
doc.Image = t.getImage(m0)
doc.Photo = t.getPhoto(m0)
doc.Audio = t.getAudio(m0)
doc.LivePhoto = t.getLivePhoto(m0)
doc.Video = t.getVideo(m0)
// a motion photo is the file's own xmp plus the video tika extracted from
// it; the xmp alone proves nothing, a share can strip the appended clip
if i := slices.IndexFunc(metas[1:], isVideo); i >= 0 {
doc.MotionPhoto = t.getMotionPhoto(m0, metas[i+1])
}
t.addFacets(&doc, metas)
if langCode := t.detectLanguage(attemptCtx, doc.Content); langCode != "" && t.CleanStopWords {
doc.Content = CleanString(doc.Content, langCode)
@@ -150,10 +154,9 @@ 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
// Remote tells whether extracting ri goes to tika, only a file with content does
func (t Tika) Remote(ri *provider.ResourceInfo) bool {
return ri.GetType() == provider.ResourceType_RESOURCE_TYPE_FILE && ri.GetSize() > 0 && ri.GetSize() <= t.ContentExtractionSizeLimit
return ri.GetType() == provider.ResourceType_RESOURCE_TYPE_FILE && ri.GetSize() > 0
}
// Probe asks tika for its version, which tells a tika that is down or hangs
@@ -184,6 +187,27 @@ func (t Tika) attemptError(ctx, attemptCtx context.Context, ri *provider.Resourc
return err
}
// addFacets takes the facets of the file itself, not of its embedded parts
// (cover art, clips)
func (t Tika) addFacets(doc *Document, metas []map[string][]string) {
if len(metas) == 0 {
return
}
m0 := metas[0]
doc.Location = t.getLocation(m0)
doc.Image = t.getImage(m0)
doc.Photo = t.getPhoto(m0)
doc.Audio = t.getAudio(m0)
doc.LivePhoto = t.getLivePhoto(m0)
doc.Video = t.getVideo(m0)
// a motion photo is the file's own xmp plus the video tika extracted from
// it; the xmp alone proves nothing, a share can strip the appended clip
if i := slices.IndexFunc(metas[1:], isVideo); i >= 0 {
doc.MotionPhoto = t.getMotionPhoto(m0, metas[i+1])
}
}
// 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.
+54 -3
View File
@@ -34,6 +34,8 @@ var _ = Describe("Tika", func() {
rmetaStatus int
rmetaHangs bool
versionHangs bool
rmetaPath string
rmetaBytes int
srv *httptest.Server
tika *content.Tika
)
@@ -65,13 +67,16 @@ var _ = Describe("Tika", func() {
}
case "/language/string":
out = language
case "/rmeta/text":
case "/rmeta/text", "/rmeta/ignore":
rmetaPath = req.URL.Path
if rmetaHangs {
// the server notices the client leaving only once the body is read
_, _ = io.Copy(io.Discard, req.Body)
<-req.Context().Done()
return
}
received, _ := io.ReadAll(req.Body)
rmetaBytes = len(received)
if rmetaStatus != 0 {
w.WriteHeader(rmetaStatus)
return
@@ -193,13 +198,59 @@ var _ = Describe("Tika", func() {
Expect(errors.Is(err, content.ErrUnreachable)).To(BeTrue())
})
DescribeTable("sends only files with content within the size limit to tika",
Context("with a file over the content extraction size limit", func() {
oversized := &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_FILE, Size: 8_000_000}
BeforeEach(func() {
body = strings.Repeat("x", 100)
tika.ContentExtractionSizeLimit = 10
retriever := &contentMocks.Retriever{}
retriever.On("Retrieve", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader(body)), nil)
tika.Retriever = retriever
})
It("extracts the metadata from the head of the file, without the content", func() {
fullResponse = `[{"Content-Type": "image/jpeg", "tiff:Make": "Google", "tiff:ImageWidth": "4080", "tiff:ImageLength": "3072", "tk:content": "not asked for"}]`
doc, err := tika.Extract(context.TODO(), oversized)
Expect(err).ToNot(HaveOccurred())
Expect(rmetaPath).To(Equal("/rmeta/ignore"))
Expect(rmetaBytes).To(Equal(10))
Expect(doc.Photo.CameraMake).To(Equal(libregraph.PtrString("Google")))
Expect(doc.Image.Width).To(Equal(libregraph.PtrInt32(4080)))
Expect(doc.Content).To(BeEmpty())
})
It("keeps the metadata when tika fails on the cut", func() {
fullResponse = `[{"Content-Type": "image/jpeg", "tiff:ImageWidth": "4080", "tk:exception:container-exception": "org.apache.tika.exception.TikaException: TesseractOCRParser bad exit value 1 err msg: Premature end of JPEG file"}]`
doc, err := tika.Extract(context.TODO(), oversized)
Expect(err).ToNot(HaveOccurred())
Expect(doc.Image.Width).To(Equal(libregraph.PtrInt32(4080)))
})
It("does not count a head tika rejects as a failure of the file", func() {
rmetaStatus = http.StatusUnprocessableEntity
_, err := tika.Extract(context.TODO(), oversized)
Expect(err).ToNot(HaveOccurred())
})
It("still reports an unreachable tika", func() {
rmetaStatus = http.StatusServiceUnavailable
_, err := tika.Extract(context.TODO(), oversized)
Expect(err).To(MatchError(content.ErrUnreachable))
})
})
DescribeTable("sends only files with content 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("file over the limit", &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_FILE, Size: math.MaxInt64}, true),
Entry("folder", &provider.ResourceInfo{Type: provider.ResourceType_RESOURCE_TYPE_CONTAINER, Size: 1}, false),
)