mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-12-05 05:43:36 -05:00
feat(webdav): extract a source image once per file, not once per size
What an extractor makes of a file does not depend on the size that was asked for, so it is kept under one key per file and read before the file is even downloaded. An empty entry says the file carries nothing, which keeps the next size from asking Tika again; a failed extraction is not remembered. The file cache now replaces what a key holds, as the other two backends already did, because an entry whose value can change has to be replaceable.
This commit is contained in:
1 parent
6b2c30219c
commit
5d98850cd9
5 files changed
+116
-24
No files matched your search
@@ -12,7 +12,7 @@ The webdav service provides various `GET` endpoints to get the thumbnails of a f
|
||||
|
||||
When `OC_TIKA_URL` (or `WEBDAV_TIKA_URL`) is set, an Apache Tika server (4.2.0 or newer) supplies the preview image for documents, raw photos, audio cover art and other types. Every file that is not a directly supported image is sent to Tika; `OC_TIKA_THUMBNAIL_MIME_TYPES` (or `WEBDAV_TIKA_THUMBNAIL_MIME_TYPES`) restricts that to a list of mime types, where an entry like `image/x-nikon-nef:image/x-raw-nikon` maps a type to the one Tika knows the format by. Tika takes a declared type only when it refines what it detected itself, so an entry pins a subtype its detector left at the parent type, a raw photo it only read as a tiff. The webdav service calls `PUT /unpack/preset/thumbnail`, so the Tika server has to run with the `thumbnail` catalog preset active: start it with `TIKA_PRESETS=thumbnail`, a comma separated list of the presets to activate. Without Tika, audio cover art and GeoGebra thumbnails are still extracted by the webdav service itself; those built-in extractors are deprecated. A type Tika takes is attempted even when `OC_THUMBNAILS_ADDITIONAL_SOURCE_TYPES` does not announce it, so a direct request can get a preview that a listing reports as absent. An image type is only sent to Tika when the list names it, because the generator behind the URL may read it itself, an imagor with ImageMagick reads heic where the built-in one does not. Naming a type also restricts Tika to the named ones, so a deployment that sends raw photos to Tika has to name the document types it wants from Tika as well. The thumbnail is written in the type the **file's** own type maps to (`OC_THUMBNAILS_ADDITIONAL_OUTPUT_TYPES`), not in whatever type Tika hands back, so the answer is the same before and after a cache hit. That is also why a windows binary is mapped to `image/png` by default: the icon Tika reads out of it carries transparency that a JPEG would flatten onto black.
|
||||
|
||||
Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose.
|
||||
Generated thumbnails are cached by the webdav service itself. The cache backend defaults to `file`, storing entries under `$OC_BASE_DATA_PATH/thumbnails/cache` (override with `WEBDAV_THUMBNAILS_CACHE_BACKEND` and `WEBDAV_THUMBNAILS_CACHE_DIR`). Use the `s3` backend when running multiple instances behind a load balancer so they share one cache. A backend nobody can serve, an unknown name or an `s3` backend without bucket, region and credentials, fails at startup instead of serving without a cache, as long as previews are enabled. A service that is not AWS needs `WEBDAV_THUMBNAILS_CACHE_S3_ENDPOINT` too, and it is always addressed over https. The `memory` backend is bounded and drops its oldest entries; `none` disables caching on purpose. The cache also keeps the image an extractor made of a file, under one entry per file, so a second size does not extract again and a file that carries no image is only asked once. Nothing expires: a changed file is a new entry because the key carries its checksum, but an extractor that learns to read a format it could not read before does not reach the files it already answered for. After such an upgrade, an Apache Tika release among them, empty the cache (`WEBDAV_THUMBNAILS_CACHE_DIR`, or the bucket) to have them asked again.
|
||||
|
||||
#### Thumbnail Query String Parameters
|
||||
|
||||
|
||||
+4
-17
@@ -456,27 +456,14 @@ var _ = Describe("FileCache", func() {
|
||||
Expect(original).To(Equal([]byte("original")))
|
||||
})
|
||||
|
||||
It("should be idempotent - Put is no-op if file already exists", func() {
|
||||
It("should overwrite existing keys", func() {
|
||||
key := "ab/cd/ef1234567890/400x400.jpg"
|
||||
err := cache.Put(key, []byte("v1"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info1, err := os.Stat(filepath.Join(tmpdir, "ab", "cd", "ef1234567890", "400x400.jpg"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
modTime1 := info1.ModTime()
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
err = cache.Put(key, []byte("v2"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cache.Put(key, []byte("v1"))).To(Succeed())
|
||||
Expect(cache.Put(key, []byte("v2"))).To(Succeed())
|
||||
|
||||
data, err := cache.Get(key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]byte("v1")))
|
||||
|
||||
info2, err := os.Stat(filepath.Join(tmpdir, "ab", "cd", "ef1234567890", "400x400.jpg"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(info2.ModTime()).To(Equal(modTime1))
|
||||
Expect(data).To(Equal([]byte("v2")), "a key whose value can change has to be replaceable")
|
||||
})
|
||||
|
||||
It("should handle empty data", func() {
|
||||
|
||||
@@ -36,10 +36,6 @@ func (c *FileCache) Put(key string, data []byte) error {
|
||||
imgPath := filepath.Join(c.dir, key)
|
||||
dir := filepath.Dir(imgPath)
|
||||
|
||||
if _, err := os.Stat(imgPath); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -142,6 +142,17 @@ func thumbnailStorageKey(checksum, mimeType string, w, h int, format, operation
|
||||
return hash[:2] + "/" + hash[2:4] + "/" + hash[4:] + "/" + fmt.Sprintf("%dx%d-%s.%s", w, h, operation, format)
|
||||
}
|
||||
|
||||
// sourceStorageKey is where the image an extractor made of a file is
|
||||
// remembered. What an extractor finds does not depend on the size that was
|
||||
// asked for, so this one entry answers every request for the file, and an
|
||||
// empty entry says the file carries no image at all.
|
||||
func sourceStorageKey(checksum string) string {
|
||||
if len(checksum) >= 6 {
|
||||
return checksum[:2] + "/" + checksum[2:4] + "/" + checksum[4:] + "/source"
|
||||
}
|
||||
return checksum + "/source"
|
||||
}
|
||||
|
||||
// ThumbnailWorkflow owns the complete thumbnail generation pipeline:
|
||||
// stat → validate → cache check → download → preprocess → generate → cache → respond.
|
||||
type ThumbnailWorkflow struct {
|
||||
@@ -481,7 +492,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
// in webdav: real images (incl. gif) are streamed straight through undecoded;
|
||||
// non-image sources are converted to image bytes here so the generator always
|
||||
// receives an image.
|
||||
imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, logger)
|
||||
imgStream, srcType, cleanup, err := w.sourceImage(ctx, ref, auth, mimeType, tr.Filename, checksum, logger)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoThumbnail) {
|
||||
// a file that carries no thumbnail is an answer, not a failure, and
|
||||
@@ -537,7 +548,7 @@ func (w *ThumbnailWorkflow) generate(ctx context.Context, ref *providerv1beta1.R
|
||||
// generator decides whether it can read it.
|
||||
// - text/plain is rendered to an image here (the only true conversion).
|
||||
// - audio and geogebra sources have their embedded image extracted to bytes.
|
||||
func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename string, logger log.Logger) (io.Reader, string, func(), error) {
|
||||
func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta1.Reference, auth, mimeType, filename, checksum string, logger log.Logger) (io.Reader, string, func(), error) {
|
||||
m, _, _ := mime.ParseMediaType(mimeType)
|
||||
|
||||
// the preprocessor decides what a type needs. No converter means the file
|
||||
@@ -550,6 +561,22 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta
|
||||
Filename: filename,
|
||||
})
|
||||
|
||||
// what the extraction found is remembered per file, so a second size does
|
||||
// not send the file to Tika again, and a file that carries nothing is only
|
||||
// asked once. The answer is read before the file is downloaded at all.
|
||||
sourceKey := sourceStorageKey(checksum)
|
||||
if converter != nil && w.cache != nil {
|
||||
if cached, err := w.cache.Get(sourceKey); err == nil {
|
||||
if len(cached) == 0 {
|
||||
return nil, "", nil, ErrNoThumbnail
|
||||
}
|
||||
|
||||
//the cache holds bytes, so the type comes from them: the generator
|
||||
//sniffs them too, this only tells it what to expect
|
||||
return bytes.NewReader(cached), http.DetectContentType(cached), func() {}, nil
|
||||
}
|
||||
}
|
||||
|
||||
body, err := w.fileDownloader.DownloadStream(ctx, ref, auth)
|
||||
if err != nil {
|
||||
return nil, "", nil, fmt.Errorf("download: %w", err)
|
||||
@@ -567,16 +594,39 @@ func (w *ThumbnailWorkflow) sourceImage(ctx context.Context, ref *providerv1beta
|
||||
|
||||
img, err := converter.Convert(bytes.NewReader(fileBytes))
|
||||
if errors.Is(err, preprocessor.ErrNoThumbnail) {
|
||||
//the file carries no image, which is an answer and worth remembering;
|
||||
//a failed extraction is not, it may succeed on the next try
|
||||
w.rememberSource(sourceKey, nil)
|
||||
return nil, "", nil, ErrNoThumbnail
|
||||
}
|
||||
if err != nil || img == nil {
|
||||
logger.Debug().Err(err).Msg("could not convert file to image")
|
||||
return nil, "", nil, fmt.Errorf("%w: could not get image", ErrNotFound)
|
||||
}
|
||||
w.rememberSource(sourceKey, img.Data)
|
||||
|
||||
return bytes.NewReader(img.Data), img.ContentType, func() {}, nil
|
||||
}
|
||||
|
||||
// maxCachedSourceBytes bounds one remembered source image. A preview a camera
|
||||
// embeds is about a megabyte, a rendered page a few; the limit is what keeps
|
||||
// the memory backend, which evicts in insertion order, from throwing out the
|
||||
// thumbnails it serves to make room for one source.
|
||||
const maxCachedSourceBytes = 8 << 20
|
||||
|
||||
// rememberSource keeps what an extractor made of a file, or the empty entry
|
||||
// that says it made nothing. An image too large to keep is simply not kept:
|
||||
// the extraction runs again next time, which costs time, not correctness.
|
||||
func (w *ThumbnailWorkflow) rememberSource(key string, data []byte) {
|
||||
if w.cache == nil || len(data) > maxCachedSourceBytes {
|
||||
return
|
||||
}
|
||||
if w.maxInputSize > 0 && uint64(len(data)) > w.maxInputSize {
|
||||
return
|
||||
}
|
||||
_ = w.cache.Put(key, data)
|
||||
}
|
||||
|
||||
// supportsMimeType reports whether a preview is attempted for the type: the
|
||||
// announced source types plus whatever a configured Tika takes.
|
||||
func (w *ThumbnailWorkflow) supportsMimeType(mimeType string) bool {
|
||||
|
||||
@@ -829,6 +829,65 @@ var _ = Describe("ThumbnailWorkflow", func() {
|
||||
Expect(captured.data).ToNot(Equal(mp3Bytes))
|
||||
})
|
||||
|
||||
It("keeps what an extractor found, under one key for the whole file", func() {
|
||||
mp3Bytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "empty.mp3"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", mp3Bytes)
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
cached, err := testCache.Get("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(cached).To(Equal(captured.data), "the cover art is kept as the source, not per size")
|
||||
})
|
||||
|
||||
It("sends the kept source instead of extracting a second time", func() {
|
||||
pngBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "noise.png"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(testCache.Put("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source", pngBytes)).To(Succeed())
|
||||
|
||||
//the file itself is not an mp3: extracting it would fail, so what
|
||||
//reaches the generator can only come from the cache
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3"))
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Width: 128,
|
||||
Height: 128,
|
||||
}
|
||||
|
||||
_, err = wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(captured.data).To(Equal(pngBytes))
|
||||
})
|
||||
|
||||
It("asks once for a file that carries nothing, whatever size follows", func() {
|
||||
Expect(testCache.Put("1f/0c/9f1b6e4b4b2a9c1d7f3e8a5b6c7d8e9f0a1b/source", nil)).To(Succeed())
|
||||
|
||||
wf2, captured := setupPreprocessTest(GinkgoT(), gatewayClient, logger, testCache, "audio/mpeg", "song.mp3", []byte("not an mp3"))
|
||||
|
||||
tr := &requests.ThumbnailRequest{
|
||||
Ref: spaceRef("storageid$spaceid!opaqueid", "song.mp3"),
|
||||
Filename: "song.mp3",
|
||||
Width: 256,
|
||||
Height: 256,
|
||||
}
|
||||
|
||||
_, err := wf2.Execute(context.Background(), tr, testToken, logger)
|
||||
Expect(err).To(MatchError(ErrNoThumbnail))
|
||||
Expect(captured.data).To(BeEmpty(), "the generator is not asked at all")
|
||||
})
|
||||
|
||||
It("extracts the embedded thumbnail from geogebra slides", func() {
|
||||
ggsBytes, err := os.ReadFile(filepath.Join("..", "..", "preprocessor", "test_assets", "ggs_test.ggs"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Reference in new issue
Block a user